Skip to content

Speed up dictGetDescendants and dictGetChildren for blocks with many parent keys - #131775

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:dict-get-descendants-clearable-loop-set
Nov 18, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:dict-get-descendants-clearable-loop-set

Conversation

@groeneai

@groeneai groeneai commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129258

Changelog category (leave one):

  • Performance Improvement

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

dictGetDescendants and dictGetChildren are faster when many keys of a block have children: the set that detects loops in the hierarchy no longer zeroes a buffer sized for the whole block once per such key. The dictGetDescendants queries of the hierarchical_dictionaries performance test run about 6x faster.

Description

detail::getDescendants (src/Dictionaries/HierarchyDictionariesUtils.h) keeps a set that detects loops in the hierarchy. It is reserved to the block's row count and cleared after every requested key that has children, and HashSet::clear zeroes the whole buffer: 1 MiB per such key at the default block size. In tests/performance/hierarchical_dictionaries.xml the first block holds 50,000 keys with children, so each dictGetDescendants query zeroes 52 GB, and memset takes 89% of its CPU samples. That is why these five queries take 1.1-1.2 s on amd CI and about half that on arm (#129258, long queries).

The set is now a ClearableHashSet, whose clear is O(1) (a version counter), as in arrayUniq and arrayDistinct. Lookups, inserts, the reserve and the loop handling are unchanged; cells grow from 8 to 16 bytes.

Validation on release builds of master with and without the change:

  • CI's perf.py over the unchanged test, 8 pinned cores, both seat orders: the five dictGetDescendants queries go from 0.98-1.04 s to 0.13-0.18 s (ratio 0.13-0.17); the ratio of the five dictGetHierarchy queries stays at 0.98-1.05.
  • dictGetChildren over the same 1M keys: 973 ms to 79 ms. One key with 1M descendants, and 950k keys without children: unchanged within noise.
  • Identical output on both builds for dictGetDescendants (all levels, levels 1 and 2) and dictGetChildren over flat, hashed, hashed with 16 shards and hashed_array dictionaries with self-loops and cycles, at block sizes 1, 7, 1000 and 65409. The HierarchyDictionariesUtils gtest and the hierarchical dictionary stateless tests (50 randomized runs each) pass.

The performance test is unchanged.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits November 15, 2026 10:03
detail::getDescendants reserves its loop-detection set to the block's
row count (65409 rows -> 131072 cells, 1 MiB) and clears it after every
requested key that has children. HashSet::clear() zeroes the whole
buffer, so the cost is (keys with children in the block) x (block size).
In tests/performance/hierarchical_dictionaries.xml the 50,000 keys with
children are all in the first block: 52 GB of memset per query, 89% of
its CPU samples.

Use ClearableHashSet, whose clear() bumps a version counter, as
arrayUniq and arrayDistinct do for a set reused per row.

Measured with perf.py over the unchanged test on release builds of
master 6ea176f, 8 pinned cores, both seat orders: the five
dictGetDescendants queries go from 0.98-1.04 s to 0.13-0.18 s (ratio
0.134-0.174), the five dictGetHierarchy queries stay at a ratio of
0.975-1.053. dictGetChildren over the same 1M keys: 973 ms -> 79 ms.
The cost no longer follows the block size: 959 ms at
max_block_size = 65409 vs 232 ms at 8192 before, 98 vs 126 ms after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the loop-set comment: clearing runs only for requested keys that have children.

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; 1 finding) plus my own cold review (1 finding).

# Sev Finding Verdict Evidence / action
1 💡 The new comment says the set is cleared after every requested key, but keys without children continue before the clear (HierarchyDictionariesUtils.h:299, l.312-315 vs l.424) AGREE, not blocking Comment wording only, no code change; handled in the final comment pass before publication
2 💡 ClearableHashSet cells are 16 B instead of 8 B, so the per-call reserve(keys_size) buffer doubles (1 MiB to 2 MiB at the default block size) AGREE, not blocking Stated in the description; one allocation per block, measured: leaves-only query +0.3-1 ms of execution per 950k rows, one-key 1M-descendants query +2 ms of ~30 ms execution, both within noise at the query level

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

Session id: cron:clickhouse-review-slot-8:20261115-100500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT dictGetDescendants('hierarchical_flat_dictionary', number + 1) FROM numbers(1000000) FORMAT Null on the test's own dictionaries: 959 ms at max_block_size = 65409 vs 232 ms at 8192 before the change (the cost follows the block size, not the rows), 98 vs 126 ms after. memset is 89% of the CPU samples before, 9.5% after.
b Root cause explained? The loop-detection set in detail::getDescendants is reserved to the block's row count (1 MiB at 65409 rows) and cleared after every requested key that has children; HashSet::clear zeroes the whole buffer. 50,000 such keys in the first block = 52 GB of memset per query.
c Fix matches root cause? Yes. The set is a ClearableHashSet, whose clear is O(1). Nothing else changes; the performance test is unchanged.
d Test intent preserved / new tests added? No test is changed. The hierarchical_dictionaries performance test measures exactly this path; the HierarchyDictionariesUtils gtest and the hierarchical dictionary stateless tests pin the semantics.
e Both directions demonstrated? Yes. perf.py over the unchanged test, both seat orders: the five dictGetDescendants queries take 0.98-1.04 s on master and 0.13-0.18 s with the change; the dictGetHierarchy ratios stay at 0.98-1.05.
f Fix is general across code paths? Yes. The one set serves dictGetDescendants (all levels and a given level) and dictGetChildren for every layout through getKeysDescendantsArray. getHierarchy and getIsInHierarchy never clear per key.
g Fix generalizes across inputs (params/datatypes/wrappers)? Output identical byte for byte on both builds over flat, hashed, hashed with 16 shards and hashed_array dictionaries, all levels / level 1 / level 2 / children, block sizes 1, 7, 1000, 65409, with self-loops, 2- and 3-cycles and absent keys; key 0 is a normal cell in ClearableHashSet. Nullable parent and NULL key tests pass.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or persisted state.
i Invariants and contracts preserved? After clear, find returns null for every key inserted before (older version = empty cell); resize keeps only current cells; the UInt32 version starts at 1 per call and grows at most once per row. Cells are 16 bytes instead of 8 (2 MiB per call at the default block size).

Session id: cron:clickhouse-impl-slot-5:20261115-084201

@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a27a9ce]

Summary: ✅


AI Review

Summary

Replacing the temporary loop-detection HashSet with ClearableHashSet removes repeated buffer clearing in dictGetDescendants and dictGetChildren. No actionable findings at PR head a27a9ce6905145b12bc33f5da3dbc2c5c359931e. Existing hierarchy tests cover both traversal strategies, zero keys, and cycles; the CI performance measurements corroborate the claimed benefit: the five descendant queries improve from 1.04–1.09 seconds to 0.139–0.182 seconds.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-dictionary Dictionaries (in-memory key-value, periodically refreshed from sources). labels Nov 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a27a9ce69 with master 4564d472d (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7df1b6c

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
Performance Comparison (amd_release, master_head, 3/6) infra, not from this PR: killed by the 7200 s job timeout (Job timed out ... exit code [-15]) while still running tests, because test selection made all 142 tests of the shard mandatory with --max-queries 0. It used the 2026-11-15 NightlyCoverage cohort (79929b2c), which collected no coverage #131772 (mine, merged after this run was created; not in the tested tree)
Performance Comparison (amd_release, master_head, 6/6) infra, same cause: killed by the 7200 s job timeout while running the 141 mandatory tests of the shard #131772 (mine, merged after this run was created; not in the tested tree)
Performance Comparison (arm_release, master_head, 6/8) / formats_columns_nullable #28 perf noise, not from this PR: the known arm slow mode of the native ORC ByteRleDecoder / BooleanRleDecoder on a File(ORC) Nullable(Int8) count (+43.7%); this PR changes only HierarchyDictionariesUtils.h #130200 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #131772, #130200 (the owners above)

The amd_release shards 1/6 (which ran hierarchical_dictionaries.xml), 2/6, 4/6, 5/6 and the other arm_release shards finished green.

Session id: cron:our-pr-ci-monitor:20261115-143011

@Algunenano Algunenano self-assigned this Nov 16, 2026
@Algunenano
Algunenano enabled auto-merge November 18, 2026 09:57
@Algunenano
Algunenano added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 78a44bb Nov 18, 2026
193 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 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-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