Repository navigation
Do not consume an empty final chunk in merging transforms - #117048
Conversation
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
|
Workflow [PR], commit [49f3609] Summary: ✅
AI ReviewSummaryThis PR changes Final Verdict✅ No findings. LLVM Coverage ReportMeasured on commit 49f3609.
Changed lines: Changed C/C++ lines covered: 72/76 (94.74%) · Uncovered code |
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 units7 translation units recompiled, 6 s compile time in total, 7 of them have a recent master baseline. |
…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
…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]>
…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]>
`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".
Changelog category (leave one):
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) inMergingSortedTransformwhen an input delivers a trailing empty chunk together with the end of its stream, e.g. underoptimize_read_in_order.Description
When an input of
IMergingTransformBasefinishes its port in the samepreparecycle that delivers a trailing empty chunk —BufferChunksTransform, which sits underMergingSortedTransformfor reads in order, drains its buffer exactly this way — the runtime path ofIMergingTransformBase::preparepassed the empty chunk to the algorithm.MergingSortedAlgorithm::consumethen pushed an empty cursor into the sorting queue:SortingQueueStrategy::Batch, the zero-size batch failschassert(max_rows > 0)inMergedData::rowsToInsertBeforeFlush— this is the AST fuzzer failureLogical error: 'max_rows > 0'on the querySELECT untuple(arrayJoin(arrayJoin(col1.n))) FROM nested__fuzz_31 ORDER BY id DESC NULLS LAST LIMIT -2147483649, 1048575 SETTINGS optimize_read_in_order = 1;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 withempty_chunk_on_finish(the join transforms) keep receiving their final emptyconsume, which theno_datapath 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%29Workflow [PR]
Sync PR [sync-upstream/pr/117048]