dongjoon-hyun commented on code in PR #60392:
URL: https://github.com/apache/spark/pull/60392#discussion_r4560087124


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -2644,18 +2644,25 @@ class Analyzer(
   }
 
   /**
-   * A rule that binds procedures to the input types and rearranges arguments 
as needed.
+   * A rule that binds procedures to the input types and rearranges arguments 
as needed, and
+   * records the bound procedure in a [[ResolvedBoundProcedure]].
    */
   object BindProcedures extends Rule[LogicalPlan] {
     def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators {
-      case Call(ResolvedProcedure(catalog, ident, unbound: UnboundProcedure), 
args, execute)
+      case c @ Call(ResolvedProcedure(catalog, ident, procedure), args, _)
           if args.forall(_.resolved) =>
-        val inputType = extractInputType(args)
-        val bound = unbound.bind(inputType)
-        validateParameterModes(bound)
+        val boundProcedure = procedure match {
+          case unbound: UnboundProcedure => 
unbound.bind(extractInputType(args))
+          case bound: BoundProcedure => bound

Review Comment:
   **[6] A `Call` over a plain `BoundProcedure` now goes through the binding 
checks, so some CALLs that ran on master now fail.**
   
   Following up on item 2 
([thread](https://github.com/apache/spark/pull/60392#discussion_r4554437715)): 
binding these instead of failing them looks good to me. One detail of the 
[reply](https://github.com/apache/spark/pull/60392#discussion_r4559812185), 
though: master did not bind such a `Call`. Its `BindProcedures` matched only 
`ResolvedProcedure(catalog, ident, unbound: UnboundProcedure)` (L2651 on 
master), so a `Call` over a procedure that is only a `BoundProcedure` was 
coerced and invoked as it was. Now this branch also runs 
`validateParameterModes` and `defaultRearrange` on it. So an extension-built 
`Call(ResolvedProcedure(cat, ident, p), args)`, where `p` is only a 
`BoundProcedure`, now fails with `INTERNAL_ERROR` in two cases that ran on 
master when the argument count matched:
   
   - `p` has an `OUT` or `INOUT` parameter ("Unsupported parameter mode" from 
`validateParameterModes`);
   - `p` declares a required parameter after an optional one 
(`unexpectedRequiredParameter` from `defaultRearrange`).
   
   A wrong argument count already failed on master, with `requirement failed`, 
so `WRONG_NUM_ARGS` there is an improvement.
   
   Rejecting these may well be intended, since Spark does not support `OUT` 
parameters. Could the description list it under the user-facing changes? Its 
"It also binds a `Call` over a procedure that is only a `BoundProcedure`" does 
not say that such a `Call` can now fail.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/v2ResolutionPlans.scala:
##########
@@ -226,6 +226,19 @@ case class ResolvedProcedure(
   override def output: Seq[Attribute] = Nil
 }
 
+/**
+ * A procedure that `BindProcedures` has bound to the arguments of a CALL, or 
accepted as already
+ * bound, with the arguments rearranged to match its parameters. It is a 
separate node from
+ * [[ResolvedProcedure]] because a procedure may implement both 
`UnboundProcedure` and
+ * `BoundProcedure`, so its type does not show whether it was bound.
+ */
+case class ResolvedBoundProcedure(

Review Comment:
   **[7] Correction to my item 3: keeping the three fields of `Call` does not 
make the backports compatible for extensions.**
   
   Item 3 
([thread](https://github.com/apache/spark/pull/60392#discussion_r4554437729)) 
said the three fields would help with the backports, and your 
[reply](https://github.com/apache/spark/pull/60392#discussion_r4559812661) on 
@peter-toth's Finding 1 concludes that the backports have no compatibility 
change. The fields do keep the constructor, `copy` and the extractor linking. 
But the analyzed plan still changes for extensions:
   
   - The child of a bound `Call` is now this node. In every release from v4.0.0 
to v4.3.0, `ProcedureArgumentCoercion` and `InvokeProcedures` match 
`Call(ResolvedProcedure(_, _, procedure: BoundProcedure), args, _)`. An 
extension rule or strategy with that pattern, built against 4.0 to 4.3, still 
compiles and links after a backport, but it no longer matches, so it silently 
skips every CALL. #58994 adds the same pattern in `DataSourceV2Strategy`, as 
the description says.
   - `BindProcedures` now also takes a `Call` over a plain `BoundProcedure` 
(item 6), and CheckAnalysis fails a resolved `Call` that is not bound with 
`INTERNAL_ERROR`.
   
   The description's paragraph for Spark extensions already says this for 
master. Could each backport's description keep that paragraph too, instead of 
saying there is no compatibility change?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -2408,8 +2412,9 @@ case class Call(
   override def simpleString(maxFields: Int): String = {
     procedure match {
       case ResolvedProcedure(catalog, ident, _) =>
-        val name = s"${quoteIfNeeded(catalog.name)}.${ident.quoted}"
-        simpleString(name, maxFields)
+        simpleString(V2TableUtil.toQualifiedName(catalog, ident), maxFields)
+      case ResolvedBoundProcedure(catalog, ident, _) =>

Review Comment:
   **[10] Nit: this branch is the same as the one at L2414.**
   
   Both print `V2TableUtil.toQualifiedName(catalog, ident)`, so a later change 
to how a CALL prints its name has to go into both, or EXPLAIN would print bound 
and unbound CALLs differently. A small parent trait of `ResolvedProcedure` and 
`ResolvedBoundProcedure` with `catalog` and `ident` would let one case cover 
both. Could they share one, or is it simpler to keep the two lines?



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/procedures/UnboundProcedure.java:
##########
@@ -41,6 +41,11 @@ public interface UnboundProcedure extends Procedure {
    * set to {@code true}. In such cases, the field name will match the name of 
the target procedure
    * parameter. If the argument is not named, {@link 
ProcedureParameter#BY_NAME_METADATA_KEY} will
    * not be set and the name will be assigned randomly.
+   * <p>
+   * When analyzing a CALL statement, Spark calls this method once, after all 
arguments are

Review Comment:
   **[8] Nit: "once" could say once per analysis.**
   
   This is right for one analysis, but Spark analyzes the same CALL again under 
EXPLAIN and on each run, and binds each time. The new test at 
ProcedureSuite.scala:573 counts two binds for one CALL and one EXPLAIN. A 
connector that keeps state in `bind()` could read "once" as once per statement. 
Could it say "once per analysis of a CALL statement"?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -1007,6 +1007,10 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
                 throw SparkException.internalError("Invalid input for 
procedure")
             }
 
+          case c: Call if c.resolved && !c.bound =>

Review Comment:
   **[9] Nit: the two `Call` cases could be one.**
   
   This case and the one at L1002 split the same `resolved` and `bound` state 
over two guards. One case would keep them together. It would also call 
`checkArgTypes()`, and so the procedure's `parameters`, once instead of twice 
for a failing CALL, although that double call predates this PR:
   
   ```scala
             case c: Call if c.resolved =>
               if (!c.bound) {
                 throw SparkException.internalError(
                   s"CALL is resolved but not bound: ${c.procedure.nodeName}")
               }
               c.checkArgTypes() match {
                 case TypeCheckResult.TypeCheckSuccess =>
                 case mismatch: TypeCheckResult.DataTypeMismatch =>
                   c.dataTypeMismatch("CALL", mismatch)
                 case _ =>
                   throw SparkException.internalError("Invalid input for 
procedure")
               }
   ```
   
   A passing `Call` still reaches the checks after this match, as it does now 
through `case _`. Could they be merged?



##########
sql/core/src/main/scala/org/apache/spark/sql/catalyst/analysis/InvokeProcedures.scala:
##########
@@ -40,7 +40,7 @@ class InvokeProcedures(session: SparkSession) extends 
Rule[LogicalPlan] {
   private def invokeProcedures(plan: LogicalPlan): LogicalPlan = plan 
resolveOperators {
     case c: Call if c.resolved && c.bound && c.execute && 
c.checkArgTypes().isSuccess =>
       session.sessionState.optimizer.execute(c) match {
-        case Call(ResolvedProcedure(_, _, procedure: BoundProcedure), args, _) 
=>
+        case Call(ResolvedBoundProcedure(_, _, procedure), args, _) =>

Review Comment:
   **[11] Minor: this predates the PR, but optimizer rules can still put a node 
between the `Call` and its procedure here, and the CALL then fails with 
`INTERNAL_ERROR`.**
   
   This runs the whole optimizer on the `Call` and expects 
`Call(ResolvedBoundProcedure(...), ...)` back. Rules that rewrite any 
`UnaryNode` do not keep that shape:
   
   - `RewritePredicateSubquery` rewrites a `UnaryNode` with an IN subquery 
(`subquery.scala:329`). For a `BOOLEAN` parameter, `CALL cat.ns.p(1 IN (SELECT 
1))` binds and passes `checkArgTypes`, and `InvokeProcedures` runs in the 
Resolution batch, before CheckAnalysis could report 
`UNSUPPORTED_IN_EXISTS_SUBQUERY`. The optimizer then returns 
`Call(Join(ResolvedBoundProcedure, ..., ExistenceJoin), ...)`.
   - `ExtractPythonUDFs` puts a `BatchEvalPython` under the `Call` for a Python 
UDF argument.
   
   Both fall to L46, "Unexpected plan for optimized CALL statement". Master has 
the same match over `ResolvedProcedure`, so this is not a regression. Could 
this take the procedure from `c` and only the arguments from the optimized 
`Call`? After a rebase on master, the foldability check from SPARK-61557 would 
then report both as `NON_FOLDABLE_ARGUMENT`. A follow-up JIRA would be fine too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/PullOutNondeterministic.scala:
##########
@@ -36,6 +36,8 @@ object PullOutNondeterministic extends Rule[LogicalPlan] {
     case p if !p.resolved => p // Skip unresolved nodes.
     case p: Project => p
     case f: Filter => f
+    // A CALL must keep its procedure as its child, which `Call.bound` and 
`checkArgTypes` read.
+    case c: Call => c

Review Comment:
   **[12] Minor: following up on item 1 
([thread](https://github.com/apache/spark/pull/60392#discussion_r4554437707)), 
the `Call` case I suggested covers only this rule.**
   
   Thank you for taking that option. Because `bound` and `checkArgTypes` read 
the child, every rule that rewrites the child of a generic `UnaryNode` needs 
its own `Call` exception. `RewriteWithExpression` already has one 
(`RewriteWithExpression.scala:109`), this PR adds this one, and the optimizer 
rules in item 11 still have none. Keeping the procedure out of `children` once 
it is resolved would remove the need for these exceptions, but that is a larger 
change than this PR needs. This case is fine for this PR. Could a follow-up 
JIRA track the rest?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to