Skip to content

Speed up groupUniqArray for numeric types - #110917

Merged
alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
raimannma:group-uniq-array-crc32-hash
Jul 23, 2026
Merged

alexey-milovidov merged 7 commits into
ClickHouse:masterfrom
raimannma:group-uniq-array-crc32-hash

Conversation

@raimannma

@raimannma raimannma commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Use HashCRC32 (as in uniqExact) instead of DefaultHash for integer keys in groupUniqArray, and mark add as ALWAYS_INLINE final so the batch loop devirtualizes and inlines it. Single-threaded aggregate-only benchmark, 100M rows / 64 distinct UInt64: 303 ms → 140 ms, on par with uniqExact (143 ms); up to 3× at higher cardinalities. The element order of the (unsorted) result array changes for integer keys; three tests that depended on it are switched to sorted output via arraySort.

Changelog category (leave one):

  • Performance Improvement

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

Speed up groupUniqArray for numeric types by up to 3x by using CRC32 hashing (as in uniqExact) and inlining the per-row insertion.

Version info

  • Merged into: 26.7.1.1365 (included in 26.7 and later)

Use HashCRC32 instead of DefaultHash (intHash64) for integer keys,
matching uniqExact, and devirtualize/inline `add` in the batch loop
by marking it ALWAYS_INLINE final.

Single-threaded aggregate-only benchmarks (interleaved A/B, n = 12,
significant under permutation tests at p < 0.001):

- 100M rows, 64 distinct UInt64: 303 ms -> 140 ms (2.2x), now on par
  with uniqExact (143 ms)
- 30M rows, 4096 distinct: 130 ms -> 43 ms (3.0x)
- 30M rows, 262144 distinct: 219 ms -> 81 ms (2.7x)
- Float64 (inlining only; hash unchanged): 400 ms -> 257 ms (1.6x)

Result order of the unsorted output array changes for integer keys;
three order-dependent test references are updated accordingly.
The serialized aggregate state format is unchanged (a plain list of
elements), verified compatible in both directions against 26.6.1.
Sort the result arrays with arraySort (and mapApply for the map column)
instead of relying on hash-dependent set iteration order, so the tests
no longer need reference updates when the hash function changes.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 17, 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.

Thanks, looks good!

@alexey-milovidov alexey-milovidov self-assigned this Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [99fc0b0]

Summary: ✅


AI Review

Summary

This PR switches numeric groupUniqArray to HashCRC32 and marks add as ALWAYS_INLINE final to speed up the hot path. The inlining change looks fine, but the hash swap is not an internal-only optimization: because the aggregate still serializes by iterating the hash table, it changes the persisted bytes of groupUniqArrayState for numeric, Enum, Date, and DateTime arguments without any versioning or compatibility gate.

Findings

❌ Blockers

  • src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp:42 Swapping DefaultHash for HashCRC32 changes hash-table iteration order, and serialize still writes elements in that iteration order at lines 103-109. That makes groupUniqArrayState / AggregateFunction(groupUniqArray, T) bytes change for the same logical input for numeric, Enum, Date, and DateTime arguments even though the aggregate-state format is unversioned. Existing tests already treat aggregate-state bytes as a compatibility surface (for example 02751_ip_types_aggregate_functions_states), so this is a backward-compatibility break, not just a result-order change.
    Suggested fix: preserve the legacy serialized representation for existing revisions, or add explicit state-format versioning / a compatibility gate before changing the hash-dependent order.
Final Verdict

Status: ❌ Block

Minimum required actions:

  • Avoid changing the serialized bytes of numeric / Enum / Date / DateTime groupUniqArrayState without versioning or a compatibility mechanism.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR narrowly optimizes the groupUniqArray aggregate function (CRC32 hashing for integer keys plus an inlined, devirtualized per-row add). Neither flagged ClickBench query executes groupUniqArray, and their CPU time is essentially flat (Q4 ~2665 vs ~2685 ms, Q15 ~2601 vs ~2604 ms) despite -17.5% and -21.3% wall-clock deltas, so both flagged improvements are run-to-run variance rather than real effects and have been downgraded. The actual impact of this change should be judged from the new groupUniqArray perf test, not from ClickBench Q4/Q15.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 257 212 -17.5% <0.0001 aggregation: This PR only changes the groupUniqArray aggregate (CRC32 hashing + inlined add), which ClickBench Q4 does not use; CPU time is flat (~2665 vs ~2685 ms) so the -17.5% wall-clock shift is run-to-run variance.
⚠️ 15 not_sure 244 192 -21.3% <0.0001 aggregation: Q15 does not call groupUniqArray, the only function this PR touches; CPU is essentially unchanged (~2601 vs ~2604 ms) while wall time dropped 21.3%, so the improvement is variance, not a PR effect.

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.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 71b3f811-2bde-4301-ae49-1cd587f39b17
  • MIRAI run: fa58b335-671b-4008-a955-a105e4a6e4a9
  • PR check IDs:
    • clickbench_94309_1784754800
    • clickbench_94316_1784754800
    • clickbench_94325_1784754800
    • tpch_adapted_1_official_94345_1784754800
    • tpch_adapted_1_official_94364_1784754800
    • tpch_adapted_1_official_94379_1784754800

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate the failure in the Upgrade check (amd_release): report — Error message in clickhouse-server.log: DDLWorker(rdb_test_1_2): ... Mapping for table with UUID=... already exists ... UUID collision (TABLE_ALREADY_EXISTS, code 57) in a Replicated database. This is unrelated to this PR, which only changes numeric groupUniqArray to use HashCRC32 and inlines add in AggregateFunctionGroupUniqArray — there is no path from that aggregate function to DDLWorker UUID mapping during the upgrade check. Please provide a fix in a separate PR, or link it here if one is already in progress.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Confirmed unrelated to this PR, and it is a known chronic upgrade-check flake.

The captured failure (rdb_test_1_2, a Replicated test DB) is the self-healing DDLWorker recovery loop on the upgrade restart:

<Error> DDLWorker(rdb_test_1_2): Error on initialization of rdb_test_1_2: Code: 57. DB::Exception: Mapping for table with UUID=... already exists. ... UUID collision ... (TABLE_ALREADY_EXISTS)

On the restart DatabaseReplicatedDDLWorker re-runs recoverLostReplica; a stale local table still owning a UUID (a leftover _tmp_replace_* from CREATE OR REPLACE, or a not-yet-dropped table) makes DatabaseCatalog::addUUIDMapping hit the non-fatal TABLE_ALREADY_EXISTS branch (code 57, not LOGICAL_ERROR). initializeMainThread logs it, waits 5s, retries, and self-heals, so the server stays up (11/12 upgrade sub-tests pass, including "Server successfully started") and only the post-restart error-log scrub trips. Recurs across 25+ unrelated PRs in the last 30 days.

Separate fix already open: #107126 adds a targeted upgrade_runner.sh allow-list entry for exactly this benign rdb_test_ recovery line, same class as #106616 and #106516 (which you merged). It is mergeable but has had no CI since 2026-07-02, blocked on the manual-approve label.

@alexey-milovidov

Copy link
Copy Markdown
Member

Thanks for the analysis. I re-triggered CI on #107126 (the can be tested label was stale, so no CI had run there since 2026-07-02). Once it goes green and merges, this Upgrade check red clears on the next master merge. Everything else here is green, the PR is approved, and there are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

Status update: CI on #107126 has finished and is fully green (mergeable, no failing checks). It only needs an approval and merge; once it lands on master, the Upgrade check red here clears on the next master merge. This PR itself remains green otherwise, approved, with no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110917&sha=84a9c80aa85307d4b14902c4da7d8c0a7f14cfff&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The failed test is 03100_lwu_29_concurrent_merges (timeout, then Server died) in Fast test (arm_darwin). It is unrelated to this PR (which only changes the hash function used by groupUniqArray for numeric types): CIDB shows the same test failing on 6 different PRs over the last 30 days (#110015, #110567, #109415, #109794, #103182), and there is no open issue tracking it yet.

The other reds at 84a9c80 are all known issues (test_check_table — #111289, fixed on master by #111353, now pulled in by merging master; test_replicated_table_structure_alter — #110036; stress hung check — #107941; Cannot start clickhouse-server — #111376) or runner-level infra deaths (perf shard amd 3/6 with an empty report).

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. No fix in progress and no tracking issue for 03100_lwu_29_concurrent_merges (only #107042, which covered a different amd_tsan ZK-session-expiry variant of this test), so I will open a separate fix PR.

From the arm_darwin run the test ran 411.95s against the 60s fast-test limit before the per-test timeout killed the client; the Server died is the follow-on cleanup hitting 300s SOCKET_TIMEOUT against a still-busy server, not an abnormal termination. The scenario is a background OPTIMIZE ... PARTITION ID 'all' FINAL parked in the rmt_merge_task_sleep_in_prepare failpoint racing a foreground patch-partition OPTIMIZE ... FINAL + UPDATE, then wait. I will reproduce it locally, fix it, and link the PR here.

@groeneai

Copy link
Copy Markdown
Collaborator

Update after reproducing and reading the CI server log: this arm_darwin failure is 03100_lwu_29_concurrent_merges being an innocent victim of a whole-server freeze, not a bug in the test or in the concurrent-merge scenario. Correcting my earlier note.

Evidence from the run's clickhouse-server.log (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110917&sha=84a9c80aa85307d4b14902c4da7d8c0a7f14cfff&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29):

  • The test's own queries all completed. The failpoint-slept background OPTIMIZE ... 'all' FINAL slept exactly 3s (the rmt_merge_task_sleep_in_prepare duration: prepare at 13:55:52.272, merged at 13:55:55.415), the foreground patch OPTIMIZE + UPDATE and the final OPTIMIZE all ran, and DROP TABLE ... SYNC removed the table from ZooKeeper at 13:55:55.974. So the concurrent-merge race resolved cleanly.
  • About 0.2s later the whole server stopped executing queries. server.log line volume drops from ~272k lines in minute 13:55 to ~1k in 13:56, only background pools keep logging, and exactly one user query starts after 13:56:05 (the runner's own SELECT 1 /*liveness check*/), which never returns.
  • The CI watchdog then logged Hung check failed: server is not responding and SIGTERM'd it. The 411.95s / Server died is the runner's post-test DROP DATABASE cleanup hitting the 300s SOCKET_TIMEOUT against the frozen (not crashed) server, so 03100 is just the test slot that happened to be current.

03100's rmt_merge_task_sleep_in_prepare is a ONCE failpoint; it fired once and was consumed by 03100's own merge, and did not leak into other tables. So a test change cannot fix this, and there is no 03100-specific defect in this run.

This is the chronic "Hung check failed, possible deadlock found" family (tracked in #107941). At the freeze onset the concurrently running tests were 04007_pipeline_stuck_ping_pong_deadlock (its queries are the last user activity before the freeze) and 01882_check_max_parts_to_merge_at_once (actively launching merges); those are a more plausible locus than 03100 for the deadlock, but I have not proven the exact code path, so I am flagging them only as a lead for the hung-check investigation, not a conclusion.

Given that, I do not think a separate fix PR on 03100 is warranted for this failure. The other recent CIDB failures under this test name are also distinct victims (host-OOM, quota-leak from the 04603_quota_zero_interval cleanup, and replica-shutdown), except a single #103182 NOT_FOUND_COLUMN_IN_BLOCK: 'id' in MergeTreeSelect(InOrder) which looks like a genuinely separate lightweight-update issue worth its own look. Happy to dig into either the hung-check locus or the #103182 signature if you'd like.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.10% 86.20% +6.10%
Functions 90.90% 92.00% +1.10%
Branches 72.30% 78.30% +6.00%

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

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Regarding the AI Review blocker (serialized groupUniqArrayState bytes changing for integer keys) — I believe it is a false positive, and no state versioning or compatibility gate is needed:

  • The state layout is unchanged: serialize writes a varint count followed by fixed-width little-endian elements, and deserialize calls Set::read, which re-inserts each element into the hash set. Deserialization is completely order-agnostic, so states written by old servers are readable by new servers and vice versa, in both directions of a rolling upgrade.
  • Byte-identity of groupUniqArrayState for the same logical input has never been a stable surface: the serialized bytes already depend on insertion and merge order at runtime (thread partitioning of partial aggregates, the order in which distributed states arrive), so two servers of the same version routinely produce different bytes for the same logical set today. Versioning cannot make that deterministic, and nothing in the codebase compares these states byte-wise.
  • The cited test 02751_ip_types_aggregate_functions_states covers IPv4/IPv6 arguments, which do not take the is_integer path (IPv4 is a strong typedef, not an integer type in the is_integer sense) — that test is untouched by this PR and passes unchanged in the green stateless runs on the current head.
  • Precedent: uniqExact has used HashCRC32 with the same unversioned count-plus-elements serialization since its introduction; iteration order of the underlying hash table has never been versioned for set-backed aggregate states.

The only user-visible effect is the element order of the (unsorted) result array, which is declared in the PR description and was part of the approved change; the three order-dependent tests were switched to arraySort.

Separately, the single CI red on 99fc0b0 is test_distributed_ddl/test.py::test_default_database[configs_secure] failing with Sanitizer assert found for instance zoo2-1 — a TSan report in clickhouse-keeper during test shutdown, unrelated to this aggregate-function change (this PR touches only AggregateFunctionGroupUniqArray.cpp and three test files). The same test failed the same way on #92323 (amd_asan_ubsan) on 07-15/07-16, so it is a cross-PR flake. I have re-run the failed job.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110917&sha=99fc0b0d7264b8abda888bb35b61b9223c4c8850&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%202%2F6%29 (the Keeper sanitizer assert in test_distributed_ddl) and provide a fix in a separate PR. If the fix is already in progress, link it here. Note: the TSan report itself is not in the archived logs.tar.gz (Keeper stderr stays inside the container), which may itself be worth fixing in the log collection.

@groeneai

groeneai commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Confirmed: this is the known systemic Keeper TSan false positive, unrelated to the groupUniqArray change in this PR.

Root cause. TSan reports a data race in NonblockingBoundedQueue on the slot.value handoff between tryPush (raft commit thread) and tryPop (response thread), i.e. the queue's normal producer/consumer path. It surfaces as Sanitizer assert found for instance zoo* during cluster.shutdown(). Introduced by the KeeperDispatcher overhaul #101757.

Fix already in progress: #107083 (al13n321, open, approved by antonio2368, Keeper maintainer) adds NO_SANITIZE_THREAD to tryPush/tryPop in src/Common/NonblockingBoundedQueue.h; the investigation (with the same CIDB signature and per-test spread) is in #106801. Linking it here per your note rather than opening a duplicate fix PR.

Spread (CIDB, last 30d). The Sanitizer assert found for instance zoo* signature hit 19 times across 18 distinct PRs and 19 distinct integration tests (only 2 on master pushes), with test_distributed_ddl/test.py::test_default_database[configs_secure] among them. So it is a cross-PR flake, matching your read; not specific to this PR.

Log-collection gap. Confirmed: the Keeper TSan report never reaches the archived logs.tar.gz because Keeper stderr stays inside the container. I don't see an existing PR/issue for this, so I'll open a separate follow-up to capture Keeper sanitizer stderr in the integration-test log archive and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the log-collection gap: opened #111523 — integration tests now capture Keeper sanitizer stderr in the collected logs.

Root cause: clickhouse-keeper (a BaseDaemon) only redirects fd 2 to a file when logger.stderr is set, and the integration Keeper configs set only <log>/<errorlog>. So a sanitizer report (written to raw fd 2) reaches only the container stream; the zoo* containers aren't in cluster.instances, so shutdown()'s per-instance scan skips them and detection falls back to the docker compose logs --follow capture, which is torn down at shutdown and isn't archived into logs.tar.gz — exactly why the TSan report couldn't be found here.

Fix redirects Keeper stderr/stdout to the already-bind-mounted /var/log/clickhouse-keeper/ and makes shutdown() scan that file, verified end-to-end on a real Keeper cluster (both directions). The TSan race itself is separate and tracked in #107083.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 23, 2026
Merged via the queue into ClickHouse:master with commit f72697e Jul 23, 2026
352 of 353 checks passed
@raimannma
raimannma deleted the group-uniq-array-crc32-hash branch July 23, 2026 07:13
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 23, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jul 26, 2026
A Keeper sanitizer report (e.g. a TSan data race in clickhouse-keeper) is
written to raw process stderr (fd 2). clickhouse-keeper, a BaseDaemon, only
redirects fd 2 to a file when logger.stderr is set; the integration keeper
configs set only <log>/<errorlog>, so the report reaches only the container
stderr stream. The zoo* containers are not in ClickHouseCluster.instances, so
the per-instance stderr.log scan in shutdown() never covers Keeper, and
detection falls back to the 'docker compose logs --follow' capture, which is
torn down at shutdown and is not archived into logs.tar.gz. That is why the
Keeper sanitizer report could not be found in the collected logs on ClickHouse#110917.

- docker_compose_keeper.yml: redirect Keeper stderr/stdout to
  /var/log/clickhouse-keeper/ (already bind-mounted and archived) via
  '-- --logger.stderr=... --logger.stdout=...', mirroring server nodes.
- helpers/cluster.py shutdown(): also scan each Keeper instance's stderr.log
  for the sanitizer sign, so the report is detected deterministically once
  Keeper fd 2 no longer reaches the docker.log capture.

The TSan race itself is unrelated to this change and is tracked in ClickHouse#107083.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…crc32-hash

Speed up groupUniqArray for numeric types
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
A Keeper sanitizer report (e.g. a TSan data race in clickhouse-keeper) is
written to raw process stderr (fd 2). clickhouse-keeper, a BaseDaemon, only
redirects fd 2 to a file when logger.stderr is set; the integration keeper
configs set only <log>/<errorlog>, so the report reaches only the container
stderr stream. The zoo* containers are not in ClickHouseCluster.instances, so
the per-instance stderr.log scan in shutdown() never covers Keeper, and
detection falls back to the 'docker compose logs --follow' capture, which is
torn down at shutdown and is not archived into logs.tar.gz. That is why the
Keeper sanitizer report could not be found in the collected logs on ClickHouse#110917.

- docker_compose_keeper.yml: redirect Keeper stderr/stdout to
  /var/log/clickhouse-keeper/ (already bind-mounted and archived) via
  '-- --logger.stderr=... --logger.stdout=...', mirroring server nodes.
- helpers/cluster.py shutdown(): also scan each Keeper instance's stderr.log
  for the sanitizer sign, so the report is detected deterministically once
  Keeper fd 2 no longer reaches the docker.log capture.

The TSan race itself is unrelated to this change and is tracked in ClickHouse#107083.

Co-Authored-By: Claude Opus 4.8 <[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 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