Skip to content

Allow the preliminary DISTINCT to abandon deduplication on mostly-unique input - #116508

Merged
nihalzp merged 6 commits into
ClickHouse:masterfrom
nihalzp:preliminary-distinct-abandon
Sep 2, 2026
Merged

nihalzp merged 6 commits into
ClickHouse:masterfrom
nihalzp:preliminary-distinct-abandon

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Runtime:

image image

Memory:
image

Related: #114645

The preliminary (per-stream) DISTINCT pays off only when it removes rows: the final DISTINCT deduplicates its output anyway, so on mostly-unique input the preliminary transforms keep a second full copy of the unique keys in their per-stream hash tables and pay a hash probe per row for nothing.

This PR lets the preliminary DISTINCT give up: its transforms now run the DeduplicationAbandonController introduced for the per-partition IN (subquery) set build in #114645. The controller observes the first chunks (five chunks, or earlier once the observed set reaches 16 MiB for wide keys) and, when nearly all rows survive deduplication (≥ 90% unique), the transform drops its hash table and passes the remaining chunks through untouched. Duplicate-heavy inputs never abandon and keep the preliminary reduction.

This is sound because the preliminary DISTINCT is best-effort by contract: duplicates from different streams pass through it even when it deduplicates, so every consumer already tolerates duplicates, and a final DISTINCT deduplicates the output again. Abandoning only changes how many duplicates reach the final, never the result. It applies to every preliminary DISTINCT, including shard-side plans of distributed queries (bounded by the 90% threshold, a shard ships at most ~11% more rows on the inputs where it fires). It is not applied when the step carries a limit hint (SELECT DISTINCT ... LIMIT n without subsequent ordering), because stopping the input early after enough distinct rows requires counting them, and the reading-in-order path is unaffected (the sorted transform deduplicates by ranges and accumulates nothing worth abandoning).

The behavior is controlled by the new setting allow_preliminary_distinct_abandoning (enabled by default) and observable through the new profile event DistinctTransformsAbandonedDeduplication, which also covers the set-build path from #114645.

Measured on 30M unique UInt64 rows in a 16-partition MergeTree table, SELECT DISTINCT (5 runs, first 2 discarded):

threads before after
16 1114 MB / 0.130 s 576 MB / 0.074 s
64 1377 MB / 0.885 s 825 MB / 0.875 s

On a 10M-row mostly-unique LowCardinality(Nullable(String)) key the peak drops from 2.25 GB to 1.20 GB at 16 threads. Duplicate-heavy inputs (100M rows, 1M unique) are unchanged within noise.

Changelog category (leave one):

  • Performance Improvement

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

The preliminary (per-stream) DISTINCT now abandons deduplication when the observed input is almost entirely unique, freeing its hash tables and skipping per-row hashing: the final DISTINCT deduplicates the output anyway, so on unique data this roughly halves the memory of SELECT DISTINCT and speeds it up (measured 1114 MB → 576 MB and 0.130 s → 0.074 s on 30M unique rows). Controlled by the new setting allow_preliminary_distinct_abandoning; observable via the new profile event DistinctTransformsAbandonedDeduplication.


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

Version info

  • Merged into: 26.9.1.507 (included in 26.9 and later)

@yariks5s yariks5s self-assigned this Aug 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bac8502]

Summary: ✅


AI Review

Summary

This PR teaches the preliminary per-stream DISTINCT to drop its hash table on mostly-unique input and exposes that through DistinctTransformsAbandonedDeduplication. The main local path looks consistent, but the serialized-plan path still violates the PR's own "do not abandon when limit_hint is present" contract, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/DistinctStep.cpp:88,155-182] [dismissed by author -- https://github.com/Allow the preliminary DISTINCT to abandon deduplication on mostly-unique input #116508#discussion_r3863391435] allow_abandoning is now derived from limit_hint == 0, but DistinctStep::serialize still drops limit_hint and DistinctStep::deserialize reconstructs every serialized step with 0. Distributed-plan workers then build directly from that deserialized step in src/QueryPipeline/DistributedPlanExecutor.cpp:842-851, and AST-less plan execution does the same in src/Interpreters/executeQuery.cpp:3200-3214. That means a remote PreDistinct for SELECT DISTINCT ... LIMIT ... can still abandon even though the planner explicitly disabled it to preserve limit-aware early stopping. I still consider this real because the dismissal only notes that remote limit_hint handling was already incomplete on master; this PR adds a new behavior gate that now also depends on that missing state. Suggested fix: serialize limit_hint (or an explicit allow_abandoning flag) and keep it through deserialization before building the worker pipeline.
Tests
  • ⚠️ Add a focused serialized-plan round-trip or distributed functional test for SELECT DISTINCT ... LIMIT ... proving that a deserialized PreDistinct does not increment DistinctTransformsAbandonedDeduplication. The new stateless tests only cover the local pipeline-build path.
Final Verdict

Changes requested: the distributed / serialized PreDistinct path still breaks the new limit_hint contract.

LLVM Coverage Report

Measured on commit bac8502.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 74/74 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 26, 2026
/// The preliminary deduplication is best-effort (a deduplicating consumer follows), so on
/// mostly-unique input the transform may abandon it and free its hash table - unless a limit
/// hint is set: an abandoned transform cannot count the distinct rows to stop the input early.
const bool allow_abandoning = pre_distinct && settings.allow_preliminary_distinct_abandoning && limit_hint == 0;

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.

allow_abandoning is keyed off limit_hint == 0, but DistinctStep::serialize still drops limit_hint (serialize even notes that the follower would need to re-derive it) and deserialize reconstructs the step with 0. Both off-node plan executors then build from that deserialized step (src/QueryPipeline/DistributedPlanExecutor.cpp:841-845, src/Interpreters/executeQuery.cpp:3191-3200), so a remote PreDistinct for SELECT DISTINCT ... LIMIT ... can still abandon even though the original planner explicitly disabled it.

That breaks the new "don't abandon when a limit hint is present" contract for serialized/distributed execution, and the worker fragment often cannot recover the hint on re-optimization because the LIMIT sits above the coordinator-side final DISTINCT, not above the shipped preliminary one. Please serialize limit_hint (or an explicit allow_abandoning bit) and cover the deserialize/build path with a focused round-trip test.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an existing master behavior and improvements to it are out of scope for this PR. Even if limit_hint is dropped, this is not a correctness issue.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bac850206 with master 8627fa22f (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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2509d5f4-9e0e-4816-aef5-d4339ebbc8a8
  • MIRAI run: 80fb8f16-ca8e-4917-ba19-663e43f26084
  • PR check IDs:
    • clickbench_775454_1788287511
    • clickbench_775461_1788287511
    • clickbench_775467_1788287511
    • tpch_adapted_1_official_775476_1788287511
    • tpch_adapted_1_official_775489_1788287511
    • tpch_adapted_1_official_775524_1788287511

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM👍

@nihalzp
nihalzp added this pull request to the merge queue Sep 2, 2026
Merged via the queue into ClickHouse:master with commit fc9bebf Sep 2, 2026
175 checks passed
@nihalzp
nihalzp deleted the preliminary-distinct-abandon branch September 2, 2026 02:00
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 2, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@nihalzp @yariks5s — title/description suggestions:

Description (currently misleading):

  • Why: The body states the cost is bounded: "bounded by the 90% threshold, a shard ships at most ~11% more rows on the inputs where it fires". That inverts the sampling direction. The 90% threshold applies to the rows the controller has OBSERVED, not to the whole input, and the decision is irreversible. On SELECT DISTINCT number % 5000000 FROM numbers_mt(200000000) (2.5% unique overall) the controller abandons and the preliminary step ships 200M rows instead of ~40M - 5x, not 1.11x.

  • Suggested addition:

    Note on the bound: the 90% unique rate is measured over the chunks observed so far, not over the whole input, and abandoned is never re-evaluated. Any key whose repeat period exceeds 5 * max_block_size rows in scan order looks 100% unique inside the observation window, so the cost is not bounded by 1/0.9. Measured on this build: SELECT DISTINCT number % 5000000 FROM numbers_mt(200000000) FORMAT Null, max_threads=8 runs 1.99s with the setting on vs 0.94s with it off.

Ignore if intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

@nihalzp @yariks5s — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance 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.

4 participants