Skip to content

Keep the filter column distinct when resolving a planner-only NOT NULL filter - #119106

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-planner-only-filter-keeps-output-column
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-planner-only-filter-keeps-output-column

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not for changelog: this fixes a master-only regression that was never part of a release.

Description

Related: #114817 (an unreleased regression from it).

resolvePlannerOnlyFilters rebuilds a FilterStep with remove_filter = true, using a surviving
conjunct's result_name as the filter column. collectFilterConjuncts unwraps aliases, so that
conjunct can be a column of the step's own output header: push-down had wrapped that predicate in a
__filter<name> alias so the removal could not hit the stream column (ActionsDAG.cpp:3768-3779),
and the unwrap discards that protection. FilterTransform then erases the column, and since the pass
replaces node.step, no updateInputHeader reaches the parent JoinStepLogical, whose
expressions still hold an input node for it. Nor can it be pruned, being a join output.

I re-establish the alias at the rebuild site when the chosen filter node's name collides with the
output header, the same idiom and reason as ActionsDAG.cpp:3774-3779.

Reproducer, on defaults:

SELECT deleted, b, c
FROM (SELECT 'v' AS b, toNullable('x') AS a, 1 AS deleted) AS q
INNER JOIN (SELECT 'x' AS a, 'w' AS c) AS s ON q.a = s.a
WHERE deleted AND (c != b);

A debug build aborts with Input nodes size mismatch in dag (JoinExpressionActions.cpp:138, from
chooseJoinOrder). With the join reorder off the query is instead rejected with
NOT_FOUND_COLUMN_IN_BLOCK, and a NATURAL JOIN variant with UNKNOWN_IDENTIFIER, so release builds
are affected too. All three return the correct rows after the change. A Nullable join key is required:
it makes the join condition null-rejecting, which produces the marker.

Validation: the new test reddens without the change and passes with it (two scenarios, each with the
join reorder on and off, asserting result rows), plus 50 runs on default randomization and 50 with a
forced join-order seed. Eight of the nine stateless tests #114817 touched pass with no reference
change; the ninth sets query_plan_derive_not_null_filters_from_joins = 0, so it returns before the
changed branch.

Where it shows up in CI

Example report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=118979&sha=ef26353f73160ecf71c7681c5d618d448637f813&name_0=PR

SELECT toDateTime(check_start_time) AS t, pull_request_number AS pr, check_name
FROM default.checks
WHERE position(test_name, 'Input nodes size mismatch in dag') > 0
  AND check_start_time > now() - INTERVAL 30 DAY
  AND test_status IN ('FAIL','ERROR')
ORDER BY t FORMAT TabSeparatedWithNames
t                     pr      check_name
2026-08-16 07:39:41   110210  AST fuzzer (amd_debug, targeted, old_compatibility)
2026-08-18 05:34:39   111844  AST fuzzer (amd_debug, targeted, old_compatibility)
2026-09-09 12:31:43   118979  Stress test (arm_msan)
2026-09-09 14:12:23   109235  Stress test (arm_tsan)
2026-09-09 14:21:59   118056  AST fuzzer (arm_asan_ubsan)
2026-09-09 15:20:24   103044  BuzzHouse (amd_debug)
2026-09-09 19:00:12   119042  AST fuzzer (amd_debug, targeted)

#114817 merged at 08:08 UTC on 2026-09-09. Five rows followed the same day, on five check flavours and
two architectures, every one on an unrelated PR. The two August rows share only the message text, whose
hash forms the failure id; that older shape was fixed by #110227. The query behind the 14:21:59 row was
captured and reproduces this mechanism locally.

This does not touch src/Interpreters/JoinExpressionActions.cpp, so it does not overlap my open #108787.


Workflow [PR]
Sync PR [sync-upstream/pr/119106]

…L filter

resolvePlannerOnlyFilters rebuilds a FilterStep with remove_filter = true, using
a surviving conjunct's result_name as the filter column name. Because
collectFilterConjuncts unwraps aliases, that conjunct can be a column of the
step's own output header: filter push-down wraps a pushed predicate in a
__filter<name> alias so the removal cannot hit the same-named stream column
(ActionsDAG.cpp:3768-3779), and the unwrap discards that protection.

checkAndRemoveFilterColumn then erases the column, shrinking the step's output
header. The pass replaces node.step outright, so no updateInputHeader reaches
the parent JoinStepLogical, whose expression DAG still holds an input node for
the erased column, and that node cannot be pruned because the column is also one
of the join's outputs. chooseJoinOrder is the first consumer to notice:
JoinExpressionActions requires the DAG's input count to equal the left plus
right header widths, and aborts with "Input nodes size mismatch in dag". With
the join reorder disabled the same inconsistent plan reaches execution and
throws NOT_FOUND_COLUMN_IN_BLOCK instead, and a NATURAL JOIN variant, where
both sides carry a column of that name, throws UNKNOWN_IDENTIFIER.

Re-establish the alias at the rebuild site when the chosen filter node's name
collides with the step's output header, which is the same operation, for the
same reason, as the push-down site.

A Nullable join key is needed to reproduce: it makes the join condition
null-rejecting, which is what makes deriveNotNullFiltersFromJoin emit the
planner-only marker.

Related: ClickHouse#114817

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

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

Pre-publication review by an independent model (engine: codex; 1 finding), plus my own cold review
(4 nits). No blockers.

# Sev Finding Verdict Evidence / action
1 ⚠️ Asserting only result rows does not prove the changed path runs, since disabling NOT NULL filter derivation yields the same reference DISAGREE The test file was run both ways on identity-verified binaries: RC=134 with no output on the unpatched build, all four rows on the patched one; the bare query fails three distinct ways on base (SIGABRT, NOT_FOUND_COLUMN_IN_BLOCK, UNKNOWN_IDENTIFIER). The scenario needs the test's own pinned SETTINGS edited: query_plan_derive_not_null_filters_from_joins = 1 is pinned per query, is absent from clickhouse-test's randomizer, and a query-level SETTINGS beats runner injection, so it cannot become 0 in CI nor if the default is flipped. I did not add the suggested full-output EXPLAIN PLAN actions = 1 reference: it would bake __filter__table1.is_active and the __tableN qualifiers into the tree.
2 💡 The row oracle would go quietly green if some other pass stopped feeding this shape into resolvePlannerOnlyFilters noted, not blocking Real but not specific to this fix. A cheap guard, if wanted later: SELECT count() > 0 FROM (EXPLAIN PLAN actions = 1 <query>) WHERE explain ILIKE '%__filter%is_active%'.
3 💡 Three sibling carriers could interact with the re-established alias no action, verified safe removeAliasesForFilter unwraps aliases only below the filter node, so the new root alias survives; trySplitSingleAndFilter unwraps before testing for and, so AND-chain splitting is unaffected; the stale same-named alias left in the cloned DAG is unreachable and removeUnusedActions deletes it before the step is built.

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

Session id: cron:clickhouse-review-slot-10:20260909-211000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @antaljanosbenjamin, could you review this? resolvePlannerOnlyFilters rebuilds a FilterStep with remove_filter = true from a surviving conjunct's result_name, but collectFilterConjuncts had already unwrapped the __filter<name> alias that push-down adds for exactly this hazard, so the removal erases the step's own stream column and the parent JoinStepLogical is left holding a DAG input for a column its child no longer produces.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f78b8ab]

Summary: ✅


AI Review

Summary

This PR re-aliases a surviving planner-only filter conjunct before rebuilding the FilterStep, which is the right direction for the reported join-header mismatch. The patch is not complete yet, though: the generated __filter... name is still not made unique, so valid queries that already expose that name can still leave the rebuilt step with an invalid header. I would not merge it until that alias is uniquified.

Findings

❌ Blockers

  • [src/Processors/QueryPlan/Optimizations/resolvePlannerOnlyFilters.cpp:234-237] The new alias only avoids colliding with the original column name, not with the alias name it generates. If the child already exposes __filteris_active, ActionsDAG::updateHeader emits both the new filter output and that pass-through column under the same name. Different structures fail immediately in Block::insert; matching structures survive only until erase(filter_column_name) removes the name index for the remaining column. The "keep the filter column distinct" contract is therefore still violated for valid queries that project __filter<name>.
    Suggested fix: loop until the generated filter name is absent from the whole step header, or reuse the uniquifying _filter_<name>_<idx> pattern from ActionsDAG::createActionsForConjunction, and extend the regression test with an existing __filter<name> output column.
