dongjoon-hyun commented on code in PR #60392: URL: https://github.com/apache/spark/pull/60392#discussion_r4554437729
########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala: ########## @@ -2368,27 +2368,27 @@ case class CloseCursor(cursor: Expression) extends LeafCommand /** * The logical plan of the CALL statement. + * + * @param bound whether `BindProcedures` has bound the procedure and rearranged the arguments to Review Comment: **[3] Could the binding be recorded in the child instead of a separate flag?** This says `bound` can't be derived from the procedure type. It could be derived from the child, though, if `BindProcedures` replaced `ResolvedProcedure` with a node for the bound procedure, for example `ResolvedBoundProcedure(catalog, ident, procedure: BoundProcedure)`, and `bound` stayed a `def` over the child: - `BindProcedures` no longer matches after binding, because its pattern needs a `ResolvedProcedure` over an `UnboundProcedure`. So it binds once without the `!c.bound` guard. - The match in `checkArgTypes` is total again, and the flag can no longer disagree with the child, which is what item 1 runs into. - `Call` keeps its three fields, which would also help with [the backports](https://github.com/apache/spark/pull/60392#discussion_r4554246097). The cost is one more leaf node, plus updating the matches in `simpleString`, `ProcedureArgumentCoercion`, `InvokeProcedures` and `checkArgTypes`. If the field stays, dropping its `= false` default would at least turn a positional rebuild into a compile error. Only `AstBuilder` and `BindProcedures` construct a `Call`. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala: ########## @@ -2368,27 +2368,27 @@ case class CloseCursor(cursor: Expression) extends LeafCommand /** * The logical plan of the CALL statement. + * + * @param bound whether `BindProcedures` has bound the procedure and rearranged the arguments to + * match its parameters. This can't be derived from the procedure type, as a + * procedure may implement both `UnboundProcedure` and `BoundProcedure`. */ case class Call( procedure: LogicalPlan, args: Seq[Expression], - execute: Boolean = true) + execute: Boolean = true, + bound: Boolean = false) Review Comment: **[2] A resolved `Call` that `BindProcedures` cannot bind now passes analysis and silently does nothing.** Before this PR, a `Call` over any `BoundProcedure` counted as bound. Now `bound` defaults to `false`, and only `BindProcedures` sets it, only for an `UnboundProcedure`. So `BindProcedures`, `ProcedureArgumentCoercion`, `InvokeProcedures` and the `Call` case in CheckAnalysis all skip a `Call` like these: - `Call(ResolvedProcedure(catalog, ident, p), args)` where `p` is only a `BoundProcedure`, which is allowed since `ResolvedProcedure.procedure` is a `Procedure`; - a bound `Call` that an extension rebuilds positionally, which resets `bound` to `false`. Analysis succeeds. `Call` is not a `Command`, so `spark.sql("CALL ...")` returns without running the procedure, and an action fails with the message-less `UnsupportedOperationException` from `ExplainOnlySparkPlan.doExecute`. Before this PR, the first kind was coerced and invoked. Spark itself never builds such a `Call`, so this only affects extensions, as the description says. Still, failing loudly would be safer than a silent no-op. The smallest change I see is to make `bound` part of `resolved`, so the existing unresolved-operator check in CheckAnalysis reports it: ```scala override lazy val resolved: Boolean = bound && childrenResolved && expressions.forall(_.resolved) ``` `BindProcedures` checks `args.forall(_.resolved)`, not `c.resolved`, and the other readers already check `bound` together with `resolved`, so Spark's own flow does not change. A CheckAnalysis case for `c.resolved && !c.bound` would also work. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala: ########## @@ -2368,27 +2368,27 @@ case class CloseCursor(cursor: Expression) extends LeafCommand /** * The logical plan of the CALL statement. + * + * @param bound whether `BindProcedures` has bound the procedure and rearranged the arguments to + * match its parameters. This can't be derived from the procedure type, as a + * procedure may implement both `UnboundProcedure` and `BoundProcedure`. */ case class Call( procedure: LogicalPlan, args: Seq[Expression], - execute: Boolean = true) + execute: Boolean = true, + bound: Boolean = false) extends UnaryNode with ExecutableDuringAnalysis { override def output: Seq[Attribute] = Nil override def child: LogicalPlan = procedure - def bound: Boolean = procedure match { - case ResolvedProcedure(_, _, _: BoundProcedure) => true - case _ => false - } - def checkArgTypes(): TypeCheckResult = { require(resolved && bound, "can check arg types only after resolution and binding") val params = procedure match { - case ResolvedProcedure(_, _, bound: BoundProcedure) => bound.parameters + case ResolvedProcedure(_, _, boundProcedure: BoundProcedure) => boundProcedure.parameters Review Comment: **[1] A CALL that is not run fails with `INTERNAL_ERROR` when an argument is nondeterministic.** This match still expects a `ResolvedProcedure` child, but `bound` is now stored, so it survives a child rewrite. A `Call` that is not invoked during the Resolution batch (EXPLAIN, an argument that cannot be coerced, or `parse_sql` under `InvokeProcedures.withoutInvocation`) reaches the "Nondeterministic" batch. There, `PullOutNondeterministic` (`PullOutNondeterministic.scala:68`) treats it as a `UnaryNode` whose output equals its child's output (both are empty), and rewrites it into `Call(Project([rand() AS _nondeterministic], ResolvedProcedure), ...)`. `withNewChildInternal` keeps `bound = true`, so CheckAnalysis calls `checkArgTypes()`, the `require` at L2388 passes, and this match throws `scala.MatchError`. `QueryExecution` turns that into an `INTERNAL_ERROR`. For example, with the suite's `UnboundNonExecutableSum`: ```scala sql("EXPLAIN CALL cat.ns.sum(rand(), 1)").head().getString(0) ``` - Before this PR, the derived `bound` is `false` for the `Project` child, so this prints a plan. On the 4.3.0 release it prints `Call [cast(_nondeterministic#N as int), 1], false`. - With this PR, it prints `Error occurred during query planning:` followed by the `INTERNAL_ERROR`. `CALL cat.ns.p(rand())` for a `DATE` parameter hits the same error. Before, it passed analysis and failed in `collect()` with a bare `UnsupportedOperationException`. The existing EXPLAIN tests use only literal arguments, so CI does not show this. Two ways to fix it: - Skip `Call` in `PullOutNondeterministic` (`case c: Call => c`). The procedure name then stays in EXPLAIN, and the `DATE` case fails with `DATATYPE_MISMATCH`. An EXPLAIN-only CALL with a nondeterministic argument would fail with `INVALID_NON_DETERMINISTIC_EXPRESSIONS` instead of printing a plan. - Or require a `ResolvedProcedure` child here and in the CheckAnalysis guard, which keeps the previous behavior. Either way, a test with `EXPLAIN CALL cat.ns.sum(rand(), 1)` would pin it. ########## sql/core/src/test/scala/org/apache/spark/sql/connector/ProcedureSuite.scala: ########## @@ -974,6 +1015,45 @@ class ProcedureSuite extends SharedSparkSession with BeforeAndAfter { override def description: String = "simple sum integers" } + abstract class TimestampProcedure extends BoundProcedure { + override def description: String = "returns a timestamp and an optional label" + + override def isDeterministic: Boolean = true + + override def parameters: Array[ProcedureParameter] = Array( + ProcedureParameter.in("ts", DataTypes.TimestampType).build(), + ProcedureParameter.in("label", DataTypes.StringType).defaultValue("'none'").build()) + + def outputType: StructType = new StructType() + .add("ts", DataTypes.TimestampType) + .add("label", DataTypes.StringType) + + override def call(input: InternalRow): java.util.Iterator[Scan] = { + val result = Result(outputType, Array(InternalRow(input.getLong(0), input.getUTF8String(1)))) + Collections.singleton[Scan](result).iterator() + } + } + + object SimpleTimestampProcedure extends TimestampProcedure with SimpleProcedure { + override def name: String = "simple_ts" + } + + class RebindingTimestampProcedure(binds: AtomicInteger, isBound: Boolean) Review Comment: **[5] Nit: the rebinding helper only checks `call()`.** The catalog instance and the instance from `bind()` share `parameters`. So this test shows that `call()` reaches the bound object, but not that coercion and `checkArgTypes` read the bound object's `parameters`. Both come from the same `ResolvedProcedure` today, so this would only pin it down. Nothing reads the unbound instance's `parameters`, so asserting `isBound` there too would work. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala: ########## @@ -2648,14 +2648,15 @@ class Analyzer( */ object BindProcedures extends Rule[LogicalPlan] { def apply(plan: LogicalPlan): LogicalPlan = plan resolveOperators { - case Call(ResolvedProcedure(catalog, ident, unbound: UnboundProcedure), args, execute) - if args.forall(_.resolved) => + case c @ Call(ResolvedProcedure(catalog, ident, unbound: UnboundProcedure), args, execute, _) + if !c.bound && args.forall(_.resolved) => val inputType = extractInputType(args) - val bound = unbound.bind(inputType) - validateParameterModes(bound) + val boundProcedure = unbound.bind(inputType) + validateParameterModes(boundProcedure) val rearrangedArgs = - NamedParametersSupport.defaultRearrange(bound, args, SQLConf.get.resolver) - Call(ResolvedProcedure(catalog, ident, bound), rearrangedArgs, execute) + NamedParametersSupport.defaultRearrange(boundProcedure, args, SQLConf.get.resolver) + Call( Review Comment: **[4] `c.copy(...)` would keep the other fields of `Call`.** `c` is already bound here, and the sibling code uses `copy`: `c.copy(args = coercedArgs)` in `ProcedureArgumentCoercion`, and `stageForExplain` and `withNewChildInternal` in `Call`. The constructor works today. But if `Call` gets another field with a default, the pattern at L2651 stops compiling while this call still compiles and silently resets that field. That is the same hazard the description points out for extensions. ```scala case c @ Call(ResolvedProcedure(catalog, ident, unbound: UnboundProcedure), args, _, false) if args.forall(_.resolved) => ... c.copy( procedure = ResolvedProcedure(catalog, ident, boundProcedure), args = rearrangedArgs, bound = true) ``` ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala: ########## @@ -2368,27 +2368,27 @@ case class CloseCursor(cursor: Expression) extends LeafCommand /** * The logical plan of the CALL statement. + * + * @param bound whether `BindProcedures` has bound the procedure and rearranged the arguments to + * match its parameters. This can't be derived from the procedure type, as a + * procedure may implement both `UnboundProcedure` and `BoundProcedure`. */ case class Call( procedure: LogicalPlan, args: Seq[Expression], - execute: Boolean = true) + execute: Boolean = true, + bound: Boolean = false) Review Comment: Two details for the backports: - branch-4.0 and branch-4.1 have one more three-field pattern, `case Call(UnresolvedProcedure(CatalogAndIdentifier(catalog, ident)), args, execute)` in `ResolveProcedures`, and no `SimpleProcedure`. So this PR does not apply there as is. - A compiled `case Call(p, args, execute)` keeps linking, because scalac compiles a case-class pattern to `instanceof` and accessor calls rather than `unapply`; it just ignores `bound`. Construction and `copy` are what break: `Call(p, args)` compiles to `new Call(LogicalPlan, Seq, boolean)`, and both fail with `NoSuchMethodError`. An explicit `Call.unapply(c)` would fail with a `ClassCastException` instead. I checked this with `javap` on code compiled against the 4.3.0 jar. Item 3 of my review sketches a way to keep the three fields of `Call` on every branch. -- 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]
