Skip to content

Add a stateless test for the trailing empty chunk in IMergingTransformBase - #117259

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:stateless-repro-trailing-empty-chunk-merge
Sep 1, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:stateless-repro-trailing-empty-chunk-merge

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Add SQL-level regression coverage for the trailing empty chunk in IMergingTransformBase::prepare.

Description

The reproducer in this test is @ tiandiwonder's, supplied in
#116805 (comment). I am adding it to the
suite, with the comments trimmed and one of his two queries settled by measurement.

Related: #117048
Related: #116805

#117048 fixed IMergingTransformBase::prepare: an input that finishes its port in the same cycle it
delivers a trailing empty chunk had that chunk consumed by the merge. This test reaches that state
through a real read-in-order pipeline, where BufferChunksTransform is the producer and the tail of
each partition holds only empty arrays. #117048's description says the trigger "cannot be constructed
deterministically from SQL"; this shows that it can.

Verification: reverting only #117048's hunk on a debug build reddens the test 10 times out of 10,
each time as Logical error: 'max_rows > 0' in MergedData::rowsToInsertBeforeFlush reached from
MergingSortedAlgorithm::mergeBatchImpl with the batch sorting queue, which aborts the server. On
master it passes 50/50 under randomized settings and 24/24 run against itself in parallel. The
pipeline-shape checks, one over each of the two runtime statements, also hold unchanged under
allow_experimental_analyzer = 0 and serialize_query_plan = 1, the settings the old-analyzer and
distributed-plan test lanes install, and drop to 0 when buffering is disabled.

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; the gtest also builds its inputs by hand, where this test drives the
real pipeline.

The assertion is the only oracle this test carries: the empty cursor is heapified and compared before
that assertion is reached, so the release-visible row loss stays covered by the gtest's
TwoInputsTrailingEmptyChunk. count and sum in the second query detect lost or duplicated rows,
not reordering.


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

Version info

  • Merged into: 26.9.1.473 (included in 26.9 and later)

…mBase

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

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

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

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

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

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

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

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

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

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

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

Related: ClickHouse#117048
Related: ClickHouse#116805

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds) - 6 findings adjudicated

Before opening this PR I ran two rounds of independent cold review of the resulting code plus a
second-model review gate, and adjudicated every finding. Recorded here for auditability.

Round 1

# Severity Finding Verdict
❌ 1 major The non-redundancy argument claimed SortingQueueStrategy::Default is not reachable from SQL. It is: Interpreters/SortedBlocksWriter.cpp builds a MergingSortedTransform with that strategy for a partial-merge join spilling to disk, and Storages/MergeTree/MergeTask.cpp selects it for background merges. Only the narrow claim holds: neither the default strategy nor the single-input shape is reachable through the read-in-order path this query drives. AGREE, corrected in the description and the commit message
❌ 2 major Nothing in the test asserted that buffering and the sorted merge are actually in the plan. count and sum are invariant under pipeline shape, so a planner change that stopped inserting BufferChunksTransform for this shape would leave the test green and silently vacuous. AGREE, pipeline-shape assertion added with a negative control
⚠️ 3 nit The commit message pinned a source line number, which rots. AGREE, replaced by the symbol name
💡 4 nit read_in_order_two_level_merge_threshold is randomized over [0,100] and the fixture holds 8 parts, so a low draw could reshape the read-in-order pipeline. AGREE, measured. The low band is in fact unreachable here: a FINAL read returns from spreadMarkRangesAmongStreamsFinal before the branch that computes need_preliminary_merge. Swept t in {0,1,2,4,7,8,9,100} with the delivered value read back per row; the shape holds at every draw

Round 2

# Severity Finding Verdict
❌ 5 major The new shape assertion pins no lane settings, and plan shape is also moved by CI lane flags, which are runner options rather than randomized settings, so the 50-run randomized sweep cannot reach them. If a lane does not insert buffering, the new statement reds that lane. The nearest precedent in the suite, 04357_distributed_final_do_not_merge_partitions.sql, uses the same predicate on the same query family and defends itself with no-old-analyzer plus pinned parallel-replicas and distributed-plan settings. DISAGREE, refuted by measurement. The lanes install exactly allow_experimental_analyzer=0 and serialize_query_plan=1. Running the whole file under each of those, and under parallel replicas, gives output byte-identical to the reference (same md5 on all four arms); the same probe returns 0 with buffering disabled, so the channel is sensitive rather than blind. Parallel replicas additionally cannot reach a FINAL read: that branch asserts !is_parallel_reading_from_replicas
💡 6 nit PR metadata: relationship lines used shorthand rather than full GitHub URLs, and function names were written as f() rather than f. AGREE, both fixed in this description

On finding 2 the gate asked for an exact-count assertion on the four BufferChunks processors. I
used a boolean instead, because the exact-count form is measurably fragile: sibling
03168_read_in_order_buffering_1 ran 267,342 times green across 44 check names in 60 days with
exactly one failure, and that failure was its BufferChunks line count moving from 1 to 2 in a
distributed-plan and parallel-replicas configuration. A > 0 predicate absorbs both that and the
processor multiplicity EXPLAIN PIPELINE collapses onto one line.

Noted and not acted on: the second boolean in that statement is redundant, since BufferChunks
has a single construction site and the merge is added immediately after it in the same branch, so
the two columns cannot fall independently. It is kept because it is self-documenting and was
measured non-decorative (one partition, hence one stream, drops both).

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 10/10. Revert #117048's hunk (git checkout 49f3609beda^ -- src/Processors/Merges/IMergingTransform.cpp), rebuild debug, run the test: [ FAIL ] Reason: server died 32 every time. Not a rate.
b Root cause explained? Yes. InputPort::pullData caches is_finished with no HAS_DATA term, so the pre-fix guard !input_chunk.hasRows() && !virtual_row && !input.isFinished() let a rowless chunk from an already-finished port reach state.has_input = true. A zero-row cursor then entered the batch sorting queue and rowsToInsertBeforeFlush(..., max_rows = 0, ...) tripped chassert(max_rows > 0).
c Fix matches root cause? No source fix in this PR: the fix is #117048, already on master. The coverage is validated against that fix's exact inverse hunk rather than against instrumentation markers.
d Test intent preserved / new tests added? New test added; nothing weakened or removed. Both regression queries were measured to reach the defect site on the reverted build, so neither arm is decorative. A third statement pins the pipeline shape the other two depend on, because count/sum are invariant under it; its own negative control (read_in_order_use_buffering = 0) reddens it on the reference diff.
e Both directions demonstrated? Yes, on the final shipped file. Red: 10/10 with the fix reverted (Build ID 2fa56d54...), each run asserting the server's buildId() matches the on-disk binary. Green (Build ID 28531718...): 50/50 under randomized settings, 24/24 self-parallel, 10/10 on the restored build.
f Fix is general across code paths? Carriers enumerated. prepareInitializeInputs already discarded rowless first chunks pre-fix; the other IMergingTransform subclasses share the fixed base prepare; SortingQueueStrategy::Default is out of reach of this query's pipeline because SortingStep::mergingSorted hard-codes Batch (other callers do reach it, Interpreters/SortedBlocksWriter.cpp and Storages/MergeTree/MergeTask.cpp, so it stays covered by #117048's gtest rather than being unreachable); the vertical-merge half of the seam (ColumnGathererStream::onSourceExhausted) is deliberately left to #116805.
g Fix generalizes across inputs (params/datatypes/wrappers)? A type-wrapper matrix does not apply: the fixed code is type-agnostic pipeline plumbing and this is a test file. The load-bearing axis is the settings matrix, and all six settings are pinned per-query so the runner's randomization cannot move them.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. Test-only: no setting default, no serialization format, no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? No source contract is touched. The test's own header comment states a standing property of the merge (it must not consume a rowless chunk), not a reference to the fix.

Session id: cron:clickhouse-impl-slot-4:20260831-035500

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dc6aa78]

Summary: ✅


AI Review

Summary

This PR adds a stateless SQL regression test for the trailing empty-chunk path in IMergingTransformBase::prepare. The current revision covers both the debug/sanitizer exception path and the release-visible row-count invariant, and it now pins the wrapped query shape that earlier discussion identified as a blind spot. I did not find remaining correctness, coverage, or metadata issues in the current diff.

Final Verdict

✅ No blocking issues found in the current revision.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger, could you review this? It adds SQL-level coverage for #117048, a read-in-order FINAL pipeline where BufferChunksTransform finishes its output port in the same cycle it pushes a trailing empty chunk, which before that fix reached MergedData::rowsToInsertBeforeFlush with max_rows = 0. Test-only; the last statement pins the pipeline shape with EXPLAIN PIPELINE so the coverage cannot go silently vacuous.

groeneai and others added 2 commits August 31, 2026 07:11
…s pipeline shape

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

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

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

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

Related: ClickHouse#117048
Related: ClickHouse#116805
…dget

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

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

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

Related: ClickHouse#117048
Related: ClickHouse#116805

Co-Authored-By: Claude Opus 5 <[email protected]>
@PedroTadim PedroTadim self-assigned this Sep 1, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Sep 1, 2026
Merged via the queue into ClickHouse:master with commit b66b352 Sep 1, 2026
174 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants