Skip to content

Lay out the consecutive-keys cache so no per-row store crosses a 16-byte boundary - #125280

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/consecutive-keys-cache-layout
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/consecutive-keys-cache-layout

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112928

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

set_packed_keys query #1 (a keys64 (UInt32, UInt32) IN probe) runs about 22% slower in a few percent of arm PR binaries since 2026-10-10, on every run of the binary: 8 of 330 PR runs, 0 of 58 master runs, e.g. #112928 perf 3/6, where it is the only slower query.

All extra samples are in Set::executeImplCase<SetMethodKeysFixed<...UInt64...>>, whose machine code is identical in every such build. Its per-row loop keeps the consecutive-keys cache on the stack and, on every miss, writes misses and value with one 16-byte stp at an offset that is 8 mod 16. Whether that store crosses a cache line depends on unrelated code (caller stack depth, static TLS size). Of the 37 CI arm binaries with this code that I inspected, the 16 where it does not cross are all fast; of the 21 where it crosses, the 7 slow ones are exactly those whose frame lands at one particular stack position.

The change puts misses first in LastElementCacheBase, keeps value at its offset with alignas(max(alignof(Value), 8)), and aligns the cache member to 16 bytes only in states that use the cache. Each per-row store is then an aligned 8-byte store or a 16-byte store at a 16-aligned address. States without the cache (join key getters, key8/key16 sets) keep their exact layout.

Validation on aarch64 objects, master vs this PR: the keys64 probe's stp x17, x10, [sp, #0x88] becomes str x17, [sp, #0x90] + str x10, [sp, #0xa0]; paired misses+value stores go 17 -> 0 in Set.cpp.o and 149 -> 0 in Aggregator.cpp.o; HashJoin.cpp.o is byte-identical. 267 stateless tests pass. I have no arm hardware and this PR's reference build is usually fast, so the removal of the slow mode is inferred, not measured; arm PR runs after merge will show it.

🤖 Generated with Claude Code


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

…ytes

`set_packed_keys` query ClickHouse#1 (keys64 `(UInt32, UInt32) IN (subquery)`) runs
about 22% slower in a few percent of arm PR binaries, on every run of that
binary. All extra time is in `Set::executeImplCase<SetMethodKeysFixed<keys64>>`,
whose code is identical in every build. Its per-row loop keeps
`LastElementCache` (empty@0, found@1, misses@8, value@16) on the stack and on
every miss writes `misses` and `value` with one 16-byte `stp` at an offset that
is 8 mod 16. Whether that store crosses a cache line is decided by unrelated
code (caller stack depth, static TLS size); all slow CI builds have the
crossing placement.

Put `misses` first and keep `value` at +16 via
`alignas(max(alignof(Value), 8))`, so every `LastElementCache` keeps its size,
alignment and `value`/`is_null` offsets. Align the cache member to 16 only in
states with `consecutive_keys_optimization`, so states without the cache
(join key getters, key8/key16 sets) keep their exact layout. `misses` and
`value` are no longer adjacent, and each per-row store is an aligned 8-byte
store or a 16-byte store at a 16-aligned address.

aarch64 objects, master vs this change: the keys64 probe's
`stp x17, x10, [sp, #0x88]` becomes `str x17, [sp, #0x90]` and
`str x10, [sp, #0xa0]`; one-pair `misses`+`value` stores go 17 -> 0 in
Set.cpp.o and 149 -> 0 in Aggregator.cpp.o; HashJoin.cpp.o is byte-identical.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings over 2 passes) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The arm slow-mode removal is claimed without an arm before/after measurement AGREE, fixed in the PR text No arm hardware here, so I narrowed the contract: the title states the layout change, and the description says the slow-mode removal is inferred, not measured, with post-merge arm runs as the check
2 ⚠️ The optimizer could still combine cache writes into a store that crosses 16 bytes DISAGREE aarch64 objects from the same toolchain and flags: cache-write sites crossing 16 bytes are 0 of 33 in Set.cpp.o and 0 of 345 in Aggregator.cpp.o; the keys64 per-row stp x17, x10, [sp, #0x88] becomes two 8-byte str; HashJoin.cpp.o is byte-identical
3 💡 alignas(cond ? 16 : alignof(Cache)) would be ill-formed for a cache-enabled Value aligned above 16 noted, not blocking No such Value exists; clang rejects an under-aligned alignas at compile time, so it cannot change a layout silently
4 💡 The census sentence omitted the 14 fast builds whose store also crosses a line AGREE, fixed in the PR text Description now gives both counts

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261011-223400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Static: the aarch64 object of Set.cpp on master reproduces the CI binary's per-row stp x17, x10, [sp, #0x88] (cache at sp+0x80, frame 0x1d0) on demand. The timing itself needs arm hardware and a line-crossing draw, which I do not have.
b Root cause explained? The keys64 IN probe keeps LastElementCache (empty, found, misses, value) on the stack and writes misses + value with one 16-byte pair at 8 mod 16 on each miss; it crosses a cache line when unrelated code (stack depth, static TLS size) puts the cache base at a matching position. The 16 CI builds without that placement are all fast; of the 21 with it, the 7 slow ones are exactly those at one stack position.
c Fix matches root cause? Yes: the layout of the per-row state is the only local lever; no test, harness or gate change.
d Test intent preserved / new tests added? No new test: tests/performance/set_packed_keys.xml is the oracle in perf CI. 267 stateless tests (IN, DISTINCT, nullable keys, aggregation in order, consecutive keys) pass; 6 of them 50x with randomized settings: 300/300.
e Both directions demonstrated? aarch64 objects BASE vs FIX: one-pair misses+value stores 17 -> 0 (Set.cpp.o), 149 -> 0 (Aggregator.cpp.o); line-crossing at real stack offsets 9 -> 0 (Set.cpp.o).
f Fix is general across code paths? One cache type serves every hash method with the consecutive-keys cache (Set probe and build, GROUP BY, DISTINCT). HashJoin.cpp.o (cache disabled) is byte-identical.
g Fix generalizes across inputs (params/datatypes/wrappers)? Layout probed for Value of 1 to 40 bytes (UInt8..UInt256, string_view, PairNoInit<UInt64/UInt128, char *>), nullable and not: size, alignment and value/is_null offsets unchanged; UInt256 values are written as 16-aligned pairs.
h Backward compatible? (maintainer-approved exception only) Yes: per-block in-memory state only; no serialization, setting or format change.
i Invariants and contracts preserved? Fields are used by name only. States without the cache keep their exact size and alignment; states with it gain 16-byte alignment (and up to 8 bytes); all are stack locals, and the stack and operator new are 16-aligned.

Session id: cron:clickhouse-impl-slot-6:20261011-211700

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9fe99ed]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, targeted) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb
Integration tests (arm_binary, distributed plan, targeted) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb
Integration tests (amd_tsan, targeted) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb
Integration tests (arm_binary, 1/4) FAIL
test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested FAIL cidb
test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected FAIL cidb

AI Review

Summary

This PR reorders LastElementCacheBase and over-aligns the cache/value members in src/Common/ColumnsHashingImpl.h so the hot-path cache stores land on 16-byte-aligned addresses without changing the cache's observable behavior. I did not find a correctness or integration issue in the current code: the change is confined to layout, the cache is only accessed through typed members, and the non-cache instantiations are left on their existing layout path.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9fe99eda1 with master ef230ad3f (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.

Object file sizes

48 object files changed (+44.23 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 23.34 MiB 23.38 MiB +36.35 KiB (+0.15%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

Picks up ClickHouse#125292, the fix for test_copy_of_temporary_table_under_unrelated_name.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d50226a

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
Integration tests (arm_binary, 2/4) / test_database_disk/test.py::test_copy_of_temporary_table_under_unrelated_name not from this PR (it only changes the cache layout in ColumnsHashingImpl.h): the test still expected a startup failure that the duplicate-UUID rule of #123902 no longer produces, and it failed the same way on about 70 other PRs and on master at the time. The tested tree predates the test fix #125292 (mine, merged), merged master @ 9fe99ed
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR: the previous-release (26.9) server's DDL queue is wedged by the KILL PART_MOVE_TO_SHARD entry of 05082, so the upgraded server replays the backlog (the BACKUP ... ON CLUSTER of 02907 whose initiator was killed, and a CREATE TABLE of ddl_test_for_opentelemetry that hits TABLE_ALREADY_EXISTS) #122132 (mine, merged); it still needs its 26.9 backport (requested on #122132)
Mergeable Check, PR praktika rollups of the rows above #125292 and #122132 (mine, merged), as above

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261012-140015

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9fe99ed

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
Integration tests (amd_asan_ubsan, db disk, targeted), (amd_tsan, targeted), (arm_binary, 1/4), (arm_binary, distributed plan, targeted) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested not from this PR (it only changes the cache layout in ColumnsHashingImpl.h): the Spark 4.0 runner image of #117198 broke this test on master, where it failed on every commit between that merge and its revert, and on more than 70 other PRs. The tested tree predates the revert #125455 (external, merged)
Integration tests (arm_binary, 1/4) / test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected same cause as the row above #125455 (external, merged)
Mergeable Check, PR praktika rollups of the rows above #125455 (external, merged), as above

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-020010

This branch has not been deployed

No deployments
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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant