Skip to content

Fix an adaptive aggregator abort on lazily replicated columns - #115034

Merged
nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-adaptive-aggregation-replicated-source
Aug 17, 2026
Merged

nihalzp merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-adaptive-aggregation-replicated-source

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Aggregator::sealPendingChunks coalesces several staged mini-chunks into one, concatenating each
aggregate argument column across the minis. It clones the destination from the first source and
then calls prepareForSquashing and insertRangeFrom, both of which assert_cast every source to
the destination's class. That assumes all minis share one physical representation per position.

They do not. Lazy column replication is decided per block: a join materializes a block whose
replication does not grow the output and leaves the others wrapped in ColumnReplicated
(HashJoinResult.cpp), so one stream legitimately mixes wrapped and dense blocks for the same
column. recursiveRemoveSparse in the staging path deliberately preserves the wrapper, so the mix
reaches the seal and the cast aborts:

Logical error: 'Bad cast from type DB::ColumnReplicated to DB::ColumnVector<unsigned long>'
Received signal Aborted (6)

Two sites abort, both reproduced locally: insertRangeFrom for the numeric vectors, which do not
override prepareForSquashing (the signature above), and prepareForSquashing itself for String,
Nullable, Array, Map, Tuple, Variant, Dynamic and Object. The fix normalizes the whole sources
vector, including the front, before the destination is cloned, so one gate covers both sites and
destination and sources stay drawn from the same normalized set. The structureEquals gate keeps
the homogeneous case allocation-free, so lazy replication keeps its benefit where it is uniform,
and mirrors what Squashing.cpp already does for the identical hazard.

Reachable from ordinary SQL: a JOIN feeding a GROUP BY with enable_adaptive_aggregator = 1
and enable_lazy_columns_replication = 1, both defaults. In a release build assert_cast degrades
to static_cast, so the same input reads a ColumnReplicated through a ColumnVector layout and
copies from a bogus data pointer instead of failing loudly.

AdaptiveAggregation.cpp was added by #111459 and is on no release branch, so no backport applies.

Found by CI in Stress test (arm_msan) on an unrelated pull request:
report,
fatal.log.

Version info

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

groeneai and others added 4 commits August 16, 2026 12:36
…ation seal

Aggregator::sealPendingChunks coalesces staged mini-chunks by cloning its
destination from the first source and then calling prepareForSquashing and
insertRangeFrom, both of which assert_cast every source to the destination's
class. That assumes all minis share one physical representation per aggregate
argument position, and only ColumnConst was stripped.

Lazy column replication is decided per block: HashJoinResult materializes the
blocks whose replication does not grow the output and leaves the others wrapped
in ColumnReplicated. The staging path preserves the wrapper (recursiveRemoveSparse
keeps it and ColumnReplicated::index returns a ColumnReplicated), and the frozen
kernel receives the raw block columns rather than the unwrapped copies
prepareAggregateInstructions builds. So one stream legitimately mixes wrapped and
dense columns at the same position and the cast aborts:

  Bad cast from type DB::ColumnReplicated to DB::ColumnString
  Received signal Aborted (6)

Two sites abort, both reproduced: prepareForSquashing for String, Nullable, Array,
Map, Tuple, Variant, Dynamic and Object, and insertRangeFrom for the numeric
vectors, which do not override prepareForSquashing. Normalizing the whole sources
vector including the front, before the destination is cloned, covers both and
keeps destination and sources drawn from the same normalized set. The
structureEquals gate leaves the homogeneous case allocation-free, so lazy
replication keeps its benefit wherever it is uniform. This mirrors the treatment
Squashing already applies to the identical hazard.

In a release build assert_cast degrades to static_cast, so the same input reads a
ColumnReplicated through a ColumnVector layout and copies from a bogus data
pointer instead of failing loudly.

Found by CI in Stress test (arm_msan) on an unrelated pull request. The aborting
file was added to master by ClickHouse#111459 and is on no release branch, so no backport
applies.
The test asserted only the aggregated values, and those are produced whether
or not several staged batches are ever buffered together. sealPendingChunks
publishes a lone batch through an earlier return, and a lone lazily replicated
batch is unwrapped downstream, so a configuration that keeps the backlog at one
batch never reaches the code this change fixes and the test passes on an
unfixed build. Either external-aggregation threshold produces that
configuration by draining the backlog as it grows, and the test runner
randomizes both, so the test was green on a broken binary for a routinely drawn
setting combination.

Pin the settings the coalescing depends on, following the convention of the
other tests in this family, and add an assertion that the coalescing actually
ran: AdaptiveAggregationSealedChunks is incremented after the single-batch
return, so a non-zero count means at least one seal saw two or more batches.
The counter is read from query_log through a log_comment carried by the
adaptive arms alone.

Measured on the reverted source: with an external threshold forced, the test
without these changes passes 6 of 6 while this version fails 5 of 11, every
failure carrying a Bad cast signature. Reverting only the threshold pin turns
the new assertion to zero and fails the test while all nine value lines still
match, so the assertion is what closes the gap rather than the pins alone.
The test asserted that a multi-batch seal ran, which is necessary but not
sufficient: the coalescing only normalizes when the buffered batches disagree
at an argument position, and a wrapped first batch absorbs the mix on its own.
On the unfixed server such a run produces correct values and a non-zero
sealed-chunk count, so the test could pass while the code it covers was broken.

Count the normalizations separately and assert that count per argument
representation, so a normalized seal in one arm cannot vouch for another.

Pin the table layout in the CREATE and the remaining join-shape settings. Lazy
replication is decided per output block, and the reader's block size follows the
table's granularity settings, which the test runner randomizes; leaving them
open made a mixed batch a coin flip. With the layout pinned the unfixed server
aborts on 10 of 10 runs, against 3 of 8 before.

Co-Authored-By: Claude Opus 5 <[email protected]>
The test asserts ProfileEvents from its own query_log. With parallel replicas
the partial aggregation runs on the replicas, and their counters never reach the
initiator's query_log, so those assertions read zero on a correct server. The
dedicated job takes its parallel replicas settings from the default profile, so
a SET in the test body cannot turn them off.

The tag both excludes the test from that job and forces the setting off
everywhere else. Verified in both senses against a corrupted-tag control, since
a malformed tags line is silently ignored.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 rounds, all findings resolved)

This change went through four independent cold-review rounds, each paired with a second-model gate
pass, before publication. The src/ fix was re-derived from scratch in every round and never changed
after the first; every round of findings was about whether the regression test can actually fail when
the fix is removed. The final round's gate returned no findings.

# Finding Verdict
❌ The test could pass on an unfixed binary: sealPendingChunks returns early when only one batch is buffered, and both external-aggregation thresholds are randomized per run, so a run that drains one batch at a time never reaches the guarded code. AGREE. Pinned those thresholds and the other settings this family pins, and added a AdaptiveAggregationSealedChunks > 0 assertion. The counter increments after the early return, so a non-zero value proves a seal ran with at least two batches.
❌ That assertion was still satisfiable on an unfixed binary: a run whose first batch is the wrapped one absorbs the mix silently, giving correct values and a non-zero seal count with no abort. AGREE. Added a counter incremented inside the normalization guard, plus one assertion per representation with distinct log_comments, so "reached the seal" and "reached the normalization" are separately observable and one representation cannot vouch for another.
❌ The new positive assertions read zero on a correct binary under parallel replicas, because the partial aggregation runs on the replicas and remote ProfileEvents never reach this server's query_log. AGREE. Tagged no-parallel-replicas. Verified the tag is not a no-op in each of its effects against a corrupted-tag control: it forces enable_parallel_replicas = 0 for the test, and the dedicated ParallelReplicas job skips the test outright. The seal is local to one aggregating producer, so no coverage is lost.
⚠️ The normalization counter is incremented before the conversion loop, so it would stay non-zero if the conversion became a silent no-op. DISAGREE. All three code citations are accurate, but the asserted outcome has no reachable witness: the counter sits inside the mismatch guard, so the runs that increment it are exactly the runs that abort when the normalization is missing. That mutant was run: 8 of 8 failed with a real Bad cast signature, none via a zero counter. The genuinely silent shape, a wrapped first source, is caught on the unfixed binary instead, where the test fails with correct values, no abort and a zero counter.
💡 Two nits I raised and withdrew: the assertions repeat one WHERE predicate, and they bound the scan by wall clock rather than by query id. No action. A .sql test has no factoring mechanism that avoids re-execution, and the sibling family writes it the same way. The time bound is redundant rather than load-bearing: each run gets a fresh random database and every assertion filters on it, which is stronger isolation.

Test validation, each measurement against a control: the test fails 8 of 8 on the unfixed binary,
every run carrying the real abort signature and the seal frame in the stack; it passes 20 of 20 and
50 of 50 under full randomization with the fix, plus 11 of 11 across the rest of this family; and each
of the four assertions was shown to fail on its own when only the behaviour it guards is removed,
while the other assertions and all nine value lines still match.

Session id: cron:clickhouse-review-slot-48:20260816-194000

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc9795b]

Summary: ✅


AI Review

Summary

This PR fixes Aggregator::sealPendingChunks so mixed lazily replicated and dense aggregate-argument columns are normalized before the seal clones its destination, which closes the bad-cast / wrong-layout failure in both prepareForSquashing and insertRangeFrom. The implementation matches the existing Squashing treatment for the same representation hazard, and the new stateless test exercises both the prepareForSquashing path (String / Nullable(UInt64)) and the plain insertRangeFrom path (UInt128). I did not find a correctness, safety, or evidence gap in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 13/16 (81.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. JOIN where one key window in eight matches three right rows and the rest match one, feeding max() over a left column, with enable_adaptive_aggregator = 1, adaptive_aggregator_freeze_threshold = 0, enable_lazy_columns_replication = 1, max_threads = 4, max_block_size = 4096, query_plan_join_swap_table = 0. Run through clickhouse-test, so with its own setting randomization active, the shipped test aborts on every run on pristine master (8 of 8 this round, 10 of 10 in the round before the no-parallel-replicas tag was added), every failure carrying a real Bad cast signature and sealPendingChunks in the stack; 50/50 green with the fix. The table layout is pinned in the CREATE, because the granularity settings the runner randomizes decide the reader's block boundaries and the join makes its replication decision per block. The test also asserts that the coalescing it targets actually ran and that it actually normalized, via AdaptiveAggregationSealedChunks and a per-arm AdaptiveAggregationSealNormalizations, so a configuration that skips either fails the test instead of passing it silently. Negative controls on the unfixed binary: enable_lazy_columns_replication = 0 passes, enable_adaptive_aggregator = 0 passes, so both features are required.
b Root cause explained? sealPendingChunks coalesces staged mini-chunks by cloning its destination from the first source and then calling prepareForSquashing and insertRangeFrom, both of which assert_cast every source to the destination's class. That assumes one physical representation per argument position. Lazy column replication is decided per block in HashJoinResult, and the staging path keeps the wrapper (recursiveRemoveSparse preserves it, ColumnReplicated::index returns a ColumnReplicated), while the frozen kernel is handed the raw block columns rather than the unwrapped copies prepareAggregateInstructions makes. So one stream mixes wrapped and dense columns at the same position and the cast fails.
c Fix matches root cause? Yes. It normalizes the sources whose heterogeneity is the defect, in the function whose own invariant is violated, before the destination exists. Not a guard at the abort site, not a widened cast, no setting change, no assert_cast relaxed. Verbatim the treatment Squashing.cpp already applies to the identical hazard, structureEquals gate included.
d Test intent preserved / new tests added? New test added, nothing weakened. 04676_adaptive_aggregation_replicated_argument: three arms (String, UInt128, Nullable(UInt64)), each computed twice, once through the adaptive aggregator and once through the baseline one, so the pair asserts the coalesced values and not merely the absence of an abort. Parallel-safe, no no-parallel tag; the settings the coalescing depends on are pinned at file level because the runner randomizes them, the table layout is pinned in the CREATE for the same reason; and four final assertions fail the test if the coalescing did not run (AdaptiveAggregationSealedChunks) or if it ran without normalizing anything, asserted per arm (AdaptiveAggregationSealNormalizations), so the test cannot pass by never reaching the fixed code. Those four assertions read the initiator's query_log, which is why the test is tagged no-parallel-replicas: with parallel replicas the partial aggregation runs on the replicas and their ProfileEvents never reach this server, so the assertions would read zero on a correct binary. The tag was verified to take effect in both of its senses, each against a corrupted-tag control: it forces enable_parallel_replicas = 0 for the test's queries, and the dedicated job skips the test.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Base aa40047782eb88bb28261ebea18ab90317c23daa: aborts with Bad cast from type DB::ColumnReplicated to DB::ColumnString / ... to DB::ColumnNullable / ... to DB::ColumnVector<wide::integer<128ul, unsigned int>>, signal 6, sealPendingChunks in the stack. Fix 5a54054060172eeefa9f493c09e959d922d34b6d: correct results matching the baseline aggregator, no abort.
f Fix is general across code paths? Yes. The normalization sits at the sources vector, so it covers both downcast sites, prepareForSquashing and insertRangeFrom, and every column class behind them. Both were reproduced separately: ColumnVector does not override prepareForSquashing, which is why the reported UInt64 case aborts at insertRangeFrom while String and Nullable abort one line earlier, so a fix touching only the reported line would have left the other site broken. The front is normalized too, so destination and sources always come from the same normalized set. This is the only clone-from-front concatenation in the file, and sealPendingChunks has one implementation. The counts_only seal paths are structurally immune, measured rather than assumed: sealValueStagedChunkDeduplicated, sealValueStagedChunkConcatenated and concatenateStagedKeys contain zero references to IColumn, ColumnPtr, insertRangeFrom or prepareForSquashing, against 11 in the fixed function.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, 23 arms verified adaptive-versus-baseline on the mixed fixture, all matching: String, FixedString(20), UInt128, UInt256, Nullable(UInt64), Nullable(String), LowCardinality(String), LowCardinality(Nullable(String)), Decimal128(4), DateTime64(3), UUID, IPv6, Array(UInt64), Map(String, UInt64), Tuple(UInt64, String), JSON, Dynamic, Variant(UInt64, String), plus min, argMax, groupArray, sumMap, uniqExact, quantile. LowCardinality cannot enter the mix at all because isLazyReplicationUseful rejects it, so an LC column is never wrapped. Const is already handled one line earlier. removeSpecialRepresentations also strips Sparse recursively inside Tuple, and only Replicated(Sparse) occurs, never the reverse.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting added or defaulted differently, so no SettingsChangesHistory.cpp entry; no serialization or on-disk format change; behaviour changes only in the case that currently aborts. AdaptiveAggregation.cpp is absent from every active release branch, so no backport applies and none is requested.
i Invariants and contracts preserved? Yes. The invariant established is that within one position all sources share structureEquals with the destination, and it is established before destination exists, so no partially built column is observable. structureEquals is the same discriminator Squashing relies on, and ColumnReplicated::structureEquals returns false against any non-replicated column, which is the direction needed. Record counts, bucket offsets and the (bucket, mini) walk order are untouched, so a record keeps one position across the key, hash and payload arrays. No lock, allocation ordering or error path changed. Downstream the drain still handles a chunk that stays wrapped, because prepareAggregateInstructions unwraps replicated columns where it needs a concrete representation, which is what licenses the gate to skip the homogeneous case.

Session id: cron:clickhouse-impl-slot-5:20260816-185800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @Avogar, could you review this? sealPendingChunks clones its coalescing destination from the first staged batch and then downcasts every batch to that class, but lazy replication is decided per block, so one argument position can mix ColumnReplicated and dense columns and the cast aborts. The fix normalizes the whole source vector, front included, behind a structureEquals gate so the homogeneous case stays allocation-free.

@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dc9795b96 with master ce6df4653 (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 694.64 MiB 691.62 MiB -3.01 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - dc9795b

CI is fully finished on this head and it is clean: 177 check-runs, 157 success / 20 skipped,
0 failed, 0 cancelled, 0 still running. Config Workflow and Finish Workflow both succeeded,
and the praktika report is top-level OK with 0 dropped jobs, so the filtered matrix is a real
run rather than a void one. CIDB has 337828 rows across 159 checks for this commit.

Check / test Reason Owner / fixing PR
Config Workflow / Pre Hooks (20:07:48Z, 20:52:02Z) superseded: can be tested label was not yet applied when the workflow first dispatched not applicable, the same job re-ran green at 21:19:59Z on this identical commit

Those two CIDB rows are historical, not open. Both predate the label being applied; the same
Config Workflow job then completed success at 21:19:59Z on the same commit_sha, and the
praktika report for this head reports 0 dropped jobs at every depth, which is why the run is
treated as covered rather than label-gated.

The regression test 04676_adaptive_aggregation_replicated_argument ran 45 times across 21
distinct jobs on this head with 0 failures. All ten Stress test (*) flavours, Upgrade check (amd_release) and the fuzzer jobs are green. Counts come from an aggregate CIDB query over this
commit, not from a tally of the job list.

Session id: cron:our-pr-ci-monitor:20260817-020000

@nihalzp
nihalzp added this pull request to the merge queue Aug 17, 2026
Merged via the queue into ClickHouse:master with commit 68f372e Aug 17, 2026
531 of 535 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 17, 2026
adityaksolves pushed a commit to adityaksolves/Clickhouse that referenced this pull request Aug 18, 2026
…ree arms

04676_adaptive_aggregation_replicated_argument asserted
AdaptiveAggregationSealNormalizations > 0 separately for each of its three
argument representations. That counter is incremented in
Aggregator::sealPendingChunks only when the batches one producer has buffered
together disagree in physical representation at that argument position, which
requires three things: at least two batches buffered in one producer, both
representations reachable, and one producer holding blocks of both classes.

The test pins the settings governing the second condition. The first depends on
the staged payload size, since stageChunk publishes a batch as-is above a byte
threshold and sealPendingChunks returns before either counter when only one mini
chunk is buffered. The third is a read pool and thread scheduling outcome. So a
non-zero count for a single query is not an engine guarantee, and the per-arm
assertion asserted a property the engine does not promise. It failed on about
1.9% of the runs the test appeared in, 19 times across 19 unrelated pull
requests in 14 days, always one line flipping 1 to 0.

Randomization is not the cause. The failure reproduces with randomized settings
disabled and with enable_lazy_columns_replication 0, the very setting the test
pins, so there is nothing to clamp and a no-random-settings tag would hide the
flake rather than address it.

Summing the counter over the three arms states the property that does hold: the
seal normalized somewhere in the query set. The three queries stay separate, so
each keeps its own value comparison and its own abort site, and the aggregate
sealed chunks assertion, the six value lines and the tags are unchanged. The
same LIKE predicate the sealed chunks assertion already uses is reused, and the
three log_comment values are kept so per-arm attribution remains available in
query_log.

What this gives up is the per-run guarantee that every representation exercised
the normalization. Across CI runs each arm still does in about 99.4% of runs,
and a binary without the normalization fix aborts on whichever position first
sees heterogeneity.

Validated locally on a debug build: the old form failed 2 of 300 runs in the
same interleaved loop where the new form passed 300 of 300; of 600 runs 6 had an
arm at zero and all 6 still had a non-zero total; with the normalization loop
reverted the new form aborts 20 of 20 with Bad cast from type
DB::ColumnReplicated to DB::ColumnVector in sealPendingChunks, so the regression
oracle still detects the original defect. 50 runs with randomized settings and
50 without both pass.

The test was added by ClickHouse#115034.
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants