Repository navigation
Conversation
The AST fuzzer hit chassert(max_rows > 0) in MergedData::rowsToInsertBeforeFlush, called from MergingSortedAlgorithm::mergeBatchImpl: 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 On a port with a non-empty header, "no data this step" has to be carried as a chunk with 0 rows and N columns, because OutputPort::pushData rejects a chunk whose column count differs from the header. Chunk::empty() is !hasRows() && !hasColumns(), so such a chunk is truthy and no `if (!chunk)` test in the tree sees it; ISimpleTransform::work() manufactures exactly this shape on purpose. IMergingTransformBase::prepare() did test hasRows(), but only in conjunction with !input.isFinished(). InputPort::isFinished() is (IS_FINISHED) && (HAS_DATA == 0), yet it short-circuits on the is_finished cache that pullData() fills from the pre-swap flags with no HAS_DATA term. So for the last chunk of an input whose producer finished while that chunk was in flight, one prepare() call reads not-finished at the pull and finished at the guard. The rowless chunk then becomes state.has_input, MergingSortedAlgorithm::consume() pushes a cursor over empty columns, and with that cursor alone in the queue updateBatchSize() yields 0, so rowsToInsertBeforeFlush is asked to insert zero rows. Route a rowless non-virtual chunk to the existing state.no_data path when the port is finished. That is what the next prepare() for the same source would produce anyway, so no row is dropped; prepareInitializeInputs() already skips such a chunk unconditionally, and the mid-merge path was the only hole. Seven of the eight sorted-merge algorithms index row 0 of the cursor unconditionally, and FinishAggregatingInOrderAlgorithm is the only one that guards with hasRows(). ColumnGathererStream builds no cursor: it throws RECEIVED_EMPTY_DATA on such a chunk today, and now takes the same source-exhausted path as a source that finishes without pushing anything. The three join algorithms receive the finished signal one step earlier, which is what empty_chunk_on_finish exists for. The assertion was added by 544a6b8; the empty-cursor state it trips on comes from the batch sorting queue and used to be absorbed by the insert-whole-chunk fast path that the call now precedes. The regression test is a new arm in the existing gtest_blocks_size_merging_streams module, because no natural producer of the rowless chunk could be found from SQL: with a probe on the guard, no rowless non-virtual chunk reached a merging transform in 907 stateless tests or in 41 configurations of the reported query, while the guard site itself executed over 126000 times and a forced arm proved the probe live. SortingQueueImpl::push() is left as it is, asymmetric with its own constructor, because it becomes unreachable for this state and src/Core/SortCursor.h is being rewritten elsewhere. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (click to expand)An independent reviewer read the resulting code cold, without the author's evidence, and a separate
Fix rounds this review: 2. Gate spend on this PR: $60.22. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260827-172800 |
|
Workflow [PR], commit [16ca15e] Summary: ❌
AI ReviewSummaryThis PR adds Findings
Tests
Final VerdictStatus:
LLVM Coverage ReportMeasured on commit 16ca15e.
Changed lines: Changed C/C++ lines covered: 118/120 (98.33%) · Uncovered code |
|
cc @vdimir @davenger, could you review this? |
Routing a rowless chunk from a finished input to the source-exhausted path hands
ColumnGathererStream a notification it does not handle. Gathering is driven by
`row_sources_buf` and re-requests a source only while the mask still maps rows to
it, so the default no-op `onSourceExhausted` leaves `merge` asking the same
finished source again. `consume` used to raise `RECEIVED_EMPTY_DATA` for that
input, and the existing guard in `merge` cannot stand in for it: it tests
`sources[n].size`, which still holds the size of the block the source delivered
earlier.
An override restores that error, and finishes rather than raising it when a single
source is read without a mask, where an exhausted source has already delivered
everything the result needs. That case is reachable for a vertical merge of one
part with no skipped rows, where the rows_sources file is not written at all.
Both states already spun before this change, when a required source finished with
no trailing chunk: without the override each spins at 100 percent CPU, 200001
`merge` calls with `next_required_source` pinned at 0 and `sources[0].size` at 2.
Four arms cover it, each pinned to one condition by a mutation that leaves the
others passing. Dropping the `row_sources_buf.eof()` conjunct spins one source
whose mask still demands rows; dropping the pass-through branch turns the
no-mask arm into `RECEIVED_EMPTY_DATA`; dropping the handling for a rowless chunk
from an input that has NOT finished loses the rows that input still owes, which
`RowlessChunkFromUnfinishedInput` catches as `{0, 1, 2, 3, 100, 101}` against the
expected eight keys.
The comment on the test source named `ISource::prepare` as the origin of the
rowless chunk shape. `ISimpleTransform::work` is what builds it, so that a
chunk's column count matches a non-empty header; `ISource::prepare` only finishes
the port while such a chunk is still in flight.
Co-Authored-By: Claude Opus 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units23 translation units recompiled, 148 s compile time in total, 23 of them have a recent master baseline. |
CI finish ledger - 1f4ec66CI is fully finished on this commit and clean, so there is no failure for this ledger to assign an owner to.
Session id: cron:our-pr-ci-monitor:20260828-063000 |
The same fix landed on master as `49f3609beda3` ("Do not consume an empty final
chunk in merging transforms"), and master's version is the superset: besides
setting `no_data`, it also clears `state.input_chunk`. Took master's version of
`IMergingTransform.cpp`.
What remains from this branch is the part master does not have: the same guard in
`ColumnGathererTransform`, and the regression tests in
`src/QueryPipeline/tests/gtest_blocks_size_merging_streams.cpp`. Those assert the
behaviour both implementations provide, but they were not run here - there is no
build in this environment - so the unit-test job is the check for them.
The translation unit was compiled after the resolution.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
….cpp
Requested in review: a reader landing on both files should not have to work out
which arm pins what.
`RowlessChunkFromFinishedInput` covers the same condition as
`gtest_merging_sorted_empty_chunk.cpp`, a rowless last chunk delivered as the
port finishes, and checks the merged keys rather than the row count. Reverting
master's whole rowless-chunk guard reddens both arms of that file and both arms
here.
`RowlessChunkFromUnfinishedInput` covers the other direction. Dropping only the
"input has not finished, wait for it" branch from master's guard loses the rows
the source still owed, {0, 1, 2, 3, 100, 101} for eight expected keys, while
both arms of that file stay green.
|
The Not caused by this PR. The failure has hit every |
The three `ColumnGathererTest` arms drove a real `ColumnGathererTransform` pipeline to completion. The defect they pin, an exhausted gather source re-requested forever, is a busy spin inside a single `PullingPipelineExecutor::pull` call, so on a binary without the fix they do not fail, they never return. `Bugfix validation (unit tests)` builds the merge base with only the changed test files overlaid and needs at least one touched test to fail there. A hang is neither a failure nor a crash, so the job spent its full 4 hour budget in `SingleSourcePassThrough` and was killed, reporting ERROR. Drive the transform through its ports instead, stepping `prepare` and `work` for a bounded number of rounds, the way `gtest_grouping_aggregated_transform_bucket_pushed_once.cpp` does. Port exhaustion, `IMergingTransformBase::prepare` and the dispatch to `onSourceExhausted` remain the production ones, so the arms also fail if that dispatch is removed. What they assert is unchanged, the rows gathered for the pass-through case and `RECEIVED_EMPTY_DATA` for the two shortage cases. Measured one arm per process on a debug build: the three arms fail in 0.34 s wall instead of hanging, both on the merge base and with the fix present but the dispatch removed from `IMergingTransform`. With the fix all seven arms in the file pass, including 50 repeats.
|
That job rebuilds the merge base with only the changed test files overlaid and needs at least They now drive the transform through its ports, stepping One arm per process, debug build:
The last row is what the previous shape would have passed. @ tiandiwonder the two |
| { | ||
| /// A single source with no mask is passed through block by block, so once it is exhausted it has | ||
| /// delivered everything the result needs and the merge is done. | ||
| if (sources.size() == 1 && row_sources_buf.eof()) |
There was a problem hiding this comment.
Finishing the single-source case here makes the existing fast path in ColumnGathererStream::merge (src/Processors/Transforms/ColumnGathererTransform.cpp:126-135) the committed result, but that branch still returns sources.front().column verbatim instead of using the result_column-aware whole-block logic from :98-112 / :160-170. That matters for representation-sensitive columns: ColumnGathererStep still passes merge_max_dynamic_subcolumns_in_*_part into this transform (src/Storages/MergeTree/MergeTask.cpp:1972-1985), and ColumnDynamic::chooseDynamicStructureForMerge / ColumnObject::chooseDynamicStructureForMerge can shrink even a one-part merge to the chosen variant/path set. As written, a single-part vertical merge can now stop hanging but still write the source Dynamic / JSON layout instead of the merged one. Please route this branch through the same helper as the other whole-block returns, and add a one-part JSONDynamicPaths / JSONSharedDataPaths regression.
There was a problem hiding this comment.
Verified before acting, and I am not making this change. Three measurements.
This PR does not touch that branch. The whole source diff against the merge base is the new onSourceExhausted: +15 lines in ColumnGathererTransform.cpp, +1 in the header. merge()'s single-source fast path, including the verbatim res.addColumn(std::move(sources.front().column)), is unmodified master code.
The override contributes no column data, so it cannot make a layout the committed result. One instrumented build, with the override switchable off to reproduce master's no-op, one arm per process:
| override | master | |
|---|---|---|
| chunks carrying columns | 1 | 1 |
| rows emitted | 3 | 3 |
| fast-path returns / rows | 1 / 3 | 1 / 3 |
| terminal empty chunk | 1 | 0 |
onSourceExhausted entries |
1 | 998 (loop bound) |
Master emits the identical chunk from the identical branch, then never terminates. The override adds one empty chunk and finishes. So there is no state where master commits a merged layout and this PR commits the source one, because master commits nothing.
The regression you ask for cannot arm the branch. I ran it: a one-part Dynamic vertical merge with merge_max_dynamic_subcolumns_in_wide_part = 1. The setting does reach the transform (num_inputs=1 max_dynamic_subcolumns=1, once per gathering column), the merge rewrites the part, and the fast path takes 0 hits. Both columns return through the result_column-aware routes (:181-187; a two-part control also hits :160-170). The counter is live in that binary, since it fires in a unit test built from the same file. Entering :126-135 needs row_sources_buf at eof with source rows still unread, the mismatch the note at :124-125 already flags, and a vertical merge writes one mask entry per row.
Forced into that state at unit level the branch does return the source structure Variant(Float64, Int8, SharedVariant, String) where the merge had chosen one dynamic type plus the shared variant, so the asymmetry you describe is real. It is pre-existing, I have no query that reaches it, and I am not editing core merge code on a reading alone.
|
Correcting my earlier review comment on this PR: I said the Here is the reproducer, as a stateless test. It joins the existing
-- An input can finish its port while the chunk it just pushed is still in flight, so a merging
-- transform can pull a chunk with no rows from an input that already reads as finished:
-- `InputPort::pullData` caches `is_finished` with no `HAS_DATA` term. Here `BufferChunksTransform` is
-- the producer. The tail of every partition holds only empty arrays, so the last chunk it pushes is
-- the `0 rows / N columns` shape `ARRAY JOIN` builds, and the merge is still busy with the other three
-- partitions when the port finishes.
DROP TABLE IF EXISTS t_read_in_order_3;
CREATE TABLE t_read_in_order_3 (p UInt8, k UInt32, v UInt32, vals Array(UInt32))
ENGINE = ReplacingMergeTree(v) PARTITION BY p ORDER BY k
SETTINGS min_bytes_for_wide_part = 0, index_granularity = 8;
-- Keep two parts per partition so the per-partition `FINAL` merge is a real merge.
SYSTEM STOP MERGES t_read_in_order_3;
INSERT INTO t_read_in_order_3 SELECT number % 4, number, 1, if(number >= 3000, [], [toUInt32(number)]) FROM numbers(4000);
INSERT INTO t_read_in_order_3 SELECT number % 4, number, 2, if(number >= 3000, [], [toUInt32(number)]) FROM numbers(4000);
-- Without the fix this reaches `MergedData::rowsToInsertBeforeFlush` with `max_rows = 0`, which is
-- `Logical error: 'max_rows > 0'` in debug and sanitizer builds. Every setting below is load-bearing,
-- and the query must run bare: reading the result through an aggregate changes the plan and the
-- rowless chunk never reaches the merge.
SELECT k, x FROM t_read_in_order_3 FINAL ARRAY JOIN vals AS x ORDER BY k
SETTINGS do_not_merge_across_partitions_select_final = 1, optimize_read_in_order = 1,
read_in_order_use_buffering = 1, max_threads = 1, max_block_size = 1
FORMAT Null;
-- The rowless chunk must displace neither the rows its own source still owes nor the other sources'.
SELECT count(), sum(k), sum(x) FROM
(
SELECT k, x FROM t_read_in_order_3 FINAL ARRAY JOIN vals AS x ORDER BY k
SETTINGS do_not_merge_across_partitions_select_final = 1, optimize_read_in_order = 1,
read_in_order_use_buffering = 1, max_threads = 1, max_block_size = 1
);
DROP TABLE t_read_in_order_3;
Verified 3/3 from a clean data directory: each run produces 4 Every setting in the query is load-bearing, so they are pinned per-query rather than via
Insensitive to Two caveats. I could not confirm the assertion actually fires on an unfixed debug build — my binary is Since the code it covers is master's via #117048, whether this lands here or as a follow-up is your call. |
tiandiwonder
left a comment
There was a problem hiding this comment.
Two things on the metadata, now that master has moved under this PR. (The reproducer and the correction to my earlier comment are in a separate comment, so I won't repeat them here.)
0a602ae31ae merged master, which already carries the IMergingTransformBase::prepare change via #117048 (49f3609beda, merged 2026-08-29). So the diff is now ColumnGathererStream::onSourceExhausted plus the test arms — git diff 1f4ec667b7f..HEAD over those three files is empty, the code itself is unchanged and still correct.
But the description still presents the prepare guard as "The change", and the changelog entry still reads "Fixed a logical error max_rows > 0 in MergedData::rowsToInsertBeforeFlush during a sorted merge". As written, CHANGELOG.md would attribute Alexey's fix to this PR, and #117048 isn't linked anywhere in the body. The entry wants rewriting around what remains: ColumnGathererStream has no onSourceExhausted override on master, so a required-and-exhausted source hits the no-op base and merge re-requests it forever.
That moves the category question rather than settling it. Two paths reach the spin and they aren't equivalent — the pre-existing one from b2b7bdb327e (required source finishes with no chunk at all), and the one #117048 widened (finishes with a trailing rowless chunk). #117048 is on unreleased master, so only the first can support "user-visible misbehavior in an official stable release". I stressed that path: 40 OPTIMIZE ... FINAL runs across a ReplacingMergeTree and a MergeTree with lightweight deletes, both forced onto the vertical algorithm, merge_max_block_size from 1 to 8192 — 0 hangs, 0 errors, with the probe confirming the gatherer was active (155 events). So the spin doesn't look reachable from ordinary vertical merges, which cuts against that category rather than for it. The new override's throw arm is correspondingly defensive rather than a regression risk, and both of its conditions are pinned by RequiredSourceExhausted and SingleSourceWithRemainingMask.
Also worth correcting: the Validation section's "No plain-SQL reproducer" no longer holds — see the other comment.
|
No need to apologise, and the reproducer is the useful half. Metadata. The retarget landed at 2026-08-30 11:23:33Z, about twelve hours before your review, and was the last body edit until the category change I just made. The entry reads:
Category. Changed to Reproducer. Follow-up PR, not this one. It covers #117048's |
| { | ||
|
|
||
| /// Pushes the given blocks in order, sending a chunk that carries the header columns and no rows in | ||
| /// place of every empty entry, and finishing the port in the same `prepare()` as the last entry. A |
There was a problem hiding this comment.
prepare rather than prepare() here — the prose refers to the method, not a call. (the Status prepare() override and processor->prepare() you added are code, those are fine.)
| /// place of every empty entry, and finishing the port in the same `prepare()` as the last entry. A | |
| /// place of every empty entry, and finishing the port in the same `prepare` as the last entry. A |
There was a problem hiding this comment.
Applied verbatim in 16ca15e.
I also swept the other 29 comment lines this PR adds for the same two classes, a method written as f() in prose and an unbackticked class/file/function name, and your two are the only hits, so there is nothing else of this kind left in the diff.
| start = 100; | ||
| auto second = getBlockWithSize(key_columns, 2, 1, start); | ||
|
|
||
| /// Alternate the sources so that gather() cannot copy a whole block at once, then ask for one |
There was a problem hiding this comment.
same here, plus it's missing backticks.
| /// Alternate the sources so that gather() cannot copy a whole block at once, then ask for one | |
| /// Alternate the sources so that `gather` cannot copy a whole block at once, then ask for one |
… config so the upgrade check can start the previous release)
CI finish ledger for 6b4fa92Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
Two facts behind that second row, because praktika already classifies it correctly and the red still stands.
The residual is that the retry is whole-run only, so a run mixing an infra-killed job with a real failure Session id: cron:our-pr-ci-monitor:20260831-013002 |
Prose references to a method are written as `f`, not `f()`, and literal names are wrapped in inline code (.claude/CLAUDE.md). Comment-only; the `prepare()` calls in the code are untouched. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Opened as #117259. The mutation check holds, so it is a live regression test for #117048 rather than a marker-only one: Two changes to the version posted here, both from measurement. The aggregate-wrapped query needs Thanks for the reproducer, @ tiandiwonder. |
…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
|
Fixing PR for the |
…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]>
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
AST fuzzer (amd_debug) / Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID 2270-3258) |
pre-existing trunk logical error: a distributed read whose header carries no table column diverges from what RemoteSource pushes |
#113469 (mine, open) |
Stress test (amd_tsan) / Logical error: Unexpected return type from A. Expected B. Got C (STID 3262-40c8) |
pre-existing trunk logical error on the globalIn shape, where a partially folded argument leaves the function's declared and actual return types disagreeing |
#116980 (external, open) |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / Container memory budget exceeded (/docker) |
same leaf OOM as above | #117202 (external, merged 2026-08-31), absent from this tree |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) |
/docker cgroup leaf OOM kills the concurrent shutdown gdb attaches; job ERROR, no test failed |
#117202 (external, merged 2026-08-31), absent from this tree |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
same leaf OOM as above | #117202 (external, merged 2026-08-31), absent from this tree |
CH Inc sync |
- | CH Inc sync (private, not actionable) |
The Container memory budget exceeded (/docker) rows are one signature, not several. The
/docker cgroup leaf that bounds the nested test containers is capped at 40.78 GiB, and
docker compose stop signals every node of a cluster at once, so each node that outlives the
60 s deadline attaches gdb at the same moment. On an ASan build each attach holds about
3.4 GiB of anonymous memory, so a nine-node cluster asks for roughly the whole leaf and the
kernel kills the debuggers. #117202 serializes that attach and is merged, but
fixpresence puts it OUTSIDE the tree this run built (compare(fix...head) reports this head
behind the fix commit 7fc3004ed25a, and the fix symbol GDB_ATTACH_LOCK is absent at
16ca15e1e389 while present at 7fc3004ed25a), so the run predates it. These rows clear when the
branch next picks master up. I am not merging master here purely to re-run CI, to keep the
review load down.
Measured caveat, stated so it is not a surprise later: on true-master trees that DO contain
#117202, the 2/6 and 5/6 shards are clean (0 of 4 post-fix trees) but 6/6 still fires
(4 of 4). So a 6/6 row may return after the master merge. That residual is tracked, and its
fixing-PR link will be posted here if it does.
This PR's diff is the MergedData::rowsToInsertBeforeFlush batch merging change. It touches
neither distributed header construction, nor globalIn folding, nor the integration harness.
Mergeable Check, Finish Workflow and PR are praktika aggregators. They report the rows
above and carry no separate defect. Config Workflow, Style check and Code Review are all
success on this head.
Session id: cron:our-pr-ci-monitor:20260831-183000
…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]>
|
Dear @tiandiwonder, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ColumnGathererStreamnow finishes, or reports an error, when a gather source it still needs is exhausted, instead of requesting that source forever.Description
Related: #117048
IMergingTransformBasereports an input that finished without data throughonSourceExhausted.ColumnGathererStreamdid not override it, so the default no-op leftnext_required_sourcepointing at the finished source and the transform requested it again. With the override removed, each of the threeColumnGathererTestarms below runs until it is killed: 99 percent CPU for 15 s, no rows produced.ColumnGathererStreamis the gatherer of a vertical merge, so this is a background merge that never completes.The override splits the two cases. A single source read without a
row_sourcesmask is passed through block by block, so once it is exhausted the result is complete and the merge finishes. When the mask still maps rows to a source that cannot deliver them the gathered column would be short, so that case keeps the existingRECEIVED_EMPTY_DATAerror rather than looping.The
IMergingTransformBase::preparehalf of this report shipped separately in #117048, so what is left here is the gatherer and its tests. Two of the five arms cover master's guard:RowlessChunkFromFinishedInputis the casegtest_merging_sorted_empty_chunk.cppalso covers, andRowlessChunkFromUnfinishedInputis the direction it does not, where the source that pushed the rowless chunk is still running.No SQL query is known to reach either arm, so this is
Not for changelog; the user-visiblemax_rows > 0failure is #117048's. Forced vertical merges do not spin (40 runs overReplacingMergeTreeandMergeTreewith lightweight deletes, gatherer active; measured in review by @ tiandiwonder), and a vertical merge writes onerow_sourcesentry per output row, so the mask is never at eof with rows still unread: that is the only way into the pass-through branch, and it took 0 hits on one-part and two-part merges.Found by
AST fuzzer (amd_debug, targeted), STID 2508-4725: report.Validation
Debug build, one arm per process, each mutation applied on its own.
Mutations of
ColumnGathererStream::onSourceExhausted:ColumnGathererTestarmsSingleSourcePassThroughRECEIVED_EMPTY_DATAinstead of all 3 rowsSingleSourceWithRemainingMaskrow_sources_buf.eof()conjunct droppedMutations of master's
IMergingTransformBase::prepare:RowlessChunkFromFinishedInputRowlessChunkFromUnfinishedInputgtest_merging_sorted_empty_chunk.cppmax_rows > 0max_rows > 0{0, 1, 2, 3, 100, 101}for eight expected keysAll 7 arms pass on the head of this branch.
Workflow [PR]
Sync PR [sync-upstream/pr/116805]