Skip to content

Fix Block structure mismatch when the split filter column name clashes with an input - #111930

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-split-filter-header-leak
Jul 27, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-split-filter-header-leak

Conversation

@groeneai

@groeneai groeneai commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108142
Related: #108210

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):

Fix a logical error Block structure mismatch in IntersectOrExceptStep stream: different number of columns that could happen when the filter split optimization (query_plan_split_filter) ran on a WHERE whose filter column name is also an input column name. The optimization left an internal __split_filter column in the branch output header, which then diverged from the sibling branch of a set operation such as INTERSECT or UNION.

Description

trySplitFilter hand-rolled a workaround for the case where the filter column name is also an input name: it called ActionsDAG::splitActionsForFilter without avoid_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 inner FilterStep could keep the column. The outer ExpressionStep cannot drop it, because the second half's inputs still carry the original name and ActionsDAG::updateHeader passes through unmatched header columns. The synthetic name therefore reached the branch output header, and IntersectOrExceptStep::checkHeaders compared 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 an ALIAS onto it. This PR deletes the hand-rolled workaround, passes both flags inside splitActionsForFilter (it has a single caller, so the signature and ActionsDAG.h are unchanged), and takes the filter column name from split_nodes_mapping, the same idiom as splitSingleAndFilter in FilterStep.cpp. __split_filter no 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:

SELECT x FROM (SELECT arrayJoin([materialize(1), NULL]) AS x GROUP BY NULL) WHERE NULL
INTERSECT DISTINCT
SELECT 1;

The same header leak also aborts with UNION ALL and EXCEPT. The new test 04628_split_filter_name_clash_header_leak covers 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

  • Backported to: 26.7.4.21, 26.6.3.40, 26.5.7.44

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 3 findings total;
1 fix round executed between them).

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test was vacuous twice over: it asserted the absence of the literal __split_filter, a string this PR deletes, and nothing pinned that the optimization actually ran, so forcing query_plan_split_filter = 0 reproduced the reference byte-identically AGREE — fixed @ cd52dcc Replaced with two positive assertions over one EXPLAIN json = 1, header = 1: countSubstrings(explain, '[split]') > 0 and the branch output header column count via JSONExtractArrayRaw. Proven in three directions: passes with the fix, fails on the header assertion (not just the downstream abort) with the fix reverted, and fails with query_plan_split_filter = 0 forced
2 ⚠️ The value-equivalence query did not exercise the split at all (trySplitFilter bails on it via split.second.trivial()), so it proved nothing about value preservation under the rename AGREE — fixed @ cd52dcc Confirmed by EXPLAIN: the old shape emits no [split] step, and so did four sibling shapes. Replaced with a query that provably splits and whose filter column name is also an input name consumed downstream, with a [split] assertion attached so a future plan change cannot re-hollow it
3 ⚠️ Two existing tests that pin the [split] step marker in their .reference were not in the regression sweep AGREE — verified @ cd52dcc 02576_predicate_push_down_sorting_fix and 03356_array_join_subcolumns_indexes both run OK. Neither can be perturbed: the rename in ActionsDAG::split fires only when a promoted node collides with an existing input name, and neither test has such a collision
4 💡 [split] is also emitted by liftUpArrayJoin, so the marker is not structurally unique to the optimization under test AGREE — noted, not blocking It discriminates empirically (0 with the optimization disabled), and the load-bearing regression detector is the header column count, which is marker-independent. ')[split]' would be the exact probe
5 💡 The new comment in splitActionsForFilter should backtick literal names and write split rather than split() DISAGREE Contradicted by the surrounding file: only 22 of 247 comment lines in ActionsDAG.cpp use any backtick, Block appears unbackticked in comments with no backticked occurrence, and the new comment deliberately mirrors the phrasing at ActionsDAG.cpp:2499-2500 which documents the same mechanism. The trailing-parens form has 213 occurrences across src/Interpreters/*.cpp, including decorrelate(), pop() and getConjunctionNodes() in this same file

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-11:20260726-031800

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand. clickhouse local -q "SELECT x FROM (SELECT arrayJoin([materialize(1), NULL]) AS x GROUP BY NULL) WHERE NULL INTERSECT DISTINCT SELECT 1" aborts on master (debug) with Block structure mismatch in IntersectOrExceptStep stream: different number of columns, exactly the AST fuzzer signature. The original fuzzer query from the report also reproduces on demand. Minimized mechanically from the fuzzer query, guided by an instrumented build that logged when the name-clash branch of trySplitFilter was taken.
b Root cause explained? Yes. trySplitFilter calls splitActionsForFilter without avoid_duplicate_inputs, so when the filter column name is also an input name the first DAG half gets two same-named outputs (pass-through input + promoted computed node). Lines 81-94 patched that by renaming the FIRST match to the literal __split_filter, which is the pass-through, not the computed node, and passed remove_filter (computed for the ORIGINAL name in the OTHER half) as the removal flag for the synthetic name. When that flag is false the inner FilterStep keeps the column, and the outer ExpressionStep cannot drop it because split.second's inputs still carry the original name and ActionsDAG::updateHeader passes through unmatched header columns. __split_filter therefore reaches the branch output header, and the parent-header refresh loop in optimizeTreeFirstPass pushes the 4-column header into IntersectOrExceptStep::checkHeaders against the sibling's 3.
c Fix matches root cause? Yes, and it is a net deletion, not a guard. The hand-rolled clash workaround is removed and the collision is handled by ActionsDAG::split(nodes, /*mapping=*/true, /*avoid_duplicate_inputs=*/true), which renames the promoted computed node in the first half AND repairs the second half (adds an input under the new name, rewrites the old node into an ALIAS onto it). The filter name is then read from split_nodes_mapping, the same idiom as splitSingleAndFilter in FilterStep.cpp. No symptom guard was added at the checkHeaders site. Post-condition verified: grep -rn '__split_filter' src/ returns 0 hits.
d Test intent preserved / new tests added? New test 04628_split_filter_name_clash_header_leak.sql. No existing test was modified or weakened. Over a single EXPLAIN json = 1, header = 1 of the leaking branch it asserts (1) that the optimization actually fired, via countSubstrings(explain, '[split]') > 0, and (2) the branch output header COLUMN COUNT, via length(JSONExtractArrayRaw(explain, 1, 'Plan', 'Header')). Asserting the count rather than the absence of a literal name is deliberate: it is exactly the quantity checkHeaders compares, and it still fails if a stray internal column reappears under a different name. It also asserts (3) that INTERSECT, EXCEPT and UNION ALL all complete, and (4) the result VALUES of a second query whose filter column name is also an input name and whose value is consumed downstream, so a mis-resolved rename would surface as wrong values or NOT_FOUND_COLUMN_IN_BLOCK. The marker assertions make the file impossible to pass without the optimization running: forcing query_plan_split_filter = 0 makes the test FAIL. SQL test, no no-parallel tag, plan settings pinned so the [split] marker is a reliable discriminator.
e Both directions demonstrated? Yes, via the patch-file A/B procedure with Build-ID verification. Pristine master (Build ID 5d70d58f...): the new test prints 1 2 on the first line, that is the marker fired and the branch header carries 2 columns instead of 1, and only then aborts at the INTERSECT with exit 134. The header assertion fails first, so the test does not depend on the abort. With the fix (Build ID 3bdabf7c...): test passes, header count 1, and the original fuzzer query returns cleanly. 50/50 randomized runs of the new test passed. Additionally, with the fix present but query_plan_split_filter = 0 forced, the test FAILS, which proves the assertions are not vacuous.
f Fix is general across code paths? Yes. The fix is at the source (splitActionsForFilter + trySplitFilter), not at the consumer, so every consumer of the leaked header is covered by one change: IntersectOrExceptStep::checkHeaders (the reported site), UnionStep::checkHeaders, and the other multi-input assertBlocksHaveEqualStructure steps. trySplitJoin in the same file was inspected: it builds its dag via createActionsForConjunction and performs no synthetic rename, so it has no clash path. splitActionsForFilter has exactly one caller (re-verified at HEAD), which is why the flags could be set inside it with no signature change and no ActionsDAG.h churn. Other synthetic __ names in Optimizations/ (__filterpushdown_src*, __global_row_index, __is_deleted_*, __quantize_*) do not use this split-clash-rename pattern.
g Fix generalizes across inputs (params/datatypes/wrappers)? Set-operator matrix covered in the test: INTERSECT DISTINCT (reported), EXCEPT DISTINCT, UNION ALL. Type wrappers are deliberately not part of this fix: the divergence is column COUNT, not type or const-ness, and the reported column is Nullable(Nothing) only because the fuzzer predicate is NULL, so no removeNullable/removeLowCardinality normalization was added anywhere. Correctness was checked across a matrix of clash shapes where the second half re-exports the filter column, consumes its value arithmetically, and aggregates over it; every case matched the query_plan_split_filter=0 reference output. The shape kept in the test is the one that provably reaches trySplitFilter (the [split] marker is asserted), so the value assertion is not testing an unsplit plan.
h Backward compatible? Yes. No setting default change, no new setting, no format or serialization change, so no SettingsChangesHistory.cpp entry and no experimental gate. This is internal query-plan header bookkeeping. avoid_duplicate_inputs is a no-op without a genuine name collision, so plans that do not hit the clash are unchanged.
i Invariants and contracts preserved? The restored invariant: a name minted while splitting a filter never escapes into a plan step's output header, and the two DAG halves agree on every column name they exchange. split() upholds the second half of that itself by aliasing the old node onto a new input under the renamed name, which is what makes reading the name from split_nodes_mapping safe. The remove_filter verdict is still computed on the original name in split.second and applied to the mapped name, which is correct because the rename targets only the promoted computed node while the second half keeps resolving the predicate under the original name. This is the wrong-results hazard in this area, so it was checked empirically rather than by reasoning alone: every query in the clash matrix returns output identical to the unsplit (query_plan_split_filter=0) plan. Regression sweep: 367 prewhere/lazy-materialization/filter-pushdown/explain/intersect tests plus 826 analyzer/where/group_by/union tests were run on both binaries, and every failure was reproduced on pristine master with the same cause (missing test.hits dataset, missing cluster/ZooKeeper/minio config, or pre-existing flakiness), so none is attributable to this change.

Session id: cron:clickhouse-impl-slot-7:20260726-014800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @novikd — could you review this? It deletes the hand-rolled name-clash workaround in trySplitFilter (which renamed the wrong output to a literal __split_filter and reused a removal verdict computed for the other DAG half, leaking the column into the branch output header) and instead lets ActionsDAG::split handle the collision with avoid_duplicate_inputs, taking the filter name from split_nodes_mapping. Note the same change was written in Feb 2024 by @ KochetovNicolai in bd1edc1 ("Fixing splitFilter.") on a branch that never landed.

@yariks5s yariks5s self-assigned this Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8b2e5c7]

Summary: ✅


AI Review

Summary

This PR correctly removes the broken manual __split_filter rename from trySplitFilter and switches that path to ActionsDAG::split(..., /*avoid_duplicate_inputs=*/ true), but it still leaves the sibling filter-splitting path in FilterStep unchanged. The result is that the split-filter name-clash invariant is only repaired for query_plan_split_filter; the default query_plan_merge_filters path can still manufacture structurally different same-named columns and fail with the same Block structure mismatch family, so I do not think this is ready to merge yet.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/FilterStep.cpp:197-205] The fix only hardens trySplitFilter. splitSingleAndFilter still calls dag.split({filter_node}, true) without avoid_duplicate_inputs, then prepends the promoted atom to first.outputs. Once one AND atom has already been promoted into the remainder, a later split can create two same-named columns with different structure in the intermediate header, and ActionsDAG::updateHeader will still bind them to the wrong INPUT nodes or raise the same Block structure mismatch / AMBIGUOUS_COLUMN_NAME exception family. Apply the same duplicate-input repair in this path as well, and keep a regression for the repeated JOIN ... ON plus WHERE reproducer tracked in #111955.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 26, 2026
/// 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);

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

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.

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.

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.

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.

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.

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:

  1. ASTWithAlias::appendColumnName (src/Parsers/ASTWithAlias.cpp:75-81) returns the alias only when preferAliasToColumnName() is set, and that flag is set in exactly three places, all in QueryAliasesVisitor.cpp (:66, :113, :150): WITH-section entries and _subquery names. An inline (expr AS alias) in WHERE never gets it, so ast->getColumnName() at ActionsVisitor.cpp:1194 yields the derived spelling. EXPLAIN actions = 1 on your query confirms it: AND column: plus(__table1.number, 1_UInt8), not number.
  2. ActionsVisitor is reachable only from ExpressionAnalyzer (grep -rl 'Interpreters/ActionsVisitor.h' src/ returns 2 files), i.e. the old analyzer, while your query pins enable_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 splitSingleAndFilter unchanged.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cd52dcc

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / 04546_constant_join_shrink_stored_blocks flaky (13 unrelated PRs + 2 master in 30d; the job's own randomized-settings rerun passed 15/15) #111921 (mine, merged 2026-07-26T14:19:28Z) - the failing build predated it, so I merged master @ 8478862 to pick it up
AST fuzzer (amd_msan) / MemorySanitizer: use-of-uninitialized-value (no STID) MSan uninit abort with no stack: sanitizer.log holds only the warning line, stderr.log shows MemorySanitizer: nested bug in the same thread, aborting. then LLVM ERROR: IO failure on output stream: Broken pipe, so MSan died while printing its own report. 11 hits / 11 distinct PRs / 0 master in 30d, all singletons a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

Neither is caused by this PR: the diff is ActionsDAG.cpp + splitFilter.cpp + one stateless test. Config Workflow, Fast test (amd + arm_darwin), Style check and all three Bugfix validation jobs are green, and the new test 04628 passes everywhere.

Fresh CI is now running on 8478862 (the master merge).

Session id: cron:our-pr-ci-monitor:20260726-183000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8478862

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 (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, parallel, 2/3) / 04627_analyzer_compatibility_final_all_joined_tables deterministic (3/3 reruns), missing enable_analyzer pin on a new test, hits master and every PR running this check #111991 (external, merged 2026-07-26T23:38:49Z) - merged master to pick it up @ 8b2e5c7
Integration tests (amd_msan, 6/8) / test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies flaky (28 hits / 24 unrelated PRs + 6 master, 30d, across 8 different integration shards) a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Stress test (amd_msan) / Hung check failed, possible deadlock found a cancelled odbc() query sat 396s blocked in a Poco HTTP header read (ReadWriteBufferFromHTTP::initialize -> HTTPClientSession::receiveResponse -> poll), so the XDBC bridge read never returned and the executor could not tear down a fix task is created (investigating at full effort - fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable)

No failure is PR-caused: this PR's diff is ActionsDAG.cpp, Optimizations/splitFilter.cpp and one
new stateless test, and Config Workflow, Fast test (amd + arm_darwin), Style check and all
non-skipped Bugfix validation jobs are green. The new test
04628_split_filter_name_clash_header_leak passed on every shard.

I merged master (8b2e5c7768e790) so the next run picks up #111991; that clears the first line.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Ledger follow-up: the owner column for test_storage_rabbitmq/test_system_stop.py::test_refresh_survives_unready_dependencies now resolves to a fixing PR.

Fixing PR: #111480 (ours, open).

Root cause is not a too-tight wait. While a stream is stopped, SYSTEM REFRESH grants exactly one out-of-order streaming cycle. That cycle builds a RabbitMQSource and starts the AMQP delivery loop asynchronously, so the first hasPendingMessages poll sees nothing, the source returns 0 rows and breaks before reaching the bounded waitForMessages path. The single permit is spent on an empty cycle and the queued messages stay unconsumed, which is the observed expected 6 rows ... got '1'. The fix is still absent from master (driveLoopUntilMessage has no occurrences there), which is why the signature keeps hitting master.

#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 Bugfix validation (integration tests, amd64/aarch64), which run the changed tests against un-fixed master on purpose; both jobs report success and 19 sibling tests in the same module fail there identically.

One scope note for anyone reading a raw CIDB sweep on this test name: four modules define test_refresh_survives_unready_dependencies (rabbitmq, kafka, nats, s3_queue), so a LIKE match conflates them. The test_storage_s3_queue variant is a separate object-storage defect with separate owners and is not covered by #111480.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (amd_msan) stackless MemorySanitizer: use-of-uninitialized-value line on the finish ledger above: #112008 (library change: ClickHouse/llvm-project#118).

That failure is an observability defect in the MSan runtime rather than a test problem. ScopedErrorReportLock::Lock records the reporting thread and clears it only in Unlock, and printing a report round-trips to the out-of-process llvm-symbolizer, so an asynchronous profiler signal regularly lands mid-report; if its handler touches uninitialized memory the second report re-enters the lock, takes the same-thread branch and calls internal__exit without printing anything. That is why every one of these arrives with zero frames and STID: None. #112008 blocks asynchronous signals for the duration of the report, keeping the synchronous ones deliverable.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Another occurrence of the same __split_filter leak, hit by the AST fuzzer on an unrelated PR (#109455, report) — here the sibling of the set operation is a plain UNION ALL, and the error is Block structure mismatch in UnionStep stream: different number of columns:

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 __split_filter Nullable(Nothing) column; the query succeeds with query_plan_split_filter = 0. Might be worth adding as a test case if this branch does not already cover the UNION ALL shape.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Already covered. The third case in 04628_split_filter_name_clash_header_leak is exactly this shape, and on master it aborts with the identical message.

Your query on a debug build of master (859a9abe2597) at default settings:

Logical error: 'Block structure mismatch in UnionStep stream: different number of columns:
__table1.x Variant(Tuple(Nullable(Nothing), Tuple(Decimal(76, 7), UInt8), Int64), UInt16) ...
__table1.x Variant(Tuple(Nullable(Nothing), Tuple(Decimal(76, 7), UInt8), Int64), UInt16) ..., __split_filter Nullable(Nothing) ...'

On this branch's head (8b2e5c77, prebuilt build_amd_debug) the same query returns the empty result, byte for byte what query_plan_split_filter = 0 returns on master. Same leaked column, same call site, so the one fix covers it.

Per-shape matrix over the test's reproducer, master versus this branch:

sibling master this branch
INTERSECT DISTINCT abort, IntersectOrExceptStep stream: different number of columns ok
EXCEPT DISTINCT abort, IntersectOrExceptStep stream: different number of columns ok
UNION ALL abort, UnionStep stream: different number of columns ok, returns 1

__split_filter appears in the abort text of all three master cells and in none of the branch cells. The full test file aborts on master and matches its reference on this branch.

On adding your query as a fourth case, I would rather not unless you prefer otherwise. The UNION ALL case already pins the same step and the same leaked column, and the test's first query asserts the branch output header column count (expected 1), so a leak under any other name fails it as well. Your query adds the Variant and Decimal256 shaping from the fuzzer but no additional mechanism, and adding it means another push on a PR whose CI is already green. Say the word and I will add it.

Breadth, for the record. CIDB over 45 days, failures whose context contains __split_filter: 13 rows across 12 pull requests, 2 of them on master. 9 are UnionStep and 4 are IntersectOrExceptStep, so the plain UNION ALL sibling is the more common of the two, and the row behind your report is the 13th. All of them are this one call site.

One detail if you try to reproduce with the job's own settings: the old_compatibility variant sets compatibility = '24.3', and under that the query is rejected earlier with Code: 386 ... NO_COMMON_TYPE, identically on both binaries. At default settings it aborts as quoted above.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit 4d82505 Jul 27, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Discharging the fixing-PR link promised for the Stress test (amd_msan) / Hung check failed, possible deadlock found line of the finish ledger on 84788620b746b5c00af1121143172495ae3f13fe: #112144.

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 clickhouse-server.stress.log.zst says otherwise:

  • the retry log shows nine attempts, each ending after almost exactly 60.0 s, which is http_receive_timeout as the hung check's own Settings: field reports it ('60'), so the receive timeout is applied;
  • the 396s figure and the stacktraces: block are a mid-loop snapshot taken inside attempt 7, not one uninterruptible 396 s read;
  • the bridge did answer on the last attempt, with HTTP 500 nanodbc ... HY000: Connection refused.

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 ReadWriteBufferFromHTTP::doWithRetries never consulted query cancellation and its inter-attempt backoff is an uninterruptible sleep, so the budget was 9 x http_receive_timeout plus 32.7 s of accumulated backoff = 572.7 s, matching the observed 545.8 s. max_execution_time = 60 fired at 23:53:30 and was ignored for eight more minutes. odbc() reaches that loop because StorageXDBC is an IStorageURLBase, so it reads its result rows through StorageURLSource and ReadWriteBufferFromHTTP.

Nothing here was caused by this PR: its diff is ActionsDAG.cpp, Optimizations/splitFilter.cpp and one stateless test, none of which touches HTTP reads, XDBC or cancellation.

pull Bot pushed a commit to peijunlin2008/ClickHouse that referenced this pull request Jul 27, 2026
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]>
scanhex12 pushed a commit to scanhex12/ClickHouse that referenced this pull request Jul 29, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 29, 2026
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.
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 11, 2026
alexey-milovidov added a commit that referenced this pull request Aug 11, 2026
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]>
robot-ch-test-poll4 added a commit that referenced this pull request Aug 11, 2026
Cherry pick #111930 to 26.5: Fix Block structure mismatch when the split filter column name clashes with an input
robot-clickhouse added a commit that referenced this pull request Aug 11, 2026
… filter column name clashes with an input
robot-ch-test-poll4 added a commit that referenced this pull request Aug 11, 2026
Cherry pick #111930 to 26.6: Fix Block structure mismatch when the split filter column name clashes with an input
robot-clickhouse added a commit that referenced this pull request Aug 11, 2026
… filter column name clashes with an input
robot-ch-test-poll4 added a commit that referenced this pull request Aug 11, 2026
Cherry pick #111930 to 26.7: Fix Block structure mismatch when the split filter column name clashes with an input
robot-clickhouse added a commit that referenced this pull request Aug 11, 2026
… filter column name clashes with an input
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 11, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 12, 2026
Backport #111930 to 26.7: Fix Block structure mismatch when the split filter column name clashes with an input
alexey-milovidov added a commit that referenced this pull request Aug 12, 2026
Backport #111930 to 26.5: Fix Block structure mismatch when the split filter column name clashes with an input
clickhouse-gh Bot added a commit that referenced this pull request Aug 14, 2026
Backport #111930 to 26.6: Fix Block structure mismatch when the split filter column name clashes with an input
@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov @yariks5s can you finish the remaining backports?

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

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants