Skip to content

Do not run distributed-plan rewrites on the child plans of a Merge table - #113636

Closed
alexey-milovidov wants to merge 6 commits into
masterfrom
fix/merge-child-plan-distributed-const-mismatch
Closed

alexey-milovidov wants to merge 6 commits into
masterfrom
fix/merge-child-plan-distributed-const-mismatch

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a logical error (Block structure mismatch) when reading from a Merge table over children with internal set operations (e.g. a Buffer table) with make_distributed_plan enabled.

A child plan of ReadFromMerge that acquired no exchange steps is united into the parent pipeline in the same process and is never serialized as a distributed fragment. With make_distributed_plan = 1, the plan optimization still ran materializeConstantsForSetOperationBranches on every plan: it materialized the constants of the Union inside a Buffer child (destination table + buffers), while a sibling child kept them const. That broke the equal-headers invariant across the children of ReadFromMerge and failed with a logical error at pipeline assembly (Block structure mismatch in Pipe stream: different columns), or with Cannot convert column ... because it is non constant in source stream but must be constant in result for a single Buffer child.

The fix gates materializeConstantsForSetOperationBranches on the plan actually containing logical exchange steps. The rewrite exists because plan serialization stores only column names and types, so constness is re-derived per step after a fragment is deserialized — and a plan with no exchanges is never split into serialized fragments (convertToDistributed keeps it as a single stage executed in the same process), so it must keep its constants. Distributed planning of the child plans themselves is untouched: a Merge table over Distributed tables intentionally converts each child plan to a distributed plan on its own (see #108401 and 04367_distributed_plan_merge_scatter_multishard).

Minimal reproducer:

CREATE TABLE t1 (k UInt64) ENGINE = EmbeddedRocksDB PRIMARY KEY (k);
CREATE TABLE t2 ENGINE = Buffer(currentDatabase(), 't1', 1, 1, 10, 10000, 1000000, 10000000, 100000000);
SET make_distributed_plan = 1, distributed_plan_execute_locally = 1;
SELECT DISTINCT 1 FROM merge('^t') QUALIFY materialize(1); -- LOGICAL_ERROR before this fix

Found by the AST fuzzer on #100173: AST fuzzer (amd_debug, targeted) report.

Additionally, the review surfaced an adjacent pre-existing bug, fixed here as well: reading the destination table of a Buffer table can return a full column where the plan over the buffers keeps it constant (constants come back materialized from a Distributed destination), and a full column cannot be converted back to a constant, so such reads failed with ILLEGAL_COLUMN (Cannot convert column ... because it is non constant in source stream but must be constant in result) — with or without make_distributed_plan, and with or without a Merge table on top:

CREATE TABLE dest (k UInt64) ENGINE = MergeTree ORDER BY k;
CREATE TABLE dist (k UInt64) ENGINE = Distributed(test_shard_localhost, currentDatabase(), 'dest');
CREATE TABLE buf (k UInt64) ENGINE = Buffer(currentDatabase(), 'dist', 1, 1, 10, 10000, 1000000, 10000000, 100000000);
SELECT DISTINCT 42 FROM buf QUALIFY materialize(42); -- ILLEGAL_COLUMN before this fix

StorageBuffer::read now materializes such constants in the buffers branch and unites the branches on the materialized header. This also covers the mixed local/distributed ReadFromMerge child shape raised in the review (a Buffer child over a Distributed destination next to a non-distributed sibling), which failed at child plan creation inside StorageBuffer::read — before the plan-level guard is ever reached.

Related: #100173

A child plan of `ReadFromMerge` is united into the parent pipeline in the
same process and is never serialized as a distributed fragment. With
`make_distributed_plan` enabled, `QueryPlan::buildQueryPipeline` (and the
`optimize` calls on the child plans) still ran distributed-plan-only
rewrites on it — `materializeConstantsForSetOperationBranches` materialized
the constants of the `Union` inside a `Buffer` child (destination table +
buffers), while a sibling child kept them const, breaking the equal-headers
invariant across the children of `ReadFromMerge`:

    Logical error: Block structure mismatch in Pipe stream: different columns:
    9223372036854775806_UInt64 UInt64 UInt64(size = 0)
    9223372036854775806_UInt64 UInt64 Const(size = 0, UInt64(size = 1))

Found by the AST fuzzer on #100173:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100173&sha=22dee0374690f4c09727a81023ef38fe4e515785&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [be64272]

Summary: ✅


AI Review

Summary

This PR fixes two closely related constness mismatches: distributed-plan-only set-operation materialization was being applied to Merge child plans that never become serialized fragments, and StorageBuffer::read could still try to convert a full column from a Distributed destination back into a constant buffers header. On the current head, the LogicalExchange guard matches the actual fragment-serialization boundary, the StorageBuffer header normalization fixes the mixed local/distributed child shape raised in review, the added stateless tests cover both regressions, and current CI for PR #113636 is green.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.00% 79.10% +0.10%

Changed lines: Changed C/C++ lines covered: 26/26 (100.00%) · 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 6, 2026
@davenger davenger self-assigned this Aug 6, 2026
The previous commit cleared `make_distributed_plan` in the optimization
settings of the child plans of `ReadFromMerge`, but that disabled the whole
distributed planning of the children, and a `Merge` table over `Distributed`
tables intentionally converts each child plan to a distributed plan on its
own (see #108401). This failed the `Fast test` on
04367_distributed_plan_merge_scatter_multishard:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113636&sha=d2b378e20bfae32ba1ace67846ff6c59f235f8be&name_0=PR&name_1=Fast%20test

Fix it at the actual defect instead: `materializeConstantsForSetOperationBranches`
exists because plan serialization stores only names and types, so constness is
re-derived per step after a fragment is deserialized. A plan with no logical
exchange steps is never split into serialized fragments (`convertToDistributed`
keeps it as a single stage executed in this process), so the rewrite must not
touch it. Gate the rewrite on `planContainsLogicalExchange`, and restore the
plain optimization settings for the child plans of `ReadFromMerge`.

Verified locally: 04812_merge_children_distributed_plan_const_mismatch fails
with `Block structure mismatch` on the unpatched binary and passes with this
change; 04367_distributed_plan_merge_scatter_multishard,
04613_distributed_plan_merge_broadcast_join and
04319_distributed_plan_set_operation_const_columns (and the rest of the
distributed_plan family, 22 tests) pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing be6427216 with master a4966ed74 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.04 MiB 689.03 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

…rns full columns

Reading the destination table of a `Buffer` table can return a full column
where the plan over the buffers keeps it constant: constants come back
materialized from a `Distributed` destination. `StorageBuffer::read`
converted the destination plan to the buffers header by name, and a full
column cannot be converted back to a constant, so such reads failed with
`ILLEGAL_COLUMN` ("Cannot convert column ... because it is non constant in
source stream but must be constant in result") - with or without
`make_distributed_plan`, with or without a `Merge` table on top.

Materialize such constants in the buffers branch instead and unite the
branches of the `Buffer` read on the materialized header. This also covers
the mixed local/distributed child shape of `ReadFromMerge` raised in the
review of #113636: a `Buffer`
child over a `Distributed` destination next to a non-distributed sibling.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113636&sha=19599f4bece8181932b7946020cbd5c03f49f9f9&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

test_spark_session_recovery/test.py times out (>900 s) launching the pyspark Java gateway (Popen of launch_gateway never completes). It is unrelated to this PR (a query-plan change): the same failure hit three different PRs (#113636, #110479, #113697) within ten hours starting 2026-08-06 23:46 UTC, so it looks like a fresh environment/infrastructure problem in the integration-test image or runner.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

Investigated. Confirmed unrelated to this PR, but it is not an image or runner problem: it is a fork deadlock in the test's own process, and the test is mine (added in #113430), so I own it.

The stack proves no JVM was ever launched. The deepest frame is subprocess.py:1944:

java_gateway.py:97   proc = Popen(command, **popen_kwargs)
subprocess.py:1039   __init__
subprocess.py:1944   part = os.read(errpipe_read, 50000)

subprocess.py:1944 is the parent's "wait for exec to fail or succeed" loop, reading the child's CLOEXEC error pipe. The kernel closes that pipe only when the child execs or dies, so reaching this frame and blocking means the forked child never got to exec. Consistent with that, the job log has 0 occurrences of spark-submit and no JAVA_GATEWAY_EXITED. Neither the JVM, the network, nor the Paimon jar baked in on 2026-08-05 can be involved in a fork that never execs.

Why the fork can hang. pyspark/java_gateway.py:96-97 passes preexec_fn (a one-line signal(SIGINT, SIG_IGN)). That disables both of CPython's safe launch paths: the posix_spawn fast path requires preexec_fn is None (subprocess.py:1863) and so does vfork (_posixsubprocess.c:1227), so a plain fork() is used and _posixsubprocess.c:799-801 calls back into Python inside the child, under its own comment "This is where the user has asked us to deadlock their program". _posixsubprocess.c:1001 states the rule: "preexec_fn is NOT SAFE if your application uses threads. It may trigger infrequent, difficult to debug deadlocks." Measured with strace on the same parent: with preexec_fn it is clone(...SIGCHLD); without it, vfork(), where the parent is suspended until exec and this deadlock cannot exist.

Reproduced both directions locally (parent with one sibling thread holding a lock at fork time, then Popen(["/bin/true"], preexec_fn=...)): with preexec_fn the parent is still blocked after 8 s at exactly that _execute_child frame and the child sits in futex_do_wait, never execed; without it, rc=0 in 0.00 s.

Why only this test. It is the only test in the tree that kills the gateway JVM and makes launch_gateway run again inside a live pytest-xdist worker: three SIGKILLs and the only test-side call of _reset_pyspark_class_state. Every other Spark suite launches the gateway once at session start, when the worker has almost no threads. The failing worker had 13 live threads at timeout (kazoo, pymongo, ThreadPoolExecutor, fsspec, py4j, execnet), which is precisely the threads + fork + Python condition CPython warns about. So the 2026-08-06 onset is the test reaching that population, not an infrastructure change.

Fix, verified both directions: translate that trivial preexec_fn into start_new_session=True, so no Python runs in the forked child and CPython takes the vfork path. The isolation pyspark wants is preserved and is actually stronger. A terminal SIGINT is delivered to the foreground process group, and the child then has its own session and group rather than merely ignoring the signal while sharing the parent's group. Unpatched arm deadlocks, patched arm completes in 0.00 s.

One correction to a reading on a sibling thread: the #113430 fix is present in these builds (behind_by=0 for both heads), so this is not a build that predates it. #113430 fixed a stale cached gateway (... does not exist in the JVM); this is the relaunch's own fork deadlock, a second and distinct defect.

I will open the separate PR and link it here. The same failure on #110479 and #113697 has this same single cause, so it will be one PR for all three.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

The fix PR is #113870.

It replaces pyspark's preexec_fn on the gateway launch with start_new_session, so no Python runs in the forked child and CPython can take an exec-only launch path. Two things came out of reviewing it that are worth stating here, since both change the scope I described above:

  • The launch is shared, so the fix had to be. The helper installs the safe launcher as an import side effect, which reached only the suites that import it; test_paimon_spark_smoke and test_storage_delta_shuffles build their sessions straight from pyspark.sql.SparkSession, and both launch after cluster.start(), when the worker already has live threads. Launching once at session start makes the deadlock rarer, not impossible. All eight Spark suites now share the one launch path.
  • The regression test could only fail slowly. Its deadlock is inside the Popen constructor, so no call carrying a timeout of its own is ever reached and the 900 s global bound was the only one, i.e. a regression would have stalled a worker for fifteen minutes instead of reporting. It now carries its own pytest.mark.timeout: with the launch left unpatched it fails in 120.12 s at os.read(errpipe_read), the frame this failure reported, and passes in under a quarter of a second with the fix (0.17-0.22 s over five runs).

Also for the record on scope: I checked whether the two suites that were missing the safe launcher had ever hit this. Over 30 days test_storage_delta_shuffles has 9 failures in 52844 runs and test_paimon_spark_smoke has 0 in 1144, and none of those 9 carries launch_gateway, errpipe_read or the 900 s timeout, so they are unrelated signatures. Routing them through the shared launch is closing a reachable gap, not a failing one.

Same single PR covers #110479 and #113697.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both remaining CI failures on bea222ed are unrelated to this PR:

The AI review verdict on this head is ✅ Approve and the single review thread is resolved, so this PR is ready for a human review/merge.

pull Bot pushed a commit to weiyilai/ClickHouse that referenced this pull request Aug 12, 2026
…ame column

A predicate typed against a view header (e.g. `information_schema.tables`,
where `engine` is `Nullable(String)`) could be pushed down to the underlying
storage (`system.tables`, where `engine` is `String`) and evaluated over a
block with the mismatched column type, failing with a logical error
`Unexpected return type from toString. Expected Nullable(String). Got String`.

Two fixes:
- `buildFilterActionsDAG`: skip a name-based input replacement when it would
  change the input type. Parent `FUNCTION` nodes are rebuilt with their
  existing `function_base`, so a differently-typed input made the rebuilt DAG
  (including the DAG captured inside `indexHint`) internally inconsistent.
- `canEvaluateSubtree` in `VirtualColumnUtils`: match the allowed inputs by
  type as well as by name, so a mismatched predicate subtree is not pushed
  down (the filter is still applied upstream).

Found by the AST fuzzer:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113636&sha=bea222ed980b6db96146b4fe56dc968fa2280dd1&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
on ClickHouse#113636

Closes: ClickHouse#113982

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (bea222ed980b → be64272160b2, zero conflicts) to clear a red that has since become fixable on master:

The merge did not disturb this PR's diff: master touched optimizeTree.cpp only to change the signature of optimizeExchanges, and the guard added here (make_distributed_plan && planContainsLogicalExchange(root) before materializeConstantsForSetOperationBranches) plus the StorageBuffer::read constant materialization are unchanged. Both affected translation units (optimizeTree.cpp, StorageBuffer.cpp) compile clean against merged master.

AI review verdict on the previous head was ✅ Approve with no unresolved review threads; awaiting fresh CI and a human merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Superseded by #114753, which ports the reviewed fix onto current master and retains Alexey Milovidov as author.

pvillamil pushed a commit to pvillamil/ClickHouse that referenced this pull request Aug 14, 2026
…rns full columns

Reading the destination table of a `Buffer` table can return a full column
where the plan over the buffers keeps it constant: constants come back
materialized from a `Distributed` destination. `StorageBuffer::read`
converted the destination plan to the buffers header by name, and a full
column cannot be converted back to a constant, so such reads failed with
`ILLEGAL_COLUMN` ("Cannot convert column ... because it is non constant in
source stream but must be constant in result") - with or without
`make_distributed_plan`, with or without a `Merge` table on top.

Materialize such constants in the buffers branch instead and unite the
branches of the `Buffer` read on the materialized header. This also covers
the mixed local/distributed child shape of `ReadFromMerge` raised in the
review of ClickHouse#113636: a `Buffer`
child over a `Distributed` destination next to a non-distributed sibling.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants