spark-test commented on code in PR #60768:
URL: https://github.com/apache/spark/pull/60768#discussion_r4650399091
##########
sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala:
##########
@@ -125,10 +126,24 @@ class UDFRegistration private[sql] (session:
SparkSession, functionRegistry: Fun
case udf: SparkUserDefinedFunction =>
toScalaUDF(udf, _)
}
- functionRegistry.createOrReplaceTempFunction(name, builder, source)
+ functionRegistry.createOrReplaceTempFunction(
+ name, rejectNamedArguments(name, builder), source)
named
}
+ /**
+ * Wraps the builder of a Scala or Java function, which takes its arguments
by position only, so
+ * that a call with a named argument fails the analysis, instead of the
execution.
+ */
+ private def rejectNamedArguments(
+ name: String,
+ builder: Seq[Expression] => Expression): Seq[Expression] => Expression =
{ children =>
+ if (children.exists(_.isInstanceOf[NamedArgumentExpression])) {
+ throw QueryCompilationErrors.namedArgumentsNotSupported(name)
Review Comment:
**Blocking (P1):** This throw also runs for calls that do not resolve to
this function. `SessionCatalog.resolveScalarFunctionByIdentifier`
(SessionCatalog.scala:2683-2695) invokes a temporary function's builder first,
and only then does `handleViewContext` (SessionCatalog.scala:2571-2585) hide
the function from a stored view that did not capture it. Under the default
order (`system.builtin`, `system.session`, then the view's schema), the builder
of a same-named function registered through `spark.udf.register` is therefore
invoked while a view is resolved, even when the view's call belongs to another
function.
For example, following the code: after `CREATE FUNCTION default.f(x BIGINT)
RETURNS BIGINT RETURN x + 1` and `CREATE VIEW default.v AS SELECT f(x => 1L) AS
r`, a session that runs `spark.udf.register("f", (x: Long) => x + 1)` and then
`SELECT * FROM default.v` gets 2 on the base branch, because the temporary `f`
is built, discarded, and `default.f` resolves. With this change the speculative
build throws `NAMED_PARAMETERS_NOT_SUPPORTED` for `f` before the filter runs,
so reading the view fails during analysis with an error about a function the
view does not use. The same applies to temporary views created from SQL text
before the function was registered, and to the bodies of SQL functions that
such views call.
**Recommended change:** In SessionCatalog.resolveScalarFunctionByIdentifier
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/catalog/SessionCatalog.scala,
lines 2683-2695), return None for a temporary function that
isTempFunctionVisibleInContext reports as hidden, before invoking its builder.
Otherwise build the function and pass it through handleViewContext as today.
Add SQL view and function resolution tests that read a permanent view calling a
persistent SQL function with a named argument, in a session that has registered
a same-named function through spark.udf.register.
**Why this works:** Deciding visibility first means the builder of a hidden
temporary function never runs. Neither the named-argument rejection nor any
other builder failure can then escape for a function the view cannot see, and
resolution moves on to the next candidate on the path, as the stored-view
filter intends. Visible temporary functions are built, filtered and recorded as
before, through the side-effect-free visibility check that SessionCatalog
already uses for ownership probes (SessionCatalog.scala, lines 2463-2471).
**Compatibility:** Outside stored views, and inside a view that captured the
temporary function, the function is built and its name is recorded exactly as
on the base branch. Named-argument calls that resolve to a function registered
through spark.udf.register therefore still fail during analysis with
NAMED_PARAMETERS_NOT_SUPPORTED.
**Risks:** Builders of temporary functions that a stored view did not
capture no longer run while the view is resolved. The errors they raised there
on the base branch, such as WRONG_NUM_ARGS from an arity-checked Scala or Java
function or NAMED_PARAMETERS_NOT_SUPPORTED from a Python UDF without
named-argument support, no longer fail views that do not use them. Every view
that resolved on the base branch resolves to the same functions, so the change
needs no flag to roll it back.
**Constraints:** Keep the visibility check inside the existing synchronized
block of resolveScalarFunctionByIdentifier (SessionCatalog.scala, lines
2689-2691). Do not record the name of a hidden temporary function, so
permanent-view creation still rejects only the temporary functions a view body
actually uses.
**Exclusions:**
- The same build-before-filter order is left unchanged in
resolveTableFunctionByIdentifier (SessionCatalog.scala, lines 2701-2715) and in
the unused private resolveInNamespace (lines 239-254). No table-function
builder or caller that this change concerns can throw for a hidden temporary
function.
**Verification:**
- **Regression:** Create a persistent SQL function f with one BIGINT
parameter, and a permanent view whose body calls f(x => 1L) while no temporary
function f exists. Then register a same-named Scala closure through
spark.udf.register and read the view. The read returns the persistent
function's result instead of failing with NAMED_PARAMETERS_NOT_SUPPORTED. The
same holds when the temporary function is a UserDefinedFunction, a typed
Aggregator or a UserDefinedAggregateFunction, and when the view is a temporary
view created from SQL text before the function was registered.
- **Behavior:** In the same session, a top-level named-argument call to the
registered temporary function still fails during analysis with
NAMED_PARAMETERS_NOT_SUPPORTED, and a positional call to it still returns its
result.
- **Compatibility:** Outside stored views, creating a permanent view whose
body calls the temporary function positionally still fails with the
temporary-object reference error. A temporary view that calls it positionally
still resolves to the temporary function when read.
##########
sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala:
##########
@@ -125,10 +126,24 @@ class UDFRegistration private[sql] (session:
SparkSession, functionRegistry: Fun
case udf: SparkUserDefinedFunction =>
toScalaUDF(udf, _)
}
- functionRegistry.createOrReplaceTempFunction(name, builder, source)
+ functionRegistry.createOrReplaceTempFunction(
+ name, rejectNamedArguments(name, builder), source)
named
}
+ /**
+ * Wraps the builder of a Scala or Java function, which takes its arguments
by position only, so
+ * that a call with a named argument fails the analysis, instead of the
execution.
+ */
+ private def rejectNamedArguments(
Review Comment:
**Non-blocking (P2):** Because this helper is private to the classic
`UDFRegistration`, only the builders that its two `register` methods install
reject named arguments. Functions created with `CREATE [TEMPORARY] FUNCTION ...
AS '<class>'` get their builders from
`SessionCatalog.makeFunctionBuilderAndInfo` (SessionCatalog.scala:2085-2109): a
`UserDefinedAggregateFunction` class goes through
`SparkUDFExpressionBuilder.makeExpression`
(BaseSessionStateBuilder.scala:502-518), which checks only the argument count,
Hive UDF classes go through `HiveUDFExpressionBuilder`
(HiveSessionStateBuilder.scala:200-259), and V2 function classes go through
`V2ExpressionUtils.bindFunction`. V2 functions loaded from a function catalog
are bound in `FunctionResolution.resolveV2Function`
(FunctionResolution.scala:826-837). Each of them keeps the
`NamedArgumentExpression` as an argument, so a call such as `f5(x => 1L)` still
passes analysis and fails with `INTERNAL_ERROR` during execution. The same `Use
rDefinedAggregateFunction` class thus gets the new analysis error when
registered with `spark.udf.register` (the `f4` case in the new test) and the
old `INTERNAL_ERROR` when created with `CREATE TEMPORARY FUNCTION`. If these
routes are meant to stay out of this PR, a TODO at this helper that names them
would make the partial coverage visible to readers.
**Recommended change:** Move the check that the PR adds to the classic
UDFRegistration
(sql/core/src/main/scala/org/apache/spark/sql/classic/UDFRegistration.scala,
lines 138-145) into a shared helper beside NamedParametersSupport in catalyst,
and keep the spark.udf.register wrapper on that helper. Apply the helper in the
builders that both branches of SessionCatalog.makeFunctionBuilderAndInfo
create, the one that binds a V2 function class and the one that calls
functionExpressionBuilder.makeExpression, and in
FunctionResolution.resolveV2Function before a V2 catalog function is bound. Add
tests to the function command tests, the Hive UDF tests and the DataSourceV2
function tests that call a class-based UserDefinedAggregateFunction, Hive UDF
classes and V2 functions with a named argument.
**Why this works:** Every route that builds a positional-only JVM function
then rejects a named argument before any expression is built, with the same
NAMED_PARAMETERS_NOT_SUPPORTED error and function name. A call that would
otherwise carry an unevaluable named argument into execution fails during
analysis instead.
**Risks:** A query or stored view that contains a named-argument call to a
class-based or V2 function succeeds on the base branch only when the call is
never evaluated, such as when the optimizer removes it, and will fail during
analysis afterwards, as such calls to built-in functions already do. The call
never produces a value on the base branch, so failing such a query early loses
nothing the call produced, and the change has no flag to roll it back.
**Constraints:** Land this change together with, or after, the change that
makes SessionCatalog skip building temporary functions a stored view cannot
see. Without it, a temporary class-based function would break stored views that
do not use it, which is the failure the stored-view finding describes. The
shared check must reject a call when any argument, not only the first, is
passed by name. It must keep the existing NAMED_PARAMETERS_NOT_SUPPORTED error
and parameters for every route.
**Exclusions:**
- The built-in function wrapper (FunctionRegistry.scala, lines 1306-1310)
and the Python UDF builder (UserDefinedPythonFunction.scala, lines 75-92) keep
their own checks. Moving them onto the shared helper is left out because they
already reject named arguments with the same error.
**Verification:**
- **Behavior:** Create a UserDefinedAggregateFunction class once with CREATE
TEMPORARY FUNCTION and once with CREATE FUNCTION. Called with a named argument,
each fails during analysis with NAMED_PARAMETERS_NOT_SUPPORTED naming the
function. Called positionally, each returns its result.
- **Behavior:** In a Hive-enabled session, a Hive UDF class and a GenericUDF
class created with CREATE TEMPORARY FUNCTION fail during analysis with
NAMED_PARAMETERS_NOT_SUPPORTED for a named-argument call, and positional calls
are unchanged.
- **Behavior:** A V2 function loaded from a function catalog, and a V2
UnboundFunction class created with CREATE FUNCTION, fail during analysis with
NAMED_PARAMETERS_NOT_SUPPORTED for a named-argument call, and positional calls
are unchanged.
- **Regression:** In a session that has created a temporary class-based
function with the same name as a persistent SQL function, reading a permanent
view that calls the persistent function with a named argument returns the
persistent function's result.
- **Compatibility:** A persistent SQL function called with a named argument
still returns the same result as the equivalent positional call.
##########
sql/core/src/test/scala/org/apache/spark/sql/UDFSuite.scala:
##########
@@ -171,6 +171,33 @@ class UDFSuite extends SharedSparkSession {
)
}
+ test("SPARK-62146: error reporting for named arguments - udf") {
+ val legacyUdaf = new UserDefinedAggregateFunction {
+ def inputSchema: StructType = new StructType().add("a", LongType)
+ def bufferSchema: StructType = new StructType().add("sum", LongType)
+ def dataType: DataType = LongType
+ def deterministic: Boolean = true
+ def initialize(buffer: MutableAggregationBuffer): Unit = {}
+ def update(buffer: MutableAggregationBuffer, input: Row): Unit = {}
+ def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit = {}
+ def evaluate(buffer: Row): Any = buffer.getLong(0)
+ }
+ withUserDefinedFunction("f1" -> true, "f2" -> true, "f3" -> true, "f4" ->
true) {
+ spark.udf.register("f1", (x: Long) => x + 1)
+ spark.udf.register("f2", udf((x: Long) => x + 1))
+ spark.udf.register("f3", udaf(KryoBufAggregator()))
+ spark.udf.register("f4", legacyUdaf)
+ Seq("f1", "f2", "f3", "f4").foreach { name =>
+ val call = s"$name(x => 1L)"
Review Comment:
**Nit (P3):** Every case here registers a one-parameter function and calls
it with its only argument named, so `children.exists(...)`, a check of only the
first argument, and a check that every argument is named all give the same
answer on these inputs. If the check in `rejectNamedArguments`
(UDFRegistration.scala:141) were later narrowed to either of the latter, all
four cases would still pass, while a mixed call such as `g(1L, b => 2L)` on
`spark.udf.register("g", (a: Long, b: Long) => a + b)` would again build a
`ScalaUDF` with an unevaluable argument and fail with `INTERNAL_ERROR` during
execution.
**Verification:**
- **Behavior:** Register a two-parameter Scala function with
spark.udf.register and call it with a positional argument followed by a named
one. The call fails during analysis with NAMED_PARAMETERS_NOT_SUPPORTED, naming
the function and pointing at the call, so the test fails if the check is
narrowed to the first argument or to calls whose arguments are all named.
--
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]