Skip to content

Fix an endless loop in ColumnGathererStream when a gather source is exhausted - #116805

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-rowless-chunk-as-merge-data
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:fix-rowless-chunk-as-merge-data

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 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):

ColumnGathererStream now finishes, or reports an error, when a gather source it still needs is exhausted, instead of requesting that source forever.

Description

Related: #117048

IMergingTransformBase reports an input that finished without data through onSourceExhausted. ColumnGathererStream did not override it, so the default no-op left next_required_source pointing at the finished source and the transform requested it again. With the override removed, each of the three ColumnGathererTest arms below runs until it is killed: 99 percent CPU for 15 s, no rows produced. ColumnGathererStream is 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_sources mask 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 existing RECEIVED_EMPTY_DATA error rather than looping.

The IMergingTransformBase::prepare half 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: RowlessChunkFromFinishedInput is the case gtest_merging_sorted_empty_chunk.cpp also covers, and RowlessChunkFromUnfinishedInput is 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-visible max_rows > 0 failure is #117048's. Forced vertical merges do not spin (40 runs over ReplacingMergeTree and MergeTree with lightweight deletes, gatherer active; measured in review by @ tiandiwonder), and a vertical merge writes one row_sources entry 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:

Arm Mutation Without it
all three ColumnGathererTest arms whole override removed, as on master endless loop: 99 percent CPU, killed at 15 s, 0 rows
SingleSourcePassThrough pass-through branch dropped RECEIVED_EMPTY_DATA instead of all 3 rows
SingleSourceWithRemainingMask row_sources_buf.eof() conjunct dropped endless loop

Mutations of master's IMergingTransformBase::prepare:

Mutation RowlessChunkFromFinishedInput RowlessChunkFromUnfinishedInput gtest_merging_sorted_empty_chunk.cpp
whole rowless-chunk guard reverted max_rows > 0 max_rows > 0 both arms red
only the "input has not finished, wait" branch dropped passes {0, 1, 2, 3, 100, 101} for eight expected keys both arms pass

All 7 arms pass on the head of this branch.


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

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent reviewer read the resulting code cold, without the author's evidence, and a separate
model re-reviewed the diff each round. Findings and verdicts:

# Finding Verdict
❌ The added comments claimed that every merging algorithm indexes row 0 of the cursor it would build from a rowless chunk. Agreed, fixed. False for 5 of the 12 concrete algorithms: FinishAggregatingInOrderAlgorithm::consume returns on !hasRows(), ColumnGathererStream builds no cursor and throws instead, and the three empty_chunk_on_finish algorithms take an empty Input as their completion signal. Both comments now state the invariant without the universal claim.
❌ The pre-PR gate answer for virtual rows asserted that a rowless virtual chunk underflows 0 - 1 to SIZE_MAX and passes the assertion. Agreed, fixed. That state does not exist: setVirtualRow ends with setColumns(columns, 1), so a virtual chunk always carries exactly one row and mergeBatchImpl returns early before insertable_rows is computed. The !virtual_row conjunct is still required, because a virtual row is legitimately merge data.
❌ The regression test asserted only that 8 rows came out. The fixture seeds the two sources with disjoint keys and then never inspects a value, so a mutant emitting one source's rows twice would pass. Agreed, fixed. The arm now asserts the exact sequence {0, 1, 2, 3, 100, 101, 102, 103}, and that this is load-bearing is measured rather than argued: against a fixture mutant reseeding the second source onto the first source's keys, the new oracle reddens on {0, 0, 1, 1, 2, 2, 3, 3} while a build differing only in restoring the old row-count oracle passes that same mutant. The release-build effect of this state is wrong values at a plausible row count, not a missing row.
⚠️ The test would pass on unfixed code in a release build, since chassert compiles away there, so it does not prove the behaviour outside debug and sanitizer builds. Disagreed, with evidence. The fact is right, the consequence is not. unit_tests_dbms has no release-build job here: it is consumed by UNITTEST_AMD_ASAN_UBSAN, UNITTEST_AMD_TSAN, UNITTEST_AMD_MSAN and UNITTEST_LLVM_COVERAGE only (ci/defs/defs.py:499-502, ci/defs/job_configs.py:1068-1102), and chassert is live under DEBUG_OR_SANITIZER_BUILD (base/base/defines.h:85). There is also nothing for a release-build oracle to assert here: with the assertion compiled out, MergedData::insertChunk accepts the rowless chunk, pull() returns it with zero rows and IMergingTransform::work drops it, so this arm's unfixed release output is identical.
⚠️ Detecting the fix needs a probe that requires the source-exhausted notification to arrive. Disagreed, with evidence. In the pipeline this arm can build, that notification has no observable consequence: onSourceExhausted calls releaseDeferredSource, which decrements prefetches_in_flight only for a source in PrefetchIssued (never here, with no deferral and no virtual rows), and sets merge_advanced_past_source, already redundant because the arm passes limit = 0 and the consumer tests limit == 0 || merge_advanced_past_source. Observing its absence would need a bespoke recording IMergingAlgorithm, pinning a test to an internal API. The value assertion above was taken instead.
💡 ColumnGathererStream is the one carrier whose outcome does not obviously improve: it throws RECEIVED_EMPTY_DATA on such a chunk today, and afterwards takes the pre-existing source-exhausted path. Noted, not blocking. The error is unchanged in kind and only moves site: consume threw RECEIVED_EMPTY_DATA at ColumnGathererTransform.cpp:205, merge() now throws it at :145, since sources[].size is written only in Source::update and stays 0. Only the sources.size() == 1 && row_sources_buf.eof() branch can re-request the same source, and its own comment records that state as one row_sources_buf cannot produce; it is reachable today through the port-finished path, so this adds an arrival route rather than a state. With a probe on the guard, no rowless non-virtual chunk reached a merging transform in 907 stateless tests or 41 configurations of the reported query. Recorded rather than guarded, in a file this change deliberately leaves alone.
💡 The description did not name the CIDB test id alongside the check name and the report URL. Fixed before publication.

Fix rounds this review: 2. Gate spend on this PR: $60.22.

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. taskset -c 0 build/src/unit_tests_dbms --gtest_filter='MergingSortedTest.RowlessChunkFromFinishedInput' aborts on demand on the unfixed tree. No randomization, no server, no timing dependency.
b Root cause explained? YES. A port with a non-empty header must carry "no data" as 0 rows / N columns, Chunk::empty() is !hasRows() && !hasColumns() so it is truthy, and IMergingTransformBase::prepare's hasRows() test was conjoined with !input.isFinished(), whose cache pullData sets from the pre-swap flags without a HAS_DATA term. One prepare therefore reads not-finished at the pull and finished at the guard, the rowless chunk becomes merge data, consume pushes a cursor over empty columns, and with that cursor alone in the queue the batch size is 0, so rowsToInsertBeforeFlush is asked for zero rows.
c Fix matches root cause? YES. The change is at the layer that breaks the invariant (prepare must not deliver a rowless chunk as data), not at the assertion, not at the queue, not at a producer. No widened bound, no no-random-* tag, no data-size reduction, no defensive check masking an upstream bug.
d Test intent preserved / new tests added? YES. A source fix ships a regression test, added as one arm to the existing gtest_blocks_size_merging_streams.cpp module rather than a new file. The two pre-existing arms of that module are untouched and still pass. A negative control (only the changed condition reverted) turns the new arm red again, so it is pinned to this fix.
e Both directions demonstrated? YES. Unfixed build: Logical error: 'max_rows > 0'. with the same MergedData.cpp:255 / MergingSortedAlgorithm.cpp:616 / IMergingTransform.h:150 frames and the same SortingQueueStrategy::Batch specialization as the CI report. Fixed build: passes, both sources' rows returned, 50/50 on repeat. Both arms on Build-ID-verified binaries.
f Fix is general across code paths? YES. One condition covers every merging algorithm at once: 7 of the 8 sorted-merge algorithms index row 0 of the cursor unconditionally, FinishAggregatingInOrderAlgorithm already guarded, and ColumnGathererStream builds no cursor. prepareInitializeInputs already skipped such a chunk, so the two paths now agree. Siblings checked and deliberately not changed: SortingQueueImpl::push (unreachable after this change) and IInflatingTransform::work (a rowless chunk on a port is legal).
g Fix generalizes across inputs (params/datatypes/wrappers)? YES by construction: the condition tests the chunk's row count, so it is type- and setting-independent. Exercised across both queue strategies (Batch in the test and in every SortingStep shape, Default via OPTIMIZE ... FINAL), 8 algorithms, 1 to 3 sources, max_block_size 100 and 8192. The !virtual_row conjunct is preserved on purpose: a virtual row is legitimately merge data, and setVirtualRow gives its chunk exactly one row, so it is never the rowless case.
h Backward compatible? (maintainer-approved exception only) YES. No setting, no serialization format, no on-disk change, no new validation on existing data, so no SettingsChangesHistory.cpp entry and no experimental gate. Only the internal step ordering inside one prepare() changes.
i Invariants and contracts preserved? YES. The invariant: IMergingAlgorithm::consume(Input &, size_t) receives either a chunk with rows, or, only when empty_chunk_on_finish, a default-constructed Input. It now holds on every path including the NeedData early return. state.input_chunk is read at exactly one place, under state.has_input, so it is dead on the new path, and the one algorithm that reads chunk infos off an input chunk already guards with hasRows(). Termination is preserved: merge() returns required_source only after queue.removeTop(), so the queue shrinks monotonically. No lock, allocation or lifetime change.

Session id: cron:clickhouse-impl-slot-4:20260827-172800

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [16ca15e]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Unexpected return type from A. Expected B. Got C (STID: 3262-40c8) FAIL cidb
AST fuzzer (amd_debug) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) ERROR
Container memory budget exceeded (/docker) ERROR cidb

AI Review

Summary

This PR adds ColumnGathererStream::onSourceExhausted so an exhausted gather source no longer gets re-requested forever, and it rewrites the regression tests so the unfixed behavior fails in bounded time. I would still request changes: the new completion path leaves the single-source fast path returning the source column verbatim, which can bypass the merged Dynamic / JSON structure chosen from merge_max_dynamic_subcolumns_*.

Findings

⚠️ Majors

  • [src/Processors/Transforms/ColumnGathererTransform.cpp:213] [dismissed by author -- https://github.com/Fix an endless loop in ColumnGathererStream when a gather source is exhausted #116805#discussion_r3890398574] The new onSourceExhausted override now lets the single-source / no-mask case terminate, but ColumnGathererStream::merge still returns sources.front().column directly in its sources.size() == 1 && row_sources_buf.eof() fast path (src/Processors/Transforms/ColumnGathererTransform.cpp:126-135) instead of using the result_column-aware whole-block logic already used at :98-117 and :155-178. That is not dead code: initialize always runs chooseDynamicStructureForMerge / takeOrCalculateStatisticsFrom first, and MergeTask explicitly allows the rows_sources file to be omitted for a single source part at src/Storages/MergeTree/MergeTask.cpp:1808-1812. A one-part vertical merge can therefore finish now but still write the source Dynamic / JSON layout, ignoring merge_max_dynamic_subcolumns_* and producing the wrong JSONDynamicPaths / JSONSharedDataPaths for the new part. Suggested fix: route the single-source fast path through the same helper used by the other whole-block returns, then add a focused one-part regression.
Tests
  • ⚠️ Add a one-part vertical-merge or mutation regression for Dynamic / JSON with merge_max_dynamic_subcolumns_* set below the source structure size, and assert JSONDynamicPaths / JSONSharedDataPaths after the gatherer path. The existing 03638_merge_max_dynamic_subcolumns_* tests cover the pre-merge read and the two-part merge, not the single-source rows_sources-omitted path this PR now allows to complete.
Final Verdict

Status: ⚠️ Request changes

  • Minimum required actions: make the single-source fast path preserve the merged Dynamic / JSON structure (and merged statistics if relevant), then add the focused regression above.

LLVM Coverage Report

Measured on commit 16ca15e.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 80.90% -0.10%

Changed lines: Changed C/C++ lines covered: 118/120 (98.33%) · 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 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @davenger, could you review this? IMergingTransformBase::prepare tested hasRows only in conjunction with !input.isFinished, so when a producer finished its port while its last chunk was still in flight, a chunk with 0 rows and N columns became merge data and consume pushed a cursor over empty columns, which aborts debug and sanitizer builds on chassert(max_rows > 0). Such a chunk now takes the existing source-finished path instead.

@tiandiwonder tiandiwonder self-assigned this Aug 27, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 16ca15e1e with master ac95bf3cf (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1f4ec66

CI is fully finished on this commit and clean, so there is no failure for this ledger to assign an owner to.

  • 175 check runs in a single workflow run (33131516374): 150 success, 0 failure, 25 skipped. Last completion 2026-08-28T06:19:01Z, Config Workflow and Finish Workflow both green.
  • CIDB control at this exact commit: 307057 rows across 151 checks, 0 FAIL/ERROR, so the zero is measured rather than missing ingestion.
  • All 9 Unit tests (*) arms ran and passed, which is the relevant signal here because the diff changes gtest_blocks_size_merging_streams.cpp.
  • The 5 Stateless tests (*, flaky check) skips are correct rather than lost coverage: this diff touches no stateless test, so the flaky check has nothing to re-run. The remaining skips are the routine set (Bugfix validation, PGO/BOLT toolchain, Dockers Build, Performance Comparison, PromQL Compliance, Mintlify, integration flaky). No test-matrix job was dropped.

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.
@groeneai groeneai changed the title Do not pass a chunk with no rows to merging algorithms as data Fix an endless loop in ColumnGathererStream when a gather source is exhausted Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The Upgrade check (amd_release) failure on 6054f44 is owned by #117172, which version-gates the silk.xml test config so the previous-release server can start.

Not caused by this PR. The failure has hit every Upgrade check (amd_release) run since 13:48:57Z today, across more than 20 unrelated PRs, starting when v26.8.1.2041-lts became the previous release: install.sh symlinked config.d/silk.xml unconditionally, and a 26.8 server rejects enable_silk_runtime as an unknown config element.

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

Copy link
Copy Markdown
Collaborator Author

Bugfix validation (unit tests) was red on the previous head, and it was mine.

That job rebuilds the merge base with only the changed test files overlaid and needs at least
one touched test to fail there. The three ColumnGathererTest arms pulled a real pipeline to
completion, and the defect they pin is a busy spin inside one PullingPipelineExecutor::pull
call, so without the fix they never returned rather than failing: the job sat in
SingleSourcePassThrough for 3 h 8 min and was killed at its 4 hour timeout.

They now drive the transform through its ports, stepping prepare and work for a bounded
number of rounds, as gtest_grouping_aggregated_transform_bucket_pushed_once.cpp does. Port
exhaustion, IMergingTransformBase::prepare and the dispatch to onSourceExhausted are still
the production ones, and what the arms assert is unchanged.

One arm per process, debug build:

Arm 3 ColumnGathererTest arms wall
this head pass (7/7 in the file, 50 repeats) 0.46 s
merge base, no onSourceExhausted fail x3 0.34 s
fix present, dispatch removed from IMergingTransform fail x3 0.34 s

The last row is what the previous shape would have passed. @ tiandiwonder the two
MergingSortedTest arms are untouched; only the ColumnGathererTest helper changed shape.

{
/// 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())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@tiandiwonder

tiandiwonder commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Correcting my earlier review comment on this PR: I said the BufferChunksTransform attribution "does not hold up" and reported 239 runs with zero events. It does hold up — I was probing the wrong plan shape, and one of my sweeps was self-defeating, since wrapping the query in an aggregate suppresses the state entirely. #117048's commit message is right, and so is the mechanism in your description. Sorry for the noise.

Here is the reproducer, as a stateless test. It joins the existing 03168_read_in_order_buffering_* cluster, since BufferChunksTransform is the producer, and mirrors _2's shape: run the query bare with FORMAT Null, because reading the result through an aggregate changes the plan and the rowless chunk never reaches the merge (0/30 that way, 3/3 bare).

tests/queries/0_stateless/03168_read_in_order_buffering_3.sql

-- 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;

tests/queries/0_stateless/03168_read_in_order_buffering_3.reference

3000	4498500	4498500

Verified 3/3 from a clean data directory: each run produces 4 BufferChunks -> MergingSortedTransform finish-with-data events, 4 mid-merge rowless pulls, and 1 arrival at MergedData::rowsToInsertBeforeFlush with max_rows == 0 — measured with OutputPort::finish instrumented to report calls that run with HAS_DATA still set, plus markers at the mid-merge guard and at rowsToInsertBeforeFlush. No failpoint.

Every setting in the query is load-bearing, so they are pinned per-query rather than via SET to survive the test runner's randomization:

Change Rowless pulls
as written 4
drop FINAL 0
drop do_not_merge_across_partitions_select_final 0
optimize_read_in_order = 0 0
read_in_order_use_buffering = 0 0
max_block_size = 64 0
max_threads = 4 0

Insensitive to read_in_order_use_virtual_row, read_in_order_use_virtual_row_per_block and query_plan_optimize_lazy_materialization, so those are left alone. SYSTEM STOP MERGES is there because a background merge collapsing the two parts per partition removes the inner ReplacingSorted 2 -> 1 and the shape with it.

Two caveats. I could not confirm the assertion actually fires on an unfixed debug build — my binary is RelWithDebInfo, so chassert is compiled out and the markers are the evidence that the reproducer reaches its exact site. Worth running against a debug build at #117048's parent before relying on it. And on release this path returns the correct result in every configuration I tried (3000 4498500 4498500), because SortingStep::mergingSorted passes max_block_size_bytes = 0 and use_average_block_sizes = false, so rowsToInsertBeforeFlush returns 0 and the source is retired — hence the second query, which would catch a mis-merge if another algorithm is less forgiving.

Since the code it covers is master's via #117048, whether this lands here or as a follow-up is your call.

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

ColumnGathererStream now finishes, or reports an error, when a gather source it still needs is exhausted, instead of requesting that source forever.

#117048 is linked from the Related: line at the top of ### Description and named in the sentence about the IMergingTransformBase::prepare half, and the "No plain-SQL reproducer" line is already gone from the Validation section. Your review is recorded against 0a602ae31ae, the head from before the 11:24Z pushes.

Category. Changed to Not for changelog. Your 40 forced merges agree with what I measured from the other side: the mask-free pass-through branch (ColumnGathererTransform.cpp:126-135) is entered only with row_sources_buf at eof while a source still has rows unread, and a vertical merge writes one mask entry per output row, so it never produces that state. Instrumented one-part and two-part vertical merges with merge_max_dynamic_subcolumns_in_wide_part = 1 took 0 hits on it, both gathering columns routing through the result_column clone paths instead, which is what the in-tree note at :124-125 predicts. So I have no user-runnable query for either arm, and the max_rows > 0 failure a user could actually see belongs to #117048's entry rather than this one. I will put Bug Fix back if a release-reachable path turns up.

Reproducer. Follow-up PR, not this one. It covers #117048's prepare guard rather than the gatherer this PR is now titled and changelogged around, so folding it in would blur that boundary again; and it needs both the debug-build run at #117048's parent that you flagged and a flaky check over its six load-bearing per-query settings, neither of which I want to put on a PR that is one job from finishing. It also earns its own PR because #117048's description states that the trigger "cannot be constructed deterministically from SQL", and your test contradicts that. I will post the link here.

{

/// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Suggested change
/// 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

same here, plus it's missing backticks.

Suggested change
/// 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Applied verbatim in 16ca15e.

… config so the upgrade check can start the previous release)
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger for 6b4fa92

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be
posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Cannot start clickhouse-server the previous-release server refuses to start: Code: 137 ... Unknown elements 'enable_silk_runtime', 'silk' found in config /etc/clickhouse-server/config.xml. The sibling Check failed leaf is that leaf's aggregate, not a second defect #117172 (ours, merged), merged master @ e9f1978
SQLLogic test infra: the host docker daemon died about 67 minutes into the complete-test step (Error waiting for container: Canceled: grpc: the client connection is closing: context canceled), so the job was killed with exit 125 a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

Two facts behind that second row, because praktika already classifies it correctly and the red still stands.

result_sqllogic_test.json carries ext.labels = ["infra"], the label #109673 added and the one
retry_infra_failures.yml reads. The hourly auto-retry still skipped this run, and correctly so: it
reruns only when EVERY failed job is infra, and the Upgrade check (amd_release) row above is a real
failure. Merging master removes that blocker, so a recurrence of the daemon death on the next run would
be the only failure and would be eligible for the retry.

The residual is that the retry is whole-run only, so a run mixing an infra-killed job with a real failure
can never have just its infra job rerun. That is the direction the fix task takes.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened as #117259.

The mutation check holds, so it is a live regression test for #117048 rather than a marker-only one:
reverting just that PR's hunk on a debug build reddens it 10 times out of 10 with
Logical error: 'max_rows > 0' in MergedData::rowsToInsertBeforeFlush, and on master it passes
50/50 under randomized settings.

Two changes to the version posted here, both from measurement. The aggregate-wrapped query needs
query_plan_remove_redundant_sorting = 0: without it 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 what made the wrapped form reach the state 0 times out of 30 for you. With the setting
pinned it reaches the assertion 3 times out of 3 on the reverted build, so I kept the query. I also
trimmed the header comment to the invariant the test pins and moved the mechanism into the commit
message, and added a third statement that pins the pipeline shape through EXPLAIN PIPELINE, because
count and sum are invariant under it and a planner change that stopped inserting
BufferChunksTransform would otherwise leave the test green and covering nothing.

Thanks for the reproducer, @ tiandiwonder.

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

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the SQLLogic test exit-125 line (host docker daemon death mid-run, labelled infra but never auto-retried because the run also carried a real failure): #117282

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 16ca15e1e3897e0d063864318f582f8e7350fe93

CI is fully finished on this head. Every failure below has an owner: a fixing PR (mine or
external), or a full-effort fix task whose fixing-PR link will be posted here when it opens.
Only CH Inc sync is exempt.

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

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]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Nov 19, 2026

This branch has not been deployed

No deployments
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 comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants