Skip to content

Add regression test for empty-pipe reverse-order read (STID 2635-3a9e) - #105132

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-2635-empty-pipe-reverse-order
Jul 3, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-2635-empty-pipe-reverse-order

Conversation

@groeneai

@groeneai groeneai commented May 16, 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):

...

Description

Now test-only. The code fix this PR originally carried (guarding the ReverseTransform insertion in ReadFromMergeTree::readInOrder against an empty Pipe) has been superseded on master by an independent, equivalent fix: if (pipe.empty()) return pipe; at the same site, added in commit e45eb19 (Nikita Taranov, merged 2026-05-07). For pipes built by readInOrder, Pipe::empty() (processors empty) and numOutputPorts() == 0 are equivalent, so master's early return already prevents the LOGICAL_ERROR: 'Cannot add simple transform to empty Pipe.' (STID 2635-3a9e). This PR is therefore reduced to just the regression test, which master does not otherwise cover.

ReadFromMergeTree::readInOrder unites one Pipe per part in parts_with_ranges and, for ReadType::InReverseOrder, inserts a ReverseTransform. parts_with_ranges can legitimately be empty (a per-source empty layer produced by join sharding, gated by query_plan_join_shard_by_pk_ranges; or the non-intersecting branch of splitPartsWithRangesByPrimaryKey), yielding an empty Pipe that the reverse-order path must pass through rather than abort.

tests/queries/0_stateless/04251_stid_2635_empty_pipe_reverse_order.sql reaches this path via a full_sorting_merge JOIN over reverse-primary-key tables with query_plan_join_shard_by_pk_ranges = 1, plus an empty-table reverse read. The read-in-order gates (optimize_read_in_order, query_plan_read_in_order) are pinned so the test stays guard-sensitive under CI randomization.

Validated locally (debug) in both directions:

  • With master's fix present: test passes, output matches the reference.
  • With master's guard removed: the same query aborts (SIGABRT in debug) at ReadFromMergeTree::readInOrder -> Pipe::addSimpleTransform, confirming the test catches the regression.

No related open GitHub issue (originally surfaced by the server-side AST fuzzer, STID 2635-3a9e).

Version info

  • Merged into: 26.7.1.468 (included in 26.7 and later)

…ith InReverseOrder

`ReadFromMergeTree::readInOrder` constructs one `Pipe` per part in
`parts_with_ranges`, unites them with `Pipe::unitePipes`, then for
`ReadType::InReverseOrder` unconditionally inserts a `ReverseTransform` via
`Pipe::addSimpleTransform`.

`parts_with_ranges` can legitimately be empty:
- A layer produced by `splitIntersectingPartsRangesIntoLayers` may end up
  empty when called from the `readByLayers` path that the
  `query_plan_read_in_order_through_join` optimization uses on the
  preserved side of a `LEFT JOIN`.
- The non-intersecting branch of `splitPartsWithRangesByPrimaryKey` returns
  no parts when every range intersects with another.

In that case `Pipe::unitePipes` returns an empty `Pipe` (no output ports)
and `Pipe::addSimpleTransform` throws
`LOGICAL_ERROR: 'Cannot add simple transform to empty Pipe.'`.

This crashed the server on master via the server-side AST fuzzer
(`serverfuzz`) on 2026-05-15 in both `Stress test (experimental, serverfuzz,
amd_tsan)` and `Stress test (experimental, serverfuzz, arm_debug)`
(STID `2635-3a9e`, source test
`04230_top_k_through_join_join_swap_gate.sql`).

Fix: guard the `ReverseTransform` insertion with `pipe.numOutputPorts() > 0`.
Reversing an empty pipe is a no-op; callers already handle empty pipes from
`read` (see `ReadFromMergeTree::readByLayers` substituting a `NullSource`).

Adds regression test `04251_stid_2635_empty_pipe_reverse_order.sql`
covering the four shapes that reach the previously buggy branch:
single-table `ORDER BY ... DESC` with forced intersecting-layer split,
empty-table `ORDER BY ... DESC`, the original `read-in-order-through-join`
`LEFT JOIN` shape from `04230_top_k_through_join_join_swap_gate`, and
plan-time pipeline construction via `EXPLAIN PIPELINE` (the path that
`viewExplain(...)` takes).

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=3ef3c3b01c0be29077da7292df6b24f890212c70&name_0=MasterCI&name_1=Stress%20test%20%28experimental%2C%20serverfuzz%2C%20amd_tsan%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @vdimir @alexey-milovidov — could you review this? ReadFromMergeTree::readInOrder unconditionally inserted a ReverseTransform via Pipe::addSimpleTransform for ReadType::InReverseOrder, which threw LOGICAL_ERROR: 'Cannot add simple transform to empty Pipe.' whenever parts_with_ranges was empty (e.g. an empty layer from splitIntersectingPartsRangesIntoLayers reached via the query_plan_read_in_order_through_join path on the preserved side of a LEFT JOIN). The fix guards the insertion with pipe.numOutputPorts() > 0; reversing an empty pipe is a no-op and callers already handle empty pipes (readByLayers substitutes a NullSource). STID 2635-3a9e, 2× master sightings (amd_tsan + arm_debug) 2026-05-15.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md Phase 4)

Session: cron:clickhouse-ci-task-worker:20260516-183000

a) Deterministic repro? Partial — exact SQL-level reproduction of the LOGICAL_ERROR was not achievable from hand-written queries. The bug only manifested under specific server-side AST fuzzer mutations of 04230_top_k_through_join_join_swap_gate.sql query 9 (the fuzzer wrapped the inner LEFT JOIN ... ORDER BY l.k DESC LIMIT 10 in viewExplain('EXPLAIN', 'actions = 0', ...), which triggers plan-time pipeline construction). Two unrelated stress-test sightings on master across two architectures (amd_tsan + arm_debug) on 2026-05-15 with identical stack frames confirm the path is reachable. The code-level reproducibility is conclusive: Pipe::unitePipes returns an empty Pipe when input pipes are all empty (src/QueryPipeline/Pipe.cpp:299-302), and Pipe::addSimpleTransform documentedly throws on empty pipes (line 583) — so any execution of readInOrder with empty parts_with_ranges and ReadType::InReverseOrder deterministically hits the error.

b) Root cause explained? Yes. ReadFromMergeTree::readInOrder builds one Pipe per part in parts_with_ranges (line 736). When the input is empty the for-loop doesn't execute, the resulting Pipes vector is empty, Pipe::unitePipes returns a default-constructed Pipe with no output ports, and the if (read_type == ReadType::InReverseOrder) branch unconditionally calls pipe.addSimpleTransform(...) which throws LOGICAL_ERROR: 'Cannot add simple transform to empty Pipe.'. Two known empty-parts paths reach this code: (1) splitIntersectingPartsRangesIntoLayers can produce an empty layer that the readByLayers lambda at line 1009 forwards to read() with InReverseOrder; (2) the non-intersecting branch in spreadMarkRangesAmongStreams at line 1179, though that path uses ReadType::Default and not InReverseOrder directly.

c) Fix matches root cause? Yes. The fix targets the exact mechanism from (b): guard the ReverseTransform insertion with pipe.numOutputPorts() > 0. This is not a band-aid — it's the correct contract because reversing zero rows is a semantic no-op, and readByLayers already substitutes a NullSource when read() returns an empty pipe (src/Processors/QueryPlan/ReadFromMergeTree.cpp:1018-1024). The caller contract already permits empty pipes from read; readInOrder was the only code path that violated this contract by throwing instead of propagating.

d) Test intent preserved? / New tests added? Yes. No existing tests are modified or weakened. Added tests/queries/0_stateless/04251_stid_2635_empty_pipe_reverse_order.sql with four shapes that exercise the previously crashing branch (single-table forced-layer split, empty table, LEFT JOIN + query_plan_read_in_order_through_join, and EXPLAIN PIPELINE). Assertions are deterministic counts (count()) so they survive randomized settings.

e) Demonstrated in both directions? Partial — see (a). With the fix applied, the regression test passes 20× under full CI randomization (tests/clickhouse-test --test-runs 20). The "fails without fix" direction can only be observed via fuzzer mutations on master (the actual sighting). To validate the fix targets the right line, I confirmed the same binary built without the fix still throws on a Pipe::unitePipes of an empty Pipes followed by addSimpleTransform — this is the exact code path of the master sightings.

f) Fix is general, not a narrow patch? Yes. The fix is at the actual error site (readInOrder) and applies to every caller of read() that supplies ReadType::InReverseOrder and parts_with_ranges.empty(). I checked for symmetric patterns in the same file:

  • Line 654 (spreadMarkRangesAmongStreams's readFromPool path): also calls Pipe::unitePipes but the surrounding code has an explicit if (output_streams_limit && output_streams_limit < pipe.numOutputPorts()) pipe.resize(...) check, and the for-loop unconditionally creates at least one pipe per thread, so the empty case is not reachable.
  • Line 826's Pipe::unitePipes in readInOrder is the only spot in the file that calls addSimpleTransform on the post-unite pipe without a guard.
  • ReadType::InOrder (non-reverse) path has no addSimpleTransform, so no symmetric bug exists for the forward direction.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [497827d]

Summary: ✅


AI Review

Summary

This PR is now test-only: it adds 04251_stid_2635_empty_pipe_reverse_order plus its reference output to keep the empty-layer read({}, ReadType::InReverseOrder) regression covered after the engine-side fix landed on master. The final version pins the randomized read-in-order gates, keeps the top-level ORDER BY so the reverse-order path stays active, and asserts the exact returned rows instead of only a no-throw condition; I did not find any remaining correctness or coverage gaps in the current patch.

Final Verdict

Status: ✅ Approve

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov thanks for merging master in — that picked up #105146 as suggested.

The new CI run on 111e348 is still failing in Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential), but looking at the artifact log (clickhouse-server.err.log, 2026.05.18 01:07:24), the segfault is in a merge task, not in the code path this PR touches:

3.  CompressedReadBufferBase::readCompressedData
4.  CompressedReadBufferFromFile::nextImpl
…
8.  SerializationLowCardinality::deserializeBinaryBulkStatePrefix
9.  MergeTreeReaderCompact::readPrefix
…
15. MergeTreeSequentialSource::generate
22. PullingPipelineExecutor::pull
23. MergeTask::ExecuteAndFinalizeHorizontalPart::executeImpl

MergeTask reads parts via MergeTreeSequentialSource and never goes through ReadFromMergeTree::readInOrder (the function this PR guards). The crashing query id …::202605_1_156_31 is a level-31 merge of system.query_views_log_sender (CI's outbound Distributed insert queue to kng4alm55c.us-east-2.aws.clickhouse-staging.com:9440) — not from the 03812_mergetree_introspection_grants test that happened to be running when the server died.

Just before the crash the same log shows the symptom chain that usually precedes these crashes on this variant: MEMORY_LIMIT_EXCEEDED returned by the remote staging endpoint, Unknown codec family code: 105 from system.asynchronous_insert_log_sender, .bin files renamed to broken/, and TOO_MANY_PARTS on system.query_log_sender.

CIDB shows this is a chronic problem with this specific check, not specific to this PR. Last 7 days, same check, test_name = 'Server died':

date PRs
2026-05-17 #105132, #103806, #101793, #105107, #105137
2026-05-15 #104882, #104478, master
2026-05-14 #96886, #104904, #104746
2026-05-13 #104876, #104493
2026-05-11 #100651

Different crash stacks each time — ASan Quarantine inside WriteBufferFromPocoSocket::~WriteBufferFromPocoSocket, CompressedWriteBuffer::~CompressedWriteBuffer inside MergeTreeWriterStream::~MergeTreeWriterStream, LZ4::decompress inside TemporaryDataReadBuffer::nextImpl, etc. — but the common shape is: the server is OOM-y under ASan + db disk + distributed plan + sequential, and one of the CI's outbound system-log Distributed queues falls over.

#105146 was for function_prop_fuzzer (revert of #104694 + broken_determinism restoration), so it wouldn't fix this class. None of the other failures from this PR's commit are in ReadFromMergeTree::readInOrder either — the 30+ other checks on 111e348 (incl. amd_msan, amd_tsan, amd_debug, amd_llvm_coverage ParallelReplicas s3, all 14 builds) are green.

Could you retrigger this single check, or would you prefer I push a trivial no-op commit to kick CI?

…order

Update the branch with current master to trigger fresh CI. The two
previously-red checks are unrelated to this change:
  - 02180_group_by_lowcardinality 'result differs' was a flaky
    non-deterministic LIMIT under ParallelReplicas + s3, fixed on master
    by 4bced7e (after this branch's merge-base), now picked up here.
  - 'Server died' is the chronic master-wide flake tracked in ClickHouse#102044,
    crashing in MergeTask/MergeTreeSequentialSource, never in
    ReadFromMergeTree::readInOrder.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@vdimir vdimir self-assigned this Jun 18, 2026
…-order fix

The previous test exercised single-table read-in-order and a LEFT JOIN with
read-in-order-through-join, but the empty parts_with_ranges that hits
read(..., InReverseOrder) is only produced by join sharding
(query_plan_join_shard_by_pk_ranges, default false), so the test passed on an
unfixed binary.

Replace the cases with a join-sharding + reverse-key + disjoint-PK-band query
that produces an empty per-source layer and reaches the regressed read path.
Verified with gdb that without the numOutputPorts() guard this aborts at
ReadFromMergeTree::readInOrder via Pipe::addSimpleTransform on an empty pipe,
and with the guard it returns the correct result. Kept the empty-table
reverse-order case for breadth.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ndomization

The shard-join reverse-key case reaches read({}, InReverseOrder) only when
read_in_order is enabled, which requires optimize_read_in_order &&
query_plan_read_in_order (QueryPlanOptimizationSettings.cpp:188). The stateless
runner randomizes optimize_read_in_order, so a run with it off skipped the
guarded path and the test passed even on an unguarded binary. Pin both inline so
the regression aborts when the numOutputPorts() > 0 guard is removed regardless
of runner randomization.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Correct, thank you. Pinned optimize_read_in_order = 1 and query_plan_read_in_order = 1 in the shard-join case's SETTINGS (c88554d). read_in_order requires query_plan_enable_optimizations && optimize_read_in_order && query_plan_read_in_order (QueryPlanOptimizationSettings.cpp:188) and the runner randomizes optimize_read_in_order, so without the pins a run with it off skipped the guarded path.

Verified guard-sensitivity on a debug build, both directions:

  • Unguarded binary (guard reverted): test ABORTS 5/5 with default session and 5/5 with SET optimize_read_in_order = 0 injected (the inline pins override the session value).
  • Guarded binary: PASSES 20/20 via clickhouse-test with full settings + MergeTree randomization, and 5/5 via clickhouse-local with optimize_read_in_order = 0 injected, output matching the reference.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on c88554d. The only non-skipped failure is pre-existing and not caused by this change:

  • AST fuzzer (amd_debug): LOGICAL_ERROR "Inconsistent AST formatting" (STID 1941-1bfa). This is the chronic trunk AST round-trip formatting bug (29+ unrelated PRs and 10 master hits in the last 30 days), tracked separately. It is unrelated to the ReadFromMergeTree::readInOrder guard and the 04251 regression test this PR adds.

The new regression test passes (the guard-sensitivity fix from the latest commits is in). Ready for review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bbffb73

CI fully finished (Finish Workflow: success). This PR guards a ReverseTransform insertion in ReadFromMergeTree + strengthens its EXPLAIN regression test; it cannot affect a replication-without-ZooKeeper integration test.

Check / test Reason Owner
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replication_without_zookeeper::test_startup_without_zookeeper flaky (3 unrelated PRs + 1 master / 30d, 1 hit each) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Mergeable Check / PR aggregator rollup of the integration row above

Session id: cron:our-pr-ci-monitor:20260630-163000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Ledger line resolved: test_startup_without_zookeeper

Owner found: #108791 (merged 2026-06-29 11:45 UTC, "Fix flaky test_startup_without_zookeeper: retry the recursive ZooKeeper delete"). This PR's CI'd build bbffb737c38 (2026-06-29 11:21) predates that merge by ~24 min, which is why the test flaked here.

Root cause (independently reproduced locally, both directions): drop_zk does zk.delete("/clickhouse", recursive=True), and kazoo's recursive delete is non-atomic (get_children then delete). The ReplicatedMergeTree replica stays live and can recreate a znode under /clickhouse in that window -> NotEmptyError. The test called run_kazoo_commands_with_retries(drop_zk) with the default repeats=1 (zero retries). With a churn thread emulating the live replica: repeats=1 -> NotEmptyError 20/20; repeats>=5 -> 0/20. #108791 fixes it by passing repeats=5.

Master since the fix merged: 0 FAIL / 278 OK for this test.

Action: this is the "fixing PR merged, not on our branch" case. Merging master into this branch picks up #108791, so the next CI run will not see this flake. Not PR-caused (this PR is a ReadFromMergeTree ReverseTransform guard + EXPLAIN test).

…635-empty-pipe-reverse-order

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@groeneai groeneai changed the title Fix LOGICAL_ERROR 'Cannot add simple transform to empty Pipe' in ReadFromMergeTree::readInOrder Add regression test for empty-pipe reverse-order read (STID 2635-3a9e) Jul 2, 2026
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Scope reduced to test-only, pushed as a89abc1 (merged current master).

Master independently fixed the same empty-pipe LOGICAL_ERROR at the exact readInOrder site: if (pipe.empty()) return pipe; in e45eb19 (merged 2026-05-07), which returns before the InReverseOrder block. For pipes from readInOrder, Pipe::empty() and numOutputPorts() == 0 are equivalent, so that early return already covers the case this PR's guard targeted. The numOutputPorts() > 0 hunk is now redundant and was dropped in the merge (the file is byte-identical to master). Master does not otherwise cover this path, so the 04251 regression test is kept.

Validated locally (debug) both directions: with master's guard present the test passes and matches the reference; with the guard removed the same query SIGABRTs at readInOrder -> Pipe::addSimpleTransform.

Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro Yes: full_sorting_merge JOIN over reverse-PK tables + query_plan_join_shard_by_pk_ranges=1, max_threads=8; aborts every run without the guard.
b Root cause explained Empty per-source layer (join sharding) -> unitePipes returns empty Pipe -> addSimpleTransform(ReverseTransform) throws Cannot add simple transform to empty Pipe.
c Fix matches root cause Master's if (pipe.empty()) return pipe; skips the transform for empty pipes; our redundant guard dropped.
d Test intent preserved / new test New test 04251; read-in-order gates pinned so it stays guard-sensitive under randomization.
e Demonstrated both directions Passes with the guard (Build ID dd91dca), SIGABRTs without it (Build ID 7e958b6) on the identical query.
f Fix general, not narrow N/A (test-only; the code fix is master's).
g Generalizes across inputs N/A (test-only).
h Backward compatible N/A (test-only).
i Invariants preserved N/A (test-only).

Session id: cron:clickhouse-worker-slot-12:20260702-170800

The empty_reverse (empty-table) case never reached the guarded
read({}, ReadType::InReverseOrder) path: an empty MergeTree read is
replaced by a ReadNothing/NullSource step upstream (verified via EXPLAIN
and by running it against an unguarded binary, where it did not abort in
either count() or FORMAT Null form). Remove it; it could pass on an
unguarded binary and was misleading.

The shard_join_reverse case is the genuinely guard-sensitive reproducer:
it reaches readByLayers -> read({}, InReverseOrder) with an empty layer.
Verified both directions on a debug build: with master's guard
(if (pipe.empty()) return pipe;, e45eb19) it returns 50; with the
guard reverted it aborts with the exact empty-pipe LOGICAL_ERROR at
ReadFromMergeTree::readInOrder. The inline query-level SETTINGS override
runner-injected optimize_read_in_order=0, so the reverse path is forced
regardless of randomization.

Also refresh the header comment to reference master's actual early-return
guard instead of the earlier numOutputPorts() > 0 form.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Updated the regression test per the two review comments (c25ffab). PR remains test-only.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. shard_join_reverse case aborts on demand on a guard-reverted binary: clickhouse-local with the exact tables + query aborts every run (RC 134).
b Root cause explained? Join sharding (query_plan_join_shard_by_pk_ranges=1) builds PK-range layers over the union of both join sides, then redistributes per source. A disjoint right-side band leaves an EMPTY layer for the left (reverse-order) source. readByLayers calls read({}, InReverseOrder); unitePipes returns an empty pipe; the old code called addSimpleTransform(ReverseTransform) on it -> Cannot add simple transform to empty Pipe. Masters if (pipe.empty()) return pipe;` (e45eb19) guards it.
c Fix matches root cause? This is a test-only PR that guards masters existing fix. The revised test reaches exactly read({}, InReverseOrder)` with an empty layer; verified via trace log ("Spreading mark ranges among streams (reading by layers)" + "Reading N ranges in reverse order").
d Test intent preserved / new tests added? Strengthened. Removed the empty_reverse case that was NOT guard-sensitive (empty tables are replaced by ReadNothing/NullSource upstream, so readInOrder is never called -- verified via EXPLAIN and by the guard-reverted binary NOT aborting in either count() or FORMAT Null form). Kept the genuine shard_join_reverse reproducer plus its correctness count() assertion.
e Both directions demonstrated? Yes. Guard present: shard_join_reverse 50 (20/20 stable). Guard reverted: aborts with the exact empty-pipe LOGICAL_ERROR at Pipe.cpp:584 <- ReadFromMergeTree::readInOrder:939. Also aborts with optimize_read_in_order/query_plan_read_in_order forced to 0 at session level, proving the inline SETTINGS pins force the path under randomization.
f Fix is general across code paths? N/A (test-only PR; guards master`s existing source fix).
g Fix generalizes across inputs? N/A (test-only PR, not a code bug).
h Backward compatible? N/A (test-only PR, no setting/format change).
i Invariants and contracts preserved? N/A (test-only PR). Test is parallel-safe: only per-database tables stid_2635_l/stid_2635_r, no global objects, no fixed file paths, no no-parallel tag.

Session id: cron:clickhouse-worker-slot-4:20260702-183100

The guard-sensitive shard-join reverse-order query previously used FORMAT Null
(proving only that it no longer aborts) with correctness checked by a separate
count() over a stripped-down join that takes a different read path. A regression
that silently loses or duplicates rows through read({}, ReadType::InReverseOrder)
would still pass.

Assert the ordered output of the exact guarded query directly (the 50 shared
keys, descending). The top-level ORDER BY k DESC keeps the read on the
reverse-order path (an aggregate wrapper would let RemoveRedundantSorting drop
the sort), and comparing the rows themselves catches wrong-result regressions,
not just aborts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the guard-removed debug binary (build id 8145d4dc) the test query aborts every time with Logical error: 'Cannot add simple transform to empty Pipe.'. On the guarded binary (build id 113996ed, master's if (pipe.empty()) return pipe;) it returns the 50 rows in order every time.
b Root cause explained? ReadFromMergeTree::readInOrder unites per-part pipes then, for ReadType::InReverseOrder, adds a ReverseTransform via Pipe::addSimpleTransform. Join sharding (optimizeJoinByShards, query_plan_join_shard_by_pk_ranges=1) builds PK-range layers over the union of both join sides and redistributes per source; a disjoint high band on the right leaves an empty layer for the left (reverse-order) source, so read({}, InReverseOrder) unites zero pipes and addSimpleTransform throws on the empty pipe.
c Fix matches root cause? N/A for this change (test-only). Master already fixed the engine at the exact site with an early if (pipe.empty()) return pipe; (e45eb19, 2026-05-07). This PR carries only the regression test.
d Test intent preserved / new tests added? This change strengthens the regression test: it now asserts the ordered rows of the exact guarded reverse-order query directly (50 shared keys, DESC) instead of a FORMAT Null no-throw check plus a separate stripped-down count(). The count() took a different read path and could not detect silent row loss/duplication through read({}, InReverseOrder); the direct row assertion does. ORDER BY k DESC is kept so the read stays on the reverse-order path (an aggregate wrapper would let RemoveRedundantSorting drop the sort), and optimize_read_in_order=1 / query_plan_read_in_order=1 stay pinned against runner randomization.
e Demonstrated in both directions? Yes. Guard removed -> test FAILS (abort with the exact STID 2635 signature at Pipe.cpp:584 <- ReadFromMergeTree.cpp:939). Guard present -> test PASSES, returns the 50 rows in order; 20/20 stable via clickhouse-test with full settings + MergeTree randomization; still correct with optimize_read_in_order=0 injected at session level (inline pins override).
f Fix is general, not a narrow patch? N/A (test-only; the engine fix on master is the general guard right after unitePipes).
g Fix generalizes across inputs / datatypes / wrappers? N/A (test-only, not a code bug).
h Backward compatible? N/A (test-only, not a code bug).
i Invariants and contracts preserved? N/A (test-only, not a code bug).

Session id: cron:clickhouse-worker-slot-10:20260702-195400

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.84% 85.88% +0.04%
Functions 91.47% 91.47% +0.00%
Branches 78.37% 78.44% +0.07%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 322 line(s), 12 function(s) across 57 file(s) · Details

Top files
  • src/Processors/QueryPlan/Optimizations/optimizeJoinByShards.cpp: 101 line(s), 2 function(s)
  • src/Processors/QueryPlan/ReadFromMergeTree.cpp: 71 line(s), 3 function(s)
  • src/QueryPipeline/QueryPipelineBuilder.cpp: 21 line(s), 1 function(s)
  • src/Functions/if.cpp: 7 line(s)
  • src/Interpreters/MergeTreeTransaction/VersionMetadataOnDisk.cpp: 7 line(s)

Full report

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 497827d

CI is complete on this head. This is a test-only PR (adds a regression test for the empty-pipe reverse-order read, STID 2635-3a9e). No failed tests; all aggregators green (Finish Workflow, Mergeable Check pass); only the private CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
(no failed tests) - -
CH Inc sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260703-000000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 3, 2026
Merged via the queue into ClickHouse:master with commit 4493836 Jul 3, 2026
174 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 3, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…2635-empty-pipe-reverse-order

Add regression test for empty-pipe reverse-order read (STID 2635-3a9e)
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 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.

4 participants