Repository navigation
Lazy materialization support for JOIN - #122682
Conversation
d541981 to
6ae7381
Compare
|
Workflow [PR], commit [ebe13fd] Summary: ✅
AI ReviewSummaryExtends lazy materialization to joined queries with Missing context / blind spots
Findings❌ Blockers
Final Verdict❌ Block. Preserve dependent default values across the read split, respect requested projections, and introduce the experimental opt-in gate before enabling this strategy broadly. |
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]>
Build profile diff (arm_release)Commit See the job log for details. |
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]>
e8d7eca to
5c34df8
Compare
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]>
| Use lazy materialization optimization for reading local Parquet files with the `file` table function and the `File` table engine: for `ORDER BY ... LIMIT n` queries, the columns that are not needed for sorting and filtering are read only for the `n` rows that survive the `LIMIT`. Takes effect only if `query_plan_optimize_lazy_materialization` is enabled. | ||
| )", 0, \ | ||
| {"26.8", false, true, "New setting to use lazy materialization for `ORDER BY ... LIMIT n` queries reading local Parquet files with the `file` table function and the `File` table engine."}) \ | ||
| DECLARE(Bool, query_plan_lazy_materialization_for_join, true, R"( |
There was a problem hiding this comment.
[P1] Make the new join rewrite an experimental opt-in
This default enables a new execution strategy for existing queries: merged-DAG placement, recomputation across joins, outer-join masking, and plan reconstruction. Reusing the existing lazy readers does not validate those new semantics. There are still valid-query regressions in this path, including the padded toBool exception and nested INNER JOIN/CROSS JOIN reconstruction exception identified in this review.
Please initially declare query_plan_lazy_materialization_for_join with default false and the EXPERIMENTAL flag, and align its compatibility history and changelog entry. That gives the new strategy the required opt-in rollout gate while its join semantics are being stabilized.
`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]>
| { | ||
| const auto storage_position = pruning.storage_position_of_output.at(position); | ||
| if (storage_position && std::ranges::binary_search(pruning.dropped_storage_positions, *storage_position) | ||
| && !virtuals.has(all_column_names.at(*storage_position))) |
There was a problem hiding this comment.
[P1] Preserve dependent missing-column defaults across the read split
This classifies a column as independently readable without checking its DEFAULT dependencies. For an older part missing both n DEFAULT rand64() and s DEFAULT toString(n), the join rewrite keeps n eager when a filter needs it but reads s lazily. The lazy reader has no access to the already generated n, so filling s evaluates rand64 again and breaks n = toUInt64(s) within the same result row.
CREATE TABLE l (k UInt64) ENGINE = MergeTree ORDER BY k;
CREATE TABLE r (k UInt64, payload String) ENGINE = MergeTree ORDER BY k;
INSERT INTO l SELECT number FROM numbers(1000);
INSERT INTO r SELECT number, toString(number) FROM numbers(1000);
ALTER TABLE l ADD COLUMN n UInt64 DEFAULT rand64();
ALTER TABLE l ADD COLUMN s String DEFAULT toString(n);
SELECT l.k, l.n = toUInt64(l.s) AS same, r.payload
FROM l JOIN r ON l.k = r.k
WHERE l.n % 2 = 0
ORDER BY l.k LIMIT 20
SETTINGS query_plan_lazy_materialization_for_join = 1,
optimize_move_to_prewhere = 0,
query_plan_join_swap_table = 0,
query_plan_optimize_join_order_limit = 0,
enable_join_runtime_filters = 0,
enable_parallel_replicas = 0;Reproduced with the CI binary for 7a99f4bfd: disabling the setting gives same = 1 for all 20 rows; enabling it gives same = 0 for all 20. The relevant split logic is unchanged at this head.
Keep dependent default expressions in the same read as their eager inputs, as the object-storage split already does, or pass those generated inputs into the lazy evaluation. Please add an on/off regression over a part created before the columns were added.
Cherry pick #122682 to 26.10: Lazy materialization support for JOIN
Backport of #122682 with `query_plan_lazy_materialization_for_join` off by default. The settings history says the setting was added in 26.10 with `false`; master enables it in 26.11. - The new tests of the feature set `query_plan_lazy_materialization_for_join = 1` themselves, as their `EXPLAIN` checks counted on the default. - `join_lazy_indexing.xml` is back to the 26.10 version: it pinned the setting off only because it was on by default, and the server it is compared with does not know the setting. - The reference of `04105_limit_by_into_sort_explain` is the 26.10 one with only the change of #122682 (one `Expression` less above the left read); the rest of the master reference came from a change that 26.10 does not have. Related: #122682 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Backport #122682 to 26.10: Lazy materialization support for JOIN
Lazy materialization over joins stopped at an `ArrayJoinStep`: the subtree below it, a `FINAL` read included, became one source, so none of its columns were read lazily. An `ARRAY JOIN` repeats each row once per element, as a join repeats the rows that match several times, so it is looked through now: - `ArrayJoinStep` takes part in removing unused columns. Each column of its input is the column of its output at the same position; the step keeps the ones it reads, the array joined columns and the inputs of its element filter. - The merged plan DAG represents the step by `ArrayJoinStep::toActionsDAG`, and counts it as a join above the values below it. An unaligned `ARRAY JOIN` and a step with an element filter are not looked through. The frontier already computes the elements below the `LIMIT`. - The row index of a lazily read table is repeated with the rows, which the lazy read handles as for a join. - A carried value can be copied from an output that is an alias of it: the step outputs its elements as aliases of the `arrayJoin` nodes. On a reproducer of a customer query, `FINAL` + `ARRAY JOIN` + `JOIN` + `LEFT JOIN` with `LIMIT 100` (`max_threads = 4`): 7.57 s, 22.1 GiB read, 625 MiB of memory with the feature off, and 4.95 s, 10.1 GiB, 323 MiB with it on, with the same result. Related: ClickHouse#122682 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude
Related: #122952
Lazy materialization so far worked for one table: for ORDER BY ... LIMIT n, the columns that the sort and the filters do not need are read only for the n rows the LIMIT returns. This PR extends it to LIMIT n queries over joins, with or
without ORDER BY. Then the heavy columns of the MergeTree tables (and of object storage tables, with query_plan_optimize_lazy_materialization_for_object_storage) are read only for the rows that survive the LIMIT, not for every row the
joins produce, replicate and keep in their hash tables.
How it works:
value used by a filter below and by the result above is recomputed above rather than carried through every join. Values that cannot be recomputed - stateful, non-deterministic, with side effects, or a branch of a short-circuit
function that could throw - are computed where the plan computes them and carried.
a copy of its own (__lazy_carried_N). Above the LIMIT, one JoinLazyColumnsStep per such read fetches the deferred columns by the row index, and the deferred values are computed from them.
replicas and distributed plans. Such a source is still a source for the other sides where possible: a join that cannot prune its columns, or a read that cannot be split, does not stop the other sides from being read lazily.
The new setting query_plan_lazy_materialization_for_join enables it (on by default). It takes effect only with query_plan_optimize_lazy_materialization.
A known limitation: the rewrite runs before projection selection, so a read whose columns are read lazily cannot use a projection.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Lazy materialization now works for
LIMIT Nqueries over JOINs. Controlled by the new settingquery_plan_lazy_materialization_for_join, enabled by default.Workflow [PR]
Sync PR [sync-upstream/pr/122682]
Version info
26.11.1.231-master(included in26.11and later)26.10.2.47