Skip to content

Fix LOGICAL_ERROR in parallel replicas for window function over a constant subquery - #108045

Open
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fix-parallel-replicas-window-const-header
Open

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fix-parallel-replicas-window-const-header

Conversation

@groeneai

@groeneai groeneai commented Jun 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #103695 (same Invalid number of columns in chunk pushed to OutputPort family)

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 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), STID 2270-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

CREATE TABLE t (s String) ENGINE = MergeTree ORDER BY s;
INSERT INTO t SELECT toString(number) FROM numbers(2000);

SELECT count(*) OVER () FROM (SELECT 0 FROM t)
SETTINGS enable_parallel_replicas = 1, max_parallel_replicas = 2,
    cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost',
    parallel_replicas_for_non_replicated_merge_tree = 1,
    parallel_replicas_local_plan = 0, prefer_localhost_replica = 0,
    enable_analyzer = 1;

Root cause

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, whose own outputs are empty for count(*) 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 the RemoteSource with too few columns and the chunk pushed by the replica did not match the output port.

The fix preserves the constant in the only_analyze ReadNothingStep header 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]

…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)
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT count(*) OVER () FROM (SELECT 0 FROM t) (t = MergeTree with 2000 rows) under enable_parallel_replicas=1, max_parallel_replicas=2, cluster_for_parallel_replicas='test_cluster_one_shard_three_replicas_localhost', parallel_replicas_for_non_replicated_merge_tree=1, parallel_replicas_local_plan=0, prefer_localhost_replica=0, enable_analyzer=1 crashes the server 3/3 runs on a clean data dir.
b Root cause explained? Parallel replicas read up to WithMergeableState. The coordinator computes the RemoteSource header from an only_analyze plan where the inner subquery is replaced by a ReadNothingStep built from projection types only, so a projected literal constant becomes a plain (non-const) column. A real replica emits a ColumnConst. ActionsDAG's duplicate_const_columns keeps an unused ColumnConst flowing through the Before WINDOW step (whose own outputs are empty for count(*) OVER ()) while a plain column is projected away. So the analyze header has 0 columns but the replica streams 1 (the const) -> OutputPort::pushData LOGICAL_ERROR "Expected 0, found 1".
c Fix matches root cause? Yes. The fix preserves const-ness in the only_analyze ReadNothingStep header (builds a ColumnConst for ConstantNode projections) so the coordinator header matches what the replica actually produces. It targets the analyze/execute header divergence directly, not the crash site.
d Test intent preserved / new tests added? New regression test 04365_parallel_replicas_window_over_const_subquery added. No existing test weakened.
e Both directions demonstrated? Yes. The test SQL crashes the pre-fix binary (server DEAD, "Expected 0, found 1 / Chunk: UInt8(size = 2000)") and returns correct results on the fixed binary (2000 / 2000 / 2000 1 z, server alive). Build IDs differ (pre-fix 5cb0faeb... vs fixed 8d6338a5...).
f Fix is general, not a narrow patch? Yes. The fix is at the source of the analyze/execute header divergence (the only_analyze subquery ReadNothingStep), so it covers all constant projection columns (0, toInt128(0), folded 1+1, multiple consts, const + real column mixed). Non-constant projections keep prior behavior. Verified no regressions: 6 window-function + 23 analyzer/const/subquery/projection stateless tests produce byte-identical output vs master. A first attempt that passed a null column for non-const projections caused NOT_FOUND_COLUMN_IN_BLOCK; that was found and fixed (non-const columns keep the type-based 2-arg constructor).

Session id: cron:clickhouse-worker-slot-3:20260620-193900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai — could you review this? It fixes a server crash (Invalid number of columns in chunk pushed to OutputPort) for a window function over a constant subquery under parallel replicas: the coordinator's only_analyze mergeable header dropped an unused constant column (built as a plain column by the inner-subquery ReadNothingStep) that a replica actually streams as a ColumnConst. The fix preserves const-ness in that analyze header so it matches real execution.

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

clickhouse-gh Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c282d32]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue
Build (amd_darwin) ERROR
Stateless tests (amd_debug, sequential) ERROR
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) ERROR
Integration tests (arm_binary, distributed plan, 4/4) ERROR
Integration tests (amd_tsan, 2/6) ERROR
Integration tests (amd_llvm_coverage, 2/8) ERROR
Docker keeper image ERROR
Install packages (amd_release) ERROR

AI Review

Summary

This PR fixes the original parallel-replicas header mismatch for constants that are created inside the immediate subquery projection, and the new query_log oracle now proves the positive cases really use parallel replicas. The remaining problem is that the analyze-only probe still rebuilds every projection input as a fresh plain column, so constness that already exists below this level is lost and the same Invalid number of columns in chunk pushed to OutputPort exception is still reachable on the current head.

Findings

❌ Blockers

[src/Planner/PlannerJoinTree.cpp:2828-2834] The only_analyze path now discovers constants by running projection_dag.updateHeader(input_header), but input_header is synthesized from input->result_type->createColumn() for every INPUT. That preserves constness only when it originates inside the outer projection itself; it destroys constness that comes from a child subquery or an ALIAS expression before the projection is evaluated. As a result, shapes like SELECT DISTINCT count(*) OVER () FROM (SELECT identity(c) FROM (SELECT 0 AS c FROM t)) still let the initiator prune the unused column while the shard keeps streaming a ColumnConst, so the PR's original RemoteSource column-count exception is still reproducible.

Suggested fix: derive the probe header from the real child source header instead of synthetic plain inputs, so already-constant ColumnNode inputs stay constant through updateHeader. Add focused regression coverage for the nested-subquery case above and for SELECT DISTINCT count(*) OVER () FROM (SELECT a FROM t2) where a is UInt8 ALIAS identity(0).

Final Verdict

Changes 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 only_analyze and real execution.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 20, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For the new UNION ALL regression coverage (commit 2fb3843b2f8):

# Question Answer
a Deterministic repro? Yes. On a no-fix binary (this hunk reverted to HEAD~1), the plain QueryNode shape SELECT DISTINCT count(*) OVER () FROM (SELECT 0 FROM t) crashes every time with Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1, under the exact PR settings on test_cluster_one_shard_three_replicas_localhost.
b Root cause explained? Yes. For the plain subquery the whole window query is delegated as one ReadFromRemoteParallelReplicas; the coordinator builds the inner subquery's mergeable header via only_analyze, where a projected literal becomes a plain column and is pruned while the replica streams a ColumnConst, so the RemoteSource has too few columns. For UNION ALL only each plain leaf (SELECT 0 FROM t) is delegated; Union/Window/Distinct and const materialization (explicit COLUMN Const in each branch's Before WINDOW) run on the coordinator, so no const-projecting only_analyze header feeds a remote read.
c Fix matches root cause? Yes. The existing query_node fix targets the only path that reaches the divergence. The UnionNode arm is proven unreachable for this shape, so the correct action is coverage, not speculative plumbing for a dead path.
d Test intent preserved / new tests added? Yes. No existing assertions changed. Added 3 UNION ALL queries (the bot's exact shape, different-const-values per branch, const+extra-column) demonstrating the shape does not crash under parallel replicas.
e Both directions demonstrated? Yes. Plain shape: crashes on no-fix binary, passes on fix binary. UNION ALL shapes: survive on both binaries (so they are valid no-crash coverage). Test .sql run verbatim diffs clean against .reference on the fix binary (Build ID 1cf7c7adf5ffc0bc56b9e717aa9d902af8be200d).
f Fix is general, not a narrow patch? Yes. Verified the UnionNode arm is unreachable for the const-window-parallel-replicas divergence via EXPLAIN PLAN and 11 UNION ALL / UNION DISTINCT / nested / 3-branch / GROUP BY / PARTITION BY variants, all of which survive the no-fix binary. No sibling code path carries the same reachable divergence for this shape.

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

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 7bb35d4a862. Failure dispositions:

All other jobs pass. The earlier Build (arm_tidy) failure was on the superseded commit 64e8476f6e0 and is already fixed in 8e6566ba144.

@devcrafter devcrafter self-assigned this Jun 22, 2026
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the follow-up source fix (commit ab311a2237b) addressing the bot's identity(0) change-request.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT DISTINCT count(*) OVER () FROM (SELECT identity(0) FROM t_window_const) with enable_parallel_replicas=1, parallel_replicas_local_plan=0, prefer_localhost_replica=0, max_parallel_replicas=2, parallel_replicas_for_non_replicated_merge_tree=1, enable_analyzer=1 aborts every time with Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1; the control SELECT 0 ... passes.
b Root cause explained? identity has isSuitableForConstantFolding()==false, so the analyzer keeps it a FunctionNode (not a folded ConstantNode). At execution identity returns its constant argument unchanged, a ColumnConst. The only_analyze ReadNothingStep header only special-cased ConstantNode, so identity(0) got a plain UInt8 column; the unused column was then pruned on the coordinator while the replica kept the ColumnConst, so the coordinator's RemoteSource header had 0 columns and the replica's chunk had 1 -> mismatch -> LOGICAL_ERROR.
c Fix matches root cause? Yes. Instead of the ConstantNode-only check, for each projection node I build its ActionsDAG with no inputs; if it references no source column I evaluate it via the same ActionsDAG::updateHeader path real planning uses (updateHeader -> evaluatePartialResult executes constant-only functions at header time), and keep the result only when it is a ColumnConst. This makes the analyze header produce the ColumnConst exactly as real execution does.
d Test intent preserved / new tests added? Yes. Added the bot's identity(0) shape and the mixed identity(0) AS c, s shape to 04365_parallel_replicas_window_over_const_subquery; existing assertions unchanged.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Without the change the updated test aborts the server at the identity(0) line (client exit 32, Invalid number of columns ... OutputPort); with the change the full test diffs clean (20/20 deterministic) and the server stays alive.
f Fix is general across code paths? Yes. The fix replaces the narrow ConstantNode special-case with the generic updateHeader evaluation, so all constant-evaluating projections take the same path. The sibling union_node arm is unchanged (it has no projection nodes; its non-reachability was shown for the earlier UNION ALL CR). It is not a symptom guard.
g Fix generalizes across inputs? Yes. Verified identity(0), 1+1, ignore(0), identity(toUInt32(7)), nested identity(identity(0)), two-const identity(0) AS a, identity(1) AS b, and the mixed identity(0) AS c, s (const + column) shapes all pass with the server alive. Column-referencing projections (e.g. identity(s)) add an INPUT, so they are left on the plain-column path (verified they take the fallback).
h Backward compatible? Yes. Internal planner header construction only; no setting, on-disk/wire/replication format, or default behavior change. SettingsChangesHistory.cpp not applicable.
i Invariants and contracts preserved? Yes. The fix makes the analyze (only_analyze) header MATCH the real-execution header (the very invariant whose violation caused the crash). The DAG is evaluated only when it has no INPUT nodes and a single output, so updateHeader({}) cannot hit NOT_FOUND_COLUMN_IN_BLOCK; the ColumnConst is recreated with the projection's declared type, preserving the column's type contract.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up commit 6e33604, ignore(s))

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT DISTINCT count(*) OVER () FROM (SELECT ignore(s) FROM t_window_const) under the PR's parallel-replicas settings aborts every time on the pre-fix head (ab311a2) with Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1.
b Root cause explained? ignore has isSuitableForConstantFolding()==false so the analyzer keeps it a FunctionNode (not a ConstantNode), but executeImpl always returns ColumnConst(UInt8). ignore(s) references source column s, so the projection ActionsDAG has a non-empty INPUT; the prior fix's getInputs().empty() gate skipped it, leaving a plain UInt8 in the only_analyze header while the replica streams the ColumnConst, so the coordinator prunes the unused column and the replica keeps it -> 0-vs-1 mismatch.
c Fix matches root cause? Yes. Drops the getInputs().empty() gate and evaluates each projection via updateHeader fed a header of the expression's own input columns (the real-planning path), keeping the result only when it is a ColumnConst. This is the bot's preferred fix.
d Test intent preserved / new tests added? Added ignore(s) and ignore(s) AS c, s to 04365 (.sql + .reference). Existing assertions unchanged.
e Both directions demonstrated? Yes, on Build-ID-distinct binaries (control f2a0a02f vs fix 07fdbc2e). Updated test crashes the server at the ignore(s) line without the fix (exit 134, prints first 5 rows then aborts); passes 15/15 with the fix.
f Fix is general across code paths? Yes. The single only_analyze header-construction site is the only place that built a type-only header; generalizing it covers all constant-output projections (folded literals, source-free identity(0), and source-referencing ignore(s)) through one updateHeader path.
g Fix generalizes across inputs? Verified: ignore(s), ignore(s) AS c, s, ignore(toUInt64(s)), CAST(ignore(s) AS Nullable(UInt8)), toLowCardinality(0), and mixed const+col lists all preserve the constant (return 2000). Non-const projections (identity(s), materialize(0), length(s), toUInt32(s), tuple(s,0), rand(), arrayJoin) take the plain-column fallback unchanged (behavior identical to control).
h Backward compatible? N/A. Analyze-only header construction; no setting/format/on-disk change.
i Invariants and contracts preserved? Yes. updateHeader is fed real (empty) input columns matching the DAG's INPUT names/types, satisfying its NOT_FOUND_COLUMN_IN_BLOCK precondition; the const result is materialized via type->createColumnConst(0, value) so the header column matches the projection type. The header still has one column per projection (block-structure invariant). PLACEHOLDER/correlated projections are excluded via correlated_subtrees.notEmpty().

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (follow-up commit f234e66e777)

CI on the previous head (6e33604e17de) hit a Fast test failure: 03215_analyzer_replace_with_dummy_tables aborted with a LOGICAL_ERROR ("No set is registered for key ..."). It was caused by this PR's own only_analyze const-header rework, so it is fixed here in f234e66e777.

Pre-PR validation gate (click to expand)
# 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

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT DISTINCT count(*) OVER () FROM (SELECT ignore(s IN ('1', '2')) FROM t_window_const) under the PR's parallel-replicas settings (enable_parallel_replicas=1, max_parallel_replicas=2, parallel_replicas_local_plan=0, prefer_localhost_replica=0, parallel_replicas_for_non_replicated_merge_tree=1, enable_analyzer=1, test_cluster_one_shard_three_replicas_localhost) aborts the server every time on the prior head with Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1.
b Root cause explained? ignore has isSuitableForConstantFolding()==false and returns ColumnConst(UInt8, 0) regardless of its arguments, so the analyzer keeps it a FunctionNode (not folded to a ConstantNode), yet the real replica projection emits a ColumnConst. The only_analyze header guard projectionCanBeEvaluatedForConstHeader() rejects the whole subtree because of the in child, so the header used a plain UInt8. The coordinator pruned the unused plain column while the replica streamed the ColumnConst, giving a 0-vs-1 RemoteSource column-count mismatch.
c Fix matches root cause? Yes. tryEvaluateConstantProjectionColumn() synthesizes the ColumnConst for ignore/indexHint (constant by function semantics) without entering the unevaluable IN/subquery subtree, so the analyze-only header keeps the constant exactly like the replica. It does not widen the throwing updateHeader path that the 03215 guard protects against.
d Test intent preserved / new tests added? Yes. Added 5 shapes to 04365 (ignore(s IN tuple), ignore(s IN subquery), ignore(s IN (...)) AS c, s, toString(ignore(s IN (...))), indexHint(s IN (...))), each asserting 2000. The existing IN-guard cases (non-const s IN (...), toUInt8(s IN (...)) + 0) are kept and still assert CLUSTER_DOESNT_EXIST, so the 03215 guard coverage is preserved.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. No-fix (22f7b134): the updated 04365 aborts the server at the ignore(s IN ...) line. With fix (8054db7a): all shapes return 2000, server alive, 04365 + 03215 pass 20/20 deterministically.
f Fix is general across code paths? Yes. The fallback covers the full crash class: any always-constant function (ignore/indexHint) over an IN/subquery, plus nested constant-folding wrappers over it (toString(ignore(s IN (...)))). It does not just patch the single reported ignore(s IN tuple) case. The fix is at the only_analyze header construction (the origin of the divergence), not a defensive guard at the crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified across IN tuple, IN subquery, mixed const+column projection lists, and the nested toString(ignore(...)) wrapper. Non-constant projections (toUInt8(s IN (...)), materialize(s IN (...)), top-level s IN (...), plain columns) correctly stay on the plain-column path. The recursion only executes constant-folding functions over constant arguments, so it never executes a non-foldable side-effecting function (e.g. sleep/throwIf) at analyze time.
h Backward compatible? Yes. No setting default, on-disk/wire format, or existing-data validation change. The fix only makes the analyze-only header match real execution for an already-supported query shape that previously aborted. No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. The invariant is that the only_analyze ReadNothingStep header must match the mergeable-state header the replicas produce (same column constness per position). The fix restores that invariant for the constant-output case while leaving the plain-column path unchanged for everything else. tryEvaluateConstantProjectionColumn() only ever reads constant nodes / executes constant-evaluable functions and never visits the IN/subquery subtree, so it cannot trip the "No set is registered" LOGICAL_ERROR that the 03215 guard relies on.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand) — follow-up commit d64695e (identity wrapper)
# Question Answer
a Deterministic repro? Yes. On the prior head 3bb4aef (Build ID 8054db7a), SELECT DISTINCT count(*) OVER () FROM (SELECT identity(ignore(s IN ('1','2'))) FROM t_window_const) under the PR's parallel-replicas settings aborts every run with Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1. identity(identity(ignore(s IN ...))) and identity(ignore(s IN subquery)) reproduce identically.
b Root cause explained? identity is FunctionIdentityBase: isSuitableForConstantFolding()==false (deliberate, to block index/const-fold) yet executeImpl returns its argument column unchanged. In tryEvaluateConstantProjectionColumn it was rejected at the foldability gate and returned nullptr, so the only_analyze ReadNothingStep header used a plain UInt8, while the real projection (where ignore(...) is a ColumnConst and identity passes it through) streamed a ColumnConst. The coordinator pruned the unused plain column, the replica kept the const → OutputPort column-count divergence → LOGICAL_ERROR (aborts in debug/sanitizer).
c Fix matches root cause? Yes. Recognize transparent non-folding wrappers (identity) and let them through the existing fold-arguments-then-execute path instead of the foldability gate. The wrapper's argument is folded recursively; identity returns it unchanged, so the analyze header keeps the same ColumnConst the replica emits. Directly targets the const-propagation the wrapper performs.
d Test intent preserved / new tests added? Added to 04365_parallel_replicas_window_over_const_subquery: identity(ignore(s IN tuple)), identity(ignore(s IN subquery)), identity(identity(ignore(s IN tuple))), identity(ignore(s IN tuple)) AS c, s (all → 2000), plus a non-const boundary identity(s IN ('1','2')) asserting CLUSTER_DOESNT_EXIST (proves it is not falsely kept constant). No existing assertions weakened.
e Both directions demonstrated? Yes. Pre-fix (8054db7a): the three identity(...) shapes abort. Post-fix (Build ID a159b88f): all return 2000, server stays alive; 30×3 stress = 0 failures; the 19 output queries match .reference byte-for-byte; the new serverError boundary reports Code 701 CLUSTER_DOESNT_EXIST and the server stays alive.
f Fix is general across code paths? Yes. The single fallback tryEvaluateConstantProjectionColumn covers all only_analyze header construction for QueryNode projections. The recursion handles arbitrary nesting (identity(identity(...)), toString(ignore(...))) and composes with the existing ignore/indexHint always-const branch. No sibling planner path builds this header differently.
g Fix generalizes across inputs? Yes. Verified across IN tuple, IN subquery, nested wrappers, and the wrapper-with-extra-column shape (AS c, s); the constant is preserved in each. The complementary boundary — identity(s IN ...) and identity(toUInt8(s IN ...)) with a genuinely non-constant argument — correctly stays on the plain-column path (runtime isConstant=0), because the argument fails to fold so the function returns nullptr and the final isColumnConst check never keeps it. No false positives.
h Backward compatible? Yes. Affects only the analyze-only header used for parallel-replicas planning; no setting default, on-disk/wire format, or user-visible behavior changes. It makes the analyze header match real execution that already happens.
i Invariants and contracts preserved? Yes. Upholds the block-structure invariant this whole PR targets: the only_analyze ReadNothingStep header column set must match what the replicas stream. The IN/subquery argument subtree is still never visited (the always-const ignore/indexHint branch folds without arguments; the recursion only descends into arguments that themselves fold), so the prior "No set is registered" guard is unaffected. identity always has exactly one argument, so the recursion's per-argument fold is well-defined.

Session id: cron:clickhouse-worker-slot-0:20260629-072000

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for d7a1d63 (transparent-wrapper-by-class fix):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the prior head (Build ID a159b88f): SELECT DISTINCT count(*) OVER () FROM (SELECT __scalarSubqueryResult(ignore(s IN ('1','2'))) FROM t_window_const) under the PR's parallel-replicas settings aborts the server every time with "Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1". __scalarSubqueryResult(identity(ignore(s IN ...))) and identity(__scalarSubqueryResult(ignore(s IN ...))) reproduce too.
b Root cause explained? Yes. __scalarSubqueryResult is a FunctionIdentityBase like identity: isSuitableForConstantFolding()==false so the analyzer keeps it a FunctionNode, yet executeImpl returns its argument column unchanged. With an always-const argument (ignore(s IN ...) -> ColumnConst), the real replica projection emits a ColumnConst(UInt8). The prior fix recognized transparent wrappers by name ("identity" only), so __scalarSubqueryResult was rejected -> the analyze-only ReadNothingStep header inserted a plain UInt8 -> the unused column was pruned only on the coordinator while the replica streamed the ColumnConst -> the same OutputPort column-count mismatch.
c Fix matches root cause? Yes. functionIsTransparentConstantWrapper now recognizes the wrapper by its function class (dynamic_cast<const FunctionIdentityBase *> via the FunctionToFunctionBaseAdaptor, the access pattern already used for indexHint in ActionsDAG.cpp / Planner/Utils.cpp) instead of matching "identity" by name. Directly addresses the mechanism: any FunctionIdentityBase (identity, __scalarSubqueryResult, __actionName) now keeps its constant in the analyze-only header.
d Test intent preserved / new tests added? Yes. Added the __scalarSubqueryResult(ignore(s IN ...)) shape (tuple, subquery, and both identity-nesting orders) to 04365, all asserting 2000, plus a non-const __scalarSubqueryResult(toUInt8(s IN ...)) boundary asserting it stays on the plain-column path. Existing assertions unchanged.
e Both directions demonstrated? Yes, Build-ID-verified. WITHOUT the fix (a159b88f, == prior committed head): the new test query crashes the server. WITH the fix (d02d2258): the full 04365 test diffs clean 5/5 deterministically and the server stays alive; all 5 serverError boundaries report CLUSTER_DOESNT_EXIST.
f Fix is general across code paths? Yes. The fix is class-based, not a per-name special case, so it covers every FunctionIdentityBase subclass (identity, __scalarSubqueryResult, __actionName, and any future one) in a single check rather than enumerating names. No sibling code path needs the same patch.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified the IN argument as a literal tuple and as a subquery; nested wrappers in both orders (__scalarSubqueryResult(identity(...)), identity(__scalarSubqueryResult(...))); and a genuinely non-constant argument (__scalarSubqueryResult(toUInt8(s IN ...))) which correctly stays non-const. The argument recursion + final isColumnConst check gate the result, so the wrapper is never falsely kept constant.
h Backward compatible? Yes. No setting default, on-disk/wire/metadata format, or validation change. Pure planner header-construction fix; only adds a constant column to an analyze-only header where the real plan already had one.
i Invariants and contracts preserved? Yes. The only_analyze ReadNothingStep header is brought into agreement with the real replica projection header (the invariant the bug violated). The transparent-wrapper gate only relaxes the foldability requirement; the existing isColumnConst safety net still rejects non-constant results, so the header never gains a constant the real plan would not produce. No concurrency or data-structure invariants touched.

Session id: cron:clickhouse-worker-slot-0:20260629-082400

Comment thread src/Planner/PlannerJoinTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 27/27 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 15030cb

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

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky, trunk — under parallel replicas one statement becomes several reads of the same table on this server, each with a different query id, so the long-running holder query competes against itself for the single max_concurrent_queries slot and is rejected instead of holding it #112385 (ours, open)

The earlier partial fix #111528 (pin max_threads = 1 on the holder query) is present on this
head and does not cover the parallel-replicas route, so #112385 disables parallel replicas for
this test outright.

Session id: cron:our-pr-ci-monitor:20260729-103000

groeneai and others added 4 commits September 5, 2026 16:43
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]>
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

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 createColumn(), so they are never constant. That finds constness which originates in the projection, but it destroys constness that arrives from below. Two shapes still raise the LOGICAL_ERROR this PR is about (both reproduced on the current head, debug build):

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 1

Both 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 enable_parallel_replicas = 2 the output is byte-identical, and it still does not raise when I make parallel replicas unusable. A ParallelReplicasUsedCount assertion is the real oracle, so that goes in with the above.

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 Config Workflow timed out on its CI database lookup and every dependent job was dropped as skipped.

Block input_header;
for (const auto * input : projection_dag.getInputs())
input_header.insert(ColumnWithTypeAndName(
input->result_type->createColumn(), input->result_type, input->result_name));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c282d32dd with master 5cbca3e09 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

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

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c282d32

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. All four rows below are the same single infra defect, and one fix task owns them.

Check / test Reason Owner / fixing PR
Build (amd_debug) infra: the job could not fetch this head's PR merge ref, fatal: remote error: upload-pack: not our ref b8cb17b0ec660609fe24c2937000d73ab8171bcf (GitHub recomputed refs/pull/108045/merge after master advanced). 3 identical retries, job dead in 39s having built nothing, praktika then dropped 105 dependent jobs a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Code Review same cause, same dead merge ref, 36s a fix task is created (the same one, fixing-PR link to follow on this PR)
Finish Workflow / Post Hooks cascade of the above: all five Bugfix validation arms were dropped, so new_tests_check.py found none reporting OK. On the previous head 60816168359003b those same arms ran and reported success, which is the control a fix task is created (the same one, fixing-PR link to follow on this PR)
Mergeable Check, PR aggregators reflecting the two reds above ("Failed: 105"), no independent failure a fix task is created (the same one, fixing-PR link to follow on this PR)

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 Style check, Fast test, Build (arm_tidy), every other build flavour, all Unit tests variants, all three flaky check arms, Stateless tests (arm_binary, parallel) and (arm_binary, sequential), Stateless tests (arm_asan_ubsan, targeted), and Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6 .. 6/6).

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 Bugfix validation result. That lane returns on the next push, which this PR still owes anyway: the recursive nested-constant-source case is not fixed in this head, as disclosed at #108045 (comment).

Session id: cron:our-pr-ci-monitor:20260906-010100

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the stale merge-ref checkout failure

Fixing PR: #117282 (mine, open).

The two direct rows are already green on this head without a new commit. The hourly Retry Infrastructure Failures workflow (run 34003386124)
classified this run as an infrastructure failure at 01:14:46Z and re-ran it; on attempt 2
Code Review and Build (amd_debug) both succeeded, fetching the same merge sha
b8cb17b0ec660609fe24c2937000d73ab8171bcf that had been refused. The Finish Workflow,
Mergeable Check and PR rows follow from those two.

Two corrections to the mechanism I gave in the ledger above.

  1. Orphaning the pinned merge commit is necessary but not sufficient. Master advanced at
    21:32:43Z, 22:06:26Z and 22:07:41Z, so b8cb17b0e was three commits stale by 22:11:36Z,
    yet four other jobs starting in that same second fetched it successfully, and across the
    attempt 39 jobs fetched it against 2 refusals. A recomputation race would fail every
    concurrent job, so the refusal is per request, which is why a subset of the graph
    disappears instead of the run failing outright.
  2. The object is not deleted. The attempt-2 fetch at 01:16:37Z resolved b8cb17b0e after
    refs/pull/108045/merge had already been recomputed to 95b9cca7b05e.

Breadth, over all 331 PR-workflow runs created since 2026-09-03 that failed or are still
running: 20 jobs in 2 runs, all between 22:11Z and 00:32Z, none anywhere else. The CI
database cannot see any of it, because the job dies before praktika starts.

What is left to fix is the recovery path, and that is what #117282 does. The hourly retry
only re-runs a whole run, and only when every failed job is infrastructure, so a run that
also has one genuine failure recovers nothing. That is the state of the sibling run
33994189103 tonight: 18
jobs died in the same window while one Stateless tests (amd_llvm_coverage, old analyzer, s3 storage) job failed for real after 57 minutes, so those 18 lanes stay missing. #117282
re-runs the individual infrastructure job in that mixed case; #115569 and #113564 cover the
classifier arm and the candidate window.

Session id: cron:clickhouse-plan-slot-0:20260906-012000

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

The gap I flagged above is already fixed by #113469, and so is this PR's own target

I measured this at master 319bfd73ff35ccc with two binaries out of the same build dir: ch-base
pristine, and ch-fix = master plus the src/ diff of #113469 only, carrying none of this PR's
planner change. All shapes below use this PR's own settings, parallel_replicas_local_plan = 0
included; the correct answer is 2000 everywhere.

shape pristine master + #113469 only
(SELECT 0 AS c FROM t), this PR's target abort Expected 0, found 1 2000
(SELECT c FROM (SELECT 0 AS c FROM t)) abort 2000
(SELECT identity(c) FROM (SELECT 0 AS c FROM t)) abort 2000
(SELECT a FROM t_alias), a UInt8 ALIAS identity(0) abort 2000
three nesting levels, and a CTE source abort 2000
SELECT count() FROM (SELECT count(*) OVER () FROM t) 0, silently 2000
SELECT DISTINCT count(*) OVER () FROM t_alias no rows, silently 2000

This PR's own test file at c282d32dd1c31ba, all 113 statements, run against that same binary,
produces output byte-identical to its own reference.

#113469 does not predict constness at all: it records the column synthesized purely to learn the row
count and replaces a header made of nothing but such columns with one materialized marker, so the
initiator and the shard derive the same header by construction. Evaluating each projection against
inputs built from createColumn() can only recover constness that originates inside that projection,
which is why the last two rows above, where there is no constant to preserve, stay broken under this
PR's approach.

So I am not adding the recursive constant-source derivation I described earlier. What to do with this
PR is a call for its reviewers; #113469 is approved and waiting on #113955.

Session id: cron:clickhouse-plan-self-slot-56:20260906-053600

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants