Skip to content

Predistinct step will use bf as first pass filter before hashset - #77728

Draft
UnamedRus wants to merge 75 commits into
ClickHouse:masterfrom
UnamedRus:distinct_bf
Draft

UnamedRus wants to merge 75 commits into
ClickHouse:masterfrom
UnamedRus:distinct_bf

Conversation

@UnamedRus

@UnamedRus UnamedRus commented Mar 17, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

DISTINCT can use less memory and run faster on high-cardinality queries by probing a bloom filter before the hash set, and the final DISTINCT step can use a two-level hash set and several threads.


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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 18, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

It's a great idea! It will help when DISTINCT has a high cardinality to use a lot of memory. It will be slower otherwise.

@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d6cf70c]

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 18, 2025
@nickitat nickitat self-assigned this Mar 24, 2025
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label May 17, 2025
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2025

Copy link
Copy Markdown
Contributor

Dear @UnamedRus, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@alexey-milovidov

Copy link
Copy Markdown
Member

Good idea, what are the results?

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e225f8]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py FAIL

@UnamedRus

UnamedRus commented Jul 23, 2025 •

Copy link
Copy Markdown
Contributor Author
Complex

SELECT count()
FROM
(
    SELECT DISTINCT
        if(number % 2, number % 30000000, rand() % 80000),
        materialize('string')
    FROM numbers_mt(400000000)
) -- 15_040_000

run     max_threads time_sec    memory_gb   user_time_sec
master  x16         25.9        8.8         96
pr      x16         13.0        1.7         76
master  x8          19.8        4.8         95
pr      x8          12.8        1.1         81
master  x4          21.3        2.76        77
pr      x4          19.1        0.81        70
master  x1          63.6        1.3         63


SELECT count()
FROM
(
    SELECT DISTINCT
        if(number % 10, number % 30000000, rand() % 80000),
        materialize('string')
    FROM numbers_mt(400000000)
) -- 27_008_000

run     max_threads time_sec    memory_gb   user_time_sec
master  x16         50.0        14.5        130
pr      x16         20.6        2.2         91
master  x8          31.0        10          112
pr      x8          19.8        1.6         85
master  x4          29.1        5.5         93
pr      x4          22.3        1.3         79
master  x1          73.9        2.5         73

SELECT count()
FROM
(
    SELECT DISTINCT
        if(number % 10 = 0, number % 30000000, rand() % 80000),
        materialize('string')
    FROM numbers_mt(400000000)
) -- 3_072_000

run     max_threads time_sec    memory_gb   user_time_sec
master  x16         6.2         1.3         74
pr      x16         7.4         1.4         74
master  x8          8.9         2.3         68
pr      x8          8.7         0.8         66
master  x4          14.7        1.3         58
pr      x4          14.2        0.6         60
master  x1          47.3        0.6         47

Numeric

SELECT count()
FROM
(
    SELECT DISTINCT if(number % 2, number % 30000000, rand() % 80000)
    FROM numbers_mt(400000000)
) -- 15_040_000

run     max_threads time_sec    memory_gb   user_time_sec
master  x16         2.5         2.4         13
pr      x16         2.7         0.5         11
master  x8          1.9         1.3         10
pr      x8          2.7         0.4         10
master  x4          1.9         0.8         7
pr      x4          2.6         0.3         9
master  x1          5.0         0.3         5

@UnamedRus

Copy link
Copy Markdown
Contributor Author

I do think, that results (time & memory) are quite nice, but not nice enough for enabling it by default.
But, having it under setting should be OK. (in terms of logic/feature completeness, code still need refactoring)

Few problems:

  1. It's possible that i made mistake somewhere, and actually not all used memory counted/cpu or thread usage not exactly adhere to max_threads limit.
  2. Need proper tunning of parameters, thresholds even if static values may be OK for start, probably it should be part of statistics kinda like two-level group by.
  3. Not trivial to make representative performance test as, it need huge/slow hashtable.
  4. It would be much nicer, if we could have feature to do lazy filtering in chunks. (in preDistinctTransform just mark row as filtered and skip it in DistinctTransform) But, it need much more changes and fixes to optimizers and stuff.

@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2025

Copy link
Copy Markdown
Contributor

Dear @UnamedRus, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

@alexey-milovidov

Copy link
Copy Markdown
Member

We can create the bloom filter and switch to this method only when the hash table grows to a certain size.
We can also drop it when the bloom filter is too occupied.

@UnamedRus

Copy link
Copy Markdown
Contributor Author

It's already like that:
Basically there multiple "filter" implementations:

  1. Combined
    BF + HashSet
  2. CheckOnly
    HashSet, which doesn't add new elements, but only "filter" already seen
  3. SetParallel
    Two-Level HashSet + threadpool to check against them, like in uniqExact
  4. SetOnly
    HashSet

Logic as following:
For preDistinct
Start with Set, if number of elements in HashSet > 1_000_000 switch to Combined
Then, keep using Combined unless number of rows passed filter exceed 50% of rows in block, otherwise switch to Set.
If number of rows in HashSet > 2_000_000, switch to CheckOnly

For final Distinct step
Create Two-Level hashset if type allows that.
If, size of HashSet < 1_000_000 use one thread, otherwise use threadpool.

Anyway, there is true parallel distinct implementation, which either make "cheap" copies of chunk, or use Scatter Transform to do final step in parallel. I tried to play with something like that, but found it hard to deal with optimizations which reorder Transforms.
#89129

If it(Parallel) will be done, it may also mostly cover use case of BF pass Distinct + threadpool as well.

May be, there is still some place for BF pass Distinct + treadpool (when we are not sure that true parallel Distinct is beneficial), as it can be switched on/off dynamically, and doesn't need to change pipeline.

… bloom filter

With `number % 10 > 0` about 90% of the rows are new, which is the
threshold at which preliminary `DISTINCT` abandons deduplication, so the
query measured the abandoning path rather than the bloom filter. With
`number % 5 > 0` about 80% of the rows are new: below the abandoning
threshold and above `distinct_pass_ratio_threshold_for_disabling_bloom_filter`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 11, 2026 05:18
…er and parallel `DISTINCT` paths

The mask of rows that are known duplicates by their `LowCardinality` dictionary
index was only applied by `buildSetFilter`. Once `checkSetFilter` (`check_only`),
`buildCombinedFilter` (bloom filter) or `buildSetParallelFilter`
(`hashed_two_level`) took over, every row was hashed and probed again. Pass the
mask through these paths too and skip the masked rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 19, 2026 19:33
Resolve conflicts with the spilling of the preliminary `DistinctTransform`
(`ISpillable`): `allow_spilling_` goes right after
`max_bytes_before_pass_through_` in the constructor, and `spill` and
`getMemoryStats` now also release and account the own set (hash set, bloom
filter and `LowCardinality` filter) of the bloom-filter preliminary path.
The interpreters use `getEffectiveMaxThreads` from master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n version 21

`QueryPlanSerializationSettings::readBinary` rejects unknown names, so a
pre-26.11 peer failed to read a plan with a non-default bloom-filter setting of
`DISTINCT`. Bump `DBMS_QUERY_PLAN_SERIALIZATION_VERSION` to 21 for release
26.11 and write `distinct_set_limit_for_enabling_bloom_filter`,
`distinct_bloom_filter_bytes`,
`distinct_pass_ratio_threshold_for_disabling_bloom_filter` and
`distinct_bloom_filter_max_ratio_of_set_bits` only to peers at
`DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_DISTINCT_BLOOM_FILTER` or
above. An older peer runs its exact `DISTINCT` without the bloom filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reconcile the bloom-filter `DISTINCT` with master's parallel `DISTINCT` (ClickHouse#114550):
- `DistinctTransform` takes master's `shared_set_bytes_` and `coalesce_rows_`
  before the bloom-filter parameters.
- The own-set path (bloom filter, parallel probing) is not used when the set
  memory is accounted globally across disjoint streams (`shared_set_bytes_`),
  because it does not report to `DistinctSetMemoryTracker`.
- Coalescing flushes when the own set is released, not merely when
  `distinct_set` is absent (which it always is on the own-set path).
- The thread budget of the final `DISTINCT` is shared among all its streams,
  including streams created by the scattered parallel `DISTINCT`.
- Plan serialization version 21 now covers both
  `min_bytes_before_external_group_by` and the bloom-filter settings.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (it had become CONFLICTING after the parallel DISTINCT from #114550 landed) and pushed ffb165b8dd4.

Conflict resolution / reconciliation with parallel DISTINCT:

  • DistinctTransform now takes master's shared_set_bytes_ and coalesce_rows_, followed by the bloom-filter parameters.
  • The own-set path (bloom filter or parallel probing of the two-level set) is not used when the set memory is accounted globally across disjoint streams (shared_set_bytes_). That path does not report to DistinctSetMemoryTracker, so global max_rows_in_distinct/max_bytes_in_distinct would not see it.
  • Output coalescing now flushes when the own set is released, instead of on every chunk. On the own-set path distinct_set is always empty, so the old condition was always true and coalescing never happened.
  • The thread budget of the final DISTINCT is shared among all its streams, which now includes the streams created by the scattered parallel DISTINCT. Without this the query could run streams * max_threads workers.
  • Plan serialization version 21 now covers both min_bytes_before_external_group_by (from master) and the bloom-filter settings.

CI: fixed the settings_changes_history style failure by moving the four distinct_*bloom_filter* history records to 26.11.

Verified locally: clickhouse builds. All 57 related stateless tests pass (distinct_bloom, parallel_distinct, external_distinct, distinct_partitions, 05045_preliminary_distinct_abandoning, 02733_distinct). Spot checks of bloom filter + parallel DISTINCT give correct counts.

alexey-milovidov and others added 4 commits October 29, 2026 20:19
# Conflicts:
#	src/Core/ProtocolDefines.h
`bucket_offsets` was declared after the `ThreadPoolCallbackRunnerLocal` in
`buildSetParallelFilter`, so if scheduling threw during the second phase the
vector was destroyed before the runner's destructor waited for the workers that
read it. Declare it before the runner, and reserve the runner's tracking
capacity so that a scheduled task can never be left untracked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…_filter_limit`

The CI config sets `max_rows_in_distinct`, which disables the bloom filter and
`check_only` modes, so the test did not exercise the code it protects.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=77728&sha=151c5ce6842f8e72205497789b64f7cf723e8692&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The Performance Comparison (amd_release, master_head, 4/6) job hit the 7200 s job timeout while perf_dashboard_gate was still polling: the dashboard kept answering HTTP 404 ... performance comparison run not found for pr-77728-151c5ce6842f8e72205497789b64f7cf723e8692. The dashboard deadline did not fire before the job-level timeout, so the job ended with -15 and produced no verdict. This is unrelated to the PR changes. I merged the latest master into the branch to re-run CI.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #128236 (CI green, awaiting review).

On job 123803207537 the report and uploads ended at 01:44:11, 113 minutes into the 7200 s timer. perf_dashboard_gate then polled the 404 26 times until the kill at 01:50:51: its 600 s wait counts from the uploads, not from the job timeout, so on the longest shard it outlives the job and the own-report fallback from #125734 never runs. #128236 ends the wait 300 s before the job timeout; on this run the shard would have been judged by its own report (9 too long, 1 unstable, 0 slower) a few minutes before the kill.

The 404 itself came from the dashboard outage during the CIDB switch (2026-10-29 09:04Z to 2026-10-30). pr-77728-151c5ce6842f is registered on the dashboard now, so the re-run after your master merge should get a normal dashboard verdict.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 3 commits November 8, 2026 09:54
# Conflicts:
#	src/Core/ProtocolDefines.h
…-budget estimate

Building the hash-method state in `buildSetFilter`, `buildCombinedFilter` or
`checkSetFilter` allocates `prepared_keys`, which can exceed the size of the
input columns (a `Nullable(UInt64)` key takes about 9 bytes per row but is
packed into a 16-byte key). Mirror `DistinctSetFilter::estimateFilteringMemory`:
take the maximum of the column bytes and `estimatePreparedKeysMemory`, then add
the masks.

Add a test that runs the bloom-filter preliminary `DISTINCT` on a packed
`Nullable(UInt64)` key with a small `max_bytes_before_external_distinct`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… insertion

The existing tests never exceed `PARALLEL_DISTINCT_THRESHOLD`. The new test uses
complex keys (`hashed_two_level`), 1500000 retained keys, 65536-row blocks,
`max_threads = 4`, a single merged final stream (`allow_parallel_distinct = 0`)
and no external spilling, with duplicates across blocks, and checks the exact
result.

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

Copy link
Copy Markdown
Member

🕵 Merged current master (the branch was CONFLICTING) and pushed ecd575c1322a.

  • Conflict: src/Core/ProtocolDefines.h: master added DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_HASH_JOIN_LAYOUT = 21 next to this PR's DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_DISTINCT_BLOOM_FILTER = 21. I kept both, since the plan version is still 21.
  • Review (spill-budget estimate missed the packed keys): fixed in c72de914b779, with the new test 05570_distinct_bloom_filter_packed_keys_pass_through.
  • Review (no coverage for the parallel insertion path): added 05569_distinct_parallel_two_level_insertion in ecd575c1322a.
  • clickhouse builds and both new tests pass locally. CI on the previous head (151c5ce6842f) was green.

alexey-milovidov and others added 6 commits November 9, 2026 19:15
Resolve conflicts: `addDistinctStep` moved from `Planner.cpp` to `PlannerSteps.cpp` on master, so the bloom-filter settings are passed there now; `DistinctStep::deserialize` keeps master's serialized `limit_hint` together with the bloom-filter settings; getters got `[[nodiscard]]` as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: `buildSetFilter`, `buildCombinedFilter`, `checkSetFilter` and
`buildSetParallelFilter` construct `Method::State` without `skips_rows`. For a
method with `prepare_keys` (`SetMethodHashed`), requesting a key hashes the
following 8-256 rows ahead, including rows masked out by the `LowCardinality`
dictionary-index filter, so the single-column `LowCardinality` fast path is lost.
Pass `{.skips_rows = mask != nullptr}` as `buildDistinctFilter` already does.

This is the likely cause of the `distinct_low_cardinality_prelimit_distinct_in_order`
regression in the performance comparison:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=77728&sha=latest&name_0=PR&name_1=Performance%20Comparison%20(arm_release%2C%20master_head%2C%201%2F6)
ClickHouse#77728

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in `src/Processors/QueryPlan/DistinctStep.h`: master added the
`external_distinct_disabled` member next to this PR's bloom-filter members.
Both are kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The 26.11 release branch has been cut and `master` is now 26.12, so the four
`distinct_*bloom_filter*` settings first appear in 26.12.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (the branch was CONFLICTING) and pushed 9e225f878a38.

  • Conflict: src/Processors/QueryPlan/DistinctStep.h: master added the external_distinct_disabled member (disableExternalDistinct for streaming queries) next to this PR's bloom-filter members. Both are kept; the flag only gates ExternalDistinctTransform, so the bloom-filter path is unaffected.
  • Settings history: the 26.11 release branch has been cut and master is 26.12, so the four distinct_*bloom_filter* settings history records are moved from 26.11 to 26.12.
  • Verified locally: clickhouse builds; 171 of the 174 stateless tests matching distinct pass. The other three (00020_distinct_order_by_distributed, 00176_distinct_limit_by_limit_bug_43377, 00174_distinct_in_order) need the test.hits / test.visits datasets, which were not loaded in the local run.

This branch has not been deployed

No deployments
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. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants