Skip to content

Fix out-of-bounds read of the LowCardinality saved-hash array - #115604

Merged
thevar1able merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-lowcardinality-saved-hash-bounds
Aug 21, 2026
Merged

thevar1able merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-lowcardinality-saved-hash-bounds

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114352
Related: #29782
Related: #114993

Reported on master, no issue open for it, by AST fuzzer (amd_tsan) as a ThreadSanitizer heap-use-after-free at src/Common/ColumnsHashing.h:248 on thread MergeMutate: CI report.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed an out-of-bounds read of the cached dictionary hashes when aggregating or joining on a LowCardinality(String) key whose dictionary grows while it is being aggregated, reachable from TTL ... GROUP BY. It could yield a wrong hash, and a reported heap-buffer-overflow in sanitizer builds.

Description

IColumnUnique::tryGetSavedHash() memoized the dictionary hash array on first use and returned a bare const UInt64 * with no length. ReverseIndex::calcHashes() sizes it from the dictionary size at that moment, and ReverseIndex::insert() afterwards grows only the internal copy, so nothing extended the published one. Consumers cached the bare pointer and indexed it with a current dictionary position, past the end. Only String and FixedString keys have such an array.

TTL ... GROUP BY reaches this from ordinary SQL: TTLAggregationAlgorithm builds its aggregate columns once per block, grows the dictionary in place row by row, and aggregates once per key run, so later runs index positions the first run's snapshot never covered.

This publishes the array as a std::span derived from a single owned column, so data and length always describe the same buffer, and bounds-checks all six read sites: a position inside the span uses the memoized hash, one outside takes the existing branch that hashes from the key. That branch runs today for every numeric dictionary, so no new code path appears.

Both consumers are fixed: HashMethodSingleLowCardinalityColumn (aggregation, where it was reported) and LowCardinalityKeyGetterForJoin (joins, same unbounded pointer), as is the dictionary cache, which would otherwise resurrect an unbounded pointer on a hit. I did not produce a join query that overflows. #29782 fixed the lifetime half of this contract; this fixes the bounds half.

Validation: a new stateless test kills the server during OPTIMIZE ... FINAL on master under a sanitizer build and passes with this change, 50 of 50 runs under randomized settings. The sanitizer build is the oracle, not the SQL assertion. Reverting only the bounds check brings the report back, and results are byte-identical before and after.

Validation detail

Reproduced locally with the same frames as the linked report, under ASan, which additionally attributes the overflowed region to ReverseIndex::calcHashes via tryGetSavedHash on the first executeOnBlock and reports the read as exactly 8 bytes past a 144-byte (18-slot) allocation. Instrumenting the out-of-range branch on the reproducer shows it taken over a thousand times with a snapshot of 2 entries while positions reach 9 and beyond, so without the check those reads are all out of bounds.

Reproducer:

CREATE TABLE t (k LowCardinality(String), d DateTime, v UInt64) ENGINE = MergeTree ORDER BY k
TTL d + INTERVAL 1 SECOND GROUP BY k SET v = sum(v), d = max(d)
SETTINGS min_bytes_for_wide_part = 0, index_granularity = 1024, merge_with_ttl_timeout = 100000;

INSERT INTO t SELECT number % 1000, now() - INTERVAL 1 DAY, number FROM numbers(200000)
SETTINGS max_insert_block_size = 200000;

OPTIMIZE TABLE t FINAL;

Existing coverage could not reach this: 03774_ttl_group_by_lowcardinality.sql uses numeric LowCardinality types, where there is no saved-hash array.

Taking the fallback branch cannot split a group: the memoized value comes from StringViewHash, which is also the HashMap default hash for these keys, over the same bytes getDataAt returns. GROUP BY and join results over String, Nullable(String), FixedString and numeric keys are byte-identical on both binaries.

Eight concurrent clients running GROUP BY, spilling GROUP BY, uniqExact and a parallel_hash join over one shared dictionary return identical correct results with no sanitizer reports, exercising both sides of the publication exchange.

#114993 changes the mapping caches in the same file without touching the saved hash, so the mechanisms are independent, but it extends cache lifetime across blocks here and will likely conflict textually.


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

Version info

  • Merged into: 26.8.1.1799 (included in 26.8 and later)

IColumnUnique::tryGetSavedHash() memoized the dictionary hash array on first
use and returned a bare const UInt64 * with no length. ReverseIndex::calcHashes
sizes that array from column->size() at the moment of the first call, and
ReverseIndex::insert afterwards resizes only the internal saved_hash, so nothing
ever extended or invalidated the published array. Consumers cached the bare
pointer and indexed it with a current dictionary position, which can exceed the
snapshot. The asymmetry was visible inside ReverseIndex itself: the internal
carrier stores a container pointer, which survives a resize, while the external
API exported an element pointer, which does not.

TTL ... GROUP BY reaches this from ordinary SQL. TTLAggregationAlgorithm creates
its aggregate columns once per block, grows the LowCardinality(String)
dictionary in place row by row via insertFrom -> uniqueInsertFrom ->
ReverseIndex::insert, and calls calculateAggregates once per key run, so a later
run builds a fresh aggregation state that re-reads the first run's memoized
array while indexing positions that array never covered. Only String and
FixedString dictionaries have a saved-hash array at all, which is why the
affected method is HashMethodSingleLowCardinalityColumn over HashMethodString.

Reported by AST fuzzer (amd_tsan) on master as a heap-use-after-free at
src/Common/ColumnsHashing.h:248 on thread MergeMutate. Under ASAN the same
query reports a heap-buffer-overflow whose allocation stack names
ReverseIndex::calcHashes via tryGetSavedHash on the first executeOnBlock, and
the read is exactly 8 bytes past a 144-byte, 18-slot allocation. In a release
build nothing reports it: the read silently yields a wrong hash.

Publish the array as one immutable snapshot instead. The atomic now holds the
winning ColumnUInt64, the owning holder is assigned only by the thread that wins
the exchange, and both data() and size() are derived from that single published
object, so a length can never be paired with a different buffer. Every read site
then bounds-checks: a position inside the span uses the memoized hash, a position
outside takes the branch that already exists for numeric dictionaries and hashes
from the key, so no new code path is introduced and results do not change.

Both consumers are fixed, three read sites each: the reported
HashMethodSingleLowCardinalityColumn in ColumnsHashing.h and
LowCardinalityKeyGetterForJoin in HashJoin/KeyGetter.h, which held the same
unbounded pointer but was absent from the report.
LowCardinalityDictionaryCache::CachedValues also carries the length, otherwise a
cache hit would resurrect an unbounded pointer and bypass the fix.

setColumn still deliberately does not clear external_saved_hash: that is the
lifetime half of this contract, fixed in 342ec02 (PR ClickHouse#29782), which is
also why bounding the snapshot is safe where invalidating it would not be. A
stale snapshot stays owned and readable, merely shorter than the dictionary.

The new test uses a LowCardinality(String) GROUP BY key, which existing coverage
lacked: 03774_ttl_group_by_lowcardinality.sql uses numeric LowCardinality types,
where use_saved_hash is false, so it can never reach this path.
…n test

The test left merge_max_block_size to the CI randomizer, which draws it from
randint(1, 8192*3). Pinning it to the default keeps the fixture independent of
that axis, so what the test exercises does not vary between runs.

An in-query SETTINGS value wins over the runner's --allow_merge_tree_settings
injection: ClientBase::addMergeTreeSettings only appends a setting when the
query's own clause does not already carry it. Measured with the injection
forcing 200: the table with the pin reports merge_max_block_size = 8192 in
system.tables.engine_full, an otherwise identical table without it reports 200.

The base-side reproduction remains an abort at ColumnsHashing.h:248 on the
MergeMutate thread with the pin present, both under ordinary randomization and
with the runner forcing a low value.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change against the codebase, three times, plus my own cold review
of the resulting code each round before reading any implementation notes. Verdicts below.

# Finding Verdict
⚠️ The regression test leaves merge_max_block_size to the CI randomizer (1 to 24576), so what the fixture exercises varies between runs. Agreed. Pinned merge_max_block_size = 8192, the default, in the table's own SETTINGS, which wins over the runner's injection because ClientBase::addMergeTreeSettings only appends settings the query does not already carry. Measured with the injection forcing a low value: the pinned table reports 8192 in system.tables.engine_full, an otherwise identical unpinned table reports the forced value. The finding also asserted that a low draw would stop the unfixed binary aborting; that part did not hold and I am not repeating it as a reason. A value sweep from 1 upwards and 29 runs of the unfixed binary aborted every time. What makes the fixture reach the defect is its 1000 distinct keys, not this setting: a single-key fixture runs clean.
⚠️ The test would still pass if saved hashes were disabled entirely, and it does not exercise aggregation findKey/getHash, cache hits, or the join consumer, so those bounds checks could be removed undetected. Disagreed, with evidence. The distinction is unobservable: both branches produce the same hash for the same key by construction (the memoized value comes from StringViewHash, which is also the HashMap default hash for these keys, over the same bytes getDataAt returns), which is exactly why results do not change. No ProfileEvent, log line or system table exposes saved-hash usage, so the prescribed oracle cannot discriminate and no test in master references it. The two properties it asks for are already measured instead: reverting only the bounds check brings the identical report back, and instrumenting the branch shows a non-empty snapshot of 2 entries with positions reaching 9 and beyond.
💡 Put the CI report URL in a commit message, not only in the description. Agreed, not acted on. The report is linked in the first paragraph above, and the first commit names the check, the signature, and the file and line. Correcting this needs either an amend, which is not done here, or a commit whose only content is a URL already on the page.
💡 Use full GitHub URLs on the visible Related lines, and spell the sanitizer ASan. Agreed, both applied.

Residual I am not claiming coverage for: the join sites and aggregation findKey/getHash are
fixed on contract grounds, not from a reproducer. I did not produce a join query that overflows;
the equivalence, type-matrix and eight-client concurrency runs are the whole of their coverage.

The test file keeps the number 05023, which now also exists on master under a different name.
Duplicate numeric prefixes are common in this directory and the runner keys on the full file name.

@clickhouse-gh clickhouse-gh Bot closed this Aug 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Answer
a Deterministic repro? Yes. OPTIMIZE TABLE ... FINAL on a TTL ... GROUP BY table with a LowCardinality(String) key aborts the sanitizer build every run (not intermittent). The local stack matches the reported one frame for frame at ColumnsHashing.h:248:52 on thread MergeMutate.
b Root cause explained? Yes. tryGetSavedHash() memoized the dictionary hash array once and returned a pointer with no length; the array is sized from the dictionary size at first use, later inserts grow only the internal copy, and consumers indexed the published one with a current position. The sanitizer attributes the overflowed region to ReverseIndex::calcHashes via tryGetSavedHash on the first executeOnBlock, and reports the read as 8 bytes past an 18-slot allocation.
c Fix matches root cause? Yes. The defect is the unbounded API, so the length is published with the data at the IColumnUnique seam rather than guarding the crash site. Not a widened bound, a suppression or a defensive check over an upstream bug.
d Test intent preserved / new test added? Yes. No existing test weakened. New stateless test 05023_ttl_group_by_lowcardinality_string_key. Closes a real coverage gap: 03774_ttl_group_by_lowcardinality.sql uses numeric LowCardinality types, which have no saved-hash array and cannot reach this.
e Demonstrated in both directions? Yes. Sanitizer report on master, clean with the change, using binaries with different build ids. Additionally: reverting only the bounds check while keeping the whole span refactor brings the identical report back, and instrumenting the out-of-range branch shows it taken over a thousand times on the reproducer (snapshot of 2 entries, positions reaching 9 and beyond), so the guard is load-bearing and the test is not vacuous.
f General across code paths? Yes. Consumer enumeration closed by grep: the symbol has exactly one declaration, one override, one definition and two consumers. Both are fixed, all six read sites: ColumnsHashing.h emplaceKey/findKey/getHash (reported) and HashJoin/KeyGetter.h getHash/emplaceKey/findKey (not in the report). Verified mechanically: six reads, six bounds checks, no remaining pointer truth-test. The dictionary cache carries the length so a cache hit cannot bypass the fix. I did not produce a join query that overflows, and claim no join coverage beyond the equivalence and concurrency runs.
g Generalizes across inputs? Yes. Run on both arms: LowCardinality over String, Nullable(String), FixedString(12) and a numeric type (which returns an empty span and takes the same fallback), plus 0, 1 and 2 distinct keys, plus hash and parallel_hash joins. The nullable null-key early return still precedes every bounds check.
h Backward compatible? Yes, nothing to migrate. The array is an in-memory memo: nothing persisted, no serialization or format change, no setting added or defaulted differently, so no SettingsChangesHistory.cpp entry and no experimental gate.
i Invariants and contracts preserved? Yes. The published column stays owned, and setColumn() deliberately still does not clear it, so a stale snapshot is always bounded and readable rather than dangling. The producer publishes one object: the atomic holds the winning column, the owner is assigned only by the exchange winner, and both data and length derive from that single object, so a length can never be paired with a different buffer. Explicit acquire/release ordering; the losing thread adopts the winner's object. Eight concurrent clients running GROUP BY, spilling GROUP BY, uniqExact and a parallel_hash join over one shared dictionary returned identical correct results with no sanitizer reports.

Suites: the new test 50 of 50 under randomized settings with no failures; the low_cardinality, group_by, ttl and join suites (1426 tests) with no sanitizer reports. Failures in that sweep are missing clusters, system.query_log and data paths absent from my local server config, plus six tests that fail identically on unmodified master with the same config.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c721751]

Summary: ✅


AI Review

Summary

This PR changes IColumnUnique::tryGetSavedHash from a raw pointer to a bounded std::span, updates both aggregation and hash-join consumers to fall back to hashing from the key when a LowCardinality dictionary has grown past the saved-hash snapshot, and adds a stateless TTL ... GROUP BY regression test for LowCardinality(String). I did not find a remaining correctness, compatibility, or safety issue in the current diff.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 35/49 (71.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @nickitat, could you review this? IColumnUnique::tryGetSavedHash returned a bare pointer to a hash array sized once from the dictionary, and ReverseIndex::insert afterwards grew only the internal copy, so aggregating a LowCardinality(String) key whose dictionary keeps growing (reachable from TTL ... GROUP BY) indexed past the end. It now publishes a bounded span and both consumers, aggregation and the hash join, bounds-check it.

const UInt64 * tryGetSavedHash() const
/// The span covers the dictionary as it was when the hashes were first calculated, and is never
/// extended: positions inserted afterwards are outside it.
std::span<const UInt64> tryGetSavedHash() const

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This closes the out-of-bounds read, but it also changes tryGetSavedHash from "memoized hashes for the current dictionary" into "memoized hashes for the first prefix that ever got observed". In the TTL path that motivated the fix, aggregate_columns keeps growing one shared ColumnLowCardinality dictionary and calculateAggregates keeps handing column->cut(...) slices of that same dictionary to fresh aggregation states. Once an early run publishes (say) a 2-entry snapshot, every later run on the now-larger dictionary falls back to hashing bytes for all later-added string keys instead of using saved hashes.

That would already be a hot-path regression on its own, and HashMethodSingleLowCardinalityColumn makes it permanent by caching the truncated span under the full {dictionary hash, dictionary size} key in LowCardinalityDictionaryCache (src/Common/ColumnsHashing.h:163-186). So after the dictionary finishes growing, repeated aggregations/joins on the same shared dictionary still keep rehashing most keys from scratch.

Can we preserve the full-current-dictionary contract here instead of freezing the first snapshot forever? For example, republish a larger snapshot when column->size() outgrows the published one (while keeping older snapshots alive for existing readers), or at least avoid caching a span whose length is already smaller than the current dictionary size.

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.

The first-prefix behaviour is not introduced here. It is what master already does.

At the base commit dddf61cc, external_saved_hash is written exactly once and never extended: calcHashes() sizes the array to column->size() at the first call, insert() resizes only the internal saved_hash, and tryGetSavedHash() returns early on any non-null pointer. git grep external_saved_hash there is 6 lines, none of them a resize or a reset. It has been that way since 342ec02664188df (2021, "Fix concurrent access to LowCardinality during GROUP BY"). So master also returns first-prefix hashes for a grown dictionary; the only difference is what happens past the end, where master reads out of bounds and this PR hashes from the key.

On the cache: DictionaryKey::operator== compares hash == other.hash && size == other.size, and the key is built as {getDictionary().getHash(), dict->size()} with dict->size() read at construction. An entry is therefore only reused for a dictionary of exactly the size it had when stored. After growth the size differs, the lookup misses, and a fresh entry is stored, so a short span cannot be served for a larger dictionary. The line range is right, but the truncation does not outlive the growth.

The second remedy is a no-op: on a cache miss the constructor calls tryGetSavedHash() again, which returns the already-published snapshot, so the same short span comes back. Skipping the cache changes the bookkeeping only.

Measured, ASan, base 505b10c6 vs fix 221328a1 (all five touched files identical between the base snapshot and this PR's base):

  • shared-dictionary GROUP BY, 20M rows / 50k keys, 5 runs: median 1.434s base, 1.399s fix
  • LC JOIN, same data, 3 runs: median 4.415s base, 4.499s fix
  • TTL GROUP BY merge, 4M rows / 100k keys, where the dictionary grows well past the first-block snapshot and the fallback is taken in bulk: fix completes in 29.1s with correct results (100000 groups, sum(v)=7999998000000); base aborts, heap-buffer-overflow, READ of size 8 ... thread MergeMutate, 0 bytes after 144-byte region, symbolizing to ColumnsHashing.h:248 in emplaceKey, which is the reported signature.

The first two arms stay on the in-range path, so they bound the ordinary cost but say nothing about fallback cost. The third is the one that exercises it, and there is no base timing to compare against because base cannot run it.

Republishing on growth while keeping older snapshots readable is a reasonable thing to want, but it removes the write-once property this fix relies on for lifetime safety and needs its own retirement discipline and ordering proof. That is a change to the 2021 memoization design rather than to this bounds fix, so I would rather not fold it in here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c721751d7 with master 9965d6a45 (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
Binary Master PR Δ
programs/clickhouse-stripped 704.38 MiB 701.35 MiB -3.03 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c721751

Every failure below has an owner: a fixing PR (ours 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

CI finished clean at this head, so no line needs an owner. 173 unique check-runs, 0 incomplete,
154 success and 19 skipped, with Config Workflow and Finish Workflow both success. Corroborated
against the CI database at this commit: 0 FAIL or ERROR rows against a measured 608,115-row control
for the same commit, the only non-success job row being a skipped
Integration tests (amd_asan_ubsan, targeted).

Session id: cron:our-pr-ci-monitor:20260820-200000

@thevar1able
thevar1able added this pull request to the merge queue Aug 20, 2026
@thevar1able thevar1able self-assigned this Aug 20, 2026
Merged via the queue into ClickHouse:master with commit efcdc7d Aug 21, 2026
356 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Oct 22, 2026
…allel hash join

A `GROUP BY` on a `LowCardinality(String)` key could return the same key in
several groups when the key column comes from the probe side of a
`parallel_hash` join. The join scatters a probe block into pieces that share
the block's dictionary; one piece is aggregated first, which caches the hashes
of the dictionary, and a later piece is squashed after the join with pieces of
other blocks, which appends their keys to the same dictionary in place. The
appended keys were then past the end of the cached hashes, so they were read out
of bounds and got wrong hashes.

ClickHouse#115604 fixed the out-of-bounds
read and covered it with `TTL ... GROUP BY`. This adds the `SELECT` path, which
returns wrong results on release builds without a sanitizer: the query gives
81-108 groups instead of 60 in every run on 26.8.1.1798 (before the fix) and 60
in every run on 26.8.1.1799 (with the fix).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

GROUP BY returns the same key in multiple rows when the left side of a JOIN is SELECT DISTINCT (parallel_hash + optimize_distinct_in_order

3 participants