Repository navigation
Serialize LowCardinality GROUP BY keys without materializing full columns - #121795
Conversation
…umns `Aggregator::executeOnBlock` copied every `LowCardinality` key column into a full column before handing it to a serialized hash method. Those methods read the keys through the `IColumn` serialization interface and serialize the value at the dictionary index, so the copy - a full column allocation plus a copy of every key value - is pure overhead. Pass a non-nullable `LowCardinality` key column to the method as is. The serialized keys stay value-based, so independently built dictionaries of the input blocks do not affect the result. `LowCardinality(Nullable)` keys keep the materialized representation, which carries their null map, and top-K aggregation keeps it as well for its own ranked columns. Writing the batch of serialized keys for a `LowCardinality(String)` dictionary directly from the dictionary values avoids two virtual calls per row in the generic `IColumnUnique` path. On a 30-day observability dataset (AMD EPYC 7232P) two grouped dashboard queries run 34% and 24% lower user CPU, with 27% fewer cycles and 33% fewer cache references; peak memory drops by up to 48%. GROUP BY over `metric, region` on 200 M rows improves by 23%. The new `05241_low_cardinality_serialized_group_by` test covers multi-key `LowCardinality` GROUP BY over parts with differently ordered dictionaries, including two-level, small-block, top-K and Nullable cases.
|
Workflow [PR], commit [24a7912] Summary: ✅
AI ReviewSummaryThis PR stops materializing non-nullable Final Verdict
LLVM Coverage Report |
`HashMethodSerialized<nullable=true>` keeps a null map only for materialized `ColumnNullable` key columns, so a non-nullable `LowCardinality` key is serialized through the same value-based `IColumn` interface with `null_maps[i] == nullptr` as under the non-nullable methods. Include the `nullable_serialized` variants in `isSerialized()` so such keys are not materialized just because a sibling key is Nullable; `LowCardinality(Nullable)` keys stay materialized. Add mixed `LowCardinality(String)` plus plain `Nullable(String)` cases to `05241_low_cardinality_serialized_group_by`.
|
Addressed in 153f079:
Verification on the same base revision (pristine vs patched builds of 728fcc7):
|
`params.top_k` only says that the plan enabled the heap optimization. After the heap freezes, `executeImpl` falls back to ordinary aggregation, but the guard kept materializing every non-nullable `LowCardinality` key on the later blocks because the plan flag never changes. Consult the frozen flag of the active method's top-K heap through a new `AggregatedDataVariants::topKHeapFrozen()` helper, so the direct serialization path applies again once the ranked columns are no longer used; an active heap and `LowCardinality(Nullable)` keys keep the materialized representation. Add a deterministic freeze case to `05241_low_cardinality_serialized_group_by` using a small `group_by_top_k_optimization_observation_rows`.
|
Addressed in 331f95b. What was wrong: Runtime state: added Test: Correctness: the new test passes 10/10 repeats, on the patched and the pristine build; 43/43 adversarial differential cases; Performance (interleaved A/B, 5 reps, same revision, user CPU): deterministic early-freeze case -20% vs the previous revision of this patch and -21% vs pristine; active top-K heap that does not freeze 0.98 (within noise); main workloads unchanged ( |
|
📊 Cloud Performance Report ✅ AI verdict: No query shows a performance change that this PR caused. The only flagged query is clickbench Q28, and its verdict stays not_sure: the -6.7% change is borderline, the two tests disagree, and the PR measurements were noisy. The PR speeds up multi-key GROUP BY on non-nullable LowCardinality keys by serializing values straight from the dictionary instead of first expanding the key columns. ClickBench stores plain String columns and TPC-H uses no LowCardinality keys, so neither benchmark runs the changed code, and they could not show this optimization either way. clickbenchFlagged queries (1 of 43)
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
|
|
The ARM perf shard 4/6 failed on |
The guard before key preparation consulted only the persistent `frozen` flag, while `executeImpl` freezes the heap at the start of a block when `shouldFreeze()` is already true. The block crossing the profitability window therefore still materialized every non-nullable `LowCardinality` key, although the heap no longer ranks its rows. `AggregatedDataVariants::topKHeapInactive()` reports `frozen || shouldFreeze()` for the active method's heap. Both terms are needed: `shouldFreeze()` turns false once the heap has frozen, and an uninitialized heap must keep the materialized ranked columns. `shouldFreeze()` is side-effect free and the heap state does not change between key preparation and `executeImpl`, so the early answer matches the state `executeImpl` acts on.
…ly freezes The result query alone would also pass if the `GROUP BY` top-K optimization never engaged or if the heap stayed active for the whole run. Pin the settings the path depends on, run the freeze shape once as a `FORMAT Null` probe with a `log_comment`, and assert `ProfileEvents['AggregationTopKHeapsFrozen'] > 0` for it in `system.query_log`. The result query stays as the correctness assertion.
The test server's default profile sets `max_rows_to_group_by` to 10G (`tests/config/users.d/limits.yaml`), and `tryOptimizeGroupByTopK` bails out when the aggregation has a non-zero `max_rows_to_group_by` (`validateAggregatingStep`). The probe never froze in CI and the new assertion returned 0. Pin it to zero like the other top-K heap tests.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units581 translation units recompiled, 5671 s compile time in total, 581 of them have a recent master baseline. |
|
The four failed checks are unrelated to this change; could someone rerun them?
|
Co-authored-by: Alexey Milovidov <[email protected]>
This reverts commit c547842. The dictionary indexes of a `LowCardinality` column are random access, so the start of a value is `offsets[index - 1]`, not the end offset of the value serialized for the previous row. The loop header change from the following commit is kept. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
Thanks! This is a great optimization!
…stributed aggregation Address review: the direct `batchSerializeValueIntoMemory` path for `LowCardinality(String)` must produce keys that deserialize correctly when aggregation spills to disk or merges partial states from remote shards. Compare external and distributed results with the in-memory one, include the empty string (dictionary default slot, index 0), and prove that the query spilled. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
I'm glad this finding and optimization is useful. Your feedback will help me in my experiments. |
The flaky check failed with `Test runs too long (> 180s)` under debug and sanitizer builds: with `max_bytes_before_external_group_by = 1` every 4096-row block of 400000 rows was spilled as a two-level aggregation. Use 10x fewer rows; the external query still spills (4 parts, merged once) and all comparisons stay. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121795&sha=a52fe4db86a726bfef27eeb38a0269e8cedfea17&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 PR: ClickHouse#121795 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Pushed 95a56b0: the flaky-check reds were the new test @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121795&sha=a52fe4db86a726bfef27eeb38a0269e8cedfea17&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29 ( |
|
Acknowledged. Findings so far:
I'll follow up here with a PR that stabilizes the fixture, or with my findings if the offset cannot be removed on the test side. |
|
The cause is in the function, not the fixture: with a non-constant pattern, |
`Regexps::LocalCacheTable::getOrSet` incremented `RegexpLocalCacheHit` or `RegexpLocalCacheMiss` on every lookup, and `MatchImpl::matchOneRow` does one lookup per row whenever the pattern of `LIKE`/`match` is not a constant. `ProfileEvents::increment` does an atomic add at every level of the counter chain. The user and global levels are per-CPU since ClickHouse#105056, but the thread group level is a single row, so every thread of the query wrote the same cache line on every row. The query was bound by that line: `re2_regex_caching` `#3` took 91 ms at both 8 and 32 threads, and its cost differed between server processes, which made `#3`, `#5` and `#6` of that test noisy on the amd performance shards. The table now counts hits and misses in two members and adds them to ProfileEvents once, in its destructor. A table is a local of `vectorVector`/`vectorFixedVector`/`constantVector`, so it lives for one block on one thread: the totals per query are unchanged (a miss is still counted before `createRegexp`, so a failed compile still reports it), and the shared counter is written twice per block instead of once per row. Tables that did no lookup report nothing, as before. With `trace_profile_events = 1` these two events now give one `trace_log` row per block (with the block total) instead of one per row. Release build, 8 threads pinned to 8 physical cores, 10 server processes per binary: `#3` and `#5` 90 -> 18 ms, `#6` 94 -> 34 ms, the other queries of the test unchanged; user CPU at 8 threads over 1 thread for `#3` goes from 5.2 to 1.0. At 32 threads `#3` goes from 91 to 15 ms. The new test checks the exact hit and miss totals for the three callers (String, FixedString and constant haystacks). Related: ClickHouse#121795, ClickHouse#100759 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121795&sha=95a56b0fcccabd72181373b3e906d9c02db9ec53&name_0=PR — |
|
Acknowledged. Findings so far:
I'll follow up here with a PR, or with my findings for the |
|
Follow-up on
This is the class discussed in #122350 (comment). Merging master (which also brings #122728 for the arm red) produces a new build, and none of the other 589 showed this. |
`ColumnLowCardinality::collectSerializedValueSizes` computed sizes for every dictionary entry and then gathered them by index. Now that the prealloc serialized aggregation methods receive `LowCardinality` key columns directly, a block with a large dictionary but few surviving rows would pay a whole dictionary scan per key per block. Size `LowCardinality(String)` keys directly from the referenced offsets, mirroring `batchSerializeValueIntoMemory`, and size other types per row via `getSerializedValueSize` when the dictionary is larger than the block. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…span<char *>` Master changed the signature of `IColumn::batchSerializeValueIntoMemory` from `VectorWithMemoryTracking<char *> &` to `std::span<char *>` in 5b6ecaa, so the override added in this PR no longer overrode anything, and the merge queue build failed with "non-virtual member function marked 'override' hides virtual member function". Merge-queue report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=gh-readonly-queue/master/pr-121795-1592ef94b9a73d8d800e66d6feac4ab319d5abaf&sha=185725e81924dd2619262210708a0ca54458668b&name_0=MergeQueueCI&name_1=Build%20%28amd_binary%29 PR: ClickHouse#121795 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
GROUP BYover multipleLowCardinalitykeys now serializes the keys from the per-block dictionaries instead of copying them into full columns first, reducing CPU time and memory usage of aggregation queries overLowCardinalitydimensions.Problem
GROUP BYover severalLowCardinalitykeys (the usual shape of observability dashboards) uses a serialized hash method.Aggregator::executeOnBlockmaterialized eachLowCardinalitykey column into a full column first - a full-size allocation plus a copy of every key value - although the serialized methods serialize the value at the dictionary index anyway.Change
A non-nullable
LowCardinalitykey column is passed to the serialized method as is, including thenullable_serializedmethods, where it simply has no null map (null_maps[i] == nullptr).ColumnLowCardinality::batchSerializeValueIntoMemorywrites dictionary values of aLowCardinality(String)dictionary directly instead of resolving every row throughIColumnUniqueand the nested column.LowCardinality(Nullable)keys keep the materialized representation, and so does an active top-K heap, whose ranked columns are built from the key columns. The guard follows the runtime heap state: once the heap freezes and execution falls back to ordinary aggregation, the direct path applies again.Safety
Serialized keys are value-based:
serializeValueIntoMemory/serializeValueIntoArenaresolve the dictionary index and write the value, so per-block dictionary order does not affect group identity. The fast path writes the same[size][bytes][optional 0]frame asColumnString::serializeValueIntoMemory, andcollectSerializedValueSizesreserves exactly that. Merge and spill paths reconstruct keys from the same bytes.Tests
New stateless test
05241_low_cardinality_serialized_group_by: several parts with differently ordered dictionaries, multi-key GROUP BY, mixed LowCardinality/expression keys, two-level, small blocks, top-K, aLowCardinality(Nullable)key and a plainNullablesibling key (ordinary and two-level). It passes on the patched and on the unpatched build It also contains a deterministic top-K freeze case (a rare worst ranked pair plusgroup_by_top_k_optimization_observation_rows = 1) that exercises the transition from the ranked path to ordinary aggregation with the same multi-key LowCardinality shape.An adversarial differential battery of 43 cases (permuted per-part dictionaries, 5000-value dictionaries,
String/FixedString/numeric LC, nullable LC, empty/0x00/long/unicode strings, mixed keys,max_threads 1/8,max_block_size 1..512, two-level on/off, external spill, overflow mode, top-K,WITH TOTALS/ROLLUP) produces byte-identical results for the patched build, the unpatched build and materialized plain columns.Benchmarks
Observability dataset (99.9 M log rows, 200 M metric rows; AMD EPYC 7232P; 5 interleaved repetitions after warmup, user CPU from
system.query_log):obs_full_scan_by_service_level: 16.63 s -> 11.02 s (-34%)metrics_heavy_30d: 20.34 s -> 15.54 s (-24%), peak memory -48%GROUP BY metric, regionover 200 M rows: 20.65 s -> 15.84 s (-23%)Hardware counters (median of 3):
metrics_heavy_30dcycles -27%, cache references -33%, cache misses -30%, instructions -5%;obs_full_scan_by_service_levelcycles -34%, cache references -19%, cache misses -25%.read_bytesis identical before and after. An independent 8 M-row synthetic observability dataset shows the same direction for multi-LowCardinality GROUP BY shapes, with a String-key control unchanged.A deterministic early-freeze top-K query over a dedicated 20 M-row two-LowCardinality-key table runs 20% lower user CPU than the previous revision of this patch (which kept materializing after the freeze) and 21% lower than the pristine build; an active top-K heap that does not freeze stays within noise, and the headline workloads are unchanged.
Extending the eligibility to the
nullable_serializedmethods was verified on the same base revision: the core workloads are unchanged (obs_full_scan_by_service_level-35%,metrics_heavy_30d-24%,obs_status_by_service-14%, controls neutral), a two-LowCardinality control keeps its -15% gain, and mixed shapes with a plainNullablesibling (GROUP BY service, level, toNullable(status)) are within noise on this dataset because the copied LowCardinality columns are small relative to those queries.Workflow [PR]
Sync PR [sync-upstream/pr/121795]
Version info
26.10.1.1480-master(included in26.10and later)