[SPARK-27692][SQL] Constant fold deterministic Scala UDFs with foldable arguments #28008
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What changes were proposed in this pull request?
Constant fold deterministic Scala UDFs with foldable arguments, conservatively.
ScalaUDFs that meet all following criteria are subject to constant folding in this PR:Why are the changes needed?
This is an optimization that enables more constant folding, improving the performance of a special case of Scala UDFs.
Catalyst already implements constant folding of expressions in a few places, through the pattern
if (e.foldable) e.eval(EmptyRow). One of the optimizer rules that specifically performs constant folding isConstantFolding.ScalaUDFdoes not overridefoldable, so it isn't subject to constant folding right now.To enable constant folding of
ScalaUDFs, it's tempting to make it overridefoldable:But
ScalaUDFs are declared as deterministic by default, so it's possible for users to mis-declare a potentially exception-throwing UDF as deterministic, so for callers of the "constant folding" code pattern that do not expect an exception, overridingScalaUDF.foldablein general may have a wide impact.Instead, this PR tackles the problem in a conservative way, where the constant folding of
ScalaUDFs is only implemented in theConstantFoldingrule, with special handling to catch non-fatal exceptions when evaluating a Scala UDF during constant folding and skip folding such UDFs.Does this PR introduce any user-facing change?
No.
Caveat: this PR assumes certain semantics of
Expression.deterministic. Although it guards against potentially exception-throwing Scala UDFs being mis-declared as deterministic, it cannot guard against other kinds of mis-declarations, e.g.Users should explicitly mark such UDFs as
asNondeterministic.How was this patch tested?
Added a test case in
ConstantFoldingSuite.