Skip to content

Do not instantiate the range_hashed dictionary lookup for every attribute type - #126978

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/range-hashed-dictionary-instantiation-diet
Oct 22, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/range-hashed-dictionary-instantiation-diet

Conversation

@groeneai

@groeneai groeneai commented Oct 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126314

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

The range_hashed and complex_key_range_hashed dictionary lookup is no longer instantiated for every attribute type, which removes about 47 MiB of code from the MSan build and about 6 MiB from a release build.

Description

RangeHashedDictionary::getItemsImpl and getItemsShortCircuitImpl ran the key + range lookup (hash map find and IntervalTree::find) inside the callOnRangeType lambda. So the loop was compiled for every key type, nullability, attribute type and range column type, 2000 copies in each of the two functions under MSan plus 8800 IntervalTree callback copies, although nothing in it depends on the attribute type. The lookup is now one non-template member, findValueIndexes, returning each key's value index; the two getItems functions copy values by these indexes.

Built locally on 2ad32ae943cfe with the CI amd_msan and amd_binary cmake lines (the MSan base matches the CI artifact within 0.01 MiB):

Before After Change
MSan .text 1650.25 MiB 1602.68 MiB -47.57 MiB (headroom to the 2 GiB relocation limit 208.5 -> 257.7 MiB)
Release (no LTO) .text 470.90 MiB 464.49 MiB -6.41 MiB
Compile time of RangeHashedDictionary{Simple,Complex}.cpp and the 10 RangeHashedDictionaryGetItems*.cpp, MSan / release 700 s / 368 s 132 s / 100 s -81% / -73%

Validation: an equivalence probe (simple and complex keys, 11 attribute types, 9 range types, min/max strategy, open bounds, every dictGet* variant, query_count) gives byte-identical output on master and on this branch (debug and MSan), and each of three mutations of the new code changes it. Of 295 dictionary stateless tests the same 278 pass on master and here, and the 15 range_hashed tests pass 50 of 50 randomized runs. A pinned release benchmark (15 rounds, A/A control) shows no slowdown for simple and complex-key dictGet, lazy-default dictGetOrDefault and a Nullable(String) attribute. 02950_dictionary_short_circuit gains a range_hashed query with intDiv(1, id) as the lazy default, which throws if evaluated for the found row id = 0.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.501-master (included in 26.11 and later)

groeneai and others added 2 commits October 20, 2026 14:56
…bute type

`getItemsImpl` and `getItemsShortCircuitImpl` ran the whole key + range
lookup (key extraction, hash map find, `IntervalTree::find` with the
min/max callback) inside the `callOnRangeType` lambda, so the lookup loop
was instantiated for 2 key types x 2 nullability x 25 attribute types x 20
range column types: 4000 copies, plus 8800 `IntervalTree` callback
copies, although nothing in the lookup depends on the attribute type.

Move the lookup into one non-template member `findValueIndexes`, which
stores the value index of each key (or `value_index_not_found`), and make
the two getItems functions plain copy loops over these indexes.

Measured on 2ad32ae (local builds of the CI AMD_MSAN / AMD_BINARY
cmake lines; the local MSan base matches the CI artifact within 0.01 MiB):
- amd_msan: .text 1650.25 -> 1602.68 MiB (-47.57), 2 GiB reach headroom
  208.48 -> 257.73 MiB.
- release without LTO: .text 470.90 -> 464.49 MiB (-6.41).
- The 12 RangeHashedDictionary TUs compile in 132 s instead of 700 s
  (MSan) and 100 s instead of 368 s (release), summed per-file time.

A pinned release benchmark (15 rounds with an A/A control) shows no
slowdown for simple and complex-key dictGet, lazy-default dictGetOrDefault
and a Nullable(String) attribute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ound row from a default

The found row's value is NULL and the old default `intDiv(NULL, id)` was NULL too, so the case passed whether or not the found row was masked; with `intDiv(1, id)` the found row must stay NULL without evaluating `intDiv(1, 0)`, and the missing row gets 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 rounds, 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ 02950_dictionary_short_circuit: the range_hashed case cannot tell a found row from a missing one (found value NULL, default intDiv(NULL, id) also NULL) AGREE, fixed @ 74714a5 the default is now intDiv(1, id) as in the other layouts of the test: the found row must keep NULL without evaluating intDiv(1, 0), the missing row gets 1; masking the found row now fails with ILLEGAL_DIVISION, not masking the missing row fails the reference
2 💡 the new copy loops look like the read path's getItemsInternalImpl DISAGREE that one throws on an index past the container and counts every key as found; the dictGet paths need a not-found branch
3 💡 the 10 RangeHashedDictionaryGetItems*.cpp files could now be merged DISAGREE not needed for the saving; keeps the diff minimal

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation (a-i)
# Question Answer
a Deterministic repro The size is deterministic: llvm-nm -S -C over the linked amd_msan binary. The base has 4600 getItems* symbols (27.97 MiB) plus 8800 IntervalTree callback copies (19.76 MiB) from it. A local build of the base matches the CI artifact of 2ad32ae943cfe to within 0.01 MiB.
b Root cause The key + range lookup loop ran inside the callOnRangeType lambda of getItemsImpl / getItemsShortCircuitImpl, so it was instantiated for 2 key types x 2 nullability x 25 attribute types x 20 range types. Nothing in the lookup depends on the attribute type.
c Fix matches root cause The lookup is now one non-template member findValueIndexes (2 key types x 20 range types). The getItems functions are plain copy loops over its result, so only the copy loop is still instantiated per attribute type.
d Tests No behaviour change, so no new test; the range_hashed case of 02950_dictionary_short_circuit now uses intDiv(1, id) as the lazy default, so it fails if a found row is masked or a missing one is not. Behaviour is pinned by existing suites plus a 310-line equivalence probe (simple/complex keys, 11 attribute types incl. Nullable/Array/Map/JSON, 9 range types, min/max strategy, open bounds, dictGet/dictGetOrDefault const + lazy/dictGetOrNull, query_count/found_rate).
e Both directions Probes are byte-identical between master and the fix (debug and MSan). Three mutations of the new code each change the probe output: short-circuit mask 446 lines, max strategy 26, nullable bit 70.
f Code paths hasKeys has the same loop shape but is only 2 x 20 copies (0.22 MiB), so it is left as is. getItemsInternalImpl (read path) is unchanged. The other hashed layouts have no range dimension.
g Inputs Equivalence matrix as in (d). Range types: UInt64, Date, Date32, DateTime, DateTime64 (complex key), Int8 and Decimal32 with NULL bounds, Int128, Float64. Rows cover hits, key misses, range misses and inclusive bounds.
h Backward compatibility No setting, format or stored state is touched.
i Invariants Same value / default / mask bit per row, same query_count / found_count. TYPE_MISMATCH and std::get still run before any set_value. The complex-key arena is still rolled back per key.

@clickhouse-gh

clickhouse-gh Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5641e6a]

Summary: ✅


AI Review

Summary

The PR extracts the shared key and range lookup into RangeHashedDictionary::findValueIndexes, reducing template instantiation while retaining type-specific value copying. Review of head 5641e6a9307b36063427594c34a3947eceb9f7f0 found no actionable issues. The author's response to the existing test-preservation thread is reflected in the current diff.

Missing context / blind spots
  • ⚠️ Current-head CI is still running. No local build or executable was available. The preceding commit has the same implementation and passed 02950_dictionary_short_circuit in 25 repeated CI runs; completion of current-head CI will validate the final test-only change.
Final Verdict

✅ Approve. No new inline findings; normal CI completion remains pending.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @vdimir, could you review this and add the can be tested label so CI runs? Stage 3 of #126314: the range_hashed key + range lookup moves out of the per-attribute-type lambda into one non-template findValueIndexes, so getItemsImpl and getItemsShortCircuitImpl are only copy loops per attribute type, which removes 47.6 MiB of code under MSan and 6.4 MiB from a release build without LTO.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Oct 20, 2026
@Algunenano Algunenano self-assigned this Oct 20, 2026
@Algunenano Algunenano added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors labels Oct 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). label Oct 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 74714a5

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_asan_ubsan, azure, parallel) / 02010_lc_native flaky, not from this PR (it changes only RangeHashedDictionary): TimeoutError: timed out in insertValidLowCardinalityRow waiting for End of stream after the test's hard-coded 30 s socket deadline; the 3 reruns passed. #121512 (merged, present in this head) covers the stack-trace path only, not this valid-insert path a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
PR praktika rollup of the row above a fix task is moved to pending (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

The Config Workflow / Pre Hooks failure on this head is the earlier attempt stopped at the can be tested label; the current attempt passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261020-193013

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 02010_lc_native (valid-insert socket timeout in Stateless tests (arm_asan_ubsan, azure, parallel)): #127034


SELECT 'Range hashed dictionary';
SELECT dictGetOrDefault('range_hashed_dictionary', 'val', id, toDate('2023-01-02'), intDiv(NULL, id))
SELECT dictGetOrDefault('range_hashed_dictionary', 'val', id, toDate('2023-01-02'), intDiv(1, id))

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.

@groeneai I don't like this. Please add a extend the test instead of changing it, otherwise we can think that the behaviour was changed by this PR which would be wrong

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 5641e6a: the intDiv(NULL, id) query and its reference are back as on master, and the intDiv(1, id) query is added after it as a new case.

… and add the intDiv(1, id) one next to it

The behaviour is unchanged, so the existing query and reference stay as on master; the added query uses `intDiv(1, id)` as the lazy default, which throws if it is evaluated for the found row `id = 0`, and returns 1 for the missing row.

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

clickhouse-gh Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5641e6a93 with master 9c39d7d58 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 06dd230d2; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: binary sizes, object file sizes.

Binary sizes ⚠️
Binary Master PR Δ
programs/clickhouse-stripped 782.65 MiB 760.60 MiB -22.05 MiB (-2.82%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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 ⚠️

16 object files changed (-28.77 MiB total), 0 added.

Object file Master PR Δ
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsShortCircuitIm… 4.07 MiB 74.84 KiB -4.00 MiB (-98.21%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsImplOthers.cpp… 4.06 MiB 76.46 KiB -3.99 MiB (-98.16%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsShortCircuitIm… 3.34 MiB 42.80 KiB -3.30 MiB (-98.75%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsShortCircuitIm… 3.34 MiB 42.71 KiB -3.30 MiB (-98.75%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsImplInt.cpp.o 3.33 MiB 41.47 KiB -3.29 MiB (-98.78%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsImplUInt.cpp.o 3.33 MiB 41.36 KiB -3.29 MiB (-98.79%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsShortCircuitIm… 2.82 MiB 38.36 KiB -2.78 MiB (-98.67%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsImplDecimal.cp… 2.81 MiB 37.47 KiB -2.77 MiB (-98.70%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsShortCircuitIm… 1.19 MiB 23.20 KiB -1.17 MiB (-98.10%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryGetItemsImplFloat.cpp.o 1.19 MiB 21.37 KiB -1.17 MiB (-98.24%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionaryComplex.cpp.o 1.56 MiB 1.72 MiB +160.24 KiB (+10.03%)
src/Dictionaries/CMakeFiles/clickhouse_dictionaries.dir/RangeHashedDictionarySimple.cpp.o 1.47 MiB 1.60 MiB +129.93 KiB (+8.63%)

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

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

Median compile-time ratio to the baselines is ×0.44 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -107.7 s (-51%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Dictionaries/RangeHashedDictionaryComplex.cpp 17.2 s 18.3 s +10.7 s (+143%)
src/Dictionaries/RangeHashedDictionarySimple.cpp 16.5 s 17.9 s +10.7 s (+149%)
src/Dictionaries/registerRangeHashedDictionary.cpp 8.1 s 8.7 s +5.1 s (+146%)

Slowest changed entities of src/Dictionaries/RangeHashedDictionaryComplex.cpp:

  • InstantiateFunction DB::callOnIndexAndDataType<void, (lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:30…: +2.7 s
  • InstantiateFunction DB::callOnIndexAndDataType<void, (lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:30…: -1.0 s (-100%)
  • InstantiateFunction DB::impl::callOnRangeType<(lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:952:56)>: +1.1 s

Slowest changed entities of src/Dictionaries/RangeHashedDictionarySimple.cpp:

  • InstantiateFunction DB::callOnIndexAndDataType<void, (lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:30…: +2.7 s
  • InstantiateFunction DB::callOnIndexAndDataType<void, (lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:30…: -0.9 s (-100%)
  • InstantiateFunction DB::impl::callOnRangeType<(lambda at /ClickHouse/src/Dictionaries/RangeHashedDictionary.h:952:56)>: +1.2 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::FunctionNumericIndexedVectorHelper<DB::FunctionNum… 86.01 KiB removed -86.01 KiB (-100.00%)
programs/clickhouse-keeper COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::FunctionNumericIndexedVectorHelper<DB::FunctionNum… 85.73 KiB removed -85.73 KiB (-100.00%)
programs/clickhouse COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::FunctionNumericIndexedVectorHelper<DB::FunctionNum… 85.55 KiB removed -85.55 KiB (-100.00%)
programs/clickhouse COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::FunctionNumericIndexedVectorHelper<DB::FunctionNum… 85.18 KiB removed -85.18 KiB (-100.00%)

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5641e6a

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_storage_kafka/test_multi_consumer_quota.py::test_temporary_lock_quota_is_retained_across_rounds flaky, not from this PR (it changes only RangeHashedDictionary and the 02950 test): the new test requires a non-zero temporary-lock quota for 4 consecutive rounds, but the co-located consumers' rounds rotate the quota with period 3; it failed the same way on master and on 15+ unrelated PRs since 2026-10-20 #126965 (mine, open)
Mergeable Check, PR praktika rollups of the row above #126965 (the owner of the row above)

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

Session id: cron:our-pr-ci-monitor:20261021-160007

JTCunning pushed a commit to JTCunning/ClickHouse that referenced this pull request Oct 21, 2026
On the azure lane the default MergeTree storage policy is a write-through
filesystem cache. The test's valid native-protocol INSERT writes a one-row
part, and every file of that part reserves cache space under the cache's
priority write lock. In Stateless tests (arm_asan_ubsan, azure, parallel) on
PR ClickHouse#126978 that INSERT spent 34.07 s of 34.43 s waiting on the lock
(FilesystemCachePriorityWriteLockMicroseconds), so the server's correct End of
stream arrived 4.4 s after the python client's hard-coded 30 s socket timeout
and the test failed with TimeoutError in readStrict.

The storage is incidental to a native-protocol LowCardinality test, so pin
the table to storage_policy = 'default' (the local disk on every lane). The
part write stays MergeTree, the 30 s hang guard and the .reference are
unchanged. Same shape as ClickHouse#122567 (04344) and ClickHouse#126252 (04949) for this lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Algunenano
Algunenano enabled auto-merge October 21, 2026 22:19
@Algunenano
Algunenano added this pull request to the merge queue Oct 21, 2026
Merged via the queue into ClickHouse:master with commit d879e48 Oct 22, 2026
353 of 354 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 22, 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). pr-build Pull request with build/testing/packaging improvement 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