Skip to content

Conversation

xin-zhang2
Copy link
Contributor

Changes adapted from trino/PR#731.

Description

Motivation and Context

Impact

Test Plan

Contributor checklist

  • Please make sure your submission complies with our contributing guide, in particular code style and commit standards.
  • PR description addresses the issue accurately and concisely. If the change is non-trivial, a GitHub Issue is referenced.
  • Documented new properties (with its default value), SQL syntax, functions, or other functionality.
  • If release notes are required, they follow the release notes guidelines.
  • Adequate tests were added if applicable.
  • CI passed.
  • If adding new dependencies, verified they have an OpenSSF Scorecard score of 5.0 or higher (or obtained explicit TSC approval for lower scores).

Release Notes

Please follow release notes guidelines and fill in the release notes below.

== RELEASE NOTES ==

General Changes
* ... 
* ... 

Hive Connector Changes
* ... 
* ... 

If release note is NOT required, use:

== NO RELEASE NOTE ==

@prestodb-ci prestodb-ci added the from:IBM PR from IBM label Oct 15, 2025
Copy link
Contributor

sourcery-ai bot commented Oct 15, 2025

Reviewer's Guide

This PR implements a new optimizer rule that rewrites comparison expressions by unwrapping safe implicit casts, uses new per-type value ranges to detect out-of-range literals, and wires this feature through configuration, system properties, and supporting utility methods, alongside comprehensive unit and integration tests.

Sequence diagram for optimizer rule application in PlanOptimizers

sequenceDiagram
    participant PlanOptimizers
    participant SimplifyRowExpressions
    participant UnwrapCastInComparison
    participant ExpressionOptimizerManager
    PlanOptimizers->>SimplifyRowExpressions: rules()
    PlanOptimizers->>UnwrapCastInComparison: rules()
    UnwrapCastInComparison->>ExpressionOptimizerManager: optimize(rewrittenExpr, SERIALIZABLE, session)
    ExpressionOptimizerManager-->>UnwrapCastInComparison: optimizedExpr
    UnwrapCastInComparison-->>PlanOptimizers: rule set
Loading

Sequence diagram for UnwrapCastInComparison rule rewriting a comparison expression

sequenceDiagram
    participant Optimizer
    participant UnwrapCastInComparison
    participant Visitor
    participant FunctionAndTypeManager
    participant FunctionResolution
    participant InterpretedFunctionInvoker
    Optimizer->>UnwrapCastInComparison: rewrite(expression, session, metadata, exprOptMgr)
    UnwrapCastInComparison->>Visitor: rewriteCall(CallExpression, context, treeRewriter)
    Visitor->>FunctionResolution: isCastFunction(handle)
    Visitor->>FunctionAndTypeManager: lookupCast(CAST, sourceType, targetType)
    Visitor->>FunctionAndTypeManager: lookupCast(CAST, targetType, sourceType)
    Visitor->>InterpretedFunctionInvoker: invoke(coercion, properties, value)
    Visitor-->>UnwrapCastInComparison: rewrittenExpr
    UnwrapCastInComparison-->>Optimizer: rewrittenExpr
Loading

Class diagram for new and updated Type classes with Range support

classDiagram
    class Type {
        +Optional<Range> getRange()
        <<interface>>
    }
    class Type~Range~ {
        +Object min
        +Object max
        +Object getMin()
        +Object getMax()
    }
    Type o-- "1" Range : uses
    class BigintType {
        +Optional<Range> getRange()
    }
    class IntegerType {
        +Optional<Range> getRange()
    }
    class SmallintType {
        +Optional<Range> getRange()
    }
    class TinyintType {
        +Optional<Range> getRange()
    }
    class DoubleType {
        +Optional<Range> getRange()
    }
    class RealType {
        +Optional<Range> getRange()
    }
    class AbstractVarcharType {
        +Optional<Range> getRange()
    }
    Type <|.. BigintType
    Type <|.. IntegerType
    Type <|.. SmallintType
    Type <|.. TinyintType
    Type <|.. DoubleType
    Type <|.. RealType
    Type <|.. AbstractVarcharType
Loading

Class diagram for UnwrapCastInComparison optimizer rule

classDiagram
    class UnwrapCastInComparison {
        +UnwrapCastInComparison(Metadata, ExpressionOptimizerManager)
        +PlanRowExpressionRewriter createRewriter(Metadata, ExpressionOptimizerManager)
    }
    class UnWrapCastInComparisonRewriter {
        +static RowExpression rewrite(RowExpression, Session, Metadata, ExpressionOptimizerManager)
    }
    class Visitor {
        +RowExpression rewriteCall(CallExpression, Void, RowExpressionTreeRewriter<Void>)
        +RowExpression unwrapCast(RowExpression)
        +boolean hasInjectiveImplicitCoercion(Type, Type)
        +Object coerce(Object, FunctionHandle)
        +int compare(Type, Object, Object)
        +RowExpression falseIfNotNull(RowExpression)
        +RowExpression trueIfNotNull(RowExpression)
    }
    UnwrapCastInComparison o-- UnWrapCastInComparisonRewriter : uses
    UnWrapCastInComparisonRewriter o-- Visitor : uses
Loading

Class diagram for FeaturesConfig and SystemSessionProperties with unwrapCasts

classDiagram
    class FeaturesConfig {
        -boolean unwrapCasts
        +boolean isUnwrapCasts()
        +FeaturesConfig setUnwrapCasts(boolean)
    }
    class SystemSessionProperties {
        +static boolean isUnwrapCasts(Session)
    }
Loading

File-Level Changes

Change Details Files
Add range support to the Type system
  • Introduce getRange() default method and Range inner class in Type interface
  • Implement getRange() in numeric types (Bigint, Integer, Smallint, Tinyint)
  • Implement getRange() in AbstractVarcharType with length cap, DoubleType and RealType return empty
  • Add unit test for VARCHAR range boundaries
presto-common/src/main/java/com/facebook/presto/common/type/Type.java
presto-common/src/main/java/com/facebook/presto/common/type/AbstractVarcharType.java
presto-common/src/main/java/com/facebook/presto/common/type/BigintType.java
presto-common/src/main/java/com/facebook/presto/common/type/IntegerType.java
presto-common/src/main/java/com/facebook/presto/common/type/SmallintType.java
presto-common/src/main/java/com/facebook/presto/common/type/TinyintType.java
presto-common/src/main/java/com/facebook/presto/common/type/DoubleType.java
presto-common/src/main/java/com/facebook/presto/common/type/RealType.java
presto-main-base/src/test/java/com/facebook/presto/type/TestVarcharType.java
Introduce unwrapCasts feature flag and session property
  • Add unwrapCasts field, getter, and @config setter in FeaturesConfig
  • Expose UNWRAP_CASTS in SystemSessionProperties with default and accessor
  • Update TestFeaturesConfig for default and explicit property mappings
presto-main-base/src/main/java/com/facebook/presto/sql/analyzer/FeaturesConfig.java
presto-main-base/src/main/java/com/facebook/presto/SystemSessionProperties.java
presto-main-base/src/test/java/com/facebook/presto/sql/analyzer/TestFeaturesConfig.java
Add utility methods for cast handling and function resolution
  • Add castToBoolean helper in Expressions
  • Expose canCoerce in FunctionResolution
  • Add execute(String) in QueryAssertions for simplified SQL execution
presto-main-base/src/main/java/com/facebook/presto/sql/relational/Expressions.java
presto-main-base/src/main/java/com/facebook/presto/sql/relational/FunctionResolution.java
presto-main-base/src/test/java/com/facebook/presto/sql/query/QueryAssertions.java
Register new UnwrapCastInComparison optimizer rule
  • Add UnwrapCastInComparison rules to PlanOptimizers rule set
presto-main-base/src/main/java/com/facebook/presto/sql/planner/PlanOptimizers.java
Implement UnwrapCastInComparison rule with comprehensive tests
  • Add UnwrapCastInComparison iterative rule to unwrap casts in comparisons
  • Add TestUnwrapCastInComparison planner unit tests
  • Add TestUnwrapCastInComparison query integration tests
presto-main-base/src/main/java/com/facebook/presto/sql/planner/iterative/rule/UnwrapCastInComparison.java
presto-main-base/src/test/java/com/facebook/presto/sql/planner/TestUnwrapCastInComparison.java
presto-main-base/src/test/java/com/facebook/presto/sql/query/TestUnwrapCastInComparison.java

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Changes adapted from trino/PR#731
Original commit:
4729bc9
e23e317
48336f2
Author:
Martin Traverso

Co-authored-by: Martin Traverso <[email protected]>
@xin-zhang2 xin-zhang2 changed the title [DNR] Unwrap casts in comparison expressions feat(optimizer): Unwrap casts in comparison expressions Oct 16, 2025
Comment on lines +177 to +182
public Optional<Range> getRange()
{
// The range for double is undefined because NaN is a special value that
// is *not* in any reasonable definition of a range for this type.
return Optional.empty();
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually wonder if this is true. NaN should be treated as the highest value by convention.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tdcmeehan Thanks for the review.
You're right that Nan is treated as the largest value in Presto comparisons and ordering. However, returning NaN as the maximum value of a range would not make sense here. In this specific rule, we unwrap a CAST when it's compared to a constant, and the comparison can be further optimized if the constant exceeds the maximum value of the source type. Since NaN is the maximum value when the source type is real or double, no constant can be greater than it, so empty is directly returned in getRange to skip this check.

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

Labels

from:IBM PR from IBM

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants