Skip to content

Deserialize complex dictionary keys in the reading streams - #123883

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:complex-key-dictionary-read-per-block
Oct 5, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:complex-key-dictionary-read-per-block

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 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):

A full scan of a complex-key hashed, sparse_hashed, hashed_array or range_hashed dictionary (SELECT ... FROM <dictionary> or the dictionary table function) is faster: each reading stream now deserializes only the keys of its own block instead of one thread deserializing all keys before reading starts. A scan with LIMIT deserializes only the blocks it reads. A full scan also no longer keeps all deserialized keys in memory at once.

Description

Related: #119118

Failing job: Performance Comparison (arm_release, master_head, 4/6) on #119118, hashed_dictionary #11 (SELECT * FROM complex_key_hashed_dictionary FORMAT Null) +38.8%.

read of a complex-key hashed, hashed_array or range_hashed dictionary deserialized all keys into columns on the calling thread before DictionarySourceCoordinator started any stream, and every block then cut its range out of those columns. For the 5M-key perf dictionaries this serial loop is about half of the query, and the CPU profiles of the slow ARM runs put all of the extra time in it.

Now the coordinator gets the serialized keys (views into the dictionary's own arenas, kept alive by the coordinator) and each stream deserializes its own [start, end) range. CacheDictionary is unchanged: its keys are only valid under its lock.

Measured on x86 with the queries of the existing tests/performance tests, base vs this PR:

  • hashed_dictionary #11: 0.825 -> 0.608 s
  • hashed_array_dictionary #21: 0.498 -> 0.282 s
  • range_hashed_dictionary #9: 0.269 -> 0.140 s
  • SELECT * FROM complex_key_hashed_dictionary LIMIT 1: 0.311 -> 0.080 s
  • simple-key controls #5, hashed_array #10, range_hashed #4: no difference proven

I expect the ARM slow builds to lose most of the +38%; this PR's own ARM perf run is the first measurement there.

The new test 05321_complex_key_dictionary_read_per_block checks all five complex-key layouts and that a full scan of a dictionary with 32 MiB of keys runs under max_memory_usage = '16Mi' (on master it fails with MEMORY_LIMIT_EXCEEDED).

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 4, 2026 15:47
`read` of complex-key `hashed`, `hashed_array` and `range_hashed`
dictionaries deserialized all keys into columns on the calling thread
before any stream started, and every block then cut its range out of
those columns. For a large dictionary this serial loop is a large part
of a full scan.

Pass the serialized keys to `DictionarySourceCoordinator` instead. Each
block deserializes its own range of keys in the stream that reads it, so
the work runs in parallel, the per-block copy of the key columns is gone,
and a scan with `LIMIT` deserializes only the blocks it reads. Blocks keep
the same rows, columns and `DictionaryBlockNumber`.

The serialized keys point into the dictionary's arenas, and the
coordinator holds the dictionary, which is immutable after loading.
`CacheDictionary` keeps deserializing eagerly: its keys are only valid
under the storage lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mory

A full scan of a `hashed`, `hashed_array` or `range_hashed` dictionary
with 32 MiB of complex keys now runs under `max_memory_usage = '16Mi'`.
Before the per-block key deserialization, `read` materialized every key
on the query's thread first and the same queries failed with
`MEMORY_LIMIT_EXCEEDED`, so the test fails if the eager path comes back.

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 4, 2026
@groeneai

groeneai commented Oct 4, 2026

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 rounds, 1 finding) plus my own review (3 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test only compared output, so it also passed with the old eager key deserialization AGREE, fixed added memory-capped full scans for the three changed read implementations; on master each fails with MEMORY_LIMIT_EXCEEDED, with this PR they pass
2 💡 has_serialized_keys is redundant except for the zero-key stream limit AGREE, not changed no behavioural effect
3 💡 setSerializedKeys has a call-before-read contract; a constructor argument would enforce it AGREE, not changed all three call sites follow it
4 💡 The test's opening DROP ... IF EXISTS list does not name the three big dictionaries AGREE, not changed each is dropped right after its query

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20261004-165600

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? On x86, clickhouse benchmark A/B on two pinned release servers loaded from tests/performance/{hashed,hashed_array,range_hashed}_dictionary.xml: #11, #21, #9 and LIMIT 1 differ at 99.5% confidence on every run. The ARM per-build slow mode cannot be reproduced locally (no ARM host); this PR's ARM perf run is the first measurement there.
b Root cause explained? A complex-key full scan deserialized every key on the calling thread before any stream started. That serial loop is about half of #11, and the slow ARM job profiles put all of the extra time in it.
c Fix matches root cause? Yes: each stream deserializes only its own block's keys, so the serial phase is gone. No perf test, threshold or setting is changed.
d Test intent preserved / new tests added? New 05321_complex_key_dictionary_read_per_block checks every key and value for five complex-key layouts at max_block_size = 7, max_threads = 4, plus LIMIT, and that a full scan of a dictionary with 32 MiB of keys (hashed, hashed_array, range_hashed) runs under max_memory_usage = '16Mi'. 50/50 with random settings. The 41 existing tests using these layouts pass in a debug build (40 run, 1 skipped by its own no-debug tag).
e Both directions demonstrated? Perf, base vs this PR: #11 0.825 -> 0.608 s (both port orders), #21 0.498 -> 0.282 s, #9 0.269 -> 0.140 s, LIMIT 1 0.311 -> 0.080 s; simple-key #5, #10, #4 show no difference. The new test fails on all five layouts when a block reads [0, length) instead of [start, end), and on master its three memory-capped scans fail with MEMORY_LIMIT_EXCEEDED (the rest of the file passes).
f Fix is general across code paths? All three complex-key read implementations that deserialized eagerly: HashedDictionary (incl. sparse and sharded), HashedArrayDictionary, RangeHashedDictionary. CacheDictionary is unchanged on purpose: its keys are only valid under its lock.
g Fix generalizes across inputs (params/datatypes/wrappers)? Key columns go through the same generic per-column deserializer as before, only over [start, end). Empty dictionary gives zero blocks, as before; the last block's bound is unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or result change; blocks keep the same rows, columns and DictionaryBlockNumber.
i Invariants and contracts preserved? The key views point into the dictionary's arenas; the coordinator holds the dictionary, which does not change after loading. Streams only read the views and build their own columns. For range_hashed the key_to_index column stays last, where read_keys_func reads it.

Session id: cron:clickhouse-impl-slot-5:20261004-164400

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12df8fd]

Summary: ✅


AI Review

Summary

This PR moves complex-key deserialization for hashed, sparse_hashed, hashed_array, and range_hashed dictionary scans from the caller thread into the per-block reading streams, so full scans no longer materialize every deserialized key column up front and LIMIT queries only deserialize blocks that are actually pulled by the pipeline. I did not find a correctness, lifetime, ordering, or concurrency issue in the current implementation, and the new stateless test covers the affected layouts plus the memory-regression case that motivated the change.

Missing context / blind spots
  • ⚠️ Several heavyweight CI jobs were still pending on 2026-10-04, so I could not use completed sanitizer/build results as additional confirmation beyond the code review and the already-passing Fast test / Style check jobs.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 12df8fd.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 92.20% +0.40%
Branches 79.60% 79.60% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 4, 2026
@groeneai
groeneai requested review from nihalzp and vdimir October 4, 2026 17:23
@clickhouse-gh clickhouse-gh Bot added the comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 12df8fdf5 with master d82b0ca11 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of c586d7a82; 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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 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: 149ee380-6b50-44ed-9104-e177675fd820
  • MIRAI run: 7ec15b0b-c697-4f46-875f-03d495c765f8
  • PR check IDs:
    • clickbench_3227493_1791140746
    • clickbench_3227506_1791140746
    • clickbench_3227512_1791140746
    • tpch_adapted_1_official_3227529_1791140747
    • tpch_adapted_1_official_3227549_1791140746
    • tpch_adapted_1_official_3227563_1791140747

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Oct 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 5, 2026
Merged via the queue into ClickHouse:master with commit b62bc5c Oct 5, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 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-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants