Skip to content

Fix heap-buffer-overflow when serializing a shared quantileTDigest state - #110263

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-quantile-tdigest-serialize-shared-state
Jul 15, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-quantile-tdigest-serialize-shared-state

Conversation

@groeneai

@groeneai groeneai commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

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 a possible crash (heap-buffer-overflow) when a quantileTDigest-family aggregate-function state column was used as a GROUP BY key and serialized concurrently by several threads.

Description

Found by the AST fuzzer (AST fuzzer (arm_asan_ubsan)), STID 1777-2d0a, report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104657&sha=5d77b4a2becb4effcae858e0ea70d6b684c723c6&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29

QuantileTDigest::serialize() called compress(), which sorts the centroids buffer in place, so serialize() mutated the aggregate state. But IAggregateFunction::serialize takes a ConstAggregateDataPtr and the same state can be shared between rows: ColumnAggregateFunction::replicate/createView copies state pointers (not the states), so a replicated / const aggregate-state column used as a GROUP BY key has all rows pointing at one state. When such a column is a parallel GROUP BY key, several pipeline threads run serialize() on the same state concurrently, racing inside compress()/RadixSort and writing one element past the centroids buffer (ASAN heap-buffer-overflow in RadixSort::radixSortLSDInternal, RadixSort.h:353).

Reproducer (crashes reliably under ASan with max_threads > 1, always safe with max_threads = 1):

SELECT count() FROM (
    SELECT k FROM (
        SELECT number, (SELECT quantileTDigestState(number) FROM numbers(5000)) AS k
        FROM numbers_mt(4000000)
    ) GROUP BY k
) SETTINGS max_threads = 16;

Fix: serialize() is now const and never mutates the shared buffer. If the digest is already compacted it writes as is; otherwise it compresses a local copy. The now-unnecessary const_cast in AggregateFunctionQuantile::serialize is dropped. QuantileTDigest was the only quantile variant whose serialize was non-const.

Version info

  • Merged into: 26.7.1.963 (included in 26.7 and later)
  • Backported to: 26.6.2.71, 26.5.6.44, 26.4.5.132, 26.3.17.48, 25.8.29.20

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT count() FROM (SELECT k FROM (SELECT number, (SELECT quantileTDigestState(number) FROM numbers(5000)) AS k FROM numbers_mt(4000000)) GROUP BY k) SETTINGS max_threads=16 crashes under ASan within 3 iterations; 0 crashes in 40 runs at max_threads=1.
b Root cause explained? QuantileTDigest::serialize() called compress(), which sorts centroids in place -> serialize mutated the state. But IAggregateFunction::serialize takes a ConstAggregateDataPtr, and ColumnAggregateFunction::replicate/createView share ONE state pointer across replicated/const-column rows. As a parallel GROUP BY key, N threads run compress()/RadixSort on the same buffer -> the in-place key transform desyncs the histogram -> write one element past the buffer (RadixSort.h:353).
c Fix matches root cause? Yes. serialize() is now const and never mutates the shared buffer (writes as-is if already compacted; else compresses a LOCAL copy). Removes the mutation-during-shared-read that is the race.
d Test intent preserved / new tests added? Added 04516_quantile_tdigest_serialize_shared_state reproducing the shared-state parallel-GROUP-BY-key path. Existing tdigest tests (00649, 02286, 04327) still pass; quantile values unchanged.
e Both directions demonstrated? Yes. Pristine build (Build ID 13a5bb..): crash within 3 iters. Fixed build (edee78..): 30/30 iterations clean, 0 ASan reports, quantile results identical.
f Fix is general across code paths? Yes. QuantileTDigest was the ONLY quantile data structure whose serialize was non-const (all others already const). getImpl/getManyImpl also call compress() but run on per-group mutable finalize states, not shared states.
g Fix generalizes across inputs? Yes. The mutation happens for every input regardless of value type (QuantileTDigest<char8_t> and <unsigned long> both reproduced); the fix is value-agnostic (structural: don't mutate the shared buffer). Covers -State/-Distinct/-OrFill/-OrNull combinator wrappers that share the state pointer.
h Backward compatible? Yes. Serialized format is byte-identical (same compacted centroids written); no setting, wire, or on-disk format change.
i Invariants and contracts preserved? Yes. Now HONORS the serialize(ConstAggregateDataPtr) const immutability contract that ColumnAggregateFunction::serializedSizeEstimate already relies on ("States are immutable on the write path"). The local-copy path preserves compress()'s centroid-count-<=-max_centroids postcondition for the written bytes.

Session id: cron:clickhouse-worker-slot-0:20260713-110900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Algunenano — could you review this? QuantileTDigest::serialize() mutated the state via compress(), but serialize takes a ConstAggregateDataPtr and replicated/const aggregate-state columns share one state pointer across rows; as a parallel GROUP BY key that races several threads inside RadixSort (ASan heap-buffer-overflow). The fix makes serialize const (compress a local copy, never the shared buffer).

@Algunenano Algunenano self-assigned this Jul 13, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Jul 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7567c40]

Summary: ✅


AI Review

Summary

This PR makes serialize read-only for shared quantileTDigest aggregate states and applies the same fix pattern to sequenceNextNode, eliminating the in-place mutation that made concurrent serialization race on shared state. The current head also includes a focused regression test for the quantileTDigest reproducer, and I did not find any remaining correctness, metadata, or coverage issues in the touched code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 13, 2026
@groeneai
groeneai force-pushed the groeneai/fix-quantile-tdigest-serialize-shared-state branch from c0455c4 to dd12979 Compare July 13, 2026 13:53
QuantileTDigest::serialize() called compress(), which sorts the centroids
buffer in place, so serialize() mutated the aggregate state. But
IAggregateFunction::serialize takes a ConstAggregateDataPtr, and the same
state can be shared between rows (a replicated / const aggregate-state
column used as a GROUP BY key shares one state pointer across rows). When
such a column is a parallel GROUP BY key, several pipeline threads serialize
the same state concurrently, racing inside compress()/RadixSort and writing
one element past the centroids buffer (ASAN heap-buffer-overflow in
RadixSort::radixSortLSDInternal).

serialize() is now const and never touches the shared buffer: if the digest
is already compacted it writes as is, otherwise it compresses a local copy.
The const_cast in AggregateFunctionQuantile::serialize is dropped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-quantile-tdigest-serialize-shared-state branch from dd12979 to 543820b Compare July 13, 2026 17:26
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 543820b: the 30x loop over the 4M-row query tripped the flaky check's 180s per-run ceiling. Reduced rows 4M -> 200k (unchanged: 5000-centroid state, max_threads=16, 30 iterations) so the shared const aggregate-state is still serialized concurrently across threads.

Re-verified both directions on ARM ASan via clickhouse-test:

  • pre-fix (non-const serialize): FAILS - server dies with the heap-buffer-overflow within the first loop iterations (200k reliably trips it in 1-3 reps across fresh-server trials).
  • fixed (const serialize): 30/30 iterations return 1, ~17s per run, no ASan report.

Still reliably fails the broken code, now well under the flaky-check timeout.

alexey-milovidov and others added 2 commits July 13, 2026 21:54
The flaky check reruns changed tests ~50x and FAILs any single run over
180s (TEST_MAX_RUN_TIME_IN_SECONDS) unless the test carries the long tag.
The 30-iteration x 200k-row re-aggregation loop blew past that on the
slower sanitizer builds (msan/debug/tsan): 'Test runs too long (> 180s)'
plus hard-timeout process-group kills.

Add the long tag (exempts the 180s flaky-check FAIL and cuts the rerun
count to ~10%) and shorten the loop to 10 iterations. The pre-fix binary
trips the heap-buffer-overflow within the first 1-2 iterations under
ASan, so 10 iterations keeps the failure reliable with 5x margin while
each run finishes in a few seconds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check 180s timeout on the regression test (it was FAILing on the slower sanitizer builds: msan/debug/tsan).

Two changes (test-only, source fix untouched):

  • Tagged the test long. The flaky check reruns changed tests ~50x and FAILs any single run over 180s unless it carries long; the tag exempts that ceiling and cuts the rerun count to ~10%.
  • Shortened the loop from 30 to 10 iterations.

Reliability retained: on a pristine (pre-fix, non-const serialize()) ARM ASan build the loop trips the heap-buffer-overflow (STID 1777-2d0a signature) within the first 1-2 iterations across 6/6 fresh-server trials, so 10 iterations keeps a reliable failure with 5x margin. The fixed const serialize() never touches the shared centroids buffer, so the loop returns 10x 1 in a few seconds.

groeneai and others added 2 commits July 14, 2026 05:47
SequenceNextNodeImpl::serialize took a ConstAggregateDataPtr, const_cast-ed it
and sorted the value buffer in place. A shared/const sequenceNextNodeState
column (replicated or used as a parallel GROUP BY key) is then reordered
concurrently by several pipeline threads, which is a data race and can yield
wrong results, the same class of bug fixed for quantileTDigest in this PR. Sort
a local copy of the node pointers instead. Serialization stays byte-identical
(values are always written in sorted order).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Style check forbids raw std::vector in server code. Use the
memory-tracked drop-in for the local sorted node-pointer copy.

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

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 79.80% 85.80% +6.00%
Functions 91.70% 92.70% +1.00%
Branches 72.00% 78.10% +6.10%

Changed lines: Changed C/C++ lines covered: 13/36 (36.11%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7567c40

CI complete (Finish Workflow: pass; Mergeable Check: pass; PR aggregator: pass). No test, fuzzer, sanitizer, or stress failures on this head. The Style-check cpp violation on the prior head (302c772, bare std::vector at AggregateFunctionSequenceNextNode.cpp:304) is resolved on 7567c40 (VectorWithMemoryTracking), and all downstream jobs re-ran green.

Check / test Reason Owner
(no test failures) - -
CH Inc sync private sync (pending) CH Inc sync (private, not actionable)
Report messages praktika reporting job (red on fork PRs) CI reporting artifact, not a test failure

Session id: cron:our-pr-ci-monitor:20260714-113000

@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 14, 2026

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

This is a very good fix, bravo 👍
Even if there were some performance degradations (there are none) it would make sense.

clickhouse-gh Bot pushed a commit that referenced this pull request Jul 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 15, 2026
Backport #110263 to 26.6: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
@Algunenano

Algunenano commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

@alexey-milovidov I was assigned because I was going to review it (and was doing so, because it's important to look for similar issues and that the solution is proper). If you are going to go around reviewers, please des-assign the issue and assign the issue to yourself, then deal with the review and backports

robot-ch-test-poll2 added a commit that referenced this pull request Jul 15, 2026
Cherry pick #110263 to 25.8: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
robot-clickhouse added a commit that referenced this pull request Jul 15, 2026
alexey-milovidov added a commit that referenced this pull request Jul 15, 2026
The backported fix from #110263 used the
`::stableSort` helper from `base/sort.h`, which exists only on master. On the 26.4
branch this file uses `std::stable_sort` directly, so all builds failed with:
`error: no member named 'stableSort' in the global namespace`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110474&sha=b837d44fa0cf617c665b5beec9a24898ea437816&name_0=BackportPR

Co-Authored-By: Claude Fable 5 <[email protected]>
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 15, 2026
alexey-milovidov added a commit that referenced this pull request Jul 16, 2026
Backport #110263 to 25.8: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
alexey-milovidov added a commit that referenced this pull request Jul 16, 2026
Backport #110263 to 26.5: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
alexey-milovidov added a commit that referenced this pull request Jul 16, 2026
Backport #110263 to 26.4: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
alexey-milovidov added a commit that referenced this pull request Jul 16, 2026
Backport #110263 to 26.3: Fix heap-buffer-overflow when serializing a shared quantileTDigest state
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Aug 5, 2026
04516_quantile_tdigest_serialize_shared_state hit the runner's 600s hard
--timeout on Stateless tests (amd_llvm_coverage_per_test, per_test_coverage,
7/8) on master: 3 FAIL in 16 runs over 30 days, with strictly bimodal
durations (600120/600130/600660 ms against 5590-8790 ms on the other 13).

The cause is the randomized optimize_group_by_constant_keys, drawn false with
p = 0.05 (tests/clickhouse-test:1569) and present on 3 of the 3 failing runs.
Aggregator::executeOnBlock gates const-key detection on it
(Aggregator.cpp:1643-1648): with it on, executeImplBatch calls emplaceKey once
per block (:1059-1062); with it off, convertToFullColumnIfConst materializes
the const state column (:1660) and emplaceKey runs once per row (:1066-1081).
The aggregation method is serialized, so the test's single broadcast
quantileTDigestState is serialized 200000 times per iteration instead of about
four. The cost is exactly linear in rows (0.99 / 1.89 / 3.68 / 7.24 CPU-sec at
50k / 100k / 200k / 400k) while the pinned arm stays flat at 0.12, and the
coverage build's constant factor turns that into the hard-timeout kill.

Pinning the setting in the test's own SETTINGS clause does not weaken the
regression test. On an ASan build with QuantileTDigest::serialize and the
AggregateFunctionQuantile.h const_cast reverted to their pre-ClickHouse#110263 form, the
pinned test still detects the heap-buffer-overflow in 20 of 20 runs, while an
unpinned control on the same binary detects it in 4 of 5: all_keys_are_const
still has several pipeline threads serializing the same shared state once per
block, which is the race being pinned, and only the per-row repetition goes
away.

The long tag is kept and its comment corrected, since long covers the 180s soft
ceiling but does not raise the 600s hard --timeout (tests/clickhouse-test:6175).

The underlying O(rows) serialization of a shared aggregate state is
pre-existing and general, worst on quantileGKState (37.7 CPU-sec, already 25.7
on 26.2), whose serialize has had the same copy-and-compress shape since before
110263 (AggregateFunctionQuantileGK.cpp:455-466), so it belongs in the
Aggregator and is tracked separately.
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ile-tdigest-serialize-shared-state

Fix heap-buffer-overflow when serializing a shared quantileTDigest state
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
AGG: quantileTDigest state as a GROUP BY key, multi-threaded -> crash.
Effect in the production build a394e92: its upstream test(s) 04516_quantile_tdigest_serialize_shared_state fail on it (the server process died in 04516_quantile_tdigest_serialize_shared_state) and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04516_quantile_tdigest_serialize_shared_state.

Co-Authored-By: Claude Opus 5.5 <[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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

5 participants