Repository navigation
Description
Describe the bug
When a filter on a projection's output is pushed below the projection, PushDownFilter replaces each column with its expression. If the filter uses that column in several OR branches, the expression is copied into each branch and evaluated once per branch, for every row.
With a few branches this is cheap. With hundreds of branches on a column computed by an expensive function, the filter does hundreds of evaluations per row instead of one.
Part of #25459 (Goal 4: "A rule does not duplicate an expensive expression").
To Reproduce
link to fiddle
CREATE TABLE t(s VARCHAR) AS VALUES ('a'), ('b');
SELECT u, v FROM (SELECT upper(s) AS u, lower(s) AS v FROM t)
WHERE (u = 'A' AND v = 'x') OR (u = 'B' AND v = 'y') OR (u = 'C' AND v = 'z');physical plan
ProjectionExec: expr=[upper(s@1) as u, lower(s@1) as v]
RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
FilterExec: __common_expr_3@0 = A AND lower(s@1) = x OR __common_expr_3@0 = B AND lower(s@1) = y OR __common_expr_3@0 = C AND lower(s@1) = z
ProjectionExec: expr=[upper(s@0) as __common_expr_3, s@0 as s]
DataSourceExec: partitions=1, partition_sizes=[1]
lower(t.s) is in the filter 3 times. upper(t.s) is computed once only because its first use is not inside an OR branch, so common subexpression elimination extracts it.
The same happens when the column contains a lambda (or any other function). Here neither expression is extracted, so both are copied into every branch (6 copies):
EXPLAIN SELECT u, v FROM (
SELECT array_transform(make_array(s), x -> upper(x))[1] AS u,
array_transform(make_array(s), x -> lower(x))[1] AS v
FROM t)
WHERE (u = 'A' AND v = 'x') OR (u = 'B' AND v = 'y') OR (u = 'C' AND v = 'z');Filter: array_element(array_transform(__common_expr_4, (x) -> upper(x)), Int64(1)) = Utf8View("A") AND array_element(array_transform(__common_expr_4, (x) -> lower(x)), Int64(1)) = Utf8View("x") OR array_element(array_transform(__common_expr_4, (x) -> upper(x)), Int64(1)) = Utf8View("B") AND ... (3 branches)
Projection: make_array(t.s) AS __common_expr_4, t.s
Expected behavior
Each projected expression is evaluated once per row, and the filter compares the resulting columns:
Filter: u = 'A' AND v = 'x' OR u = 'B' AND v = 'y' OR u = 'C' AND v = 'z'
Projection: upper(t.s) AS u, lower(t.s) AS v
TableScan: t projection=[s]
Additional context
Impact: We hit this with a UDF that parses a list of key:value strings into a map and reads one key, used in a filter with hundreds of (a = .. AND b IN (..)) OR .. branches. I ran a bench with 20K rows:
OR branches |
main |
expression evaluated once per row (*) | plain columns, no expression |
|---|---|---|---|
| 10 | 70 ms | 90 ms | 1.4 ms |
| 100 | 646 ms | 110 ms | 14 ms |
| 300 | 2.13 s | 199 ms | 85 ms |
(*) To get the optimal plan I measured by making the UDF return ExpressionPlacement::MoveTowardsLeafNodes, which stops PushDownFilter from inlining it. This is only an experiment: it also stops common subexpression elimination from sharing work between the projected columns, which is why 10 branches is slower.
Related work. None of these covers the cases above:
- fix: one inlining policy for the rules that inline a projection column #25456 defines one inlining policy ("Expensive: at most one site"), but in its current form it does not change
PushDownFilter. - fix: PushDownFilter and CommonSubexprEliminate reach a fixed point #26872 keeps a filter above a projection when it uses a
__common_exprcolumn more than once. Both queries above plan the same with fix: PushDownFilter and CommonSubexprEliminate reach a fixed point #26872: the copied expressions are never extracted into a__common_exprcolumn, so the guard does not apply. - Avoid duplicating keep-in-place expressions #25388 tried to stop
PushDownFilterfrom movingKeepInPlaceexpressions and was closed as stale. As noted in [EPIC] Leaf expression pushdown and filter pushdown: bugs, decisions and tests #25459,KeepInPlaceis also the default for cheap expressions, so it cannot be the signal on its own.
Is bringing PushDownFilter under the #25456 policy planned? One possible fix can be that when pushing a filter below a projection, if the filter uses a computed column (not a plain column or constant) more than once, keep the filter above the projection instead of copying the computation into each use. This fixes both queries above. Also, filters that use a computed column only once would still be pushed down as today, so they can still reach the scan.
Activity
pepijnve commentedon Nov 21, 2026
I dropped the attempt in #25388 because it seemed to have too many side effects that prevented other optimisations from working. I got a bit stuck trying to work out the exact semantics we want for the variants of
ExpressionPlacement. Due to lack of time we ended up disabling the "move towards leaf" optimisation pass altogether as quick "fix". I would like to see this resolved as well and I'm happy to help out with solutioning but I don't have the time right know to take the lead on this myself.pepijnve commentedon Nov 21, 2026
I was looking for the examples of optimisations that no longer worked; it's in the comments on the same PR.
If I interpreted "keep in place" stricter and made more expressions return it correctly it ended up preventing filter push down. That seemed like a dealbreaker to me.
pepijnve commentedon Nov 21, 2026
My work on
casehas probably biased my thinking a bit, so maybe the suggestion below is just a bad idea... 😄Looking at the expected/requested outcome of
I was thinking that
loweris a relatively cheap function. In a more general situation the second branch might be prohibitively expensive to evaluate for each row though. Could an optimisation that turns the pattern you're describing into something like this help?This could dovetail nicely with the #26609 and #27586 which are trying to make lookup table
caseexpressions quite cheap.It does sure look like you would want some kind of cost model to aid in deciding which variant is most appropriate though. Hard to know what'll end up being most efficient without knowing the complexity of the function being invoked.
pepijnve commentedon Nov 22, 2026
@adriangb posting the question here to try to consolidate various bits of information. In #25456 (comment) you stated that the PR was incorrectly heading in the direction of interpreting
KeepInPlaceas expensive and that that seems like a wrong interpretation. It it's the AI that was heading down that path, I think we might be leading it in that direction ourselves since the documentation statesSo the documentation is kind of saying this is a coarse grained cost model. If that interpretation is incorrect, then what would a more accurate description of these variants be? Apologies that I keep revisiting this question, I just haven't been able to come up with a proper answer myself.
pepijnve commentedon Nov 22, 2026
I fed all my notes and confusion into Claude and got back what I think is a useful analysis. At least it helps me better understand things. Does this analysis sound right?
Claude
I'd rename the enum to describe where an expression's value comes from, not where it should go. The names should then stop implying cost, as "keep in place" and "move towards leaf nodes" do today.
ExpressionPlacementExprProvenanceLiteralConstantColumnInputColumnMoveTowardsLeafNodesSourceProvidableKeepInPlaceComputedshould_push_to_leaves()is_column_like()placement()provenance()Why these names
Constant, notLiteral: consumers mean "a value known at planning time." get_field needs constant keys, and the alias case already looks through to the inner expression. Literal names one particular syntax; this is about behaviour.InputColumn, notColumn: #25329 happened because__common_expr_1is a column too, but it's bound to an expensive UDF. The name should make clear the claim is only "this refers to an input column," not "this is cheap base-table data."SourceProvidable, notMoveTowardsLeafNodes:VirtualColumn(the industry term for file metadata, but awkward for struct fields) orSourceColumn(shorter, but easily confused withInputColumn).Computed, notKeepInPlace: this is the change that matters most. Today's name and docs ("an expensive expression") are why #25388, #25456 and #27631 all ended up reading it as a cost tier. Computed says only that the engine has to evaluate it.Doc points that matter more than the names
On
ExpressionPlacement: state that this is not a cost model, and that rules deciding whether copying is acceptable should use a reference-count guard (asoptimize_projectionsandmerge_would_duplicate_kept_exprdo) or a separate cost signal.On
SourceProvidableandScalarUDFImpl::placement: write the contract down. Returning it promises:It must never be produced by combining child values, as reduce in #25388 did.
On
Computed: it's the default, and changing an expression to or from it changes which rules apply to it, not how expensive it is assumed to be.Making the change
Renaming a public enum and a
ScalarUDFImpltrait method (which is also exposed through FFI) is a breaking API change. Under the API health policy it needs a deprecation path. I'd do it in two steps:LiaCastaneda commentedon Nov 23, 2026
Yes I think it would help, especially with hundreds of branches. I'm less sure about rewriting the filter itself into a CASE lookup though, not sure how well DF would handle the
CASE(like for example in a filter pushdown to scans we would need to translate the CASE), also it only supports equality predicates. Another option that comes to mind is having a pre filter from the OR:yeah I think that would be the ideal solution, but today we can't tell which functions are expensive and which are cheap. I think some kinds are a reasonable default for "expensive" though, for example lambdas run once per array element, so I don't think duplicating them is ever worth it. Maybe we can start with a fix that doesn't need a cost model, or only a very simple one. For reference here's how other engines handle this:
Trino - inlines only constants and plain column references, functions are not inlined.
postgres -- doesn't inline as well if the function is used more than once. You can also specify the cost of a function when creating it
In Spark they don't inline if the expression is expensive, every expression holds a variable to decide if its expensive, by default I think most of the functions are expensive.
Calcite inlines the expressions only if that adds at most >100 expressions
Most of them seem to use some notion of cost, but we could do something simpler and less breaking like calcite or trino
adriangb commentedon Nov 24, 2026
The original intention was that
MoveTowardsLeafNodeswould be "potentially much much cheaper to evaluate during a scan and never much more expensive" (because e.g. we can read only some struct fields, or in the case of variant can check if the fields are shredded) and forKeepInPlaceto be "leave it alone, we don't know if it's cheap or expensive". Evidently this is some sort of cost model. When we looked at struct field access specifically it was pretty clear cut: a metadata only operation clearly fits any definition ofMoveTowardsLeafNodes. The file/row functions also fit this bill and use the same mechanisms (#27669). It gets a bit more questionable with something likevariant_get: if a field is not shredded there is some work that will be done that technically could be cheaper if done after a filter.So the intention was to have some sort of really stupid cost model along the lines of "expensive or unknown" vs. "opted into / know to be cheap". But that gets a bit confused with "cheap -> should push it into scan". Maybe what we ware looking to express is "this expression is best evaluated by a scan"? I think this sort of simplistic cost model aligns with what Lía's research in #27631 (comment) shows (e.g. Spark has an "is expensive" boolean).
Regarding #27631 (comment): I'm happy to go down this path, the names you propose do make sense. I do worry about breaking API changes, but I see you propose doing docs first. Maybe it would help to list out current / proposed consumers of these APIs? Off the top of my head:
Are there any I'm missing that you can think of?
pepijnve commentedon Nov 24, 2026
I think I gave the wrong impression that this was a concrete suggestion for action. It's Claude blabbing. I mainly wanted to get confirmation if the interpretation it came up with aligned with what you had in mind when you added the functionality. The suggestions the robot gave seemed interesting so I included them as well. I share your concern about API breakage.
LiaCastaneda commentedon Nov 25, 2026
Looks like this is treated differently in different optimizer rules though 🤔 For example:
OptimizeProjectionsand CSE treat aKeepInPlaceexpression as "could be expensive" and thenOptimizeProjectionswon't merge projections if that would duplicate it, and CSE computes it once.PushDownFilterdoes the reverse: it treatsKeepInPlaceas "could be cheap" and inlines the expression into the filter, once per reference.So
PushDownFilterseems to be the only rule that duplicatesKeepInPlaceexpressions, with no limit on how many copies it can make.I think this would bite in some cases though, If
Computedmakes no claim about cost then a rule like "never duplicate aComputedexpression" can't tell cheap expressions likecol + 1or aCASTapart from an expensive UDF or a lambda, then copying is actually the better choice when the expression is cheap, here are some examples:iiuc this is part of the reason why #25388 was dropped.
Alternatively, if we had something more granular like Spark's
is_expensiveflag, we could avoid these regressions, because cheap expressions would be explicitly marked as cheap and could still be copied.Another (short-term, non-breaking) option I was thinking of is that for each conjunct of the pushed filter, count references to each
KeepInPlacecolumn. if the num of references < n, inline as today, if its above n, compute it once and filter on the column. The cases above would still regress if a single conjunct referenced them more than n times, but filters like that should be rare I think.adriangb commentedon Nov 25, 2026
Maybe I'm missing something here: Spark has a boolean, we have an enum w/ 2 options (naming and confusion aside). How is the boolean more granular?
LiaCastaneda commentedon Nov 26, 2026
I think the "granular" word was imprecise. The thing is that I think the enum values are deciding two things at once, which is where an expression is evaluated and whether if it's okay to copy it into a filter. Expressions like
CASTandarray_transform()need the same placement (KeepInPlace) since pushing them to the scan is wasteful, but they have opposite answers on copying which the KeepInPlace/MoveTowardsLeafNodes enum can't differentiate.For example with a filter like
CAST(col) > 5if we markCASTasMoveTowardsLeafNodes(because it's cheap), the cast will get computed for every row before filtering. I think that would be a regression since we waste work casting values that get filtered out afterwards. TodayCASTisKeepInPlacewhich is nice becauseCAST(col) > 5gets unwrapped tocol > 5that gets pushed to the scan, and the CAST only runs on the already filtered data.KeepInPlace:
MoveTowardsLeafNodes:
But
array_transform(...)(or any other expensive expression) is alsoKeepInPlace, soPushDownFiltertreats it the same way and copies it into every branch of the filter which is an issue when there are too many branches (the repro in this issue). For that one we'd want the opposite which is keep its placement but don't duplicate it. None of the enum values mean "normal placement but don't copy" so I think we'd need something like Spark's boolean which is independent of placement.KeepInPlace:
MoveTowardsLeafNodes
MoveTowardsLeafNodes does avoid the copies in this case, but I don't think we can mark lambdas with it because it means "this is cheap and its best evaluated at the source"
LiaCastaneda commentedon Nov 26, 2026
Anyhow maybe I'm missing something here and adding a separate flag is too much if it only fixes this issue. Happy to go with something smaller if there's a better option (I'm still getting my head around how these optimizer rules interact)
akshatsinghrajawat commentedon Nov 30, 2026
I traced this through
rewrite_projection. The filter is split into top-level AND-conjuncts before reaching it, so an OR expression stays as one predicate.replace_cols_by_columnthen substitutes the projected expression at every reference. So Lia's reference-count idea should catch the reported case.One gap I see is that counting references separately in each conjunct could miss repeated uses across different conjuncts. For example,
WHERE u > 10 AND u < 20has one reference touin each conjunct, but pushing both can still inline its definition twice.Would it make sense to count references to each projected output across the full set of predicates, and, when the count crosses a threshold, keep the conjuncts referencing that output above the projection while still pushing unrelated predicates? References in predicates that are already being kept should also be accounted for.
I also noticed that the draft of #25456 already introduces
ProjectionInliner, with shared column-resolution and reference-counting logic. Reusing that machinery seems preferable to adding another independent implementation. Its current duplication policy would need some thought, though: it allows repeated inlining of columns and leaf expressions, but that could also prevent duplication of cheap expressions likea + 1andCAST, which is exactly the regression Lia highlighted.I agree with Adrian's clarification that
KeepInPlacemeans the cost is unknown, not necessarily that the expression is expensive. I wouldn't use it alone as the duplication signal, especially given the problems with the earlier #25388 attempt.Would this broader reference-count approach be a reasonable first experiment?