Skip to content

Do not consume an empty final chunk in merging transforms - #117048

Merged
alexey-milovidov merged 1 commit into
masterfrom
fix-merge-empty-final-chunk
Aug 29, 2026
Merged

alexey-milovidov merged 1 commit into
masterfrom
fix-merge-empty-final-chunk

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

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):

Fix a logical error max_rows > 0 (and possible incorrect merge results in release builds) in MergingSortedTransform when an input delivers a trailing empty chunk together with the end of its stream, e.g. under optimize_read_in_order.

Description

When an input of IMergingTransformBase finishes its port in the same prepare cycle that delivers a trailing empty chunk — BufferChunksTransform, which sits under MergingSortedTransform for reads in order, drains its buffer exactly this way — the runtime path of IMergingTransformBase::prepare passed the empty chunk to the algorithm. MergingSortedAlgorithm::consume then pushed an empty cursor into the sorting queue:

  • with SortingQueueStrategy::Batch, the zero-size batch fails chassert(max_rows > 0) in MergedData::rowsToInsertBeforeFlush — this is the AST fuzzer failure Logical error: 'max_rows > 0' on the query SELECT untuple(arrayJoin(arrayJoin(col1.n))) FROM nested__fuzz_31 ORDER BY id DESC NULLS LAST LIMIT -2147483649, 1048575 SETTINGS optimize_read_in_order = 1;
  • with both strategies, the heap comparisons read row 0 of the empty cursor's sort columns, which mis-merges the remaining inputs in release builds: the new two-input unit test loses a row of the output without the fix.

The fix treats a finished input whose final chunk is empty (and not a virtual row) as exhausted (onSourceExhausted), exactly like the initialization path already handles empty first chunks. Algorithms with empty_chunk_on_finish (the join transforms) keep receiving their final empty consume, which the no_data path already produces.

The regression test is a unit test because the trigger — a source that finishes its output port in the same cycle that pushes a trailing empty chunk — cannot be constructed deterministically from SQL.

Found by AST fuzzer (amd_debug, targeted) on #96844: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96844&sha=a79e87275f6c044d21bd99b1b3881b795fcb79a4&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29


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

When an input of `IMergingTransformBase` finishes its port in the same cycle
that delivers a trailing empty chunk (as `BufferChunksTransform` does when
draining its buffer), `prepare` passed the empty chunk to the algorithm.
`MergingSortedAlgorithm::consume` then pushed an empty cursor into the sorting
queue: with the batch strategy the zero-size batch failed
`chassert(max_rows > 0)` in `MergedData::rowsToInsertBeforeFlush` (AST fuzzer:
`Logical error: 'max_rows > 0'` on `SELECT ... ORDER BY id DESC ... SETTINGS
optimize_read_in_order = 1`), and with both strategies the heap comparisons
read row 0 of empty sort columns, mis-merging the remaining inputs in release
builds (the new two-input test loses a row without this fix).

Treat a finished input whose final chunk is empty (and not a virtual row) as
exhausted, like the initialization path already does for empty first chunks.

Found by AST fuzzer on #96844:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96844&sha=a79e87275f6c044d21bd99b1b3881b795fcb79a4&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
@alexey-milovidov alexey-milovidov mentioned this pull request Aug 29, 2026
1 task done
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49f3609]

Summary: ✅


AI Review

Summary

This PR changes IMergingTransformBase::prepare so a finished input's trailing empty non-virtual chunk is treated as source exhaustion instead of being passed into the merge algorithm, and adds focused unit coverage for the MergingSortedTransform failure mode. I did not find a correctness, compatibility, test-contract, or PR-metadata issue in the current version.

Final Verdict

✅ No findings.

LLVM Coverage Report

Measured on commit 49f3609.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 72/76 (94.74%) · 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 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 49f3609be with master 0cba27059 (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 710.14 MiB 707.09 MiB -3.05 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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into master with commit 4108949 Aug 29, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-empty-final-chunk branch August 29, 2026 21:37
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
…s pipeline shape

Reported by clickhouse-gh[bot] on ClickHouse#117259.

The second statement kept its six load-bearing settings on its inner subquery. `clickhouse-test`
injects randomized settings as client options with `--allow_repeated_settings`, and a client option
beats a subquery-level `SETTINGS` clause, so a randomized `optimize_read_in_order = 0`, which the
runner draws from `randint(0, 1)`, dropped `BufferChunksTransform` from that statement's pipeline
while `count` and `sum` still returned the reference values: the statement passed without observing
the merge it covers. Same defect and same fix as `c11b082a534ec09` on
`04489_virtual_row_disabled_with_final`. The bare statement was never affected, its `SETTINGS`
clause is already outermost.

Each runtime statement now has a shape assertion over the exact query it runs, so neither can lose
its coverage silently. Measured on a debug build: setting `read_in_order_use_buffering = 0` in the
new assertion turns its output to `0 1`, and letting `query_plan_remove_redundant_sorting` default
to 1 turns it to `0 0`, which is the case the report describes, while the counts stay at
`3000 / 4498500 / 4498500` either way.

Validation: 50 runs under default randomization, 8 concurrent runners times 3 runs, and 3 runs each
under `allow_experimental_analyzer = 0`, `serialize_query_plan = 1` and parallel replicas, no
failures. Style checks produce no output.

Related: ClickHouse#117048
Related: ClickHouse#116805
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
…dget

`Stateless tests (amd_asan_ubsan, flaky check)` failed this test on 4 of 50 runs with
`Test runs too long (> 180s)`, while its 46 passes ran 148.7-178.8 s: a mean sitting 1.2 s
under a hard per-file ceiling, not a non-deterministic test. The flaky check is the only
mode that enables the thread fuzzer, which sleeps on every `pthread_mutex_lock` and
`unlock`, and both runtime statements read at `max_block_size = 1`, so their cost tracks
the number of one-row chunks pushed through the merge. Reading 400 rows instead of 4000
cuts it by the same factor: with the fuzzer enabled and one debug binary, 583.8 / 587.8 s
before (a third run hit the 600 s per-test kill) against 82.5 / 84.0 / 88.9 s after, which
scales the failing lane's measured maximum to about 37 s. The two runtime selects fell from
304 s and 288 s to 31 s and 30 s, while the two inserts stayed near 9 s each, an insert's
cost under the fuzzer being independent of its row count.

Shrinking this fixture is not free, and getting it wrong is silent. The state is reached
only when all four partitions hold the same number of rows with values and the same number
without, so the row count and the threshold must both be multiples of the partition count.
Three otherwise-identical fixtures that break that (1000/750, 200/150, 100/75) pass on the
reverted build while still printing correct results and correct pipeline shapes. The new
first statement pins the split, so editing either number cannot leave the test covering
nothing: with the partitions split unevenly and the row counts held constant it prints
`0 0`.

With ClickHouse#117048's hunk reverted the shipped file still reddens 10 times out of 10. On master
it passes 10/10, 50/50 under randomized settings, 24/24 against itself in parallel, and
3/3 each under `allow_experimental_analyzer = 0`, `serialize_query_plan = 1` and parallel
replicas. Style checks produce no output.

Related: ClickHouse#117048
Related: ClickHouse#116805

Co-Authored-By: Claude Opus 5 <[email protected]>
pull Bot pushed a commit to Mattlk13/ClickHouse that referenced this pull request Sep 1, 2026
…mBase

The reproducer is @ tiandiwonder's, supplied in
ClickHouse#116805 (comment).
It contradicts the note in ClickHouse#117048 that the trigger cannot be constructed
deterministically from SQL.

Mechanism. `InputPort::pullData` caches `is_finished` with no `HAS_DATA` term, so a
consumer can pull a chunk from a port that already reads as finished.
`BufferChunksTransform`, which `SortingStep::mergingSorted` inserts for a read-in-order
merge of more than one stream when `read_in_order_use_buffering` is on, drains its
buffer exactly that way. Before ClickHouse#117048 the guard in `IMergingTransformBase::prepare`
was `!input_chunk.hasRows() && !virtual_row && !input.isFinished()`, so the
`!input.isFinished()` term let a rowless chunk arriving from an already finished port
fall through to `state.has_input = true` and be consumed.
`MergingSortedAlgorithm::consume` reset the cursor from that zero-row chunk and pushed
it into the batch sorting queue; `mergeBatchImpl` then computed `insertable_rows == 0`
and called `MergedData::rowsToInsertBeforeFlush` with `max_rows = 0`.

In the test the four per-partition FINAL streams each end in rows whose `vals` is
empty, the ARRAY JOIN turns those into the zero-row chunk, and that is the last chunk
the buffer pushes while the merge is still consuming the other three partitions.

Oracle, and its limit. This test's oracle is the `chassert(max_rows > 0)` in
`MergedData::rowsToInsertBeforeFlush`, which exists only in debug and sanitizer builds;
there it goes through `abortOnFailedAssertion`, so the observation is a server SIGABRT
rather than a query error. That is the whole of what this test covers. It does not
cover the release-visible consequence: `SortingQueueImpl::push`
(`src/Core/SortCursor.h`) calls `std::push_heap`, so the zero-row cursor is
compared, reading row 0 of zero-row sort columns, before control reaches
`rowsToInsertBeforeFlush` at all. That is the row loss ClickHouse#117048's own commit message
reports, and it stays covered by that PR's `TwoInputsTrailingEmptyChunk` gtest, not by
anything here. @ tiandiwonder observed correct results on a release build in the
configurations he tried; that is an observation over those configurations.

Every setting in the query is load-bearing. @ tiandiwonder's ablation, counting the
rowless pulls that reach the merge:

  as committed                                             4
  without FINAL                                            0
  without do_not_merge_across_partitions_select_final      0
  without optimize_read_in_order                           0
  without read_in_order_use_buffering                      0
  max_block_size = 64 instead of 1                         0
  max_threads = 4 instead of 1                             0

They are pinned per query rather than with SET, so the test runner's settings
randomization cannot move them.

Validation. Reverting only ClickHouse#117048's hunk on a debug build
(`git checkout 49f3609^ -- src/Processors/Merges/IMergingTransform.cpp`) reddens
this test 10 times out of 10, each time with the assertion firing in
`rowsToInsertBeforeFlush` reached from `mergeBatchImpl` on the batch sorting queue. On
master it passes 50 out of 50 with randomized settings, and 24 out of 24 when run
against itself in parallel, so it needs no `no-parallel` tag.

The second query is @ tiandiwonder's too, kept after measuring it. It needs
`query_plan_remove_redundant_sorting = 0`: without that, the inner ORDER BY feeding an
order-insensitive aggregate is removed, and with no sort there is no merge for the
rowless chunk to reach, which is why his own sweep saw the wrapped form reach the state
0 times out of 30. With the setting pinned it reaches the assertion 3 times out of 3 on
the reverted build. `count()` and `sum()` are order-insensitive, so it detects lost or
duplicated rows, not reordering.

A third statement pins the shape the two queries depend on: `EXPLAIN PIPELINE` must show
buffering in front of a sorted merge. `count()` and `sum()` are invariant under pipeline
shape, so without it a planner change that stopped inserting `BufferChunksTransform` for
this shape would leave the test green while it covered nothing. It asserts presence as a
boolean rather than an exact processor count, so neither the number of parallel copies nor
the rendered line count can redden it.

This does not make `gtest_merging_sorted_empty_chunk.cpp` redundant. `SortingStep::mergingSorted`
builds the merge only when there is more than one stream and hard-codes
`SortingQueueStrategy::Batch`, so the gtest's single-input case and its default-strategy case are
both out of reach of this query; other callers reach the default strategy
(`Interpreters/SortedBlocksWriter.cpp`, `Storages/MergeTree/MergeTask.cpp`) but not through this
test's pipeline. The gtest also builds its inputs by hand, where this test drives the real pipeline.

Related: ClickHouse#117048
Related: ClickHouse#116805

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 24, 2026
`FillingTransform`'s suffix path treats `generateSuffixIfNeeded` returning true
as "the suffix is applicable", which does not imply it produced any rows:
`WITH FILL ... STALENESS` with an exhausted staleness window leaves the result
columns freshly `cloneEmpty()`'d. The transform still emitted a 0-row chunk
built from them; now it skips the emit.

This branch was opened as a fix for an MSan use-of-uninitialized-value found by
the AST fuzzer, where a downstream `MergingSortedTransform` built a sort cursor
over that empty chunk and compared row 0 (`ColumnVector<UInt32>::doCompareAt`).
Two commits have since removed that consequence on master, so the uninitialized
read is no longer reachable through this path:

  - d7d00c4 (2026-07-27) restricted WITH FILL to the finalizing stage,
    so `EXPLAIN PIPELINE` puts `FillingTransform` above
    `MergingSortedTransform 2 -> 1`; the empty suffix is now produced
    downstream of the only merge in the plan.
  - 49f3609 (PR ClickHouse#117048) made `IMergingTransformBase::prepare` treat a
    finished empty chunk as source exhaustion, and covers that path with
    `src/QueryPipeline/tests/gtest_merging_sorted_empty_chunk.cpp`.

Measured on an MSan build of this branch's head: with the guard reverted the
reproducer is clean and the server survives. Controls: the guarded branch still
executes with an empty column (num_output_rows=0, UInt32, 0 raw bytes), and
performing that same row-0 compare at that site still aborts the build with
use-of-uninitialized-value, so the detector is live.

The stateless test is therefore dropped: its premise was the merge-side
consumption, which ClickHouse#117048 now covers at the consumer with its own gtest, and
it could no longer fail if this change were reverted. What remains is
suppression of a pointless empty chunk, with no user-visible effect, so the
changelog category becomes "Not for changelog".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants