Skip to content

Serialize LowCardinality GROUP BY keys without materializing full columns - #121795

Merged
alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
artemkulyk:serialize-lc-keys-upstream
Oct 4, 2026
Merged

alexey-milovidov merged 18 commits into
ClickHouse:masterfrom
artemkulyk:serialize-lc-keys-upstream

Conversation

@artemkulyk

@artemkulyk artemkulyk commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

GROUP BY over multiple LowCardinality keys 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 over LowCardinality dimensions.

Problem

GROUP BY over several LowCardinality keys (the usual shape of observability dashboards) uses a serialized hash method. Aggregator::executeOnBlock materialized each LowCardinality key 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 LowCardinality key column is passed to the serialized method as is, including the nullable_serialized methods, where it simply has no null map (null_maps[i] == nullptr). ColumnLowCardinality::batchSerializeValueIntoMemory writes dictionary values of a LowCardinality(String) dictionary directly instead of resolving every row through IColumnUnique and 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/serializeValueIntoArena resolve 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 as ColumnString::serializeValueIntoMemory, and collectSerializedValueSizes reserves 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, a LowCardinality(Nullable) key and a plain Nullable sibling 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 plus group_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, region over 200 M rows: 20.65 s -> 15.84 s (-23%)

Hardware counters (median of 3): metrics_heavy_30d cycles -27%, cache references -33%, cache misses -30%, instructions -5%; obs_full_scan_by_service_level cycles -34%, cache references -19%, cache misses -25%. read_bytes is 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_serialized methods 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 plain Nullable sibling (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

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

…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.
@CLAassistant

CLAassistant commented Sep 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [24a7912]

Summary: ✅


AI Review

Summary

This PR stops materializing non-nullable LowCardinality keys on serialized GROUP BY paths, adds a direct LowCardinality(String) batch-serialization and size-collection fast path, and backs the change with focused stateless coverage for mixed nullable siblings, top-K freeze, external spill, and distributed partial aggregation. I re-checked the current diff and the resolved review threads against the code as it stands now, and I did not find a remaining correctness, safety, or hot-path regression in the submitted changes. The Performance Improvement changelog metadata also matches the user-visible effect the PR implements.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit 24a7912: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_8.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 23, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
`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`.
@artemkulyk

Copy link
Copy Markdown
Contributor Author

Addressed in 153f079:

  • isSerialized() now covers the nullable_serialized variants, so a non-nullable LowCardinality key is no longer materialized just because a sibling key is Nullable. LowCardinality(Nullable) keys remain materialized (per-column dictionary check) and top-K stays on the old path.
  • 05241_low_cardinality_serialized_group_by now has mixed LowCardinality(String) + plain Nullable(String) cases in ordinary and two-level form.

Verification on the same base revision (pristine vs patched builds of 728fcc7):

  • 43/43 adversarial differential cases exact match, including mixed nullable/non-nullable shapes
  • new test passes on the patched and on the pristine build; low_cardinality stateless subset: 135 passed / 9 skipped / 3 failures that reproduce on the pristine binary and need a cluster/keeper
  • A/B: obs_full_scan_by_service_level -35%, metrics_heavy_30d -24%, obs_status_by_service -14%, controls neutral, two-LowCardinality control keeps its -15% gain
  • mixed shapes with a plain Nullable sibling are within noise on our dataset (the copied LowCardinality columns are small relative to those queries); the chosen method there is nullable_prealloc_serialized, so the new path is exercised

@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 23, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
`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`.
@artemkulyk

Copy link
Copy Markdown
Contributor Author

Addressed in 331f95b.

What was wrong: params.top_k is only the plan-level opt-in. After method.top_k_heap freezes, executeImpl switches to ordinary aggregation, but the guard kept materializing every non-nullable LowCardinality key on the later blocks because the plan flag never changes.

Runtime state: added AggregatedDataVariants::topKHeapFrozen(), which reads the frozen flag of the active method's heap (same switch pattern as topKHeapEverRejected(); convertToTwoLevel moves the heap, so the state survives). The guard is now params.top_k && !result.topKHeapFrozen(), so an active heap keeps the materialized ranked columns, post-freeze blocks use the direct serialization path, and LowCardinality(Nullable) keys stay materialized.

Test: 05241_low_cardinality_serialized_group_by gained a deterministic freeze case — a rare worst (s, f) pair and group_by_top_k_optimization_observation_rows = 1 over 200k rows in small blocks, with GROUP BY s, f ORDER BY s, f LIMIT 2. system.events confirms AggregationTopKHeapsFrozen increments for this shape (16 heaps) and stays at 0 with a huge observation window.

Correctness: the new test passes 10/10 repeats, on the patched and the pristine build; 43/43 adversarial differential cases; low_cardinality subset unchanged (135 passed / 9 skipped / 3 environment-only failures); the two_level/top_k/serialized subset shows only CLUSTER_DOESNT_EXIST failures, which reproduce on the pristine build. The freeze query's group counts are identical to pristine across the transition.

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 (obs_full_scan_by_service_level -33%, metrics_heavy_30d -24%, obs_status_by_service -11%).

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1106 1032 -6.7% <0.0001 This PR only changes GROUP BY on LowCardinality keys that use serialized hashing, and ClickBench's hits table has no LowCardinality columns. The -6.7% change comes from noisy measurements on both sides.

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: ee363a1c-b61d-4774-a33b-2f405a54c606
  • MIRAI run: 19f3891f-6d23-411b-9ec1-8277725c56aa
  • PR check IDs:
    • clickbench_3002296_1790998034
    • clickbench_3002307_1790998034
    • clickbench_3002314_1790998034
    • tpch_adapted_1_official_3002326_1790998034
    • tpch_adapted_1_official_3002352_1790998034
    • tpch_adapted_1_official_3002366_1790998035

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 24, 2026
@artemkulyk

artemkulyk commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

The ARM perf shard 4/6 failed on timeseries_to_grid_aggregation_functions 25 and 27. Those are GROUP BY on a plain integer, no LowCardinality, so they don't go through this change. The times (0.35s and 0.37s) are in the usual range for those queries on master. I can't rerun the job from here.

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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 24a79127f with master bd202925d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

581 translation units recompiled, 5671 s compile time in total, 581 of them have a recent master baseline.

Job report

@artemkulyk

Copy link
Copy Markdown
Contributor Author

The four failed checks are unrelated to this change; could someone rerun them?

  • Integration tests (amd_tsan, 1/6): pytest session timeout (7200 s) after 1350 passed / 20 skipped, no test failed.
  • Stress test (arm_release): known crash "GroupingAggregatedTransform pushed bucket 0 twice" ([CI crash] GroupingAggregatedTransform pushData failure #115986, STID 3994-4c1d) - 206 occurrences in the last 90 days, including master CI runs.
  • Performance Comparison (amd_release, 3/6): "math_exp Repair subtree2 #2" has no GROUP BY and no LowCardinality; flagged slower 32 times vs 5199 success in 90 days, also flagged on master (2026-09-23) and passed in this PR's earlier run at 03:35.
  • Performance Comparison (arm_release, 4/6): "timeseries_to_grid_aggregation_functions Error fetching data from materialized view #7" groups by a plain UInt16 key; 194 slower + 490 unstable vs 6338 success, also flagged on master.

@alexey-milovidov alexey-milovidov self-assigned this Sep 25, 2026
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
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 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! This is a great optimization!

Comment thread src/Columns/ColumnLowCardinality.cpp Resolved
…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]>
@artemkulyk

Copy link
Copy Markdown
Contributor Author

Thanks! This is a great optimization!

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

Copy link
Copy Markdown
Member

🕵 Pushed 95a56b0: the flaky-check reds were the new test 05289_low_cardinality_serialized_group_by_external exceeding the 180 s limit under debug/sanitizer builds (every 4096-row block of 400000 rows was spilled). It now uses 10x fewer rows; the external query still spills (4 parts, merged once) and all comparisons are kept.

@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 (re2_regex_caching #3 — like with non-constant needles over numbers_mt, no GROUP BY or LowCardinality, so it does not touch this change; possibly one of the unstable tests from #100759) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Findings so far:

  • The red is the dashboard gate only: the shard's own report has re2_regex_caching #3 as success, and C3 did use master history this time (30 points, 19.1% noise, 38.3% bar vs +47.6%), so the missing-history question on Add GradualResizeProcessor to limit effective parallelism for GROUP BY on small data volumes #99495 does not cover it.
  • The query is noisy on amd by itself. Both sides are tight (p10-p90: old 0.070-0.076 s, new 0.109-0.112 s) but offset by 47%. Over the last 14 days of master, the within-run new/old ratio was at least 1.30 in 63 of 508 amd runs and at most 1/1.30 in 67 (arm: 3 and 2 of 503). #5 and #6, the other 10-pattern variants, are similarly noisy on amd (#6 is -23% in this same run), while the constant-needle #0/#1 had no in-tree flags in that window. Earlier heads of this PR had #3 at 92/96, 67/67 and 77/75 ms (old/new) on amd.

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.

@groeneai

Copy link
Copy Markdown
Collaborator

The cause is in the function, not the fixture: with a non-constant pattern, LIKE and match incremented RegexpLocalCacheHit/RegexpLocalCacheMiss once per row on a counter shared by all threads of the query. #122764 adds them once per block instead.

pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Sep 29, 2026
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121795&sha=95a56b0fcccabd72181373b3e906d9c02db9ec53&name_0=PR — qbit_l2_distance_float64_memory #0/#1 (amd 6/6, L2DistanceTransposed + ORDER BY ... LIMIT over a Memory table) and lower_upper_utf8_mixed_ascii #4 (arm 2/6, lowerUTF8/upperUTF8 over plain String columns). Neither query has GROUP BY or LowCardinality, so they do not exercise this change (which only touches the LowCardinality serialized-key aggregation path). Both job reports are also labelled disk-almost-full/under-utilized CPU. Please provide a fix in a separate PR, or link it here if one is already in progress. (Thanks for #122764 for the earlier re2_regex_caching red.)

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. Findings so far:

  • lower_upper_utf8_mixed_ascii #4 is lowerUTF8(mixed_01_clustered), one of the two queries Stabilize the mixed_01_clustered queries of the lower_upper_utf8_mixed_ascii performance test #122728 stabilizes (12 -> 14 ms here, the per-process two-level pattern described there). Stabilize the mixed_01_clustered queries of the lower_upper_utf8_mixed_ascii performance test #122728 merged at 2026-09-28 22:31Z, after these jobs started (19:43Z), so this run did not include it; a master merge picks it up.
  • qbit_l2_distance_float64_memory #0/#1: 1039 -> 2406 ms and 157 -> 328 ms, on the new server only. This is a single run: over 30 days the 99.9th percentile of #0::new on amd is 1405 ms (1800 runs, master and PRs), and the four previous heads of this PR had new and old within 1.1% (982-1128 ms), including a52fe4d, which has the same source (95a56b0 only changes a test). The other 400 queries of the shard have a median new/old ratio of 1.00 (p5 0.96, p95 1.02), and arm plus the float32 and bfloat16 variants on the other amd shards are success, so the disk-almost-full/under-utilized CPU labels alone do not explain it. Both queries read the same Memory table, filled separately in each server.

I'll follow up here with a PR, or with my findings for the qbit one if there is nothing to fix in the code or the test.

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Follow-up on qbit_l2_distance_float64_memory #0/#1 (amd 6/6): this is code placement in this build, not this change, and there is nothing to fix in the code or the test.

  • It follows the binary, not one server process. The harness's confirmation run after restarting both servers measured the same ratio (#0: new 2.38-2.45 s vs old 1.01-1.07 s in all 7 runs; confirm_changes: 0 of 2 flagged queries did not reproduce after restart). The restart keeps the binaries, so it cannot demote this.
  • The job's CPU profiles put all of the extra time in two frames: untransposeBitPlaneFloat64Impl (769 -> 2370 samples) and its calling loop in FunctionArrayDistance<L2DistanceTransposed>::executeImpl (369 -> 1106). User CPU time is 2.36x for the same rows and bytes read.
  • Both functions have identical instructions in this build and in the build of a52fe4d (same source, 95a56b0 only changes a test; #0 new/old 0.99 there), at the same offsets mod 64. Only their addresses moved (by 0x1dc0 and 0x780 bytes), because code linked before them changed size between the two master bases (b588744 and ac31ad6).
  • It happened in 1 of the 590 amd builds that ran this test since 2026-09-25 (PRs and master); the next highest ratio is 1.05.

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. Merged master into the branch (b4277fe), which pulls in #122728 for the lower_upper_utf8_mixed_ascii red and produces a fresh build for the qbit_l2_distance_float64_memory code-placement outlier. The merge was clean, and the three changed translation units compile.

Comment thread src/Interpreters/Aggregator.cpp Resolved
`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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 2, 2026
alexey-milovidov and others added 2 commits October 3, 2026 01:10
…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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into ClickHouse:master with commit fafc3c4 Oct 4, 2026
149 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). external Author is not a member of the ClickHouse organization 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