Final Verdict

❌ Changes requested. The fix direction is correct, but the rebuilt filter column name still needs a uniqueness guard before this path is safe.

LLVM Coverage Report

Measured on commit f78b8ab.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 9, 2026
/// collectFilterConjuncts unwraps aliases, so the surviving conjunct can be a column of the output header.
/// The step removes its filter column by name, which would erase that column and break the parent step.
if (filter->getOutputHeader()->has(new_filter->result_name))
new_filter = &new_actions_dag.addAlias(*new_filter, "__filter" + new_filter->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 doesn't guarantee a distinct filter column name. If the step already has a pass-through column called __filter<name>, promoting the surviving conjunct to that hard-coded alias creates a duplicate name in ActionsDAG::updateHeader: the new filter output is inserted first, then the original pass-through column. Block::insert either throws on mismatched structure or, for matching types, lets erase(filter_column_name) drop the name index for the surviving column.

That means a query that already projects something like toUInt8(7) AS __filteris_active can still fail after this rewrite, even though the old step was valid because the alias only lived under the enclosing and(...) output before resolvePlannerOnlyFilters promoted it. Please generate a unique filter alias here (same idea as the _filter_<name>_<idx> loop in ActionsDAG::createActionsForConjunction) and add that case to the regression test.

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.

Measured this before answering, and I am not making the change: the precondition is not constructible.

__filter* never reaches a header. grep -rn '"__filter"' src/ has exactly two producers: ActionsDAG.cpp:3777 (the push-down site this guard is patterned on) and this line. At both, the name is the step's own filter column and the step is built with remove_filter=true, so checkAndRemoveFilterColumn erases it. Nothing of that spelling survives into a step output header, so there is no pass-through column of that name to collide with.

The alias is one analyzer qualifier out of reach. The guard fires only when the surviving conjunct is already a column of the output header, so its name is __tableN.<id> and the alias is __filter__tableN.<id>. Every header column at that position is itself __tableN.<id>.

Your example, run verbatim and in its fully-qualified form, with this line instrumented:

SELECT is_active, name, label, `__filter__table1.is_active`
FROM (SELECT 'alpha' AS name, toNullable('k1') AS join_key, 1 AS is_active,
             toUInt8(7) AS `__filter__table1.is_active`) AS left_side
INNER JOIN (SELECT 'k1' AS join_key, 'beta' AS label) AS right_side
  ON left_side.join_key = right_side.join_key
WHERE is_active AND (label != name);
-- 1  alpha  beta  7

fires=1 surviving=[__table1.is_active] alias=[__filter__table1.is_active]
dag_out_same_name=0 dag_node_same_name=0 out_hdr_has_alias=0
out_hdr=[__table1.name, __table1.is_active, __table1.`__filter__table1.is_active`, __table1.join_key]

The projected column lands as __table1.`__filter__table1.is_active` , one qualifier away from the alias, so it cannot spell it.

Breadth: 325 invocations of this pass over the join|not_null|filter_push_down|prewhere|push_down suites (1344 tests), 0 with any same-named DAG node, DAG output or header entry, and 0 cases where the step output header changed in names or order. All 62 distinct header column names observed match ^__table[0-9]+\..

On the cited model: createActionsForConjunction uniquifies against a concrete required_inputs set and gates the loop on has_input_name_collision, so there the collision is reachable. ActionsDAG.cpp:3774-3779 has the same purpose, the same prefix and the same header.has(...) test, and does not uniquify; matching it keeps the two sites consistent.

Not adding the test either: with the precondition unreachable it passes against unpatched master, so it would assert nothing.

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f78b8ab07 with master 1401785b7 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4d7f75efa; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

A revert of #114817 was opened today as #119275. The pass this patch touches, resolvePlannerOnlyFilters, arrived in master with #114817, so if the revert lands first this becomes moot and I will close it. If the feature stays, this is the one-site fix for the Input nodes size mismatch in dag storm that followed the merge: CIDB now holds 22 occurrences in the 31 hours since, over 20 distinct pull requests plus one true-master run, on Stress test, AST fuzzer and BuzzHouse jobs and on both architectures, against 2 of an unrelated older shape in the preceding three weeks. Either resolution works for me.

@m-selmi

m-selmi commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Closing this PR, the optimization was reverted in #119275 and the fix was added to PR #119305 that reintroduces it.

@m-selmi m-selmi closed this Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Nothing outstanding from my side: I diffed the folded commit (98bd5342) against this branch and the patch is identical.

Two things worth having for the reland.

1. The family reports under two STIDs, and they are one defect. Recomputing the id from the raw CIDB dumps with the CI parser's own get_stack_trace_id (ci/jobs/scripts/log_parser.py) reproduces both ids exactly, and the top-5 frame lists differ in a single entry at depth 5: traverseQueryPlan on debug and sanitizer builds (4752-5ad8) versus optimizeTreeSecondPass on release builds (4752-5cbf), where that helper is inlined away. Frames 1 to 4 are identical (JoinExpressionActions::JoinExpressionActions from chooseJoinOrder from optimizeJoinLogicalImpl from optimizeJoinLogical), and all 9 5cbf rows in 120 days are release builds. So a 5cbf row after the reland is the same assert, not a second bug.

2. Baseline while the pass was in master: 23 CIDB rows over 21 carrier PRs plus one true-master AST fuzzer (arm_asan_ubsan) run (d8d2f994, 2026-09-10 07:58:58Z) in those ~32 hours; the three weeks before it landed had zero rows for either id. Nothing new since the revert merged, though that is only an hour of CI so far.

Scope of what I verified, so it is not read as more than it is: the regression test pins the DAG fingerprint that 7 of those 23 rows carry (it was minimised from one of the fuzzer dumps). The other 16 share the abort site but I did not reproduce them individually, so I would not assume this one commit closes the whole family. I am tracking the signature in CIDB and will open a separate PR if it comes back after the reland.

Also, the bot review on that commit (hard-coded __filter<name> alias not being unique) is answered above with a measurement showing the collision is not constructible, in case it resurfaces: #119106 (comment)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing the loop here, since three CI answers of mine point at this PR as the owner of
Input nodes size mismatch in dag (STID 4752-5ad8 / 4752-5cbf). That abort is not reachable
on any shipping code, so no fix is owed and I am not reopening this PR.

Measured today:

  • src/Processors/QueryPlan/Optimizations/resolvePlannerOnlyFilters.cpp is absent from master
    and from all 8 active release branches (26.2, 26.3, 26.4, 26.5, 26.6, 26.7, 26.8,
    30.12), every probe run with src/Interpreters/JoinExpressionActions.cpp as a positive control
    on the same ref. The pass was on master for 32 h and then 13 h, and no release branch was cut
    inside either window.
  • CIDB: the last occurrence of either sub-hash anywhere is 2026-09-10 16:49:02 UTC, 38 minutes
    before the first revert. 0 rows since the second revert (Revert "Convert OUTER join to INNER join by null-rejecting join conditions" again #120119), against 15,306 FAIL/ERROR
    rows ingested in the last 24 h. Over 14 days the assertion text appears under those two sub-hashes
    only, so nothing else is tripping it.
  • The replacement (Extend outer to inner join conversion #120253) carries none of the machinery: resolvePlannerOnlyFilters.cpp,
    FunctionPlannerOnlyFilter.h and deriveNotNullFiltersFromJoin.cpp are all absent at its current
    head 5b52d387, and convertOuterJoinToInnerJoinTransitively.cpp adds no node to the join
    expression DAG at all: it only assigns join_operator.kind. The duplicated-output-node shape this
    PR fixed has no site there.

That is consistent with what I said on the reland thread ("I am not opening a separate PR: with the
revert on master there is no resolvePlannerOnlyFilters left to patch"). Nothing further from me on
this signature. If a future reland brings the pass back, the CI scan picks the signature up again.

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants