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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -1039,8 +1039,13 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
               varName,
               c.defaultExpr.originalSQL)
 
-          case c: Call if c.resolved && c.bound && c.checkArgTypes().isFailure 
=>
+          case c: Call if c.resolved =>
+            if (!c.bound) {

Review Comment:
   **[13] A CALL whose argument is `window(...)` or `session_window(...)` 
reaches this `INTERNAL_ERROR` from plain SQL.**
   
   [Item 2](https://github.com/apache/spark/pull/60392#discussion_r4554437715) 
assumed that only an extension can build a resolved `Call` that is not bound. 
Plain SQL can reach that state too, through the time-window rules:
   
   ```sql
   CALL cat.ns.sum(window(TIMESTAMP '2026-01-01 00:00:00', '1 hour'), 1)
   ```
   
   - `TimeWindow` is never resolved (`TimeWindow.scala:127`), so 
`BindProcedures` skips this `Call`.
   - Later in the same iteration, `TimeWindowing` 
(`ResolveTimeWindows.scala:65`) takes any plan with one child, so it puts 
`Project [window] +- Filter isnotnull(ts)` between the `Call` and its 
`ResolvedProcedure`. After that, `BindProcedures` no longer matches, and 
`InvokeProcedures` skips the `Call` because `bound` is false.
   - This branch then throws `[INTERNAL_ERROR] CALL is resolved but not bound: 
Project`, and `EXPLAIN` prints that error instead of a plan. A sliding window, 
or `session_window` (`ResolveTimeWindows.scala:116`), ends in `: Filter`.
   
   On master the same statement passes analysis without invoking the procedure, 
and `collect()` throws `UnsupportedOperationException`. I checked that plan 
with the 4.3.0 release. So failing is an improvement, but `INTERNAL_ERROR` asks 
the user to report a Spark bug for their own input. Keeping the procedure out 
of `children`, as in your 
[reply](https://github.com/apache/spark/pull/60392#discussion_r4592864878) on 
item 12, would leave the `TimeWindow` unresolved, so this case would still need 
an error of its own.
   
   Could this branch give a user-facing error when a rule has put an operator 
under the `Call`, and keep `INTERNAL_ERROR` for a leaf child such as the 
`LocalRelation` in the new test? For example:
   
   ```scala
   if (!c.bound) {
     if (c.procedure.children.nonEmpty) {
       // A rule such as `TimeWindowing` put an operator under the CALL to 
evaluate an argument.
       c.failAnalysis(
         errorClass = "UNSUPPORTED_EXPR_FOR_OPERATOR",
         messageParameters = Map(
           "operator" -> c.nodeName,
           "invalidExprSqls" -> 
c.args.filterNot(_.foldable).map(toSQLExpr).mkString(", ")))
     }
     throw SparkException.internalError(s"CALL is resolved but not bound: 
${c.procedure.nodeName}")
   }
   ```
   
   A test with the statement above would pin it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/v2ResolutionPlans.scala:
##########
@@ -219,12 +219,30 @@ case class ResolvedFieldName(path: Seq[String], field: 
StructField) extends Fiel
 
 case class ResolvedFieldPosition(position: ColumnPosition) extends 
FieldPosition
 
+/**
+ * A resolved procedure that a CALL refers to, before or after 
`BindProcedures` binds it.

Review Comment:
   **[15] Nit: `ResolvedProcedure` is also the child of DESCRIBE PROCEDURE.**
   
   `DESC PROCEDURE cat.ns.p` resolves to 
`DescribeProcedureCommand(ResolvedProcedure(...))` 
(`DescribeProcedureCommand.scala:45`), and `BindProcedures` never binds that 
one. `ResolvedProcedure` has no doc of its own, so this sentence reads as if 
every `ResolvedProcedure` belongs to a CALL and gets bound. Maybe:
   
   ```suggestion
    * A resolved procedure that a CALL or DESCRIBE PROCEDURE refers to. Under a 
CALL,
    * `BindProcedures` replaces a [[ResolvedProcedure]] with a 
[[ResolvedBoundProcedure]].
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -2649,18 +2649,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
+          case other =>
+            throw SparkException.internalError(s"Unsupported procedure: 
${other.getClass.getName}")

Review Comment:
   **[14] Nit: a null procedure loses this message.**
   
   A typed pattern does not match `null`, so a `ResolvedProcedure(catalog, 
ident, null)` that an extension builds reaches this case, and `other.getClass` 
throws a `NullPointerException`. `QueryExecution` then reports the generic "The 
Spark SQL phase analysis failed with an internal error" instead of "Unsupported 
procedure". SQL cannot get here since SPARK-61553, so only the message is at 
stake. Could it print `Option(other).map(_.getClass.getName).orNull`, or match 
`case null` first?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/ProcedureSuite.scala:
##########
@@ -635,6 +645,117 @@ class ProcedureSuite extends SharedSparkSession with 
BeforeAndAfter {
     checkAnswer(sql("CALL cat.ns.simple_sum(in2 => 4, in1 => 6)"), Row(10) :: 
Nil)
   }
 
+  test("SPARK-61506: simple procedure with a late-resolving argument") {
+    // `ResolveBinaryArithmetic` rewrites the timestamp subtraction into an 
interval addition that
+    // still needs a time zone. `ResolveTimeZone` sets it in the next analyzer 
iteration, after
+    // `BindProcedures` has run in that iteration.
+    catalog.createProcedure(Identifier.of(Array("ns"), "simple_ts"), 
SimpleTimestampProcedure)
+    val tsExpr = "TIMESTAMP '2026-01-02 00:00:00' - INTERVAL '1' DAY"
+    val expected = Timestamp.valueOf("2026-01-01 00:00:00")
+    checkAnswer(sql(s"CALL cat.ns.simple_ts($tsExpr)"), Row(expected, "none") 
:: Nil)
+    checkAnswer(
+      sql(s"CALL cat.ns.simple_ts(label => 'x', ts => $tsExpr)"),
+      Row(expected, "x") :: Nil)
+    checkError(
+      exception = intercept[AnalysisException](
+        sql(s"CALL cat.ns.simple_ts($tsExpr, 'x', 1)")
+      ),
+      condition = "WRONG_NUM_ARGS.WITHOUT_SUGGESTION",
+      parameters = Map(
+        "functionName" -> toSQLId("simple_ts"),
+        "expectedNum" -> "[1, 2]",
+        "actualNum" -> "3",
+        "docroot" -> SPARK_DOC_ROOT))
+  }
+
+  test("SPARK-61506: other late-resolving arguments") {
+    catalog.createProcedure(Identifier.of(Array("ns"), "simple_ts"), 
SimpleTimestampProcedure)
+    val expected = Row(Timestamp.valueOf("2026-01-01 00:00:00"), "x") :: Nil
+    Seq(
+      "(SELECT TIMESTAMP '2026-01-01 00:00:00')",
+      "CAST('2026-01-01 00:00:00' AS TIMESTAMP)",
+      // A DATE, which needs an implicit cast to the TIMESTAMP parameter once 
bound.
+      "DATE '2026-01-02' - INTERVAL '1' DAY").foreach { ts =>
+      checkAnswer(sql(s"CALL cat.ns.simple_ts(label => 'x', ts => $ts)"), 
expected)
+    }
+  }
+
+  test("SPARK-61506: procedure that is both unbound and bound is used only 
after binding") {
+    val binds = new AtomicInteger()
+    catalog.createProcedure(
+      Identifier.of(Array("ns"), "rebinding_ts"),
+      new RebindingTimestampProcedure(binds, isBound = false))
+    checkAnswer(
+      sql("CALL cat.ns.rebinding_ts(TIMESTAMP '2026-01-02 00:00:00' - INTERVAL 
'1' DAY, 'x')"),
+      Row(Timestamp.valueOf("2026-01-01 00:00:00"), "x") :: Nil)
+    assert(binds.get() == 1)
+    // EXPLAIN does not run the procedure, so later iterations see the bound 
`Call` again and must
+    // not bind it again.
+    val plan = explain("CALL cat.ns.rebinding_ts(label => 'x', ts => TIMESTAMP 
'2026-01-01')")
+    assert(binds.get() == 2)
+    assert(plan.contains("Call cat.ns.rebinding_ts(2026-01-01 00:00:00, x)"))
+  }
+
+  test("SPARK-61506: EXPLAIN CALL with a nondeterministic argument") {
+    catalog.createProcedure(Identifier.of(Array("ns"), "sum"), 
UnboundNonExecutableSum)
+    val plan = explain("CALL cat.ns.sum(rand(0), 1)")
+    assert(plan.contains("Call cat.ns.sum(cast(rand(0) as int), 1)"))
+  }
+
+  test("SPARK-61506: CALL with a nondeterministic argument of the wrong type") 
{
+    catalog.createProcedure(Identifier.of(Array("ns"), "simple_date"), 
SimpleDateProcedure)
+    val call = "CALL cat.ns.simple_date(rand())"
+    checkError(
+      exception = intercept[AnalysisException](sql(call)),
+      condition = "DATATYPE_MISMATCH.UNEXPECTED_INPUT_TYPE",
+      parameters = Map(
+        "sqlExpr" -> "CALL",
+        "paramIndex" -> "first",
+        "inputSql" -> "\"rand()\"",
+        "inputType" -> toSQLType("DOUBLE"),
+        "requiredType" -> toSQLType("DATE")),
+      context = ExpectedContext(fragment = call, start = 0, stop = call.length 
- 1))
+  }
+
+  test("SPARK-61506: CALL over a procedure that is only bound") {
+    // Spark loads procedures as `UnboundProcedure`s, but `ResolvedProcedure` 
takes any procedure.
+    val ident = Identifier.of(Array("ns"), "proc")
+    val sum = Call(ResolvedProcedure(catalog, ident, new Sum), Seq(Literal(1), 
Literal(2)))
+    checkAnswer(Dataset.ofRows(spark, sum), Row(3) :: Nil)
+    // `BindProcedures` keeps `execute`, so this CALL is bound but not invoked.
+    val notInvoked = Dataset.ofRows(spark, sum.copy(execute = 
false)).queryExecution.analyzed
+    notInvoked match {
+      case c: Call => assert(c.bound)

Review Comment:
   **[16] Nit: this assert cannot fail.**
   
   `queryExecution.analyzed` runs CheckAnalysis, which now throws `CALL is 
resolved but not bound` for any resolved `Call` that is not bound. So if 
`BindProcedures` stopped binding this `Call`, `Dataset.ofRows` on L726 would 
throw before this line. What the block checks is the match itself: 
`BindProcedures` keeps `execute = false`, so the analyzed plan is still a 
`Call` and the procedure was not invoked. Could the block be 
`assert(notInvoked.isInstanceOf[Call])`, with the comment above saying that 
analysis already requires a bound `Call`?



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