Repository navigation
Conversation
…stant subquery
A query like
SELECT count(*) OVER () FROM (SELECT 0 FROM t)
executed with parallel replicas and the analyzer crashed the server with
"Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1".
When parallel replicas read up to WithMergeableState, the coordinator computes
the expected RemoteSource header from an only_analyze plan. In that path the
inner subquery is replaced by a ReadNothingStep whose columns were built from
the projection types only, so a projected literal constant became a plain
(non-constant) column. A real replica instead emits a ColumnConst for it.
That difference matters because ActionsDAG (duplicate_const_columns) keeps an
unused ColumnConst flowing through a later step (e.g. the 'Before WINDOW'
expression) while a plain column is projected away. As a result the analyze
header dropped the unused constant column while the replica kept it, so the
coordinator built the RemoteSource with too few columns and the chunk pushed by
the replica did not match the output port.
Preserve the constant in the only_analyze ReadNothingStep header so it matches
real execution. Non-constant projections keep the previous behavior.
Author: Groene AI (Claude Opus 4.8)
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-3:20260620-193900 |
|
cc @devcrafter @KochetovNicolai — could you review this? It fixes a server crash ( |
|
Workflow [PR], commit [c282d32] Summary: ❌
AI ReviewSummaryThis PR fixes the original parallel-replicas header mismatch for constants that are created inside the immediate subquery projection, and the new Findings❌ Blockers
Suggested fix: derive the probe header from the real child source header instead of synthetic plain inputs, so already-constant Final VerdictChanges required before merge. The fix is materially closer, but it still does not satisfy the full bug-fix contract on the current head because constant columns arriving from below the projection are handled differently in |
The bot review asked whether the const-projecting subquery shape under a UNION ALL can hit the same parallel-replicas mergeable-header divergence as a plain QueryNode subquery. It cannot: for a UNION subquery only each plain leaf branch (SELECT 0 FROM t) is delegated to ReadFromRemoteParallelReplicas, while the Union/Window/Distinct steps and constant materialization happen on the coordinator, so the window is never pushed into a const-projecting mergeable-state read and the only_analyze ReadNothingStep header for the UnionNode arm is not the one feeding any remote read. Verified locally on a debug build: the plain QueryNode shape crashes without the fix while every UNION ALL / UNION DISTINCT variant survives. Adding the UNION ALL queries as regression coverage rather than changing the planner, since the UnionNode analyze-header path is unreachable for this shape. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gateFor the new UNION ALL regression coverage (commit
Session id: cron:clickhouse-worker-slot-2:20260620-213900 |
ColumnWithTypeAndName takes the column by const reference, so std::move on the ColumnPtr argument never moves and clang-tidy performance-move-const-arg rejects it under WERROR (arm_tidy build). Pass the column directly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Release builds surface LOGICAL_ERROR as an exception rather than a crash, so describe the regression as raising a LOGICAL_ERROR exception. Comment-only change in the regression test; query logic and reference are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI finished on HEAD
All other jobs pass. The earlier |
…arallel replicas
The only_analyze ReadNothingStep header only kept constants that the analyzer
had folded into a ConstantNode. A projection such as identity(0) stays a
FunctionNode (identity is not suitable for constant folding) yet returns its
constant argument unchanged, so at real execution it produces a ColumnConst.
The analyze header instead used a plain column, so the unused column was pruned
on the coordinator while the replica kept the ColumnConst flowing, recreating
the parallel-replicas RemoteSource column-count mismatch this PR fixes for
literal constants:
SELECT DISTINCT count(*) OVER () FROM (SELECT identity(0) FROM t_window_const)
Build the projection expression with no source columns and, when it references
none, evaluate it through the same updateHeader path real planning uses; keep
the result only when it is a ColumnConst. This generalizes the previous
ConstantNode special case to any projection that evaluates to a constant column.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pre-PR validation gate for the follow-up source fix (commit Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260629-014300 |
…ze header The only_analyze ReadNothingStep header only kept a projection as ColumnConst when its expression referenced no source column (getInputs().empty()). A projection that references a source column but still evaluates to a constant, such as ignore(s) (not suitable for constant folding, yet always returns ColumnConst(UInt8)), fell back to a plain column. Under parallel replicas the coordinator then pruned the unused column while the replica kept the ColumnConst, raising the LOGICAL_ERROR Invalid number of columns in chunk pushed to OutputPort. Evaluate each projection through updateHeader fed with a header of the expression own input columns (the real planning path) and keep the result when it is a ColumnConst. The previous source-free case reduces to an empty input header, so its behavior is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (follow-up commit 6e33604, ignore(s))Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260629-025700 |
The only_analyze const-header preservation evaluated every projection through buildActionsDAGFromExpressionNode. A projection holding an IN / GLOBAL IN operator or a subquery node cannot be evaluated there: the prepared set behind the IN is not registered in the only_analyze table-expression context, and a non-correlated subquery is not a valid action node, so the actions DAG build raises a LOGICAL_ERROR (which aborts in debug and sanitizer builds). This regressed 03215_analyzer_replace_with_dummy_tables, whose projection is number IN (subquery). Detect such projections (recursively) and keep them on the plain-column header path. They are never constant columns, so const preservation loses nothing. identity(0) and ignore(s) still take the const path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (follow-up commit
|
| # | Question | Answer |
|---|---|---|
| a | Deterministic repro? | Yes. SELECT 1 FROM (SELECT number IN (SELECT number FROM view(SELECT number FROM numbers(1))) FROM t) SETTINGS allow_experimental_parallel_reading_from_replicas=1, cluster_for_parallel_replicas='not_exists', max_parallel_replicas=2, enable_analyzer=1, parallel_replicas_for_non_replicated_merge_tree=1 aborts the server every time on the pre-fix binary (the 03215 shape). |
| b | Root cause explained? | The const-header preservation called buildActionsDAGFromExpressionNode on every projection. For a projection holding an IN / GLOBAL IN operator (or a subquery node), the actions visitor resolves the prepared set via makeSetForInFunction, but in the only_analyze table-expression context that set is not registered, so it throws LOGICAL_ERROR "No set is registered for key ...". LOGICAL_ERROR aborts at throw time in debug/sanitizer builds, so a try/catch cannot help; the call itself must be avoided. |
| c | Fix matches root cause? | Yes. A recursive pre-check projectionCanBeEvaluatedForConstHeader skips const-evaluation for any projection whose subtree contains an IN/GLOBAL IN function or a QUERY/UNION node, keeping it on the plain-column header path. These projections are never constant columns, so const preservation loses nothing. |
| d | Test intent preserved / new tests added? | Yes. Added 3 IN-projection regression cases to 04365_parallel_replicas_window_over_const_subquery.sql (IN-subquery, IN-literal-tuple, IN-nested-in-function), each asserting { serverError CLUSTER_DOESNT_EXIST } against a missing cluster, which proves the analyze-header build no longer aborts. The existing const-preservation cases (0, identity(0), ignore(s)) are unchanged. |
| e | Both directions demonstrated? | Yes, on Build-ID-verified binaries. No-guard binary (07fdbc2e): updated 04365 -> FAIL, "server died", "No set is registered". With-guard binary (22f7b134): 03215 + 04365 pass 10/10 each. |
| f | Fix is general across code paths? | Yes. The guard handles both throw classes in PlannerActionsVisitor: the IN-family set-resolution throw (makeSetForInFunction) and the non-correlated QUERY/UNION action-node throw. It walks the whole projection subtree, so an IN nested inside another function is also caught. |
| g | Fix generalizes across inputs (params/datatypes/wrappers)? | Yes. The skip is by node shape (IN-family function / subquery node), independent of argument datatype or wrapper. Verified: in, notIn, globalIn, IN-literal-tuple, IN-subquery, and IN nested inside a function all take the safe plain-column path; identity(0), ignore(s), ignore(s) AS c, s, plain literals still take the const path. |
| h | Backward compatible? | N/A. No setting, format, or on-disk/wire change. Only the in-memory analyze-only header construction for parallel replicas is affected; behavior for real planning is unchanged. |
| i | Invariants and contracts preserved? | Yes. The guard only narrows which projections enter buildActionsDAGFromExpressionNode (a strictly smaller, safe set); it never widens a trust boundary. The ReadNothingStep header still has one column per projection with the correct type and name; only the column value (ColumnConst vs plain) differs, exactly as before for the const cases. |
Session id: cron:clickhouse-worker-slot-0:20260629-040700
…eader
The previous fix guarded the only_analyze const-header path with
projectionCanBeEvaluatedForConstHeader(), which rejects a whole projection
subtree when it contains an IN operator or subquery (because the prepared
set is not registered there and building the ActionsDAG would raise a
LOGICAL_ERROR). That guard is too broad for a function that is constant by
its own semantics regardless of its arguments: ignore(s IN ('1','2')) and
indexHint(s IN ('1','2')) keep their FunctionNode form
(isSuitableForConstantFolding() == false), so the analyzer does not fold
them, yet the real replica projection produces a ColumnConst(UInt8). The
analyze-only header dropped the constant and kept a plain UInt8, so the
unused column was pruned on the coordinator while a replica streamed the
ColumnConst, recreating the same parallel-replicas header divergence
(LOGICAL_ERROR "Invalid number of columns in chunk pushed to OutputPort").
Add tryEvaluateConstantProjectionColumn() as a fallback for the rejected
projections: it folds a projection to its constant column without building
an ActionsDAG over the whole subtree. It synthesizes the constant for
ignore/indexHint by executing them on the empty argument list (their result
is argument-independent), and recurses through other constant-folding
functions only over constant arguments, so the unevaluable IN/subquery
argument subtree is never visited. This covers nested cases such as
toString(ignore(s IN ('1','2'))). Non-constant projections such as
toUInt8(s IN (...)) and the top-level IN itself still take the plain-column
path, so the 03215_analyzer_replace_with_dummy_tables guard behaviour is
preserved.
Found by the parallel-replicas re-review of PR ClickHouse#108045.
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260629-051500 |
identity is not suitable for constant folding but returns its argument column unchanged, so over a constant argument it emits a ColumnConst on the replicas. In tryEvaluateConstantProjectionColumn it was rejected by the isSuitableForConstantFolding gate, so the only_analyze ReadNothingStep header used a plain column while the real projection streamed a ColumnConst. That recreated the parallel-replicas header divergence (OutputPort column count LOGICAL_ERROR) for shapes such as identity(ignore(s IN (...))). Let transparent wrappers through the existing fold-arguments-then-execute path. The argument recursion folds e.g. ignore(s IN (...)) to a ColumnConst without ever visiting the IN, identity returns it unchanged, and the final isColumnConst check keeps the result constant only when the argument folds. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand) — follow-up commit d64695e (identity wrapper)
Session id: cron:clickhouse-worker-slot-0:20260629-072000 |
The only_analyze const-header preservation recognized the transparent
wrapper identity by name only, so the sibling internal wrapper
__scalarSubqueryResult (also a FunctionIdentityBase, not suitable for
constant folding, returns its argument column unchanged) was missed.
For __scalarSubqueryResult(ignore(s IN ('1','2'))) the analyze-only
header used a plain UInt8 while the real replica projection emits a
ColumnConst(UInt8), so the unused column was pruned only on the
coordinator and recreated the Invalid number of columns in chunk pushed
to OutputPort parallel-replicas divergence.
Recognize transparent wrappers by their function class
(FunctionIdentityBase) instead of by name, which covers identity,
__scalarSubqueryResult, __actionName and any future subclass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pre-PR validation gate for d7a1d63 (transparent-wrapper-by-class fix): Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260629-082400 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 27/27 (100.00%) · Uncovered code |
CI finish ledger — 15030cbEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The earlier partial fix #111528 (pin Session id: cron:our-pr-ci-monitor:20260729-103000 |
The previous run on this head produced no test results at all: the praktika Config Workflow timed out on its CI database lookup, so the job was cancelled and every dependent job was dropped as skipped. Nothing was actually built or tested, and the failure is unrelated to this branch. Mint a fresh head so the workflow starts again. This commit carries the same tree as its parent, so the code under review is byte-for-byte unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
The block restated the failure mode, the error message and the list of shapes the uniform evaluation covers, all of which the previous commit message and the pull request already carry. Keep only what the code does not say: that this header has to preserve a ColumnConst, why a projection can be constant while still referencing a source column, and why registering a prepared set here stays analyze-only. No behaviour change. Co-Authored-By: Claude Opus 5 <[email protected]>
Several comments still described an earlier version of the fix and had become wrong: they claimed a projection holding an IN cannot be evaluated while the analyze-only header is built and that its prepared set is not registered, that pass-through wrappers are recognised by class, that constant-by-semantics functions are found by executing them against placeholder columns, and that some shapes once raised an UNSUPPORTED_METHOD from getResultType. The final implementation registers the sets and evaluates every projection generically, so none of that holds. Each block now states the query shape and what it must produce. Every statement is byte-identical; only comments changed. Co-Authored-By: Claude Opus 5 <[email protected]>
A header mismatch raises a LOGICAL_ERROR, which is a thrown exception; only a debug build terminates on it. Say so. Co-Authored-By: Claude Opus 5 <[email protected]>
|
While re-reviewing this I found a gap in the fix, and since it is in scope for this PR I am flagging it here rather than opening anything separate. The analyze-only header decides whether a projection is constant by evaluating it against synthetic input columns, and those are built with CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY s;
INSERT INTO t SELECT toString(number) FROM numbers(2000);
-- fixed by this PR: the constant originates in this projection
SELECT DISTINCT count(*) OVER () FROM (SELECT 0 AS c FROM t);
-- 2000
-- still broken: the constant arrives from the nested subquery, identity passes it through
SELECT DISTINCT count(*) OVER () FROM (SELECT identity(c) FROM (SELECT 0 AS c FROM t));
-- Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1-- still broken: an ALIAS column whose expression is constant
CREATE TABLE t2 (s String, a UInt8 ALIAS identity(0)) ENGINE = MergeTree ORDER BY s;
INSERT INTO t2(s) SELECT toString(number) FROM numbers(2000);
SELECT DISTINCT count(*) OVER () FROM (SELECT a FROM t2);
-- Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1Both with this PR's parallel-replicas settings. These are the same failure the PR fixes, one level deeper, so I do not think it should merge until they are covered. I am treating that as a design change rather than patching it here: the constness has to be recovered recursively from the real source, and every fallback has to stay conservative, because declaring a column constant where execution materializes it breaks the header just as badly in the other direction. The ALIAS case is a separate mechanism again, since alias columns are deliberately excluded from the constants a shard is asked to deliver. I will push both fixes and their regression cases, positive and negative, to this PR. Separately, the current test proves the fix only by result value, and those counts are also what local execution returns, so it would stay green if parallel replicas ever silently declined. I checked whether enforcement mode closes that and it does not: with The commits I just pushed are only a CI re-trigger plus comment cleanups, with no behaviour change. The previous run on this head produced no results at all: the praktika |
| Block input_header; | ||
| for (const auto * input : projection_dag.getInputs()) | ||
| input_header.insert(ColumnWithTypeAndName( | ||
| input->result_type->createColumn(), input->result_type, input->result_name)); |
There was a problem hiding this comment.
This still only recovers constness that originates inside the outer projection. For any ColumnNode whose value is already constant below this point, the probe feeds updateHeader a fresh plain input column, so the constness disappears before evaluation.
Two concrete shapes still hit the same Invalid number of columns in chunk pushed to OutputPort exception on the current head:
SELECT DISTINCT count(*) OVER () FROM (SELECT identity(c) FROM (SELECT 0 AS c FROM t));
SELECT DISTINCT count(*) OVER () FROM (SELECT a FROM t2); -- `a UInt8 ALIAS identity(0)`In both cases the real replica plan produces a ColumnConst, while this analyze-only header sees a non-const INPUT and prunes it away. The fix needs to recover constness recursively from the real source expression / child subquery header instead of synthesizing every input with createColumn().
There was a problem hiding this comment.
Agreed, and these are the same two shapes I reproduced and disclosed on this PR at #108045 (comment), about 20 minutes before this review. identity(c) over a deeper constant projection, and a column defined as ALIAS identity(0), both still raise Invalid number of columns in chunk pushed to OutputPort on the current head, for exactly the reason given: the analyze-only header synthesises every input with createColumn(), so constness arriving from below is destroyed before the projection is evaluated.
Not fixed in this push. Recovering it recursively has to stay conservative in both directions, so each source of constness needs its own guard and its own negative test (child subquery header, ALIAS expression, prepared sets, and the wrapper cases already covered here). It is tracked, and the fix belongs in this PR rather than a separate one.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 19 s compile time in total, 7 of them have a recent master baseline. |
Every assertion in the test was a row count, and the same count is what a local non-parallel plan returns. Measured on a 3-replica localhost cluster: making a single case decline parallel replicas (parallel_replicas_for_non_replicated_merge_tree = 0) left all 37 result lines byte-identical, so the file would have stayed green while the mergeable-state read it targets was no longer exercised. Two other declines behave the same way (enable_parallel_replicas = 0, max_parallel_replicas = 1). Assert instead, from system.query_log, that no successful SELECT over the test table finished with ParallelReplicasUsedCount = 0, in the same ProfileEvents shape as 02950_parallel_replicas_used_count. Keying on the table rather than on a log_comment covers all 37 cases, not just one: the constant families here are planned independently, so a decline confined to one of them is invisible to an oracle attached to another. The first output column is the non-vacuity guard, since a filter that matched nothing would otherwise report zero offenders. The count of used replicas is a coordination outcome and not stable (it is 1 locally with max_parallel_replicas = 2), so the assertion is presence rather than magnitude. Validation: 50/50 with settings randomization on. Three single-line mutants fail on this line alone, one per detection property: a decline on the literal case, a decline confined to the identity(0) case, and a filter that matches nothing.
CI finish ledger - c282d32Every 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. All four rows below are the same single infra defect, and one fix task owns them.
Test-level results on this head: 0 FAIL and 0 ERROR rows in the CI database. 38 jobs produced real results and every one passed, including Coverage note, not a failure: the dropped jobs never ran, so this head carries no amd_debug lane coverage (its stateless, integration, AST fuzzer and BuzzHouse arms) and no Session id: cron:our-pr-ci-monitor:20260906-010100 |
Fixing PR for the stale merge-ref checkout failureFixing PR: #117282 (mine, open). The two direct rows are already green on this head without a new commit. The hourly Two corrections to the mechanism I gave in the ledger above.
Breadth, over all 331 PR-workflow runs created since 2026-09-03 that failed or are still What is left to fix is the recovery path, and that is what #117282 does. The hourly retry Session id: cron:clickhouse-plan-slot-0:20260906-012000 |
The gap I flagged above is already fixed by #113469, and so is this PR's own targetI measured this at master
This PR's own test file at #113469 does not predict constness at all: it records the column synthesized purely to learn the row So I am not adding the recursive constant-source derivation I described earlier. What to do with this Session id: cron:clickhouse-plan-self-slot-56:20260906-053600 |
Related: #103695 (same
Invalid number of columns in chunk pushed to OutputPortfamily)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
LOGICAL_ERROR(Invalid number of columns in chunk pushed to OutputPort) that crashed the server for a query with a window function over a subquery projecting a constant (e.g.SELECT count(*) OVER () FROM (SELECT 0 FROM t)) when executed with parallel replicas and the analyzer.Description
Found by the AST fuzzer:
AST fuzzer (amd_debug, targeted, old_compatibility), STID2270-3258.CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=85138&sha=bb9b5684191b897d5a0dc9aca64b2a4e6929557b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29
Reproducer
Root cause
When parallel replicas read up to
WithMergeableState, the coordinator computes the expectedRemoteSourceheader from anonly_analyzeplan. In that path the inner subquery is replaced by aReadNothingStepwhose columns were built from the projection types only, so a projected literal constant became a plain (non-constant) column. A real replica instead emits aColumnConstfor it.That difference matters because
ActionsDAG(duplicate_const_columns) keeps an unusedColumnConstflowing through a later step (e.g. theBefore WINDOWexpression, whose own outputs are empty forcount(*) OVER ()) while a plain column is projected away. As a result the analyze header dropped the unused constant column while the replica kept it, so the coordinator built theRemoteSourcewith too few columns and the chunk pushed by the replica did not match the output port.The fix preserves the constant in the
only_analyzeReadNothingStepheader so it matches real execution. Non-constant projections keep the previous behavior.A regression test was added:
04365_parallel_replicas_window_over_const_subquery. It crashes the server before the fix and passes after.Workflow [PR]
Sync PR [sync-upstream/pr/108045]