Skip to content

Avoid per-state heap allocation in UniquesHashSet::read and batch merge - #111493

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
raimannma:uniques-hash-set-read-merge-batch
Oct 13, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
raimannma:uniques-hash-set-read-merge-batch

Conversation

@raimannma

@raimannma raimannma commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

UniquesHashSet::read allocated a heap scratch buffer for every state with m_size >= 2, while typical stored uniq states hold only a few elements. It now reads through a fixed 256-element stack chunk, which also folds the m_size <= 1 special case into the general path. merge inserted elements one by one, each hash-table probe serialized behind the previous one; it now uses the batching technique of insertMany (#95904) so misses on the destination buffer overlap. Results are bit-identical to the previous implementation, including under saturated skip_degree.

Measured with the added tests/performance/uniq_states_read_merge.xml (before vs. after, median of the built-in benchmark, single query thread):

query shape before after speedup
deserialize-only, tiny states (2/9 elements) 1.475 s 1.279 s 15.3%
merge tiny states into 1 destination 0.876 s 0.651 s 34.6%
merge tiny states, 1000 groups 2.562 s 2.135 s 20.0%
merge 500 big states (~60000 elements) into 1 dst 0.427 s 0.383 s 11.5%
merge 500 big states, 4 groups 0.462 s 0.408 s 13.2%

Changelog category (leave one):

  • Performance Improvement

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

Speed up reading and merging of uniq aggregate function states (e.g. uniqMerge over an AggregatingMergeTree) by removing a per-state heap allocation during deserialization and batching hash-table probes during merges, by 10-35% depending on state sizes and merge shape.


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

Version info

  • Merged into: 26.10.1.2296-master (included in 26.10 and later)

read() allocated a scratch buffer of m_size elements for every state with
m_size >= 2, while typical stored uniq states are tiny. Read through a
fixed 256-element stack chunk instead; this also folds the m_size <= 1
special case into the general path.

merge() inserted elements one by one, each probe serialized behind the
previous one. Apply the same batching technique as insertMany: when
spare capacity guarantees that no resize/rehash can happen mid-batch,
compute place() for a whole batch upfront so cache misses on the
destination buffer overlap. The probe-and-place body shared by
insertImpl, insertMany and merge is extracted into insertAtPlace.
The non-batched fallback re-evaluates good() per element because
shrinkIfNeed() can raise skip_degree.

Results are bit-identical to the previous implementation, including
under saturated skip_degree.
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f3555f4]

Summary: ✅


AI Review

Summary

This PR removes the per-state heap scratch allocation from UniquesHashSet::read by deserializing through a fixed stack chunk, and it batches merge probes in the same style as insertMany while preserving the tiny-state fast paths that the later ARM perf follow-up needed. I did not find a remaining correctness, compatibility, or performance-contract issue in the current version: the stateless test now crosses the 256-element read boundary and exercises saturated-skip_degree merges, and the PR body includes concrete before/after numbers for the Performance Improvement claim.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 24, 2026
numbers(150) never produced a state larger than 149 elements, so the
round-trip test never exercised the multi-chunk loop in
UniquesHashSet::read (chunk size 256). Use numbers(258) instead, which
covers state sizes 255/256/257 and still verifies the finalized
cardinality against the exact expected value.
@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 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: acd0bdd7-c63f-4017-b3f8-3877b6b83f30
  • MIRAI run: f0744c03-5f50-415c-b188-fbca30b3106f
  • PR check IDs:
    • clickbench_1135927_1791844465
    • clickbench_1135940_1791844465
    • clickbench_1135946_1791844465
    • tpch_adapted_1_official_1136219_1791844499
    • tpch_adapted_1_official_1136339_1791844523
    • tpch_adapted_1_official_1136353_1791844523

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.50% +0.10%
Functions 91.80% 91.90% +0.10%
Branches 78.50% 78.70% +0.20%

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

Full report · Diff report

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 1, 2026
The squashed commit above omitted them. Repository instructions require the
supplied CI report URL in the commit message, and a link to the corresponding
pull request when the URL carries `PR=...`.

Found by the stress test, STID `2508-224e`, check `Stress test (amd_asan_ubsan)`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111493&sha=2054925548cba91a78383141bd49da2126f92307&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29

Carrier pull request (the discoverer, not the author, it touches no join file):
ClickHouse#111493

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit f3555f47bfca01fb6cd0bf996f1c0448c5f7ef15 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 4, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 9, 2026

@alexey-milovidov alexey-milovidov 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

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111493&sha=00ba4e00e36ef6f686be7a845e86d93ee4de33e3&name_0=PR&name_1=Stress%20test%20%28arm_release%29 (Cannot start clickhouse-server: "a clickhouse-server process is running but did not become ready in 603s"; the same failure appears on master and many unrelated PRs in CIDB) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The other failure, 05230_materialized_cte_shared_by_two_ctes_in_set_subquery in the ParallelReplicas job, is tracked by #123121.

The earlier merge-queue rejection (-Wshadow in UniquesHashSet::merge) was fixed by 00ba4e0. I merged the latest master and pushed to re-run CI.

@groeneai

Copy link
Copy Markdown
Collaborator

I looked at this run. The server is not hung: it is up and answering on 9440, but every login fails with Code: 107 ... Cannot open file /var/lib/clickhouse/access/a042c951-174e-391e-583d-faeb611c64a4.sql ... (FILE_DOESNT_EXIST) (60 of 60 probes). #124917 has the same failure with a different id. Every new session builds its row policy set and fails reading one listed policy that has no file.

How the access directory got into that state (clickhouse-server.stress.log, 02:13:12 to 02:13:13):

  1. 05182_row_policy_after_final_lambda_nondeterminism creates p_row_policy_lambda. The background .list writer is already waiting (it writes after one minute).
  2. The AST fuzzer runs SYSTEM RELOAD USERS. reloadAllAndRebuildLists rewrites all .list files, including the new policy, and removes need_rebuild_lists.mark.
  3. The test drops the policy and its .sql is deleted. scheduleWriteLists sees the writer still waiting, so it does not re-create the mark.
  4. A second fuzzed SYSTEM RELOAD USERS fails to write row_policies.list (injected MEMORY_LIMIT_EXCEEDED), failed_to_write_lists is set, and no list is written again.

After the restart the mark is missing, so readLists trusts the stale row_policies.list and the dropped policy comes back without a file.

  • The startup side is covered by my open Fix server failing to start when an access entity's .sql file is missing #120943: readLists rebuilds the lists when a listed entity has no .sql file, so this server would have started. It is waiting for review.
  • The cause in steps 2 and 3 (the mark is removed while a list write is still pending) is a separate bug on master. I'll fix it in a separate PR and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix for steps 2 and 3 is #125058: scheduleWriteLists now creates need_rebuild_lists.mark before both of its early returns, so a list write that is still pending or has failed always makes the next start rebuild the lists.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai for the analysis of the stress-test failure (tracked by #120943 and #125058).

The only remaining red job on the current head 3286464a is Stateless tests (arm_asan_ubsan, azure, sequential), which ran into the job-level timeout (Timeout exceeded [9000]) with all tests passing up to that point. It is unrelated to this PR: CIDB shows the same job ending in error for 252 PR commits and 26 master commits over the last 7 days. It is addressed by #123849, which splits this job into two batches.

No code changes are needed here; the branch already contains master from 2026-10-10.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (clean, no conflicts), rebuilt, and checked that 04614_uniq_state_read_merge_roundtrip still passes. The only red job, Stateless tests (arm_asan_ubsan, azure, sequential), isn't caused by this PR. The job hit its 9000 s limit at test 1170/1180 with no test failures (job.log). A fix for the lane's runtime is already open: #123849 (it splits that lane into 2 batches).

The performance test `uniq_stored` query ClickHouse#2 (merging 2 million stored
single-element `uniq` states) regressed by 22% on ARM: the chunked read and
the batched merge add overhead that does not pay off for tiny states.
Restore the scalar read for `m_size <= 1` and use the plain merge loop when
the right-hand state has fewer than `insert_many_batch_size` elements.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111493&sha=f844d188b1bf6c9c553a5346b12da46a93d601ed&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29
ClickHouse#111493

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

Copy link
Copy Markdown
Member

🕵 The perf check flagged uniq_stored query #2 (merging 2 million single-element stored uniq states) as 22% slower on ARM (report). The regression was confirmed after a server restart. Query #1 got 17% faster in the same run.

I pushed 15375b7, which brings back the fast paths for tiny states:

  • UniquesHashSet::read again uses the scalar readBinaryLittleEndian path when m_size <= 1.
  • UniquesHashSet::merge uses the plain loop when the right-hand state has fewer than insert_many_batch_size elements.

Larger states still use the chunked read and the batched merge. 04614_uniq_state_read_merge_roundtrip passes locally. The next perf run will confirm whether the regression is gone.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (clean, no conflicts), rebuilt, and checked that 04614_uniq_state_read_merge_roundtrip still passes. The perf run on 15375b78977 shows no slowdowns: the uniq_stored tiny-state regression is gone, and uniq_stored #1 and uniq_states_read_merge #2 are 17-18% faster on ARM.

Neither red job is related to UniquesHashSet:

alexey-milovidov pushed a commit to JayPokale/ClickHouse that referenced this pull request Oct 12, 2026
…iles

`DiskAccessStorage` changes `<id>.sql` immediately and rewrites the `.list`
index files a minute later from a background thread. `need_rebuild_lists.mark`
is what tells the next start not to trust a stale index. `scheduleWriteLists`
created it only when it started a new writer thread, and assumed in its two
early returns that it already existed. Neither assumption held:

- `SYSTEM RELOAD USERS` (`reloadAllAndRebuildLists`) writes the lists and
  removes the mark while the writer thread keeps waiting, so a DDL in the rest
  of that minute changed `<id>.sql` with no mark on disk;
- after a failed list write (`failed_to_write_lists`) nothing writes the lists
  again until restart, and when that write came from `reloadAllAndRebuildLists`
  no mark existed either.

A restart from either state trusted the stale index: an entity created in the
window was lost, and a dropped one stayed listed without its `.sql`. For a row
policy every new session then fails with `FILE_DOESNT_EXIST`, which is how
`Stress test (arm_release)` on PR ClickHouse#111493 ended with a server that never became
ready.

Create the mark at the top of `scheduleWriteLists`, before both early returns.

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

Copy link
Copy Markdown
Collaborator

The AST fuzzer (amd_debug, targeted, old_compatibility) failure on 15375b78977 is the case fixed by my open #121688.

The fuzzer had recreated the table as t_05230__fuzz_0 (id Date, v UInt64) ... SETTINGS add_minmax_index_for_numeric_columns = 1, so v gets an implicit minmax index and the set for v IN (WITH d AS MATERIALIZED (... FROM c), ..., c AS MATERIALIZED (...) ...) is built during index analysis of the local shard's plan (prefer_localhost_replica = 1). That plan sees c and d only by name, so d is materialized at the same level as c and reads it too early. #121688 orders such CTEs by their dependencies.

Measured on a local server with the CI cluster config, the job's DDL and compatibility = '24.3':

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai: the AST fuzzer (amd_debug, targeted, old_compatibility) failure is tracked by #121688 and is unrelated to UniquesHashSet. CI is now fully green on f3555f47 (master merged on 2026-10-12), the PR is approved, and there are no open review threads. Nothing more to change here; the merge is left to a human.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit d1a7da6 Oct 13, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
…rter of the states

No existing query number or text changes: 2 queries are disabled and 2
copies appended as 5 and 6. The copies are queries 0 and 2 with
`WHERE k < 1250000`: the first quarter of the one part of
uniq_tiny_states (153 of 611 granules), the same mix of 2- and
9-element states; each of the 1000 GROUP BY sets ends two size degrees
smaller at the same fill.

Locally (official amd builds, perf.py, two repetitions on different NUMA
nodes, L3 capped to 1 way and to 3 ways): per-row time of the copies
0.94-1.06 of the originals', per-row user time too; the GROUP BY copy
keeps 0.86-0.995 of the effect of ClickHouse#111493 (9b9c059 -> d1a7da6,
CI x1.14 amd / x1.20 arm on query 2), the finalizeAggregation copy keeps
0.94 of the effect of the ClickHouse#129553 CI build (CI x1.31 / x1.39 on query 0).
The pair passes ran 15 runs per query and server. The copy's 80 MB of
sets sits between arm's 36 MB and amd's 105 MB shared L3, so the regime
and the effect were gated at both cache widths.

Saving: about 27 s of query time per master perf job on amd, 25 s on arm.

Related: ClickHouse#129258

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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). 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.

5 participants