Skip to content

Cherry pick #122682 to 26.10: Lazy materialization support for JOIN - #126918

Merged
robot-clickhouse-ci-1 merged 103 commits into
backport/26.10/122682from
cherrypick/26.10/122682
Oct 20, 2026
Merged

robot-clickhouse-ci-1 merged 103 commits into
backport/26.10/122682from
cherrypick/26.10/122682

Conversation

@robot-clickhouse-ci-2

Copy link
Copy Markdown
Contributor

Original pull-request #122682

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

KochetovNicolai and others added 30 commits October 7, 2026 13:48
Splitting each step's `ActionsDAG` on its own, as lazy materialization does
today, leaks intermediate results across the steps in between. For
`select a, b, a + b + c from t1 join t2 using (k) where a + b > 0 order by a
limit 10` the filter is pushed below the join, so `a + b` is computed there and
the final result needs it above the join: it becomes a column carried through
the join and replicated by it. Merged into one DAG, `a + b` is a node, and a
caller can recompute it above the `LIMIT` instead - which for that query costs
ten additions and carries nothing.

`buildMergedPlanDAG` walks an `Expression` / `Filter` / `JoinStepLogical`
subtree into a single DAG. Any other step becomes an opaque source: its output
header turns into DAG inputs and the subtree below it is left alone, which is
also what keeps a caller inside one distributed fragment.

The DAG is carried by `JoinExpressionActions`, so the set of sources each node
reads comes from `getSourceRelations` and needs no bookkeeping here, and joining
two subtrees is the `detach` / `unite` / shift sequence that `uniteGraphs` in
`optimizeJoin.cpp` already uses. Nothing is matched by name across a join
either: `unite` appends the right side after the left, and `mergeInplace` binds
same-named columns in that order, the same rule `ActionsDAG::updateHeader`
follows when it builds a step's input block.

What the DAG cannot recover afterwards is where a node was computed, so
`nodes_below_joins` records it. A node computed above a join that happens to
read one source looks exactly like one computed below it, but only the second
can be recomputed on the matched rows alone: above the join the node also ran
on rows the join stuffed with defaults or NULLs, and `x + 1` there is 1, not
the default 0.

Every step's header is checked against what the DAG produces, and the build is
refused when they differ, rather than optimizing on a wrong model of the plan.

Verified on plans with two-table, three-table, self and LEFT joins with filters
and expressions on both sides of the join: the DAG reproduced every header, and
no node reading more than one source was marked as computed below the joins.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`chooseLazyFrontier` decides, for a `Limit -> ... -> sources` subtree, which
values cross the `LIMIT` as columns and which are recomputed above it. The
currency is columns below the `LIMIT`, not arithmetic: a carried column is read
for every scanned row, goes through the sort and is replicated by every join
above, while recomputing touches at most `limit` rows. So a deferred value is
recomputed from what is already at hand, and only a value that cannot be
recomputed is carried.

For `select a, b, a + b + c from t1 join t2 using (k) where a + b > 0 order by a
limit 10` that means the sort key is the only column carried: `a + b` is
computed below for the filter and computed again above, from `a` and the `b` the
lazy read returns anyway. Where `b` is not selected the balance tips the other
way, because recomputing would read a column nothing else needs, so the sum is
carried instead - one column against one extra read, and the read below the
`LIMIT` covers every scanned row.

Two things are never recomputed. A non-deterministic or stateful value has to
agree with the filter that already used it, so it crosses as a column, though
what is computed from it may still be recomputed above. And a value the plan
computed below a join that can leave its source unmatched is recomputed on that
source's own rows, not after the merge, where it would run on the rows the join
filled with defaults or NULLs and turn `x + 1` over a stuffed 0 into 1 instead
of the default 0.

Which sources those are now comes from the join kinds `buildMergedPlanDAG`
walks, recorded as `Source::may_be_stuffed`, so a plan with no outer join above
a source - a single table, or an inner join - recomputes freely after the merge.
Getting this wrong in the strict direction is not free: requiring the dense
placement everywhere made a value whose input is carried unplaceable, and it
fell back to being carried, which is the leak this is meant to remove.

Verified against real plans for each of those cases, and against an INNER JOIN
of the same shape as the LEFT JOIN one to see the placement change with the
join kind alone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A value the plan computed below a join that can leave its source unmatched had
to be recomputed on that source's own rows, because after the merge it would run
on the rows the join filled with defaults or NULLs. That branch sees only what
the lazy read of the source returns, so a value reading anything else - a column
the main branch carries - could not be placed there and stayed below the `LIMIT`,
carrying an intermediate result across the join, which is what this is all meant
to avoid.

The mask makes that unnecessary. Any `Nullable` column from that side of the join
is NULL at exactly the unmatched rows, whatever `join_use_nulls` says - the
source's row index, or a `toNullable` marker where the source is not read lazily
- so such a value can be recomputed above the `LIMIT` like any other, on the rows
where its source matched, with the value the join stuffed standing elsewhere.
Everything it reads is available there, carried columns included.

The rows have to be masked out rather than computed and thrown away: `intDiv(1, x)`
over a stuffed `x = 0` throws whether or not its answer is used. And the mask
belongs at the value the join stuffed, not at the columns it was computed from -
substituting a default for `x` and computing `x + 1` gives 1 where the join gives
the default 0.

Only a value computed below a join needs a mask at all, and such a value reads
exactly one source, so there is one mask per value and no case analysis over
several joins. A value computed above the join ran on the stuffed rows as well
and is reproduced by recomputing it on all of them.

While here: a value nothing below the `LIMIT` used is computed above it for the
first time rather than recomputed, so a non-deterministic function needs no
column of its own. Only one whose answer the filter already used does.

On the LEFT JOIN plan that used to leave one output below the `LIMIT` for want of
a placement, everything is deferred now, with seven values recomputed under the
mask. The same plan with an INNER JOIN keeps recomputing after the merge, and a
FULL JOIN marks both sides.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Gating on `nodes_below_joins` - "computed below every join" - is wrong as soon
as the joins nest, because a value computed above an inner join and below an
outer one is then gated by nothing at all. For

  (select k, a + 1 as x from A left join B) l
  left join (select k, c + d as y from C left join D) r on l.k = r.k

`y` reads C and D and is computed above the C/D join. At a row where the outer
join matches but the inner one does not, `y` is `c + 0`, a proper value; at a
row where the outer join matches nothing, `y` is the default, not `c + 0`
recomputed. So `y` has to be gated by the outer join, `d` by the inner one, and
neither by the other: gating `y` on D's mask as well would throw away the first
row, and gating it on nothing would invent a value for the second.

So the gate belongs to a side of a join rather than to a source. A value reads
the sources of both sides of the joins below it, and those are gated by joins it
is not gated by itself; under a `FULL JOIN` no source is preserved at all, so no
source's row index can stand for the gate.

One gate per value is still enough, and it is the nearest one above it: a mask
column emitted at a join's unmatched side is carried through the joins above it
and stuffed by them in turn, so it already answers "did every join above this
point match". Walking up, that is simply the first gate a value is given.

This also does away with filling the lazily read columns as a separate concern.
A source column crossing a join is a value like any other, whose nearest gate is
that join, so it is masked by the same rule.

While here, `chooseLazyFrontier` no longer loops. It looped because a value that
could not be computed above the `LIMIT` failed its whole output, which then had
to be computed below - and that made the values behind it available to carry, so
another output could succeed on a later round. Carrying that one value instead of
failing the output does the same thing in one traversal, and drags less into the
eager branch: an output of `f(that value, heavy)` now defers, reading `heavy`
lazily, where before it was computed below the `LIMIT` in full.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`eager` and `carried` were two sets with an inclusion between them - a value
that crosses the `LIMIT` is computed below it - and the placement was spread
over three more containers besides. One entry per value says it more plainly,
and the two questions a consumer asks stay separate: what does the main branch
compute, and where does the value above the `LIMIT` come from.

The state space is smaller than the fields it replaces, on purpose. "Computed
below" and "crosses" are one axis of three values rather than two independent
flags, so a value that crosses without being computed below cannot be written
down. The mask is not stored at all: whether a value is gated, and by which
join, is a property of the DAG - `getNearestStuffing` - so keeping a copy here
would only let the two disagree. It also applies to a column the lazy read
returns exactly as it does to a recomputed one, which is now one rule instead
of two.

That leaves six reachable states, and the interesting one is a value that is
both computed below the `LIMIT` and recomputed above it: `a + b` for a filter
that needs it and a result that needs it again. That case is why the two axes
are separate rather than one enum of exclusive states.

The per-source list of lazily read inputs is derived on demand by
`collectLazyReads` rather than stored, for the same reason as the mask.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`Above::No` meant two different things - nothing above the `LIMIT` reads this,
and what reads it reads the column that crossed - while `Below` carried the
crossing decision that belongs with the readers above. So `Above` now answers
where a reader above the `LIMIT` gets the value from, with four answers that
exclude each other: nothing reads it, the crossing column, the lazy read, or it
is computed again. What is left below is a single flag for whether the main
branch computes it, which is what the main branch's own DAG is built from.

Merging the two into one enum would need six enumerators, because a value can
be computed below the `LIMIT` and computed again above it: `a + b` for a filter
that needs it and a result that needs it again, which is the case this whole
change exists for. Then "does the main branch compute it" would be a test
against four of those six, and forgetting one would be silent. Two axes keep
every question a single comparison.

`Crossing` is the one answer that needs the value below as well, so that is the
only invariant left, and `isConsistent` states it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The rule was "recompute unless that adds more than one lazily read column",
which put a number on the wrong thing. What makes a crossing column expensive
is not its own read: it is that every join above it replicates it, and a hash
join copies it into its build side, over every row that reaches there. So that
is what decides now - a join above the value means recompute, none means reuse
what the main branch already computed and let it cross.

Which side of a join becomes the build side would sharpen this, but it is not
known here: the joins are still logical, and `convertLogicalJoinToPhysical` and
the `join_swap_table` swap both come later. Treating any join above the value
the same way is the careful reading of that argument.

"Is there a join above it" is a new fact, `hasJoinAbove`, because the stuffings
do not answer it: an `INNER JOIN` stuffs neither side and replicates all the
same.

What the rule still does not weigh is the expression itself. Recomputing a
regular expression match over `limit` rows can cost more than carrying one
column, and `limit` reaches `query_plan_max_limit_for_lazy_materialization`,
which is why `preferRecomputing` says so in one place where a per-function
estimate can be asked once there is one. Note that before this whole change
nothing was ever recomputed: `ActionsDAG::split` partitions the nodes, so the
old plan computed every value exactly once and carried the intermediate ones.

Dropping the cost comparison also removes the copy of the frontier it needed.
Placing a value can only fail for the value itself - a source with no second
read, a stray input, an `arrayJoin` - because what it reads is placed on its own
terms and the worst those come to is a column that crosses. So the question is
local, `canBePlacedAbove` answers it before anything is written, and nothing has
to be rolled back.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two things were not provably linear. `cross` walked everything below the value
to mark it as computed below the `LIMIT`, once per crossing value, so a plan
with many of them did that work again and again. It now stops where the marking
already reached, which makes the whole run linear: a value is marked once, and
only a value being marked has its own children looked at.

The placement itself was mutual recursion over the DAG, which is both harder to
follow and a stack depth ClickHouse expression DAGs can reach - `ActionsDAG`
walks its own nodes with an explicit stack for that reason. It is now one
iterative walk: `decide` answers for a value on its own, and only a value to be
recomputed goes on the stack to wait for what it reads. Each value is decided
once, each edge walked once.

Writing the decision out in one place also showed that the source-column case
answers *how* to have a value above the `LIMIT`, not *whether* to: reading a
column a second time competes with letting it cross on the same terms as
recomputing does, and the sort keys still cross for free. The frontier came out
identical on the plans this was checked against.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review of the merged plan DAG, five points.

A step whose expressions cannot be represented is no longer the end of the
build. It becomes a source, the same way an aggregation or an exchange already
did, so the walk stops there and everything above it can still be deferred.
That matters most at a join: with an `arrayJoin` on one side, the whole plan
used to be given up on, while now the other side is still a source whose heavy
columns are read lazily. `buildMergedPlanDAG` therefore always answers, and the
worst answer is one source with no expressions, which a caller finds nothing to
defer in. Reading columns from below an `arrayJoin` is a separate question - the
row index would be replicated along with every other column, which is what the
transform already sorts out for a join - and the comment says so where the walk
stops.

`makeOpaqueSource` was an unhelpful name for that: `startDAGFromSource` says
what it builds, and the comment says what a source is rather than leaving
"opaque" to carry the meaning.

The header check that follows each step now says why it is there: it fails only
if the DAG stopped reproducing what a step produces, which would mean optimizing
on a wrong model of the plan, so that step becomes a source too.

Joining two subtrees no longer renumbers anything. The stuffings are a list, so
they splice, and a value points at its stuffing rather than indexing it, so the
map merges as it is. What has to stay a vector is `sources`, since a `BitSet`
of source indices reads it positionally.

Both per-join sweeps are gone. A join gates the values on a side it can leave
unmatched that no join below already gated, so each side carries the ones still
ungated and every value is visited once over the whole build. And a value has a
join above it exactly when it was created before the outermost join, so that
set is filled once at the end from a single mark rather than at every join -
the join's own values are excluded, since a join does not replicate what it
computes itself, and a higher join marks them in its turn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`optimizeLazyMaterialization3` is asked first when
`query_plan_lazy_materialization_from_merged_dag` is on, and the existing path
is asked whenever it declines, which is every plan for now. Keeping the two
side by side means the new decision can be compared against the old one query
by query, and nothing moves until it earns it.

What it does today is the deciding: the gates, the merged DAG for the subtree,
which sources a second read can reach, and the frontier over them. What it does
not do yet is rebuild the plan, and the reason is worth writing down, because
it asks something of the merged DAG that is not there.

The main branch cannot be one expression over the whole subtree. A filter
decides which rows the steps above it ever see, so computing something below it
that the query computes above it can throw where the query does not - `where
x != 0` followed by `intDiv(1, x)` is the short case. The rebuild therefore has
to walk the original steps in their own order and take from each the values the
frontier puts below the `LIMIT`, which means knowing which step each value of
the merged DAG came from. The builder has that while it merges and currently
drops it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`query_plan_lazy_materialization_from_merged_dag` named the mechanism;
`query_plan_lazy_materialization_for_join` names what it is for. It is on by
default, which changes nothing yet: `optimizeLazyMaterialization3` still
declines every plan, and the existing path is asked whenever it does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The plan cannot be rebuilt from the merged DAG as one expression, because the
steps it came from are not interchangeable: a filter decides which rows the
steps above it ever see, so computing something beneath it that the query
computes above it can throw where the query does not - `where x != 0` followed
by `intDiv(1, x)`. So what the frontier decides about a value has to be carried
out in the step that computes it, and the builder now keeps that: for every
value, the plan node whose step computes it and the node of that step's own DAG
it is a copy of. The mapping was at hand while merging and was being dropped.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`rebuildWithOneSource` carries out the frontier for a `Limit -> [Sorting] ->
chain -> read` subtree. It is not called yet - plans reading one source stay
with `optimizeLazyMaterialization2` - but it is the part of the rebuild the join
case is built on, and it was checked against that path: with it enabled, 34 of
the 37 lazy materialization tests and 137 of 150 sorting, limit, `PREWHERE` and
`FINAL` tests gave the same output as with the old path, and the rest were
artifacts of running a test twice on one server (query log windows, row
policies and Keeper state left by the first run).

The main branch is rebuilt step by step rather than as one expression, since a
filter decides which rows the steps above it see. Each step keeps the outputs
something below the `LIMIT` needs, found through the per-step node mapping of
the merged DAG, and consumes whatever the original step consumed, so the
columns passing it by stay the same. A value that crosses the `LIMIT` is
exported by the step computing it as `__lazy_crossing_<n>_<original name>`, a
name nothing else can consume, and a projection under the sorting hands over
exactly the sort keys, those values and the row index. Above the `LIMIT`, the
chain's outputs are computed again from what crossed and what the lazy read
returned, by `foldActionsByProjection`.

A read keeps more than it is asked to - `PREWHERE` and row policy inputs,
virtual columns, the inputs of an object storage `DEFAULT` expression - and for
object storage that cannot be predicted. So everything is decided before the
first change, and a column the frontier meant for the lazy read that the main
read kept anyway crosses instead. That is what makes a query selecting
`_part_offset` work: the virtual column is read eagerly for the row index, and
crosses for the result.

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

A value computed from the side of an outer join that can be left unmatched is recomputed above the
`LIMIT` as `if(mask, value, default)`, which evaluates it on the stuffed rows as well. The chooser now
allows that only for a function that is not suitable for short-circuit evaluation - cheap and never
throwing - and only where the caller has a mask for that join; any other such value is computed below
the `LIMIT` and crosses. Aliases and lazily read columns need neither.

The merged DAG also gates the values a join computes before joining, from one side, by that side's
stuffing, and records that a join sits above them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`LazyMaterializingTransform` and `JoinLazyColumnsStep` take the name of the row index column, so that
several sources can each have one. A `Nullable` index is NULL at the rows a join left unmatched: the
transform reads only the matched rows and stands the defaults at the others.

`JoinStepLogical::addPassThroughColumn` passes a column of one side through the join unchanged, which
is how a source's row index gets past the joins above it.

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

The conversion of `JoinStepLogical` to physical steps was deferred until after `applyParallelReplicas`
only with parallel replicas. It is deferred for every plan now, which gives
`optimizeLazyMaterialization3` a place to run while the joins are still logical and after PREWHERE
optimization, which needs a filter right above the read. It is not run for plans whose parts run
elsewhere, since the lazy read has to run where the main one does. The late lazy materialization
traversal asks only `optimizeLazyMaterialization2` now.

`optimizeJoinLazyIndexing` recognizes physical joins only, so it runs after the conversion as well.
The runtime filters are now pushed down while the joins are logical, so what the conversion adds
around the joins is merged afterwards. That merges an expression PREWHERE optimization left as well,
and four `EXPLAIN` references show one expression step less or a node id one higher.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`optimizeLazyMaterialization3` now rebuilds `Limit -> Sorting -> tree of Expression, Filter and
JoinStepLogical -> sources`. The main branch is the same tree, step by step: each lazily read source
adds its row index `__global_row_index_<n>` above the read, `Nullable` below a join that can leave the
source unmatched, and the joins pass it through with `addPassThroughColumn`. Above the `LIMIT`, one
`JoinLazyColumnsStep` per such source reads its deferred columns by that index, and the values the
frontier recomputes are computed from what crossed and what was read.

A step keeps a value under its own name only where something below the `LIMIT` reads it under that
name, so a crossing column does not travel up twice. A join is pruned to the columns it still reads,
and a side hands it exactly those plus the columns this rebuild added below.

The single-source rebuild is removed: plans reading one source stay with
`optimizeLazyMaterialization2`. Not handled yet, and declined: plans without ORDER BY, FINAL, and a
crossing value a join computes itself - which includes every recomputed value an outer join can stuff,
until masks are implemented.

A read whose columns were moved to a lazy read is not replaced by a projection any more: the lazy read
addresses its rows by part offsets.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A value computed from a side an outer join can leave unmatched is recomputed above the `LIMIT` as
`if(mask, value, default)`, which is what the join stands there. The mask of such a stuffing is
`isNotNull` of the row index of a MergeTree source it stuffs directly: that index is NULL exactly at
the rows it, or a join above it, left unmatched. A source used for a mask gets its row index even when
nothing of it is read lazily. The frontier is told which stuffings have a mask, and recomputes under one
only a function that cannot throw; any other such value still crosses the `LIMIT`.

The expression above the `LIMIT` is built by a fold of its own now, since
`ActionsDAG::foldActionsByProjection` cannot wrap a value. This makes lazy materialization apply to
outer joins with `join_use_nulls`, where every column of the stuffed side goes through `toNullable`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A `BuildRuntimeFilter` step above a read made the merged DAG stop there, so the build side of such a
join was never read lazily. The step passes its input through and only reads its key by name, so the
merged DAG looks through it now and records the key in `step_read_nodes`. The frontier computes those
values below the `LIMIT`, and the rebuild keeps them under their own names - for a multi-key
`ANTI JOIN` the key is a temporary tuple column nothing else reads. The rebuild puts the step back on
top of the rebuilt side.

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

The main branch was built from new steps, and every value crossing the `LIMIT` was exported under a
name of its own (`__lazy_crossing_<n>_...`), because a column keeping its name could clash with
another of the same name on its way up. Now the main branch is the original plan with fewer columns:
each step keeps its own expressions and names, and `removeUnusedColumns` takes away, top-down, what
nothing below the `LIMIT` needs any more. A column a read keeps anyway, such as a PREWHERE input, is
simply not read lazily, and crosses under the name the plan gives it.

A crossing value that no step would carry up to the top is added as an output of the step computing
it, of every step above that used to consume it (`JoinStepLogical::addInputToOutputs` for a join), and
passed through the joins it newly reaches. Where the only thing above the `LIMIT` reading a crossing
value is a node computed from it alone - the analyzer's rename of a table column, the `toNullable` of
`join_use_nulls`, a subquery's output - that node crosses instead, as the column the rest of the plan
knows. A column of the same name with another value on the way makes the pass decline.

`ReadFromMergeTree::getLazilyReadColumns` and `ReadFromObjectStorageStep::getLazilyReadColumns` say
which columns a lazy split would move without moving them, so the pass knows what each read keeps
before it changes anything. The expression above the `LIMIT` binds its columns by position, so two lazy
reads of columns with the same name need no renaming either; only the row indexes and the masks have
names of their own.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Which row FINAL keeps is decided by the sorting key, the version and the is_deleted columns, so those stay
in the main read, and the rest of the row FINAL kept is read after the `LIMIT` by its row index - the
same conditions `optimizeLazyMaterialization2` applies to its one source. A merge column the frontier
wanted read lazily crosses the `LIMIT` instead.

Lazy FINAL runs later and can replace the same read. The two compose: the set-based branch of lazy FINAL
reads `_part_offset` and `_part_starting_offset` of the rows it keeps as well, so the row index stays
consistent across the parts it splits. Where the filter is not in PREWHERE, lazy FINAL no longer applies
to a read split here, because the row index is computed between the read and the filter.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Master changed two interfaces this branch uses: `canUseProjectionForReadingStep` returns
`std::expected<void, std::string>` now, and `BuildRuntimeFilterStep` takes `RuntimeFilterBuildOptions`.

The expressions merged after the conversion of the joins lost their descriptions, because the merge got
a default-constructed `ExtraSettings`, whose `max_step_description_length` is zero; it gets the real ones
now. The two `EXPLAIN` references that change with this branch are regenerated: the runtime filters are
pushed down while the joins are logical, so a few more expression steps are merged.

Also fixes two clang-tidy findings, `performance-no-automatic-move` in `ExpressionStep` and
`modernize-loop-convert` in `mergedPlanDAG`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122682&sha=6ae738144b6343c763e05b0e71b4dad5e64acd3b&name_0=PR
PR: #122682

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

With runtime filters, the expressions around the converted joins are merged after the conversion, which
in a distributed plan also merges `Before GROUP BY` with the `WHERE` expression below it inside a
fragment. The plans are otherwise the same.

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

Co-Authored-By: Claude Opus 5.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]>
`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]>
`ColumnSparse::expand` wrote the new positions of the non-default values
into an empty copy of the offsets - out of bounds - and then kept the old
offsets, so after expanding, the values stood at their old positions and
only the size grew. Lazy materialization over a join expands the columns
of the lazy read by the rows the join matched, and with sparse columns
(`ratio_of_defaults_for_sparse_serialization = 0`) a row of the side a
join can leave unmatched got the values of another row.

The new offsets now go into a copy of the old ones, which the iterator
still reads, and replace them; a mask with too few set bytes is rejected
as for the other columns.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`LazyMaterializingTransform` read the row index as `ColumnUInt64` after
stripping only `Const`. A join hands its columns over as
`ColumnReplicated`, and without ORDER BY no sorting materializes them on
the way to the lazy read, so the cast read garbage and the server crashed.
All representation wrappers are stripped now.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
KochetovNicolai and others added 21 commits October 15, 2026 16:49
`assemble` and `copiesOfCarriedColumns` looked through every carried value for the ones
of each node. They are kept by node now, and only the copies crossing the `LIMIT`, whose
order has to be the same every time, are kept in a list in the order of the values.

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

A join that reads nothing of a side keeps a column of it, which then stays in the main
read. For an object storage read, a column whose `DEFAULT` is computed from it stays
there as well, but only the kept column was taken out of the lazy read, so the lazy read
did not read the columns it was chosen for: `LOGICAL_ERROR` for
`SELECT o.k, o.payload, m.k, m.heavy FROM o CROSS JOIN m LIMIT 2` with
`payload String DEFAULT toString(k)`. The object storage read is asked again which columns
it can leave to its lazy read, until nothing more stays in the main read.

Related: #122682 (comment)

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

The pass checked whether the current optimization makes a distributed plan, which is false
for a plan that has its exchanges already and is optimized again, so it could add lazy
steps that cannot be sent to the workers. It checks `make_distributed_plan` of the
settings now, as the other lazy materialization does.

Related: #122682 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The stateless test ran `sleepEachRow` against a cap that three repeated evaluations did
not reach, so it passed without the fix. Only the sleep functions have observable side
effects, so the unit test of the frontier checks the placement of `sleepEachRow` instead,
which it never runs, and the stateless test keeps the short-circuit case.

Related: #122682 (comment)

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

`step_mappings` was filled but no longer read since the carried values are copies.
`collectLazyReads` was used by the unit test only; the rebuild picks the lazy reads with
the reads themselves in `chooseLazyReads`.

Related: #122682 (comment)
Related: #122682 (comment)

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

A block of totals goes through the joins up to the `LIMIT` with no rows to read lazily,
so it reached the expression above the `LIMIT` without the lazily read columns:
`NOT_FOUND_COLUMN_IN_BLOCK` for a `LEFT JOIN` of a subquery with `WITH TOTALS`. A value
computed below a join is also that join's default in the totals row, which recomputing it
above the `LIMIT` would not give. The rewrite is declined where a step under the `LIMIT`,
in an opaque source too, is a `TotalsHavingStep` or a remote read, whose query can have
`WITH TOTALS`.

Related: #122682 (comment)

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

The check for a source that can produce a block of totals walked the children of the
steps only. A view with `SQL SECURITY DEFINER` is read as a sealed plan the step owns,
and so are the plans of the tables of a `Merge` table, so `WITH TOTALS` in such a view
still reached the expression above the `LIMIT` without the lazily read columns:
`NOT_FOUND_COLUMN_IN_BLOCK`. The check goes into `getChildPlans` as well.

Related: #122682 (comment)

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

A direct join reads its right table from a `JoinStepLogicalLookup`, which the physical
join finds only as its immediate child. A column of the right side crossing the `LIMIT`
added a step with its copy above the lookup, so the direct join could no longer be built:
`None of the algorithms enabled by the 'join_algorithm' setting [direct] can execute this
ALL INNER JOIN`. A join with a lookup child is not entered by the merged DAG any more, and
is a source as a whole.

Related: #122682 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Each column a lazy read returns was bound to the first input of its source with the same
name, and to nothing when no input matched. Two inputs of one name were both bound to
the first column, so the second had no slot above the `LIMIT`. A column is bound to the
next unbound input of the lazy read with its name now - inputs of one name are one column
of storage - and a column no input was chosen for is a `LOGICAL_ERROR`.

The comment of `Placement::None` says what it stands for.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- `MergedPlanDAG::getSourceOfInput` holds that every input reads exactly one source, and
  `findSourceOfInput` and `keepColumnsOfUnreadJoinSides` use it, instead of tolerating or
  checking it each.
- `findPaddedSides` returns the array the caller needs; the step branches of
  `tryBuildFromStep` share their tail, the check of the header and `step_outputs`.
- `FrontierChooser::isBlockedByPadding` is the one check of a value a join can pad and that
  cannot be recomputed under a mask.
- `Assembled::has_added_step_on_top` says that a step of this rebuild is on top of a subtree,
  instead of a set of the pointers to those steps; `assembleSource` makes its copies with
  `addCopiesOfCarriedColumns`.
- `JoinPlanRebuild` gets `chain_top` and the sort key positions once, in its constructor;
  `sort_key_nodes` is local to `prepare`; a lazy read says whether it is of MergeTree or of
  object storage; `chooseLazyReads` leaves the check for no lazy read to its caller.
- `optimizeLazyMaterialization3` takes the maximal `LIMIT` from the settings, declines for
  one source before the frontier is chosen, and requires a context where masks are computed.
- Two unused includes are removed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The branch for a join was about 160 lines. It is the sequence of `uniteRightSide`,
`gatePaddedSides`, `trackPreJoinNodes`, `collectJoinConditions` and
`collectUnreadJoinSides` now. `collectJoinConditions` fills the filters and the join
conditions in one loop over pairs of a list and its target, and finds the sides they read
in the same pass. A node of the join's own DAG is looked up with `cloneOf`, which throws
`LOGICAL_ERROR` for a node without one: the keys were looked up with `at` in one place
and with a `find` that declined in another, which could not happen.

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

`apply` followed what each column of the block holds in two parallel vectors, a value or
null, and the name of a row index, and found the row index of a lazy read by its name. It is
one vector of `Slot`s now - a value, the row index of a source, or the mask of a source - and
the row index is found by its source. The positions of the masks are taken once, after the
lazy reads, so they no longer have to be moved down for each row index a lazy read takes.

The carried values are kept once, in the order of the merged DAG, with the indices of each
node's in a map, instead of by node and again as a list of copies; `prepare` collects them in
one pass. The sources with a row index and the sources with a mask are sets of sources, as
the names follow from them, and the nearest padded side of a source is
`MergedPlanDAG::getNearestPaddedSideOfSource`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`canEvaluateOnPaddedRows` asked `IFunction::canThrow`, which falls back to whether the
function is worth evaluating lazily when it does not say whether it can throw. `toBool` is
cheap but throws for an empty string, so `toBool(s)` of the side of a `LEFT JOIN` was
recomputed above the `LIMIT` under the join's mask, evaluated at the unmatched rows, and
failed with `CANNOT_PARSE_BOOL`. It asks `IFunctionBase::canThrow` now, which assumes a
function that does not say to throw.

`toNullable`, `toTypeName` and `identity` say that they cannot throw, so that the values of
a padded side under `join_use_nulls` are still recomputed above the `LIMIT`.

Related: #122682 (comment)

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

A join that reads nothing of a side keeps a column of it for the number of rows: the
first of its inputs from that side, unless another one is needed above it. The merged DAG
imitated this rule, and took any input of the side computed below the `LIMIT` as needed.
Under `l INNER JOIN t ON l.y = t.y CROSS JOIN r`, `y` is computed below for the inner join
only, so the outer join kept `x`, which was meant for a lazy read: `LOGICAL_ERROR`
`Column x of source 0 is read lazily, but needed below the LIMIT`.

`prepare` now runs the pruning `assemble` runs, `getUnneededColumns` top-down, which only
analyzes, and moves to the main read a column meant for a lazy read that a read keeps
there; the carried values are collected again, and this goes on until the pruning keeps
none of the columns read lazily. That covers every step that keeps a column of its own,
by position. `keepColumnsOfUnreadJoinSides` and `MergedPlanDAG::unread_join_sides` are
removed.

Related: #122682 (comment)

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

`prepare` repeated the check until it kept nothing more, but a second round cannot find
anything: a column a read keeps in the main read is an input of the merged DAG, so its copy
is made at that read, which only keeps the column it already keeps, and changes nothing
above the read or at another read. The check runs once, read by read, and the carried
values are collected again after it.

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

Resolve the conflict in the reference of `04105_limit_by_into_sort_explain`:
take the new pipeline layout of the spill-capable hash join from master,
and keep the removed redundant `Expression` above the left read from this branch.

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

Lazy materialization support for JOIN
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Oct 20, 2026
@robot-clickhouse-ci-1
robot-clickhouse-ci-1 merged commit 2ce4da8 into backport/26.10/122682 Oct 20, 2026
1 check passed
@robot-clickhouse-ci-1
robot-clickhouse-ci-1 deleted the cherrypick/26.10/122682 branch October 20, 2026 10:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants