Repository navigation
Fix out-of-bounds read of the LowCardinality saved-hash array - #115604
thevar1able merged 2 commits into
Conversation
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.
Internal second-model reviewAn independent model reviewed this change against the codebase, three times, plus my own cold review
Residual I am not claiming coverage for: the join sites and aggregation The test file keeps the number |
Pre-PR validation gate
Suites: the new test 50 of 50 under randomized settings with no failures; the |
|
Workflow [PR], commit [c721751] Summary: ✅
AI ReviewSummaryThis PR changes Final Verdict✅ No findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 35/49 (71.43%) · Uncovered code |
|
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 toColumnsHashing.h:248inemplaceKey, 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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units1186 translation units recompiled, 8943 s compile time in total, 1186 of them have a recent master baseline. |
CI finish ledger - c721751Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
CI finished clean at this head, so no line needs an owner. 173 unique check-runs, 0 incomplete, Session id: cron:our-pr-ci-monitor:20260820-200000 |
…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]>
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 atsrc/Common/ColumnsHashing.h:248on threadMergeMutate: CI report.Changelog category (leave one):
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 fromTTL ... 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 bareconst UInt64 *with no length.ReverseIndex::calcHashes()sizes it from the dictionary size at that moment, andReverseIndex::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 BYreaches this from ordinary SQL:TTLAggregationAlgorithmbuilds 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::spanderived 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) andLowCardinalityKeyGetterForJoin(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 ... FINALon 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::calcHashesviatryGetSavedHashon the firstexecuteOnBlockand 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:
Existing coverage could not reach this:
03774_ttl_group_by_lowcardinality.sqluses 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 theHashMapdefault hash for these keys, over the same bytesgetDataAtreturns. 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,
uniqExactand aparallel_hashjoin 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
26.8.1.1799(included in26.8and later)