Skip to content

PushDownFilter copies a projected expression into every OR branch of the predicate #27631

Open

Description

@LiaCastaneda

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:

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

  1. pepijnve commented on Nov 21, 2026

    @pepijnve
    Contributor

    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.

  2. pepijnve commented on Nov 21, 2026

    @pepijnve
    Contributor

    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.

  3. pepijnve commented on Nov 21, 2026

    @pepijnve
    Contributor

    My work on case has probably biased my thinking a bit, so maybe the suggestion below is just a bad idea... 😄

    Looking at the expected/requested outcome of

    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]
    

    I was thinking that lower is 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?

    Filter: case conditions1 when 0 then v = 'x when 1 then v = 'y' when 2 then v = 'z' end
      Projection: lower(t.s) AS v, *
        Filter: condition1 is not null
          Projection: case upper(t.s) when A then 0 when B then 1 when C then 2 end AS condition1, *
            TableScan: t projection=[s]
    

    This could dovetail nicely with the #26609 and #27586 which are trying to make lookup table case expressions 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.

  4. pepijnve commented on Nov 22, 2026

    @pepijnve
    Contributor

    @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 KeepInPlace as 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 states

    /// A cheap expression that can be pushed to leaf nodes in the plan....
    MoveTowardsLeafNodes,
    /// An expensive expression that should stay where it is in the plan...
    KeepInPlace,
    

    So 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.

  5. pepijnve commented on Nov 22, 2026

    @pepijnve
    Contributor

    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.

    Today Proposed Meaning
    ExpressionPlacement ExprProvenance Where the value comes from, in terms the optimizer can act on. Says nothing about cost.
    Literal Constant Known at planning time, the same for every row.
    Column InputColumn A plain reference to a column of the node's input, possibly aliased. Moving or copying it costs nothing.
    MoveTowardsLeafNodes SourceProvidable The data source can produce this value as if it were a column, e.g. a struct field or file metadata.
    KeepInPlace Computed The engine has to evaluate this. It's the default and makes no claim about cost or placement.
    should_push_to_leaves() is_column_like() True for InputColumn and SourceProvidable, the two kinds every merge guard treats as free to copy.
    placement() provenance() Same change on Expr, PhysicalExpr and ScalarUDFImpl.

    Why these names

    Constant, not Literal: 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, not Column: #25329 happened because __common_expr_1 is 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, not MoveTowardsLeafNodes:

    • It states the actual claim and covers both kinds of in-tree user: get_field on a column, and input_file_name/file_row_index, which must be produced by the source.
    • The optimizer's handling (extract it, push it towards the scan, don't deduplicate it, don't inline it into pushed filters) follows from the claim, so it belongs in the docs, not the name.
    • Alternatives: VirtualColumn (the industry term for file metadata, but awkward for struct fields) or SourceColumn (shorter, but easily confused with InputColumn).

    Computed, not KeepInPlace: 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.

    • Opaque is a reasonable alternative if you want to stress "the optimizer knows nothing more."
    • Either way, the docs should say outright that a + 1 and CAST(c) fall here, and that duplication cost is a separate question.

    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 (as optimize_projections and merge_would_duplicate_kept_expr do) or a separate cost signal.

    On SourceProvidable and ScalarUDFImpl::placement: write the contract down. Returning it promises:

    • the expression depends on columns from at most one input
    • it is safe to evaluate more than once
    • the optimizer will copy it rather than share it, and CSE will skip it
    • filters on it won't be pushed through projections

    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 ScalarUDFImpl trait 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:

    1. Fix the docs first. That's cheap, non-breaking, and gives PushDownFilter copies a projected expression into every OR branch of the predicate #27631 and fix: one inlining policy for the rules that inline a projection column #25456 a shared vocabulary right away.
    2. Rename later with deprecated forwarding items, once the meanings are agreed in the [EPIC] Leaf expression pushdown and filter pushdown: bugs, decisions and tests #25459 epic.
  6. LiaCastaneda commented on Nov 23, 2026

    @LiaCastaneda
    ContributorAuthor

    Could an optimisation that turns the pattern you're describing into something like this help?

    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:

    Filter: u = 'A' AND v = 'x' OR u = 'B' AND v = 'y' OR u = 'C' AND v = 'z'
      Projection: u, lower(t.s) AS v
        Filter: u IN ('A', 'B', 'C')
          Projection: upper(t.s) AS u, t.s
            TableScan: t projection=[s]
    

    It does sure look like you would want some kind of cost model to aid in deciding which variant is most appropriate though.

    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:

    Most of them seem to use some notion of cost, but we could do something simpler and less breaking like calcite or trino

  7. adriangb commented on Nov 24, 2026

    @adriangb
    Contributor

    So 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.

    The original intention was that MoveTowardsLeafNodes would 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 for KeepInPlace to 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 of MoveTowardsLeafNodes. The file/row functions also fit this bill and use the same mechanisms (#27669). It gets a bit more questionable with something like variant_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?

  8. pepijnve commented on Nov 24, 2026

    @pepijnve
    Contributor

    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.

    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.

  9. LiaCastaneda commented on Nov 25, 2026

    @LiaCastaneda
    ContributorAuthor

    KeepInPlace to be "leave it alone, we don't know if it's cheap or expensive"

    Looks like this is treated differently in different optimizer rules though 🤔 For example:

    • OptimizeProjections and CSE treat a KeepInPlace expression as "could be expensive" and then OptimizeProjections won't merge projections if that would duplicate it, and CSE computes it once.
    • PushDownFilter does the reverse: it treats KeepInPlace as "could be cheap" and inlines the expression into the filter, once per reference.

    So PushDownFilter seems to be the only rule that duplicates KeepInPlace expressions, with no limit on how many copies it can make.

    Computed | The engine has to evaluate this. It's the default and makes no claim about cost or placement.

    I think this would bite in some cases though, If Computed makes no claim about cost then a rule like "never duplicate a Computed expression" can't tell cheap expressions like col + 1 or a CAST apart from an expensive UDF or a lambda, then copying is actually the better choice when the expression is cheap, here are some examples:

    - WHERE a + 1 > 10 OR a + 1 < 0 --> computing a + 1 twice is cheaper than materializing a new column, and the filter can still reach the scan.
    - WHERE t > 1000 OR t < 0 with t = CAST(ts AS …) from a view --> the filter has to contain CAST(ts) to be unwrapped to ts > … and reach the scan for pruning. This is an OR variant of the case that regressed in #25388.
    - WHERE floor(x) = 1 OR floor(x) = 2 through a view: the preimage rewrite only works if the filter contains floor(x).
    - (u = 'A' AND v = 'x') OR (u = 'B' AND v = 'y'): today v is only evaluated on rows where u matched. Computing it once in a projection evaluates it for every row.
    

    iiuc this is part of the reason why #25388 was dropped.

    Alternatively, if we had something more granular like Spark's is_expensive flag, 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 KeepInPlace column. 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.

  10. adriangb commented on Nov 25, 2026

    @adriangb
    Contributor

    Alternatively, if we had something more granular like Spark's is_expensive flag, we could avoid these regressions, because cheap expressions would be explicitly marked as cheap and could still be copied.

    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?

  11. LiaCastaneda commented on Nov 26, 2026

    @LiaCastaneda
    ContributorAuthor

    How is the boolean more granular?

    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 CAST and array_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) > 5 if we mark CAST as MoveTowardsLeafNodes (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. Today CAST is KeepInPlace which is nice because CAST(col) > 5 gets unwrapped to col > 5 that gets pushed to the scan, and the CAST only runs on the already filtered data.

    KeepInPlace:

    ProjectionExec: expr=[CAST(x@0 AS Int64) as t]          -- cast only on rows that passed
      FilterExec: x@0 > 5                                    -- unwrapped to the plain column
        DataSourceExec: projection=[x], predicate=x@0 > 5,
                        pruning_predicate=x_null_count@1 != row_count@2 AND x_max@0 > 5
    

    MoveTowardsLeafNodes:

    FilterExec: t@0 > 5                                      -- filter runs after the cast
      ProjectionExec: expr=[CAST(x@0 AS Int64) as t]         -- cast on every row the scan returns
        DataSourceExec: projection=[x], predicate=CAST(x@0 AS Int64) > 5,
                        pruning_predicate=x_null_count@1 != row_count@2 AND x_max@0 > 5
    

    But array_transform(...) (or any other expensive expression) is also KeepInPlace, so PushDownFilter treats 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:

    Projection: array_transform(__common_expr_1, (x) -> upper(x)) AS u, array_transform(__common_expr_1, (x) -> lower(x)) AS v
      Projection: make_array(t.s) AS __common_expr_1
        Filter: array_transform(__common_expr_4, (x) -> upper(x)) = List([A]) AND array_transform(__common_expr_4, (x) -> lower(x)) = List([x])
             OR array_transform(__common_expr_4, (x) -> upper(x)) = List([B]) AND array_transform(__common_expr_4, (x) -> lower(x)) = List([y])
             OR array_transform(__common_expr_4, (x) -> upper(x)) = List([C]) AND array_transform(__common_expr_4, (x) -> lower(x)) = List([z])
          Projection: make_array(t.s) AS __common_expr_4, t.s
            TableScan: t projection=[s]
    

    MoveTowardsLeafNodes

    Filter: u = List([A]) AND v = List([x]) OR u = List([B]) AND v = List([y]) OR u = List([C]) AND v = List([z])
      Projection: array_transform(__common_expr_1, (x) -> upper(x)) AS u, array_transform(__common_expr_1, (x) -> lower(x)) AS v
        Projection: make_array(t.s) AS __common_expr_1
          TableScan: t projection=[s]
    

    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"

  12. LiaCastaneda commented on Nov 26, 2026

    @LiaCastaneda
    ContributorAuthor

    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)

  13. akshatsinghrajawat commented on Nov 30, 2026

    @akshatsinghrajawat

    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_column then 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 < 20 has one reference to u in 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 like a + 1 and CAST, which is exactly the regression Lia highlighted.

    I agree with Adrian's clarification that KeepInPlace means 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions