Skip to content

Use the adaptive aggregator for GROUP BY over Nullable keys whose hash method packs the null map into the key - #124868

Merged
nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:adaptive-aggregator-nullable-keys
Oct 11, 2026
Merged

nihalzp merged 2 commits into
ClickHouse:masterfrom
groeneai:adaptive-aggregator-nullable-keys

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY with a Nullable key now uses the adaptive aggregator, except when that key is the only one and is a number of up to 8 bytes, a String or a FixedString, or when any key is LowCardinality. Schema inference makes such keys common in CSV, JSON and Parquet files; high-cardinality aggregations over them become up to 2x faster with up to 2.2x less memory.

Description

Closes #124668. Related: #111459.

AggregatingStep::adaptiveAggregatorRejectionReason refused the adaptive aggregator for any Nullable key. Schema inference makes most file columns Nullable (schema_inference_make_columns_nullable), so GROUP BY over such columns of file()/s3() data never used it, even with no NULLs in the data.

The frozen kernel stages a missed row under the key its method builds, then emplaces it directly into the bucket's table. That is only correct when the key value alone identifies the group. Four methods meet it and are now admitted: nullable_keys128/nullable_keys256 pack the null bitmap into the key, and nullable_serialized/nullable_prealloc_serialized serialize the null flag. The single-key methods (nullable_key8..64, nullable_key_string, nullable_key_fixed_string) keep NULL in a separate cell that the staging bypasses, so they stay rejected, and so does LowCardinality. Admitting them would merge NULL rows into the nested default's group.

Test 05340: 9 admitted and 4 rejected shapes, each with NULL next to the nested default, compared with the ordinary path, plus a staging check (it fails on master only on that check). Perf test adaptive_aggregation_nullable_keys.xml; the Nullable query of aggregation_two_level_bucket_merge.xml no longer re-enables the adaptive aggregator, so it still measures the bucket merge.

RelWithDebInfo build, 100M rows, 16 threads, enable_adaptive_aggregator 0 vs 1 (= master vs this PR here), median of 5:

keys ms memory
two Nullable numbers, count/sum/avg 1796 -> 865 10.29 -> 4.53 GiB
Nullable number + Nullable(String) 1820 -> 1146 11.69 -> 6.94 GiB
three keys with real NULLs 2401 -> 1161 10.47 -> 6.55 GiB
one Nullable(UInt64) (still rejected) 386 -> 383 unchanged

One cost case: 18.2M groups with clustered keys run 510 -> 422 ms, but peak memory goes 2.06 -> 3.48 GiB, as on the already-admitted non-Nullable path (2.00 -> 3.48 GiB).


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

Version info

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

…null map into the key

The admission gate rejected every Nullable key. Schema inference makes most
file columns Nullable, so GROUP BY over file()/s3() data never took the
adaptive path, even with no NULLs in the data.

The frozen kernel probes a row with the key holder and stages a miss as the
key value, which the drain emplaces straight into the bucket's submap. That is
correct exactly when the key value alone identifies the group:
nullable_keys128/256 write the null bitmap into the packed key, and
nullable_serialized/nullable_prealloc_serialized serialize the null flag.
The single-key methods keep NULL in the separate cell of
AggregationDataWithNullKey and hand out the nested value as the key of a NULL
row, so staging would merge NULL into the nested default's group; they stay
rejected, as does LowCardinality. The admission is per method, not per key
count: a single Nullable(Int128) or Nullable(UUID) key uses nullable_keys256
and is admitted.

The Nullable query of the aggregation_two_level_bucket_merge perf test now
inherits that file's enable_adaptive_aggregator = 0: its keys are admitted now,
and the test measures the bucket merge.

Measured (RelWithDebInfo, 100M rows, 16 threads, setting 0 vs 1): two
Nullable number keys 1796 -> 865 ms, 10.29 -> 4.53 GiB; Nullable number +
Nullable String 1820 -> 1146 ms; three keys with real NULLs 2401 -> 1161 ms.
One 18.2M-group clustered-key shape uses more memory (2.06 -> 3.48 GiB), the
same as the already-admitted non-Nullable path on those keys.

Closes ClickHouse#124668

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds): 2 major fixed, 2 nits fixed, 1 nit not changed; third round clean
  • ❌ -> fixed: the test pinned only nullable_key64 among the rejected methods. Added nullable_key_string, nullable_key_fixed_string and a LowCardinality(Nullable(String)) + Nullable shape (whose method would otherwise be nullable_prealloc_serialized); one mutation that admits all three flips each staging line.
  • ❌ -> fixed: aggregation_two_level_bucket_merge.xml re-enabled the adaptive aggregator on its Nullable query because it used to be rejected there; that shape is admitted now, so the query inherits the file's enable_adaptive_aggregator = 0 and keeps measuring the bucket merge.
  • 💡 -> fixed: changelog entry and commit message named the admitted single-key set too broadly (FixedString/String stay rejected).
  • 💡 -> not changed: no keys-only arm for the serialized _void forms; that kernel is type-generic and already runs for serialized_void on master.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two Nullable keys over numbers_mt(300000), max_threads = 4, adaptive_aggregator_freeze_threshold = 8: master logs Adaptive aggregation is not engaged: a key is LowCardinality or Nullable and stages 0 rows; with the change, 210231 rows are staged.
b Root cause explained? Admission was decided by key type, but the frozen kernel's correctness depends on the method's key layout: a staged key is emplaced directly into the bucket table, which is correct only when the key value alone identifies the group.
c Fix matches root cause? Yes. Admission is now per method: the four methods that put the null map into the key are admitted; the single-key methods that keep NULL in a separate cell stay rejected. Kernels unchanged.
d Test intent preserved / new tests added? New 05340 (9 admitted and 4 rejected shapes, NULL next to the nested default, equality with the ordinary path + staging check) and perf test adaptive_aggregation_nullable_keys.xml. The Nullable query of aggregation_two_level_bucket_merge.xml now inherits the file's enable_adaptive_aggregator = 0, so it still measures the bucket merge.
e Both directions demonstrated? Master binary: FAIL on the 9 staging lines only. Patched: OK, 50/50 randomized. Mutation admitting the single-key methods: the single equality turns 0; a second one admitting nullable_key_string/nullable_key_fixed_string and dropping the LowCardinality check flips all three rejected-arm staging lines and both string equalities.
f Fix is general across code paths? Every nullable method chooseMethod can return is classified; _void forms, two-level, spill, ROLLUP/CUBE/TOTALS covered. One caller of the gate.
g Fix generalizes across inputs (params/datatypes/wrappers)? UInt16/32/64, Int128, String and Array keys; 1 to 3 keys; NULL next to 0 and ''; count-only, no aggregate, sum; batch and per-row key serialization; LowCardinality(Nullable) still rejected.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change; results identical on both paths.
i Invariants and contracts preserved? "A staged key alone identifies its group" holds for exactly the admitted methods; the function's contract (nullptr admits, a string is the rejection reason) is unchanged.

Session id: cron:clickhouse-impl-slot-7:20261009-085300

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e12571]

Summary: ✅


AI Review

Summary

This PR narrows adaptive-aggregator admission for Nullable GROUP BY keys to the hash methods whose staged key already carries the null information, keeps the known-unsafe single-key and LowCardinality shapes on the baseline path, adds a stateless test that covers both admitted and rejected shapes, and moves the nullable perf coverage into its own benchmark while keeping the bucket-merge benchmark measuring the same thing as before. I reviewed the current diff and prior discussion and did not find a remaining correctness, safety, performance, or PR-metadata problem worth posting inline.

Final Verdict

✅ No findings to post on the current revision.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 9, 2026
@groeneai
groeneai requested review from nickitat and nihalzp October 9, 2026 09:28
@nihalzp nihalzp self-assigned this Oct 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Oct 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 6e12571dce4e1f986784afdeea072f39f0b6bd6c was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 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: 055a2a9f-5707-4f18-b50b-9397498bd03a
  • MIRAI run: 3ffa8d38-2b07-4156-8fac-6ad21179b719
  • PR check IDs:
    • clickbench_788704_1791672107
    • clickbench_788710_1791672107
    • clickbench_788716_1791672107
    • tpch_adapted_1_official_788727_1791672107
    • tpch_adapted_1_official_788741_1791672107
    • tpch_adapted_1_official_788774_1791672107

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c7644ca

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines test regression from merged #123364, not from this PR: under DatabaseReplicated the final query_log count returns 0 2 instead of 0 1 (the password stays hidden; the CREATE DICTIONARY row is counted twice). 21/21 reruns pass; the same diff is on 33 PRs in this lane today a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollup of the row above, no independent failure a fix task is created (the row above)

Session id: cron:our-pr-ci-monitor:20261009-140011

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05316_secret_arguments_declared_by_engines (DatabaseReplicated 0 1 -> 0 2) from the CI finish ledger above: #124928 (external, open).

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, the bad test is fixed - update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (includes #124928) and pushed 6e12571. The PR's own diff is unchanged; 05340_adaptive_aggregator_nullable_keys passes 20/20 locally on the merged build.

@nihalzp
nihalzp added this pull request to the merge queue Oct 11, 2026
Merged via the queue into ClickHouse:master with commit 371a1f9 Oct 11, 2026
163 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 11, 2026
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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

4 participants