Skip to content

Optimize away Coalesce over non-nullable expression #33890

Description

@roji

We should introduce a check into SqlExpressionFactory.Coalesce(), which doesn't actually add a Coalesce node if the left side is known to be non-nullable:

public virtual SqlExpression Coalesce(SqlExpression left, SqlExpression right, RelationalTypeMapping? typeMapping = null)
{
    switch (left)
    {
        case SqlConstantExpression { Value: not null }:
        case ColumnExpression { IsNullable: false }:
            return left;

        case SqlConstantExpression { Value: null }:
            return right;
    }

This would allow calling SqlExpressionFactory.Coalesce() without first checking if it's needed, simplying call sites.

Similarly, we should also perform this optimization in SqlNullabilityProcessor, which can take care of more cases.

The main difficulty here is that we have various tests exercising Coalesce functionality, which are implemented over non-nullable columns; the Coalesce node would be stripped away there, and the tests would become useless. These need to be updated.

Note: do this for Cosmos as well, but remember that the Cosmos coalesce operator (??) is for undefined rather than null.

Activity

  1. added this to the Backlog milestone on Jun 4, 2024
  2. ranma42 commented on Jun 4, 2024

    @ranma42
    Contributor

    In addition to updating/fixing the tests, another issue is that the signature in the ISqlExpressionFactory interface is:

        SqlFunctionExpression Coalesce(
            SqlExpression left,
            SqlExpression right,
            RelationalTypeMapping? typeMapping = null);

    so Coalesce is required to return a SqlFunctionExpression.

    The ISqlExpressionFactory is a public interface and changing this signature would be a breaking change (and a significant one, I am afraid).

    One could imagine another interface ISqlExpressionOptimizingFactory that only requires methods to return a SqlExpression (aka all of its outputs can be combined as subexpressions through this interface).

    Alternatively, extension methods could be used to add this functionality "directly" to ISqlExpressionFactory.

    I think that the ISqlExpressionOptimizingFactory might result in a cleaner design in the long term; conversely extension methods would allow for a more natural way to incrementally add this functionality (example: start with only COALESCE, then add IS NULL etc).

    I believe that neither would provide the benefit of this optimization for free to external consumers of the API: they would to switch from using ISqlExpressionFactory to ISqlExpressionOptimizingFactory or to use a CoalesceFoobar extension method.

    Is there any approach that could enable this? (also, how important is providing this to unmodified external consumers?)

  3. roji commented on Jun 4, 2024

    @roji
    MemberAuthor

    The ISqlExpressionFactory is a public interface and changing this signature would be a breaking change (and a significant one, I am afraid).

    I don't see this as a huge problem... We generally treat provider-facing breaking changes differently than user-facing ones, and allow ourself more leeway; this approach has proven itself over the years - we're generally in close touch with provider maintainers, and this has enabled EF to evolve without being held back too much. In addition, I really doubt lots of provider code specifically depends on Coalesce returning a SqlFunctionExpression, as opposed to SqlExpression.

    I think that the ISqlExpressionOptimizingFactory might result in a cleaner design in the long term; conversely extension methods would allow for a more natural way to incrementally add this functionality (example: start with only COALESCE, then add IS NULL etc).

    How would that be a clean design, and except for avoiding the breaking change, why would anyone want to use the non-optimizing factory?

    In general, in my mind, if someone simply wants to instantiate an expression, they can always do so directly; the factory exists mainly in order to facilitate various things (calculate type mappings). I have a hard time imagining a case where someone wants to use the factory (e.g. for type mapping inference), but does not want an optimization such as the above to be done...

    But I'm definitely interested in hearing what you think about this!

  4. ranma42 commented on Jun 4, 2024

    @ranma42
    Contributor

    The ISqlExpressionFactory is a public interface and changing this signature would be a breaking change (and a significant one, I am afraid).

    I don't see this as a huge problem... We generally treat provider-facing breaking changes differently than user-facing ones, and allow ourself more leeway; this approach has proven itself over the years - we're generally in close touch with provider maintainers, and this has enabled EF to evolve without being held back too much. In addition, I really doubt lots of provider code specifically depends on Coalesce returning a SqlFunctionExpression, as opposed to SqlExpression.

    Nice! If these interfaces can be modified we have quite a lot of flexibility for improvements 🎉

    I think that the ISqlExpressionOptimizingFactory might result in a cleaner design in the long term; conversely extension methods would allow for a more natural way to incrementally add this functionality (example: start with only COALESCE, then add IS NULL etc).

    How would that be a clean design, and except for avoiding the breaking change, why would anyone want to use the non-optimizing factory?

    I meant that the interface would probably be cleaner than the extension methods, not cleaner than the current interface; if we can leverage the existing interface so that these improvements are available to providers with little to no effort, we should definitely do so.

    In general, in my mind, if someone simply wants to instantiate an expression, they can always do so directly; the factory exists mainly in order to facilitate various things (calculate type mappings). I have a hard time imagining a case where someone wants to use the factory (e.g. for type mapping inference), but does not want an optimization such as the above to be done...

    I'll cheat and try to find some examples from other kinds of compilers.
    AFAIK the main cases in which you want to have a 1:1 mapping between "source" and "target" are related to debugging the "source code" (in our case, source query/expression) or the transformations/optimizations. I believe these are only weird/corner cases in the context of EFCore and the default factory should take care of these optimizations.
    OTOH if more logic is moved to this part, it might make sense to unit test it (independently from providers).

  5. roji commented on Jun 4, 2024

    @roji
    MemberAuthor

    Thanks, all makes sense.

    Yeah, in my mind the "just build me an expression" is handled by constructing the expression directly, which leaves the "optimizing builder" role to SqlExpressionFactory - but I may be missing something somewhere.

  6. ranma42 commented on Jun 5, 2024

    @ranma42
    Contributor

    In general, in my mind, if someone simply wants to instantiate an expression, they can always do so directly; the factory exists mainly in order to facilitate various things (calculate type mappings). I have a hard time imagining a case where someone wants to use the factory (e.g. for type mapping inference), but does not want an optimization such as the above to be done...

    Uh, I just realized that in a way there can be some transformations that make the expression more complex (and trivially simplifiable) but required for compatibility with the target language.

    An example of such transformation is in the SQL Server provider https://github.com/dotnet/efcore/blob/main/src/EFCore.SqlServer/Query/Internal/SearchConditionConvertingExpressionVisitor.cs#L41-L62

    Obviously the constant false is a simpler expression that most of the pipeline is likely to prefer, but at some point the SQL Server provider needs to replace it (currently with 0 = 1). Would it make sense to emit it directly as such (instead of as a SqlExpression) in a later phase? Maybe... but that would definitely require some changes.
    Also note that other providers might be making similar assumptions, so even simplifying trivial equalities between constant values might break some assumptions baked in external code 🤔

  7. roji commented on Jun 7, 2024

    @roji
    MemberAuthor

    @ranma42 I think what you're describing is a general difficulty in any sort of pipeline working on expression trees - if a later stage pattern-matches a very specific shape, then any change earlier in the pipeline which modifies that shape would cause that to break.

    Our general approach to address this is a robust test suite which should flag any change in the actual end SQL. Of course, there are external providers out there which may rely on a specific shape, but it's again their responsibility to properly test that their pattern-match works etc. I'm not sure what the alternative would be, except to constrain ourselves to never evolve/improve our tree - which would be a clear net negative for our users... And as I said, we generally allow ourselves a bit of leeway when it comes to provider-facing breaking changes, and foster a close relationship with provider writers to help them out. This strategy has worked out well so far...

  8. ranma42 commented on Jun 7, 2024

    @ranma42
    Contributor

    @ranma42 I think what you're describing is a general difficulty in any sort of pipeline working on expression trees - if a later stage pattern-matches a very specific shape, then any change earlier in the pipeline which modifies that shape would cause that to break.

    The case I was pointing out is not really about pattern matching, but rather expression construction; I agree that there is an inherent fragility in pattern matching expressions that are being transformed by a pipeline that evolves over time. This case might actually be simpler and I believe that it is possible to solve it guiding providers/consumers of the API towards:

    • using the SqlExpressionFactory if they want an expression with a certain meaning/semantics (regardless of its specific syntax; the factory is allowed to optimize the expression)
    • creating the expression by invoking the constructors if they want a specific syntax (not just something equivalent)

    which IIUC is what you are already recommending in #33890 (comment) Currently API consumers might not be following this advice, but it should be fairly easy to guide them in this direction (and to update EFCore itself so that it follows its own recommendations 😅 ).
    (This week I have been traveling but in the weekend I plan to play around with EFCore expressions again)

    Our general approach to address this is a robust test suite which should flag any change in the actual end SQL. Of course, there are external providers out there which may rely on a specific shape, but it's again their responsibility to properly test that their pattern-match works etc. I'm not sure what the alternative would be, except to constrain ourselves to never evolve/improve our tree - which would be a clear net negative for our users... And as I said, we generally allow ourselves a bit of leeway when it comes to provider-facing breaking changes, and foster a close relationship with provider writers to help them out. This strategy has worked out well so far...

    IIUC that the test suite is designed to test both the behavior (results/values) and the output code; I can agree that this is a very effective testing strategy 👍 (there are certainly improvement opportunities, but I believe they are mostly around coverage and test organization).

    Also it looks like most of the test suite is designed so that external providers can hook into it and re-use its tests. I imagine keeping up to date is non-trivial, but I imagine it is very effective in keeping in sync with updates to EFCore (regardless of them being considered breaking or simply significant changes in the translation pipeline).

  9. roji commented on Jun 7, 2024

    @roji
    MemberAuthor

    creating the expression by invoking the constructors if they want a specific syntax (not just something equivalent)

    Sure, though I think this generally shouldn't ever be needed. Note that even if you create a specific expression node (e.g. coalesce) because you want that node in the tree, there's no guarantee there won't be some step at some unknown future point that would optimize it away if it deems it unnecessary... This is especially problematic given that the query pipeline can be a mix of provider-specific visitors and EF visitors, possibly even interleaved together. So whether coalesce is optimized away at construction time (in SqlExpressionFactory) or two seconds later (in some visitor) doesn't seem like an important distinction.

    IIUC that the test suite is designed to test both the behavior (results/values) and the output code; I can agree that this is a very effective testing strategy 👍 (there are certainly improvement opportunities, but I believe they are mostly around coverage and test organization).

    Yeah, we also assert on actual SQL baselines (on a per-provider basis), so even changes which continue to yield correct results but change SQL (and therefore possibly affect perf) are caught.

    And yeah, this means that keeping up with the test suite in a provider is no small task - I regularly do this work in the PostgreSQL provider, which is external to this repo. But it's more than worth it.

  10. ranma42 commented on Jun 9, 2024

    @ranma42
    Contributor

    I tried doing this and its impact in the code is probably reasonable (and it provides some minor improvements in the emitted SQL as well 🥳 ). See https://github.com/ranma42/efcore/tree/generic-exprfactory

    While looking into cleaning up code that could make use of it, I found a missed optimization opportunity in the nullability processing of COALESCE #33938 (and a couple of misconfigured argumentsPropagateNullability 😅 )

  11. changed the title [-]Optimize away Coalesce over non-nullable expression in SqlExpressionFactory[/-] [+]Optimize away Coalesce over non-nullable expression[/+] on Jun 9, 2024
  12. added theissue type on Jun 15, 2025
  13. ranma42 commented on Jun 30, 2025

    @ranma42
    Contributor

    #34002 and #33938 cover a significant part of this.

    Specifically:

    • COALESCE nodes constructed on some trivially non-null/null expressions are simplified
    • COALESCE expressions are "truncated" to the first non-nullable argument
    • when possible, the COALESCE invocation is dropped

    It looks like the current implementation mainly misses two cases:

    • COALESCE(x, null) is not simplified upon construction
    • COALESCE(nullableX, nullParameter) is not simplified in nullability processing (IIRC this can happen because parameters are known to be NULL/non-null during nullability processing).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions