Repository navigation
Fix Block structure mismatch when the split filter column name clashes with an input - #111930
Conversation
…an input The AST fuzzer hit a logical error during query plan optimization: Block structure mismatch in IntersectOrExceptStep stream: different number of columns: ... __split_filter Nullable(Nothing) ... / (sibling has 3 cols) trySplitFilter hand-rolled a workaround for the case where the filter column name is also an input name. It called splitActionsForFilter without avoid_duplicate_inputs, so the first DAG half ended up with two same-named outputs (the pass-through input and the promoted computed filter node), and then renamed the first match to the literal "__split_filter". Given the append order, that first match is the pass-through, not the computed node. The rename also reused remove_filter, a flag computed for the ORIGINAL name in the OTHER half, as the removal flag for the synthetic name; when it is false the inner FilterStep keeps the column. The outer ExpressionStep cannot drop it either, because split.second's inputs still carry the original name and ActionsDAG::updateHeader passes through unmatched header columns. So __split_filter reached the branch output header, and the parent-header refresh loop in optimizeTreeFirstPass pushed the wider header into IntersectOrExceptStep::checkHeaders against the sibling branch. ActionsDAG::split already solves this collision properly when avoid_duplicate_inputs is set: it renames the promoted computed node in the first half and repairs the second half by adding an input under the new name while rewriting the old node into an ALIAS onto it, so second-half references to the original name still resolve. Delete the hand-rolled workaround, set both flags inside splitActionsForFilter (it has a single caller, so its signature and ActionsDAG.h are untouched), and read the filter name from split_nodes_mapping, the same idiom as splitSingleAndFilter in FilterStep.cpp. The rename only fires on a genuine collision, so plans without one are unchanged. __split_filter no longer exists in the source. The leak also aborts with UNION ALL and EXCEPT, since they share the same checkHeaders shape, so the test covers all three. It asserts the branch output header column count rather than the absence of a literal name, so a stray internal column would be caught under any name, and it asserts the '[split]' step marker so the file cannot pass without the optimization running. A second query keeps the clashing name live downstream and pins its result values, which proves the renamed column still resolves in the second half. Found by AST fuzzer (amd_msan) on an unrelated PR, STID 0993-315b. Same family as ClickHouse#108142 and ClickHouse#108210. Co-Authored-By: Claude Opus 4.8 <[email protected]> Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 rounds, 3 findings total;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20260726-031800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260726-014800 |
|
cc @davenger @novikd — could you review this? It deletes the hand-rolled name-clash workaround in |
|
Workflow [PR], commit [8b2e5c7] Summary: ✅
AI ReviewSummaryThis PR correctly removes the broken manual Findings
Final Verdict
|
| /// The filter name may also be an input name. Two same-named outputs of different structure in the | ||
| /// first half would break the Block invariant, so let split() rename the promoted node and repair | ||
| /// the second half. The mapping carries the final name of the filter node. | ||
| auto res = split(split_nodes, /*create_split_nodes_mapping=*/ true, /*avoid_duplicate_inputs=*/ true); |
There was a problem hiding this comment.
This only fixes the query-plan trySplitFilter path. The default query_plan_merge_filters splitter in src/Processors/QueryPlan/FilterStep.cpp:197-205 still does dag.split({filter_node}, true) without avoid_duplicate_inputs, then prepends the split atom to first.outputs.
For a non-trivial conjunct whose result name already exists as an input, that gives the first transform outputs in the shape [split_filter, original_input, split_filter]: FilterTransform::transformHeader removes only the first occurrence, but the remaining DAG still keeps its inputs ordered as [carried_filter, original_input]. ActionsDAG::updateHeader then binds the two same-named columns to the wrong INPUT nodes, so the rest of the AND chain can still see swapped columns or hit the same Block structure mismatch family under the default query_plan_merge_filters setting. I think the same rename/alias-repair needs to be applied in splitSingleAndFilter as well.
There was a problem hiding this comment.
The call shape you describe is real: splitSingleAndFilter does call dag.split({filter_node}, true) with avoid_duplicate_inputs defaulted to false (ActionsDAG.h:424), it does prepend the atom to first.outputs (FilterStep.cpp:202), query_plan_merge_filters is default-on (Settings.cpp:6373) and gates the path, and FilterTransform::transformHeader erases only one occurrence. I checked all four.
The conclusion does not follow, though, because the duplicate-name output cannot arise on that path.
split() puts a name into first.outputs from exactly two places: ActionsDAG.cpp:2666-2673 for an original input needed by both halves, and :2699-2702 for a new_inputs entry, i.e. a non-input node promoted because the second half consumes it. The bug this PR fixes needed both to fire for one name: in splitActionsForFilter the filter node is proven to be an output (tryFindInOutputs at :2911-2919), so the pass-through input was re-emitted at :2666 while the computed node was promoted at :2699, giving two same-named outputs of different structure.
splitSingleAndFilter splits condition_to_split, an interior conjunct of the and(...) tree found by walking children (FilterStep.cpp:216-241). An interior conjunct is not an output of the FilterStep DAG; the output is the top-level and(...) node, and the constructor's removeAliasesForFilter + removeUnusedActions (:277-280) drops anything else. new_inputs is only populated via used_in_result (set at :2529 from outputs, read at :2640) or when a second-half node references a first-half child (:2612-2622), so the atom is promoted once and the original same-named input is not re-emitted: the second half reads the atom's value through the promoted input, not through the original column. That is exactly why line 202 has to insert the atom by hand: it is not already in outputs, which is the structural difference from splitActionsForFilter.
Empirically, on a debug build of this branch: a Memory table with a column literally named notEquals(__table1.s.size, 0_UInt8) (the atom's exact internal result name) and WHERE notEmpty(s) AND (x + 1 > 1) AND (x < 100) splits two atoms and returns correct rows, no mismatch and no swapped columns. Same for the nested form that re-exposes the atom as an outer input via notEmpty(s) AS f, for three-level nesting, and for the variant where the atom is also a projected output. About ten shapes total, none produced a duplicate name in the split-atom transform's outputs.
So I am leaving splitSingleAndFilter unchanged. If you have a concrete query where that path yields the [split_filter, original_input, split_filter] output shape, I will fix it in this PR.
There was a problem hiding this comment.
A concrete alias-shaped case to try is:
SELECT number
FROM numbers(3)
WHERE ((number + 1) AS number) AND (number > 0) AND (number < 10)
SETTINGS enable_analyzer = 1, query_plan_enable_optimizations = 1, query_plan_merge_filters = 1, query_plan_split_filter = 0;This is the branch your current argument rules out by assuming the split atom's name is always the derived function spelling. ActionsMatcher::visit stores ast->getColumnName() directly on the FUNCTION node (src/Interpreters/ActionsVisitor.cpp:1194), so the left-most atom above really does have result_name == "number" while still reading the input number.
That makes number an input needed by both halves: the split atom uses it on the left, and the remaining conjuncts use it on the right. split() therefore emits the shared input into first.outputs at src/Interpreters/ActionsDAG.cpp:2666-2673, then promotes the aliased atom as a new_input at :2699-2702; splitSingleAndFilter prepends the atom again at src/Processors/QueryPlan/FilterStep.cpp:202. The resulting first-DAG outputs are the duplicated [number(atom), number(input), number(atom)] shape from the original comment, so after FilterTransform::transformHeader erases the first number, the next filter stage still binds the surviving two number columns to the wrong INPUT nodes.
There was a problem hiding this comment.
That query does not reproduce. On master it returns 1, 2, 3 under both analyzers, with query_plan_split_filter 0 and 1.
The naming premise is wrong in two independent ways:
ASTWithAlias::appendColumnName(src/Parsers/ASTWithAlias.cpp:75-81) returns the alias only whenpreferAliasToColumnName()is set, and that flag is set in exactly three places, all inQueryAliasesVisitor.cpp(:66,:113,:150): WITH-section entries and_subquerynames. An inline(expr AS alias)inWHEREnever gets it, soast->getColumnName()atActionsVisitor.cpp:1194yields the derived spelling.EXPLAIN actions = 1on your query confirms it:AND column: plus(__table1.number, 1_UInt8), notnumber.ActionsVisitoris reachable only fromExpressionAnalyzer(grep -rl 'Interpreters/ActionsVisitor.h' src/returns 2 files), i.e. the old analyzer, while your query pinsenable_analyzer = 1. So that file names nothing on the path you cite.
I also ran the WITH form, which does set the flag, on the old analyzer: WITH (a + 1) AS b SELECT t.b FROM t WHERE b AND (t.b > 0) AND (a < 10), so the alias b and the real column t.b are both live. Correct results, identical to the query_plan_merge_filters = 0 reference. In the variant where nothing else reads the shadowed column, that column is pruned before the split, so the collision precondition is not met either.
Your conclusion is still right, though, and I am retracting mine. I wrote:
So I am leaving
splitSingleAndFilterunchanged.
That was wrong. The site does need avoid_duplicate_inputs. The trigger is not the single-split alias shape above, it is the iterated split: splitAndChainIntoMultipleFilters (FilterStep.cpp:249-256) loops, one iteration promotes an atom into the remainder's inputs, and a later iteration promotes a second atom under that same name with a different type. On master:
CREATE TABLE t1 (id Int64, grp Int64) ENGINE = Memory;
CREATE TABLE t2 (id Int64, reviewer Int64, enabled Bool) ENGINE = Memory;
INSERT INTO t1 VALUES (1, 10), (2, 20);
INSERT INTO t2 VALUES (1, 100, true), (2, 200, false);
SELECT t1.id, t2.reviewer
FROM t1 LEFT JOIN t2 ON t1.id = t2.id AND t2.enabled = true
WHERE t1.grp = 10 AND t2.reviewer = 100 AND t2.enabled = true
SETTINGS join_use_nulls = 1, query_plan_merge_filters = 1, query_plan_convert_outer_join_to_inner_join = 1;Code: 352. DB::Exception: Block structure mismatch in (columns with identical name must have identical structure) stream: different types:
equals(__table2.enabled, 1_Bool) Nullable(UInt8) ...
equals(__table2.enabled, 1_Bool) UInt8 ... (AMBIGUOUS_COLUMN_NAME)
My earlier empirical set could not have found this: every shape I built collided same-structure names inside a single split, so none of them exercised the cross-iteration case. That is the specific reasoning error, and it is the reason I asked for a query rather than trusting the argument.
I offered to fix it here given a concrete query. The one given does not reproduce, and the real trigger is a distinct root cause with its own reproducer and regression test, tracked as #111955, so it lands in its own PR instead of being bundled into this one. That also keeps this PR's assertions about the trySplitFilter path meaningful.
…filter-header-leak
CI finish ledger - cd52dccEvery 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. Only
Neither is caused by this PR: the diff is Fresh CI is now running on 8478862 (the master merge). Session id: cron:our-pr-ci-monitor:20260726-183000 |
…filter-header-leak
CI finish ledger - 8478862Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
No failure is PR-caused: this PR's diff is I merged master ( Session id: cron:our-pr-ci-monitor:20260727-000000 |
|
Ledger follow-up: the owner column for Fixing PR: #111480 (ours, open). Root cause is not a too-tight wait. While a stream is stopped, #111480's own CI shows the fix working: this test goes FAIL to OK on all six integration shards it runs on, with the transition inside the fix-commit window. The two remaining FAIL rows on that PR are One scope note for anyone reading a raw CIDB sweep on this test name: four modules define |
|
Fixing PR for the That failure is an observability defect in the MSan runtime rather than a test problem. It does not fix the underlying uninitialized read this PR's run hit; it makes that read diagnosable, so the next occurrence should carry a real stack and a real STID. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code |
|
Another occurrence of the same SELECT DISTINCT x
FROM
(
SELECT tuple(NULL, assumeNotNull(tuple(toDecimal256(5e-324, 7), *)), -9223372036854775808) AS x, 3 AS ord GROUP BY ALL
UNION ALL
SELECT DISTINCT 1025 AS ord, 10
)
WHERE NULL
ORDER BY ALL ASC
SETTINGS allow_suspicious_types_in_order_by = 1, allow_suspicious_types_in_group_by = 1;The second header carries the extra |
|
Already covered. The third case in Your query on a debug build of master ( On this branch's head ( Per-shape matrix over the test's reproducer, master versus this branch:
On adding your query as a fourth case, I would rather not unless you prefer otherwise. The Breadth, for the record. CIDB over 45 days, failures whose context contains One detail if you try to reproduce with the job's own settings: the |
|
Discharging the fixing-PR link promised for the That ledger row's reason column is wrong on all three of its claims, so it is worth correcting on the record. It said the read had no bounded receive timeout and that the XDBC bridge never responded. The job's own
The query ran 545.8 s in total and ended on its own; the hung check merely sampled it inside its 90 s window. The real root cause is that Nothing here was caused by this PR: its diff is |
Review round r1 on the FilterStep avoid_duplicate_inputs fix. The source fix is unchanged; this only makes its test a real assertion and corrects two coverage claims. The test pinned only join_use_nulls, but the fixed code path is reached only when query_plan_merge_filters is on, and the colliding plan shape needs query_plan_convert_outer_join_to_inner_join. CI randomizes each of those to 0 with 5 percent probability, so on such a draw every case returned the expected rows on an unfixed binary and the test asserted nothing. Both settings are now pinned per query, and a plan assertion in subquery form pins the rename itself. It discriminates: 1 on the fixed build, 0 on master, 0 on a build with only the flag reverted. position() is used instead of ILIKE because _ is an ILIKE wildcard and the pattern has to match the renamed atom only. With both settings forced to 0 at session level the per-query SETTINGS still win, so the test passes on the fixed build and still fails on master. The case pinning query_plan_use_logical_join_step = 0 is removed. That setting is MAKE_OBSOLETE and no code reads it, so the case was a duplicate of the first one rather than a second code path. Two cases are added. ARRAY JOIN above the join and ORDER BY an expression above the join both throw the same exception on master, because liftUpArrayJoin and liftUpFunctions consume the remainder DAG the split produces. ActionsDAG::split has seven call sites, not four. Besides the three external callers that already pass the flag, splitActionsBeforeArrayJoin, splitActionsBySortingDescription and splitActionsForFilter pass neither. splitActionsForFilter is a real carrier of the same class on a different trigger, a promoted node whose name equals an existing input name, and is fixed separately in ClickHouse#111930; that change is file-disjoint from this one and the two were built together to confirm both tests pass. For the other two no colliding shape could be constructed: they split in one pass, on nodes that do not depend on ARRAY JOIN or on outputs resolved by distinct SortDescription names. Co-Authored-By: Claude Fable 5 <[email protected]>
Review round r1 on the FilterStep avoid_duplicate_inputs fix. The source fix is unchanged; this only makes its test a real assertion and corrects two coverage claims. The test pinned only join_use_nulls, but the fixed code path is reached only when query_plan_merge_filters is on, and the colliding plan shape needs query_plan_convert_outer_join_to_inner_join. CI randomizes each of those to 0 with 5 percent probability, so on such a draw every case returned the expected rows on an unfixed binary and the test asserted nothing. Both settings are now pinned per query, and a plan assertion in subquery form pins the rename itself. It discriminates: 1 on the fixed build, 0 on master, 0 on a build with only the flag reverted. position() is used instead of ILIKE because _ is an ILIKE wildcard and the pattern has to match the renamed atom only. With both settings forced to 0 at session level the per-query SETTINGS still win, so the test passes on the fixed build and still fails on master. The case pinning query_plan_use_logical_join_step = 0 is removed. That setting is MAKE_OBSOLETE and no code reads it, so the case was a duplicate of the first one rather than a second code path. Two cases are added. ARRAY JOIN above the join and ORDER BY an expression above the join both throw the same exception on master, because liftUpArrayJoin and liftUpFunctions consume the remainder DAG the split produces. ActionsDAG::split has seven call sites, not four. Besides the three external callers that already pass the flag, splitActionsBeforeArrayJoin, splitActionsBySortingDescription and splitActionsForFilter pass neither. splitActionsForFilter is a real carrier of the same class on a different trigger, a promoted node whose name equals an existing input name, and is fixed separately in ClickHouse#111930; that change is file-disjoint from this one and the two were built together to confirm both tests pass. For the other two no colliding shape could be constructed: they split in one pass, on nodes that do not depend on ARRAY JOIN or on outputs resolved by distinct SortDescription names. Co-Authored-By: Claude Fable 5 <[email protected]>
The guard was unconditional, so it also rejected queries whose plan is not split into fragments. Such a plan is executed locally, the synthetic __text_index_..._has_<hash> column never has to be reconstructed on a worker, and the query runs correctly today. Rejecting it was a regression. Whether a read ends up inside a shipped fragment is only decided by the tryMakeDistributed* transforms and the exchange optimization, both of which run after checkDistributedReadSupported. The check therefore moves to a separate pass that runs after them and returns early when the plan contains no exchange step, which is exactly when makeDistributedPlan produces a single stage that QueryPlan::convertToDistributed keeps local. The single-stage LOGICAL_ERROR "Column ... already added for reading" the original guard also covered no longer happens: the direct read pass bails out once index read tasks are present (ClickHouse#111930). What remains is the multi-stage failure, where a worker rebuilds the fragment against the table and the synthetic column is missing (NOT_FOUND_COLUMN_IN_BLOCK at execution). Verified against a server with the stateless worker enabled: all four shipped shapes in the test fail with that error on master and are rejected at planning time with the fix, while both single-stage shapes return the same rows as the non-distributed plan in either build. The hasTextIndexReadTasks accessor is dropped: getIndexReadTasks is public.
Resolve conflict in src/Processors/QueryPlan/Optimizations/splitFilter.cpp by taking the change from #111930: the old filter_name_clashes_with_input workaround is replaced by the split_nodes_mapping-based rename. Co-Authored-By: Claude Fable 5 <[email protected]>
Cherry pick #111930 to 26.5: Fix Block structure mismatch when the split filter column name clashes with an input
… filter column name clashes with an input
Cherry pick #111930 to 26.6: Fix Block structure mismatch when the split filter column name clashes with an input
… filter column name clashes with an input
Cherry pick #111930 to 26.7: Fix Block structure mismatch when the split filter column name clashes with an input
… filter column name clashes with an input
Backport #111930 to 26.7: Fix Block structure mismatch when the split filter column name clashes with an input
Backport #111930 to 26.5: Fix Block structure mismatch when the split filter column name clashes with an input
Backport #111930 to 26.6: Fix Block structure mismatch when the split filter column name clashes with an input
|
@alexey-milovidov @yariks5s can you finish the remaining backports? |
Related: #108142
Related: #108210
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a logical error
Block structure mismatch in IntersectOrExceptStep stream: different number of columnsthat could happen when the filter split optimization (query_plan_split_filter) ran on aWHEREwhose filter column name is also an input column name. The optimization left an internal__split_filtercolumn in the branch output header, which then diverged from the sibling branch of a set operation such asINTERSECTorUNION.Description
trySplitFilterhand-rolled a workaround for the case where the filter column name is also an input name: it calledActionsDAG::splitActionsForFilterwithoutavoid_duplicate_inputs, then renamed the first matching output of the first DAG half to the literal__split_filter. That rename landed on the pass-through input rather than the promoted computed node, and it used the removal verdict computed for the original name in the other half, so the innerFilterStepcould keep the column. The outerExpressionStepcannot drop it, because the second half's inputs still carry the original name andActionsDAG::updateHeaderpasses through unmatched header columns. The synthetic name therefore reached the branch output header, andIntersectOrExceptStep::checkHeaderscompared a 4-column header with the sibling's 3 columns.ActionsDAG::split(nodes, /*mapping=*/ true, /*avoid_duplicate_inputs=*/ true)already solves the same collision correctly: it renames the promoted node in the first half and repairs the second half by adding an input under the new name while rewriting the old node into anALIASonto it. This PR deletes the hand-rolled workaround, passes both flags insidesplitActionsForFilter(it has a single caller, so the signature andActionsDAG.hare unchanged), and takes the filter column name fromsplit_nodes_mapping, the same idiom assplitSingleAndFilterinFilterStep.cpp.__split_filterno longer exists anywhere in the source. The rename only fires on a genuine collision, so plans without one are unchanged.Found by the AST fuzzer on an unrelated PR:
AST fuzzer (amd_msan), https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=63383&sha=7141227edb42247eb136d0a095b99491123deabe&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29 (STID 0993-315b). Same family as #108142 and #108210. This is a logical error, so it is an exception that is handled normally in release builds and an abort in debug and sanitizer builds.Minimal reproducer, which fails on master and passes with this change:
The same header leak also aborts with
UNION ALLandEXCEPT. The new test04628_split_filter_name_clash_header_leakcovers all three, and asserts both that the optimization fired and the branch output header column count, so it fails if the optimization is disabled and if the internal column reappears under any name. It also checks the result values of a second query whose filter column name is an input name and whose value is consumed downstream. Value equivalence against the unsplit (query_plan_split_filter = 0) plan was verified across a matrix of clash shapes.Version info
26.7.4.21,26.6.3.40,26.5.7.44