Skip to content

Speed up IN (subquery) set building by pre-deduplicating each MergeTree partition independently - #114645

Merged
nihalzp merged 42 commits into
ClickHouse:masterfrom
nihalzp:in-set-partitions-independently
Aug 23, 2026
Merged

nihalzp merged 42 commits into
ClickHouse:masterfrom
nihalzp:in-set-partitions-independently

Conversation

@nihalzp

@nihalzp nihalzp commented Aug 13, 2026 •

Copy link
Copy Markdown
Member
image

Related: #108326
Related: #105126

The set for IN (subquery) is built by a single CreatingSetsTransform: all streams of the subquery are merged into one and every row is hashed serially, no matter how many threads read the data. If the partition expression of the subquery's table is a function of the subquery's output columns (the set is keyed on all of them), the reading will now emit each partition through a single port and each stream is deduplicated independently before the filling transform. Because a key then lives in exactly one stream, per-stream deduplication is complete, and the single filling transform only hashes unique rows — the serial part of the build shrinks from all rows to distinct rows, and the deduplication itself runs in parallel.

CREATE TABLE t (a UInt64) ENGINE = MergeTree ORDER BY tuple() PARTITION BY a % 8;
INSERT INTO t SELECT number % 1000000 FROM numbers(100000000);

OPTIMIZE TABLE t FINAL;

EXPLAIN PIPELINE
SELECT count() FROM numbers(10) WHERE number IN (SELECT a FROM t)
SETTINGS allow_creating_set_partitions_independently = 1, max_threads = 8;
(CreatingSets)
DelayedPorts 9 → 8
  (Expression)
  ExpressionTransform × 8
    (Aggregating)
    Resize 1 → 8
      AggregatingTransform
        (Expression)
        ExpressionTransform
          (Filter)
          FilterTransform
            (ReadFromSystemNumbers)
            NumbersRange 0 → 1
  (CreatingSet)
  CreatingSetsTransform                <- the single filling transform now hashes ~1M unique rows instead of 100M
    Resize 8 → 1
      DistinctTransform × 8            <- new: parallel pre-deduplication on partition-disjoint streams
        (Expression)
        ExpressionTransform × 8
          (ReadFromMergeTree)
          MergeTreeSelect(pool: ReadPoolInOrder, algorithm: InOrder) × 8 0 → 1   <- per-partition reading (8 partitions → 8 streams)

On the table above (100M rows, 1M distinct keys, 8 balanced partitions; 64-core machine, average of 3 runs after 2 warm-ups):

query off on speedup
SELECT count() FROM numbers(10) WHERE number IN (SELECT a FROM t) 0.643s 0.113s 5.7×

Adaptive abandonment of the preliminary deduplication

The per-stream DistinctTransform in front of the set fill pays off only when it removes rows: the set deduplicates anyway, so on mostly-unique input the transform removes almost nothing while its hash tables hold roughly a second copy of the unique keys next to the set being built.

To keep the optimization strictly non-regressing, the pre-deduplication observes its own effectiveness and gives up when it is not helping (DeduplicationAbandonController):

  • It accumulates, over all chunks seen so far, how many rows survived deduplication. The rate is first checked after 5 chunks — or earlier, once the observation itself retains 16 MiB of hash table, so wide keys (e.g. long strings) cannot hold multiples of that just to finish the window. From then on it is checked after every chunk, so duplicates concentrated at the head of a stream do not keep a useless hash table alive through a unique tail.
  • When at least 90% of the observed rows survive, the transform abandons: it frees its hash table and passes the remaining chunks through untouched. This is correct only because the consumer deduplicates anyway, so abandoning is allowed by an explicit constructor flag that only the set-fill call site enables.
  • The 0.9 threshold is calibrated on per-partition set builds over uniform data: keeping the deduplication is ~8–11x at ~1% uniqueness and ~1.2x at 10%, turns time-neutral but memory-negative once only about a quarter of the rows are duplicates — which the observation sees as a unique rate of about 0.9, because a stream's duplicates concentrate in its partition and repeat within the window.

The transform also mirrors the set fill's NULL handling: with the default transform_null_in = 0 the fill drops every row with a NULL in any key component, so the pre-deduplication drops them too (using the same extractNestedColumnsAndNullMap helper, plus the dictionary NULL entry for LowCardinality(Nullable) keys) instead of hashing them and letting them distort the abandon decision. Chunks fully resolved by the LowCardinality dictionary mask are likewise counted as duplicate rows. Together this keeps the abandon decision based on exactly the row population the fill would hash.

Changelog category (leave one):

  • Performance Improvement

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

Speed up set building for IN (subquery) on partitioned MergeTree tables by keeping each partition's rows within a single stream and deduplicating each stream independently, so the single set-filling transform — previously hashing every row serially — only sees unique rows. This applies when the partition expression is a deterministic function of the subquery's output columns. The optimization is not applied when the largest partition holds more than twice the rows of the average partition; the new setting force_creating_set_partitions_independently (disabled by default) bypasses this check. Controlled by the new setting allow_creating_set_partitions_independently (enabled by default).


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

Version info

  • Merged into: 26.8.1.1939 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b769b72]

Summary: ✅


AI Review

Summary

This PR adds a default-on optimization for IN (subquery) set builds over partitioned MergeTree reads: it requests partition-disjoint read streams, runs a per-stream preliminary DistinctTransform, and adds abandonment / NULL / GLOBAL IN / lazy-FINAL guards around that path. Most of the earlier correctness gaps are fixed in the current head, but one planner case still turns an already-deduplicated subquery into an extra hash-table pass with no upside.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/applyStreamDisjointness.cpp:125] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/114645#discussion_r3801011672] applyStreamDisjointness still enables CreatingSetStep::enablePreliminaryDistinct() after a final DistinctStep that already skipped stream merging. On IN (SELECT DISTINCT key FROM ...) the rows reaching CreatingSetStep are already unique by the whole set header, so the extra pre-pass cannot remove anything; for inputs that stay below the abandon window it hashes every row twice and keeps a second hash table for the whole query with zero benefit. tests/queries/0_stateless/04669_creating_set_partitions_independently.sql:110 / .reference:110 currently pin that redundant Pre-distinct: 1 plan as expected output. Suggested fix: suppress enablePreliminaryDistinct() when the immediate child is a final DistinctStep whose output header already matches the set header, and flip 04669_creating_set_partitions_independently to assert that Pre-distinct is absent for that shape.
Final Verdict

⚠️ Needs changes before merge: the optimization is otherwise in good shape, but the IN (SELECT DISTINCT ...) path is still a real performance regression on a query shape that is already fully deduplicated upstream.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 188/253 (74.31%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 13, 2026
@yariks5s yariks5s self-assigned this Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b769b727f with master 6e4e77ec8 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.50 MiB 701.51 MiB -2.99 MiB (-0.42%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

50 object files changed (+57.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/CreatingSetsStep.cpp.o 142.50 KiB 169.84 KiB +27.33 KiB (+19.18%)

737 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

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

Median compile-time ratio to the baselines is ×0.91 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -359.5 s (-8%) in total before that adjustment.

Job report

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 35 queries analysed

This sync PR adds an on-by-default query-plan optimization: parallel per-partition pre-deduplication when building the set for IN (subquery), applied only when the subquery reads a partitioned MergeTree whose partition key is a deterministic function of the subquery output. Both flagged queries (tpch_adapted Q7 and Q17) were left as not_sure because the master baseline is unstable in the current era, and their deltas — a noisy +17.9% on Q7 and a very noisy +59.4% on Q17 — are consistent with run-to-run variance rather than a real regression. Neither query exercises the new IN-subquery set-building path, so there is no regression here that is plausibly attributable to this change.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 67 79 +17.9% <0.0001 Baseline is flagged unstable in the current era, so the +17.9% is not a reliable PR signal. Q7 does not use an IN (subquery) against a partitioned table, so the new set-build optimization cannot touch it.
⚠️ 17 not_sure 64 102 +59.4% <0.0001 Measurements are very noisy on both sides and the baseline is unstable, so the +59.4% here reflects run-to-run variance rather than a real effect of this change.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 3a018afe-5c05-4e0e-9fe0-e068c9ed1041
  • MIRAI run: 725549b3-5502-458e-a43c-29cb2c65f33a
  • PR check IDs:
    • clickbench_3276_1787338585
    • clickbench_3289_1787338585
    • clickbench_3296_1787338585
    • tpch_adapted_1_official_3307_1787338585
    • tpch_adapted_1_official_3334_1787338585
    • tpch_adapted_1_official_3348_1787338586

Comment thread src/Interpreters/PreparedSets.h Resolved
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.

3 participants