Skip to content

Refactor remove-unused-columns optimization - #122952

Merged
KochetovNicolai merged 42 commits into
masterfrom
remove-unused-columns-single-pass
Oct 7, 2026
Merged

KochetovNicolai merged 42 commits into
masterfrom
remove-unused-columns-single-pass

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Before, tryRemoveUnusedColumns was a local optimization. It pruned one step against its parent, and the local loop repeated it until nothing changed. When a child could not drop a column, for example a FINAL read that keeps its sorting key, the rule added a projection above the child (absorbExtraChildColumns). It then marked the step with prevent_input_removal, so that the next round did not remove the input again. That flag had to be passed through mergeExpressions. Several earlier fixes for block structure mismatches and optimization loops came from these interactions.

Now removeUnusedColumns(root) runs once after the local loop of the first pass. If it changed anything, the local loop runs again.

  • Going down, each step says which columns of each child it does not need: getUnneededColumns(unneeded_output_positions). The step does not change yet.
  • Coming back up, the children are pruned first. Then the step takes their result: removeUnusedColumns(unneeded_output_positions, inputs) gets one PrunedInput per child, with the positions the child dropped and its new header. It returns step_changed and dropped_output_positions.
  • A child may keep more than it was asked to, such as the sorting key of a FINAL read, or append a column, such as the dummy column of a join. The step keeps an input for each such column, so the column stays consumed and no projection is needed.

The positions are unneeded and dropped positions, not required and kept ones. In the usual case nothing is dropped, so the lists are empty, and a wrong empty list keeps too much instead of dropping everything.

ExpressionStep, FilterStep and JoinStepLogical implement both methods, and ReadFromMergeTree implements removeUnusedColumns. Each input column of ExpressionStep and FilterStep is classified the same way: read or passed through, needed or not.

Removed: absorbExtraChildColumns, removeUnusedColumns.h, prevent_input_removal with its setters, the remove_inputs mode of the filter DAG pruning, and canRemoveColumnsFromOutput.

The plan changes in three EXPLAIN references (03545_analyzer_correlated_subquery_exists_asterisk, 03595_convert_any_join_to_semi_or_anti, 03836_tpch_join_order_plans): an unused exists(__table2) column is no longer computed and passed through the join, and the projection that dropped it above an exchange is gone.

This is split out of the lazy materialization for joins work, which uses the same interface.

Related: #122682

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

...

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1750-master (included in 26.10 and later)

KochetovNicolai and others added 15 commits September 29, 2026 19:43
…nStep

`removeUnusedColumns` answers which inputs a step still needs only as a side
effect of changing the step, so a pass that finds out later that it cannot
proceed has already rewritten the plan. Lazy materialization over a join tree
needs to try a candidate set of deferred columns per source and back out, so
add `getRequiredColumns`, which computes the same answer and leaves the step
alone, together with `canGetRequiredColumns` to report support for it.

`ExpressionStep` implements both on one calculation: `analyzeRequiredColumns`
returns what would change, `getRequiredColumns` returns it, and
`removeUnusedColumns` applies it. This way the two cannot drift apart.

Two helpers move to `actionsDAGUtils`:
- `findReachableNodes`, which answers what `removeUnusedActions` would keep.
  It takes a barrier predicate because `removeUnusedActions` folds constants
  before it collects the nodes to keep, and folding clears the children of a
  folded node, so plain reachability would predict fewer removals.
- `mapInputsToHeaderPositions`, moved out of `optimizeLazyMaterialization.cpp`
  where it was a static helper. It maps every input to the header column that
  input reads, which `ActionsDAG::matchInputPositionsToHeader` cannot express
  because it returns a plain list of consumed positions.

The last point also fixes `removeUnusedColumns` for headers with duplicated
column names. It used to re-match the surviving inputs to the header by name
after pruning, so when the header holds `d`, `d` and only the input reading the
second `d` survives, the step was rebuilt around the first one instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`pruneFilterDAGOutputsByPosition` computed what to prune and pruned it in one
pass, and `ReadFromMergeTree` calls it for its PREWHERE and row-level filter
DAGs, so split it rather than duplicate it:
`analyzeFilterDAGOutputPruning` answers, `applyFilterDAGOutputPruning` applies,
and `pruneFilterDAGOutputsByPosition` is the two together for callers that do
not need to ask first. `FilterStep` then implements `getRequiredColumns` and
`removeUnusedColumns` on the same analysis.

Filter positions need mapping over the erased filter column, and the filter
column stays in the DAG outputs even when nobody reads it, so the analysis
returns the pre-erase positions to keep and the value `remove_filter_column`
settles on.

Like `ExpressionStep`, this stops re-deriving input positions by name after
pruning, which fixes the same duplicated-name defect in the PREWHERE and
row-level filter paths, and it drops the sorted-set bookkeeping in favour of a
mask over the input header.
Same split as the other two steps: `analyzeRequiredColumns` works out which
outputs survive, which nodes have to be kept, and which input positions each
side still needs, and `removeUnusedColumns` applies that. This completes the
set of steps the lazy materialization chain walks, so a pass can now ask a
whole `Limit -> ... -> leaves` subtree what it would need and back out.

The analysis has to account for two things specific to this step: the join
conditions have to be computed whether or not anything reads them, and a side
that nothing else needs keeps one input so that it does not lose every column.
Both are returned as extra pruning roots, so the mutating path does not
re-derive them.

Input positions are again taken per input rather than by re-matching the
survivors to the header by name, which for a join is more than a corner case:
both sides commonly carry columns of the same name.

Verified by temporarily turning the `chassert` that compares the prediction
against the mutation into a throw, since `chassert` is compiled out in release,
and running 84 join, prewhere and lazy materialization tests: no mismatch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review of the required-columns analysis, two points that turn out to be the
same one.

`mapInputsToHeaderPositions` answered in two lists - where each input reads, and
which positions nothing reads - which a caller then had to keep in step.
`mapHeaderColumnsToInputs` answers in one, indexed by header column: the input
that reads it, or nothing, in which case the column passes the DAG by. Every
caller reads the header in order anyway, so each of them got shorter, and the
pass-through ordinal a caller's positions are given in is just a count along
that walk.

`ExpressionStep`'s plan says the same thing about its input header in one list
too, with a state per column: read and still needed, read but no longer, passed
through and asked for, passed through and dropped. The required input positions
and the dropped pass-throughs are then filters over that list rather than two
vectors built alongside each other.

The analysis no longer branches on `remove_inputs`. It asks the DAG what it
would keep, and since an input has no children, adding the inputs as roots -
which is what keeping them amounts to - keeps nothing besides the inputs
themselves. So one walk answers both cases, the two answers are recorded, and
the flag picks one when the plan is turned into a result.

Which is now `toResult` rather than a result stored inside the plan: the
positions to require and whether anything changed at all follow from the list of
column states, so there is nothing to keep in step there either.

`FilterStep` and `JoinStepLogical` read the new single list as well, though
their own plans still carry the pass-through positions in vectors; the same
treatment fits them and can follow.

Verified as before by turning the `chassert` that compares the prediction
against the mutation into a throw, since `chassert` is compiled out in release,
and running 68 join, prewhere and lazy materialization tests: no mismatch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
In `ExpressionStep` the DAG positions to keep were the caller's positions over
again: the output header holds the DAG's outputs first and the pass-through
columns after, `splitOutputPositions` leaves the first group's values alone, and
the caller's positions are sorted by contract. So they are simply the prefix
below the number of DAG outputs, and a count says that where a vector said it
twice. The pass-throughs are the remaining suffix, counted from that number,
which the one walk over the header handles as it goes.

`JoinStepLogical` had the same thing twice over. Its kept DAG positions were
pushed into the plan and into the result side by side, the result only adding
the dummy column's sentinel at the end, so one was the prefix of the other; and
the dropped positions were the complement, which the single walk that erases
them from `actions_after_join` now works out as it goes.

`FilterStep` is not the same case, and says so where it keeps its own list: the
header its caller counts in has the filter column erased from it, so those
positions are shifted back over that column before anything else, and the filter
column is added whether or not anyone asked for it.

Verified by turning the two `chassert`s that compare the prediction against the
mutation into throws and running 68 join, prewhere and lazy materialization
tests: no mismatch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… its inputs changed

`RemoveUnusedColumnsResult` encoded "nothing changed" by emptiness: an empty `required_input_positions`
meant every input was still read, and `kept_output_positions` was valid only when `changed` was set, so
every caller rebuilt the identity list itself (`effectiveKeptOutputPositions`, and the same fallbacks in
`optimizePrewhere` and in the lazy materialization pass for joins). Now both are always filled - one
entry per child, and every kept position - and a step builds the answer for "nothing changed" with the
new `IQueryPlanStep::keepEverything`.

The `NEWLY_ADDED_COLUMN_POSITION` sentinel inside `kept_output_positions`, whose only producer is the
dummy column of `JoinStepLogical`, is replaced by `added_output_count`: such columns come after the kept
ones, and the helpers that reconcile a child's header treat them as extra, as before.

`changed` is split into `step_changed`, whether the step itself changed, and `inputs_changed`, whether a
child has to produce fewer columns, so each caller asks the question it means.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`FilterDAGOutputPruningPlan` carried a `FilterDAGOutputPruningResult` that the analysis filled in piece by
piece, setting `changed` from six places. The plan now holds only what the analysis found - which
outputs and inputs go, whether the filter column flag flips - and `toResult` derives the result from it,
the way `ExpressionStep::RequiredColumnsPlan` does. `pruneFilterDAGOutputsByPosition` returns that.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`FilterDAGOutputPruningPlan` kept three facts about the input header - the pass-through columns to drop,
the positions the surviving inputs read, and whether any input goes - where `ExpressionStep` keeps one:
what each column of the input header is to the step. The `InputColumn` enum moves to `IQueryPlanStep`
so both steps use it, and its values are named alike: `ReadNeeded`, `ReadDropped`,
`PassesThroughNeeded`, `PassesThroughDropped`.

The plan also stores the position of the filter column instead of its name, with a position overload of
`ActionsDAG::foldFilterPredicateThroughMaterialize`, and one `changes_output_header` flag instead of two
flags only `toResult` read.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Each value says how a step uses one column of its input header: reads it, still needed or not, or passes
it through.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`tryRemoveUnusedColumns` was a local rule: it pruned one step against its
parent, and repeated the local loop until nothing changed. A step whose
child could not drop a column got a projection above the child
(`absorbExtraChildColumns`) and `prevent_input_removal`, so that the next
round did not undo it.

Now `removeUnusedColumns(root)` runs once after the local loop of the
first pass, and the loop runs again if it changed anything. Going down, a
step is only asked what it needs of its children (`getRequiredColumns`,
read-only). Going up, the children are pruned first, and the step takes
their result: `removeUnusedColumns(required, inputs)` gets one
`PrunedInput` per child, the positions the child dropped and its new
header. A column that the child keeps beyond the ask (the sorting key of
a `FINAL` read) or appends (the dummy column of a join) is consumed by
the step, so no projection is needed.

- `RemoveUnusedColumnsResult::kept_output_positions` becomes
  `dropped_output_positions`, which is empty when nothing is dropped;
  `added_output_count` is gone.
- A step without an output header (the `GatherSend` sink at the root of
  a distributed plan fragment) is not pruned; its children are asked for
  all columns.
- `removeUnusedColumns.h` and the absorb helpers are removed; v3 lazy
  materialization and `optimizePrewhere` use the new interface.
- Three EXPLAIN references change: an unused `exists(__table2)` column is
  no longer made and passed through the join, and the projection that
  dropped it above an exchange is gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`getRequiredColumns` now returns only `RequiredInputPositions`: per child,
the positions of its header the step reads. `RemoveUnusedColumnsResult`
keeps only `step_changed` and `dropped_output_positions`; its default is
the answer when nothing changes, so `keepEverything` is gone.

The input positions and `inputs_changed` that `removeUnusedColumns`
returned only repeated what the child had kept, and only tests read them.
`ExpressionStep` also loses `removes_any_output` and `removes_any_action`,
and `FilterStep` its `RequiredColumnsPlan` wrapper, which only the removed
fields needed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`removeUnusedColumns` and `getRequiredColumns` took the positions the
caller needs. Now they take the positions nobody needs:
`removeUnusedColumns(unneeded_output_positions, inputs)` and
`getUnneededColumns(unneeded_output_positions)`, which returns
`UnneededInputPositions`, per child the positions the step does not need.

In the usual case nothing is unneeded, so the lists are empty: the pass,
`optimizePrewhere` and a step that cannot prune no longer build lists of
all positions, and `allInputPositions` is gone. `ExpressionStep` and
`FilterStep` drop exactly what is unneeded, so their
`dropped_output_positions` is the list they were given. A wrong empty list
now keeps too much instead of dropping everything.

`ReadFromMergeTree` and `analyzeFilterDAGOutputPruning` still count what
they keep - the read keeps the sorting key for `FINAL`, the filter its
filter column - and convert once at the boundary.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The flag kept `removeUnusedColumns` from removing the inputs of an
`ExpressionStep` or `FilterStep`. It protected columns that a child could
not drop: the projection that `absorbExtraChildColumns` put above such a
child, or the step of the quantized-codes shortlist that discards the
approximate distance. Without it, the next round removed those inputs,
the child's extra columns were exposed again, and the rounds could loop.

The single pass does not need it: a child that cannot drop a column
reports it as kept, and the step keeps the input that reads it, so the
column stays consumed. So the flag, its setters in `mergeExpressions` and
`useVectorSearchWithQuantizedCodes`, and the check in v3 lazy
materialization are removed.

The `remove_inputs` parameter of the filter DAG pruning, which only the
flag set to false, is removed too, with the code for that case.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The old local rule asked it whether a step could drop an output before it
pruned the step against its parent. The single pass asks
`canRemoveUnusedColumns` only, so nothing calls it any more.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… and fix a stale comment

The code of `optimizePrewhere` that threw it moved into the single pass.
A comment of lazy FINAL still called the pass `tryRemoveUnusedColumns`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e28358b]

Summary: ✅


AI Review

Summary

This PR refactors removeUnusedColumns from repeated local pruning into a whole-plan bottom-up pass plus a second local optimization round. The overall approach looks sound, but one correctness bug still remains around duplicate input names: when a step consumes a child column that the child kept, it recreates that input from name and type only, which loses which duplicate header slot the input came from and can rebind later expressions to the wrong column.

Findings
  • ❌ Blocker — src/Processors/QueryPlan/IQueryPlanStep.cpp:106: alignInputsWithPrunedChild re-adds a kept-but-consumed child column via dag.addInput(column.name, column.type). With duplicate names, that throws away the original slot identity, so the next mapHeaderColumnsToInputs / updateHeader pass can pair a surviving expression with the wrong duplicate input. src/Processors/QueryPlan/JoinStepLogical.cpp:675 repeats the same bug in the join-specific consume path.
  • Suggested fix: preserve consumed columns by original position or input-node identity instead of recreating them from name and type alone; the rebinding must stay stable across duplicate names.
Final Verdict

Not ready to merge: the duplicate-name consume path still has a correctness bug.

LLVM Coverage Report

Measured on commit e28358b.

Metric Baseline Current Δ
Lines 88.20% 88.30% +0.10%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 685/731 (93.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 29, 2026
KochetovNicolai and others added 3 commits September 30, 2026 13:34
The local rule used to prune a read while an `Expression` that needed none
of its columns was still right above it, before `LIMIT` was pushed down
below that `Expression`. The single pass runs after the local rules, when
the `LIMIT` is already right above the read, and a step that does not take
part in the pass needs every column of its child. So the read of
`SELECT count() FROM (SELECT 1 FROM t LIMIT 500)` kept a column, and under
parallel replicas the shipped fragment no longer had an empty header
(`04546_pr_plan_based_remote_only`).

`LimitStep` passes every column through, so it takes part now: it needs of
its child what is needed of it, and the columns `WITH TIES` compares rows
by, and it drops what its child drops.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122952&sha=c812b09b5b2cf304ad778b1b576e15d5a65c9476&name_0=PR
PR: #122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`getUnneededColumns` and `removeUnusedColumns` are one protocol: a step
implements both, or neither. The two flags differed only where it did not
matter: a read has no children to ask about, and a join that cannot prune
could still be asked, but the pass never asked it. `optimizePrewhere`
checked one flag and then called the method of the other.

Now `canRemoveUnusedColumns` says the step takes part, and only a step
with children is asked `getUnneededColumns`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
KochetovNicolai and others added 7 commits September 30, 2026 14:24
…ization changed a step

`removeUnusedColumns` takes a mode now:
- `Global` walks the whole subtree, as the pass did.
- `Local` starts at one step and keeps its outputs. It walks down only while
  a step leaves something of a child unneeded, and not at all if the step
  cannot prune: it finds the columns that a change of that step left unread.

The first pass applies the local optimizations, then the global mode once,
and, if it changed anything, the local optimizations again with the local
mode as one of them (`tryRemoveUnusedColumns`, not in `getOptimizations`).
Before, the global mode and the local optimizations alternated until the
global mode changed nothing. In the stateless tests with `EXPLAIN`, the
FINAL and filter tests and the `LIMIT` tests (about 60 000 queries), the
last round ran 1151 times and applied nothing.

`optimizePrewhere` uses the local mode on the new filter step instead of
pruning the step and the read by hand.

The walk is not recursive: one stack of frames, each collecting what its
children produce once they are pruned.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
No SQL query reaches the local mode beyond one step: after the global mode,
the local optimizations make no column unread in the stateless tests. So a
unit test builds small plans by hand and checks where the local walk goes
down and where it stops, next to the global one.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`analyzeFilterDAGOutputPruning` takes the positions nobody needs, like the
steps do. `FilterStep` passes its own straight through, and only
`pruneFilterDAGOutputsByPosition`, which `ReadFromMergeTree` calls with the
positions it keeps for PREWHERE and the row policy filter, converts them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…at it drops

`FilterDAGOutputPruningPlan` becomes `FilterStep::UnneededColumnsPlan`, as
in `ExpressionStep`: it holds the DAG outputs nobody needs,
`unneeded_dag_positions`, instead of the ones to keep, and the walk over
them is `neededDAGOutputs`. Applying it to the outputs becomes a method of
the plan.

Only `ReadFromMergeTree` used the pruning from outside, through
`pruneFilterDAGOutputsByPosition`, so the analysis is a private static
method now, and the entry point for `ReadFromMergeTree` is the public
static `FilterStep::pruneDAGOutputsByPosition`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…mments

The input columns come first, then the positions, then the flags. The
comments say why the unneeded DAG outputs of `ExpressionStep` are a
prefix, that the unneeded DAG outputs of `FilterStep` never include the
filter column, and what `remove_filter_column` and `removes_any_action`
mean.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
It predicted whether `removeUnusedActions` would erase a node, but only
`pruneDAGOutputsByPosition` needed that, and it calls `removeUnusedActions`
itself, so it passes the real answer to `toResult`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e28358b5b with master d91a05305 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of eb03aea3a; 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.

Object file sizes

185 object files changed (+163.97 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/IQueryPlanStep.cpp.o 109.77 KiB 138.93 KiB +29.17 KiB (+26.57%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/actionsDAGUtils.cpp.o 189.27 KiB 212.46 KiB +23.20 KiB (+12.26%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinStepLogical.cpp.o 960.97 KiB 983.73 KiB +22.76 KiB (+2.37%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp.o 239.64 KiB 222.62 KiB -17.02 KiB (-7.10%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +764.1 s (+9%) in total before that adjustment.

Job report

KochetovNicolai and others added 4 commits October 1, 2026 11:33
…column

When the filter column of a split filter has the same name as an input,
`ActionsDAG::split` renames it in the first half, and the second half
reads it through an input under the new name, with an alias back to the
old one. `trySplitFilter` then called `removeUnusedResult` with the old
name, which removed only the alias. The filter step stopped outputting the
column, and the second half kept an input with no column in the header.
Removing unused columns rejects such an input with a logical error:

    The header [_CAST(NULL_Nullable(Nothing), 'Nullable(Nothing)'_String)]
    has a column for only 1 of the DAG's 2 inputs

Now the renamed input is removed as well, and should the second half still
read it, the filter step keeps the column.

Found by the AST fuzzer in the stress test:

    SELECT x FROM (SELECT arrayJoin([1]) AS x GROUP BY NULL WITH TOTALS) WHERE NULL
    INTERSECT DISTINCT SELECT DISTINCT 1

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122952&sha=79586cd61a93fb2471e94dd87e8a93349f0e7172&name_0=PR
PR: #122952
Related: #122714

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…nusedResult`

`ActionsDAG::removeUnusedResult` removed the output and its node only. For
the filter column of a split filter that was renamed to avoid a clash, the
node is an alias of an input under the new name, so the input stayed: the
dangling input that `2b19479cd17` cleaned up in `trySplitFilter` itself.

Now it removes the chain of nodes the result is computed by - the output
node, its only child, and so on, down to an input or a column - up to the
first node that something else still uses, and returns true if the whole
chain is gone. It throws if a node on the chain has more than one child.
`trySplitFilter` no longer needs its own cleanup.

The two callers that remove the output of a function with several
arguments - `cosineDistance` in `useVectorSearch` and the `and` of an
always-true filter in `mergeFilterIntoJoinCondition` - only wanted the
output gone, and use `removeFromOutputs` now.

PR: #122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The global pass of removing unused columns ran outside the check that
every local optimization goes through, so it ran even when the first
local pass had reached `query_plan_max_optimizations_to_apply`: EXPLAIN
showed a plan optimized past the limit, and a query applied one more
optimization before it threw. The check is now one helper, used before
each local optimization and before the global pass.

PR: #122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
#include <Processors/QueryPlan/ExpressionStep.h>
#include <Processors/QueryPlan/FilterStep.h>
#include <Processors/QueryPlan/Optimizations/Optimizations.h>
#include <Processors/QueryPlan/Optimizations/actionsDAGUtils.h>

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.

Not sure if we need that, but if not, maybe better to revert it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, looks like a part of #122682

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

I have reviewed the general logic and tests, they looks pretty good. I will take a look at the per step implementation tomorrow.

/// Nothing was applied.
stack.pop();
}
return true;

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.

My only fear is we can get into a similar issue with this that drove us to have the prevent_input_removal. But if the current tests doesn't show that, maybe it is fine.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think we can't stuck, because tryRemoveUnusedColumns returns true only if any column was removed.
It can't be a situation where the column was removed and returned. And, step drops the input only if its child can drop it from the output. I think this is a benefit of splitting into forward and backward passes.

Comment on lines +26 to +27
/// A step that cannot drop columns needs all its children produce, and outputs all it did. So does a
/// sink, which has no output at all, such as the root of a distributed plan fragment.

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.

I haven't read the rest of the code, but want to make sure I won't forget it, so I leave a comment: removing unused columns can be useful even for steps that don't produce anything, because they might be able to get rid of columns from their inputs.

However I have to see the implementation, because the wording of the comment is not clear.

/// It is guaranteed that the output header of the step will contain all columns at those positions
/// and might contain some other columns too.
/// What a child produces once its own unused columns are gone:
/// its `dropped_output_positions` and its new output header.

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.

Suggested change
/// its `dropped_output_positions` and its new output header.
/// its dropped output positions and its new output header.

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: f51dfd16-b5c7-48f4-942c-cf1dcb5886f7
  • MIRAI run: 23ecfc3a-5447-4798-87b1-010d022c52ef
  • PR check IDs:
    • clickbench_60985_1791314725
    • clickbench_60998_1791314725
    • clickbench_61004_1791314726
    • tpch_adapted_1_official_61012_1791314725
    • tpch_adapted_1_official_61021_1791314726
    • tpch_adapted_1_official_61055_1791314725

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

Apart from JoinStepLogical and ReadFromMergeTree I have reviewed the PR, looks good so far, only minor comments.

Comment thread src/Processors/QueryPlan/FilterStep.cpp Outdated
@@ -1,7 +1,8 @@
#include <Processors/QueryPlan/FilterStep.h>
#include <Processors/QueryPlan/Optimizations/actionsDAGUtils.h>

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.

This include should go intothe next block.


FilterDAGOutputPruningResult pruneFilterDAGOutputsByPosition(
ActionsDAG & dag,
FilterStep::UnneededColumnsPlan FilterStep::analyzeUnneededColumns(

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.

Just a small question: in your vocabulary is there any difference between "unneeded" and "unused"? If yes, let's make it clear. If not, let's pick one for everything.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think it's a bit different terms. Unneeded is what parent step does not need. Unused is the column not needed for the step itself. I think column can be needed but unused...
However, I did not check for consistency, and I don't think it's so important.

Comment thread src/Processors/QueryPlan/FilterStep.cpp Outdated
Comment on lines 114 to 129
for (size_t position = 0; position < header_columns.size(); ++position)
{
if (passthrough_index >= passthrough_input_header_positions.size())
throw Exception(
ErrorCodes::LOGICAL_ERROR, "Required output position {} is out of range for pass-through inputs", passthrough_index);
required_passthrough_input_header_positions.insert(passthrough_input_header_positions[passthrough_index]);
}

const auto has_to_remove_any_pass_through
= passthrough_input_header_positions.size() > required_passthrough_input_header_positions.size();
if (!header_columns.passesThrough(position))
continue;

std::set<size_t> required_dag_index_set(required_dag_indices.begin(), required_dag_indices.end());
if (next_unneeded_passthrough < unneeded_passthrough_indices.size()
&& unneeded_passthrough_indices[next_unneeded_passthrough] == passthrough_index)
{
++next_unneeded_passthrough;
plan.input_columns[position] = InputColumnUsage::PassesThroughDropped;
}
else
plan.input_columns[position] = InputColumnUsage::PassesThroughNeeded;

/// Check if the filter column is required by the caller. If not, we can remove it.
if (!remove_filter_column && !required_dag_index_set.contains(filter_col_pre_erase_pos))
{
remove_filter_column = true;
++passthrough_index;
}

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.

Would it be possible to compute the values of plan.input_columns at the end in one loop where we decide about the read columns? in that way the whole logic would be in one place. Maybe we can even unify with the same logic in Expression step, looks very very similar.

Comment thread src/Processors/QueryPlan/FilterStep.cpp Outdated
folded_dag->foldFilterPredicateThroughMaterialize(filter_col_pre_erase_pos);
/// The fold only ever replaces the filter output by a constant.
plan.fold_filter_predicate = folded_dag->getOutputs()[filter_col_pre_erase_pos]->type == ActionsDAG::ActionType::COLUMN
&& old_outputs[filter_col_pre_erase_pos]->type != ActionsDAG::ActionType::COLUMN;

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.

Cannot we check with has_materialize? Right now it seems a bit controversial:

  1. If the predicate nodes have materialize, how would be they a column node?
  2. If the predicate nodes cannot be a column, why do we check it here?

Either include this into the condition with has_materialize or turn this into an assertion.

Comment on lines +88 to +91
const size_t kept_count = old_header.columns() - pruned.dropped_positions.size();
for (size_t position = kept_count; position < pruned.header->columns(); ++position)
to_consume.push_back(pruned.header->getByPosition(position));

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.

Are we always sure the new column is added to the end? I think for join it is guaranteed, but I am not sure if that is contract in anywhere. Maybe let's add a debug only assertion (either here or from where this is called)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added a check, but afiak this is only for Join and awould like to reove this exception later

Comment thread src/Processors/QueryPlan/LimitStep.cpp Outdated
const auto & header = *input_headers.front();
std::erase_if(unneeded, [&](size_t position)
{
return std::ranges::any_of(description, [&](const auto & column) { return column.column_name == header.getByPosition(position).name; });

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.

in case the column with_ties is duplicated, it will keep all of the copies. I think it would fairly easy to keep only the first one.

KochetovNicolai and others added 5 commits October 6, 2026 13:10
- `FilterStep` decides the read and the pass-through columns of its input
  in one loop at the end. It compares the unneeded positions with the
  position of each pass-through column directly, so
  `ActionsDAG::splitOutputPositions` has no callers and is removed.
- `FilterStep`: a predicate with a `materialize` is never a constant, so the
  check for it is an assertion. The position mapping is inlined, the
  include goes into the sorted block, and the unused `<set>` include is
  removed.
- `LimitStep` keeps only the first column of each `WITH TIES` name, the one
  `LimitTransform` compares.
- In debug builds, check that a pruned step keeps its remaining columns
  first, in their order, as the step above expects.
- `optimizeLazyMaterialization.cpp`: remove the unused `actionsDAGUtils.h`
  include, and initialize `Frame::node`.

#122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The test measured the block size of a join through an outer query that
reads only `blockSize()`. The single-pass `removeUnusedColumns` now removes
the wide column from the join as unused, so a probe row is 8 bytes and all
the padded rows fit one block under the byte limit. The byte limit checks
now also read the wide column above the join, so the rows stay a kilobyte
wide.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122952&sha=edf332159304571fd38986c9aac7293d64bb7c31&name_0=PR
#122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…rch projection check

A check from master removes the distance sort output from a copy of the
projection DAG with `removeUnusedResult`. That output is a function of the
vector column and the reference vector, not a chain of nodes down to an
input, so `removeUnusedResult` now throws `LOGICAL_ERROR`.
`removeUnusedActions` runs right after, so `removeFromOutputs` gives the
same result.

https://d1k2gkhrlfqv31.cloudfront.net/clickhouse-test-reports-private/praktika.html?PR=78291&sha=ef5724604be2d7b3a2289ae28f566d996405e2a6&name_0=PR
#122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

bool changed = dag.removeUnusedActions(kept_inputs);
for (const auto & column : to_consume)
dag.addInput(column.name, column.type);

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.

Re-adding the consumed child column from only name and type loses which duplicate header slot it came from. That is fine for unique names, but this PR explicitly relies on position-sensitive handling for duplicate names (see the new ExpressionStepRequiredColumns.DuplicateNamesKeepTheirOwnPosition test).

A concrete failure is an input header like (d, d) where the expression really reads the second d, while the first d is only kept because the child could not drop it. After removeUnusedActions the surviving real input is the second d; this line appends a fresh d for the consumed first slot. On the next mapHeaderColumnsToInputs / updateHeader pass, the nth-by-name matching pairs input #0 with header position 0 and the appended consumer with position 1, so the expression is rebound to the wrong duplicate column.

This consume path needs a position-preserving representation of the kept-extra column instead of recreating it from only name/type. The join-specific expression_actions.addInput(...) path has the same issue.

A dropped column the child keeps is consumed by a new input, and inputs are
paired with header columns by name, in order: a new input reads the first
column of its name that no input reads. If a needed pass-through column of
the same name comes before the dropped one, the needed column was consumed
in its place, and the dropped one was output instead.

`ExpressionStep` and `FilterStep` now keep such a column, and do not
report it as dropped. `alignInputsWithPrunedChild` throws `LOGICAL_ERROR`
instead of consuming the wrong column, which also covers an appended
column of the child with a clashing name. The join consumes every kept
column it does not read, in header order, so it is not affected.

#122952

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit e95690a Oct 7, 2026
293 of 295 checks passed
@KochetovNicolai
KochetovNicolai deleted the remove-unused-columns-single-pass branch October 7, 2026 13:37
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 10, 2026
…runs as PREWHERE

`prepareReadingFromFormat` keeps query-level `requested_columns` / `source_header`,
which can hold subcolumns such as `n.null` or `arr.size0`, and a format-level
`format_header`, where a subcolumn that the format cannot read on its own is
replaced by its whole column (`n`). After PREWHERE, `updateFormatPrewhereInfo`
set `source_header = format_header` and rebuilt `requested_columns` from it, on
the assumption that a format supporting PREWHERE reads every subcolumn directly.
Parquet reads tuple elements directly but not `.null`, `.size0` or dynamic
subcolumns, so the read step stopped producing `n.null`:

- a later step using it failed with NOT_FOUND_COLUMN_IN_BLOCK
  (`SELECT countIf(n.null) FROM file('x.parquet') WHERE number > 5`, on released
  26.3, 26.8 and 26.9; the explicit `PREWHERE n > 5` form too);
- an unused input (`indexHint(n.null)`) was left dangling, which the input check
  added by ClickHouse#122952 reports as `The header [...] has a column for only 2 of the
  DAG's 3 inputs` (STID 2728-4657, found by the AST fuzzer).

Compute the post-PREWHERE source header by applying the PREWHERE actions to the
query-level requested block, as `SourceStepWithFilter::updatePrewhereInfo` does,
keep each requested column with its storage mapping, and keep a storage column
in `format_header` when an explicit PREWHERE consumes the column a selected
subcolumn is extracted from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants