cloud-fan commented on code in PR #60213:
URL: https://github.com/apache/spark/pull/60213#discussion_r4537919916


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -306,13 +309,20 @@ object AnalysisContext {
       // and must be recorded there. Sharing the caller's set records it; a 
nested view, by
       // contrast, stores its own and so is reset. The exception is a SQL 
function body under
       // creation, which must not inherit the dependencies of the functions it 
calls; see
-      // `shareIdentifierVariablesWithNestedSQLFunctions`.
+      // `shareTempReferencesWithNestedSQLFunctions`.
       referredTempVariableNamesUnderIdentifier =
-        if (originContext.shareIdentifierVariablesWithNestedSQLFunctions) {
+        if (originContext.shareTempReferencesWithNestedSQLFunctions) {
           originContext.referredTempVariableNamesUnderIdentifier
         } else {
           mutable.LinkedHashSet.empty
         },
+      // The same holds for the temporary functions the body binds.
+      referredTempFunctionNames =

Review Comment:
   **Blocking (P1):** This fresh set only covers what the callee's plan 
resolves inside `withAnalysisContext(function)`. A named-argument call to an 
existing scalar SQL function goes through `rearrangeArguments` in 
`makeSQLFunctionBuilder`, which puts the callee's parsed DEFAULT into the 
`SQLFunctionExpression` inputs in the caller's plan. `ResolveSQLFunctions` only 
expands the call once the enclosing `Project` is resolved, so the caller's 
`ResolveFunctions` binds that default first, and `handleViewContext` records 
any temporary function it hits in the creating function's set.
   
   Reading the code, with default settings:
   
   ```sql
   CREATE FUNCTION g() RETURNS INT RETURN 1;
   CREATE FUNCTION inner_fn(x INT, y INT DEFAULT g()) RETURNS INT RETURN x + y;
   CREATE TEMPORARY FUNCTION g() RETURNS INT RETURN 2;
   CREATE FUNCTION c1() RETURNS INT RETURN inner_fn(1);       -- created
   CREATE FUNCTION c2() RETURNS INT RETURN inner_fn(x => 1);  -- 
INVALID_TEMP_OBJ_REFERENCE on g
   ```
   
   Both are created on the base branch and in 4.3.0, and in other sessions the 
stored `c2` resolves the default under its own path. So whether a callee's 
default counts as a reference of the new function depends on how the call is 
written, contrary to the `shareTempReferencesWithNestedSQLFunctions` comment 
that a temporary function an existing function uses is that function's 
dependency. A temporary function created with `inner_fn(x => 1)` also stores 
`g` in `referredTempFunctionsNames`. Table SQL function callees are not 
affected: `ResolveSQLTableFunctions` expands them in the same iteration, inside 
the callee's context. The new tests only cover positional and zero-argument 
calls.
   
   **Recommended change:** Resolve each DEFAULT that named-argument filling 
inserts into a scalar SQL function call in a scope of its own: the caller's 
path, configs, and session as today, but with temporary-function and 
IDENTIFIER-variable recording decided by the same sharing rule a nested SQL 
function body uses. When the enclosing analysis does not share temporary 
references with nested SQL functions (SQL function creation), bindings inside 
the default go to a fresh set. Otherwise (views, CACHE TABLE, queries) they go 
to the enclosing set as they do now. Table SQL function calls need no change, 
because their inserted defaults already resolve inside the callee's context. 
Add SQL function tests for named-argument calls to a scalar SQL function whose 
omitted DEFAULT binds a temporary function, with a table SQL function called 
the same way as a control.
   
   **Why this works:** The rejection and the stored metadata read only the 
creating context's set. Once the inserted defaults are analyzed in a scope that 
applies the nested-function sharing rule, a temporary function they bind lands 
in a throwaway set during SQL function creation, just as it does when a 
positional call pads the same default inside the callee, so call syntax no 
longer decides whether it counts. Because the scope keeps the caller's path and 
configs, the default resolves to the same function it resolves to today.
   
   **Scope:** Named-argument default filling for scalar SQL function calls gets 
an isolated resolution scope that follows the nested-function sharing rule; 
tests cover named calls during function creation and for views, with a 
table-function call as a control.
   
   **Compatibility:** Scalar named-argument defaults resolve under the caller's 
path and configs and table-function named defaults under the callee's, as on 
the base branch, and views and CACHE TABLE keep recording every temporary 
function the functions they expand bind.
   
   **Risks:** The new resolution scope must leave a named-argument default's 
resolved expression identical to today's; resolving it through a separate step 
can change error timing or messages for an invalid default, and only a revert 
rolls this back.
   
   **Constraints:** Keep the caller's path, configs, and session for scalar 
named-argument defaults; do not switch them to the callee's context. Views, 
ALTER VIEW, and CACHE TABLE must still record a temporary function bound inside 
such a default, since they share every dependency of the functions they expand. 
Apply the same rule to IDENTIFIER-clause variables read inside the default, 
matching the existing nested-function sharing for variables.
   
   **Exclusions:**
   - Making scalar named-argument defaults resolve in the callee's context, as 
positional defaults and table-function named defaults do, is left out because 
it changes query results beyond this PR's problem.
   
   **Success:** CREATE FUNCTION c() RETURNS INT RETURN inner_fn(x => 1) is 
created when inner_fn's omitted DEFAULT binds a same-named temporary function, 
exactly as the positional inner_fn(1) is. A temporary SQL function created with 
such a call does not list that temporary function in 
referredTempFunctionsNames. A persistent view selecting inner_fn(x => 1) is 
still rejected, and a temporary view still records the temporary function. A 
named-argument call evaluates its omitted defaults to the same values as on the 
base branch. A function whose body calls a table SQL function with named 
arguments, omitting a parameter whose DEFAULT binds the same temporary 
function, is still created.
   
   **Verification:**
   - **Regression:** With a persistent scalar SQL function whose parameter 
DEFAULT calls an unqualified function that a temporary function of the same 
name shadows, creating a persistent scalar function and a persistent table 
function whose bodies call it with named arguments omitting that parameter 
succeeds, and calling them in a session without the temporary function returns 
the persistent function's value.
   - **Behavior:** A temporary SQL function created the same way stores no 
entry for the shadowing temporary function in its referred temporary function 
metadata.
   - **Compatibility:** A persistent view over the same named-argument call is 
still rejected for the temporary function, and the call's result in an ordinary 
query is unchanged from the base branch.
   - **Compatibility:** A persistent function whose body calls a table SQL 
function with named arguments, omitting a parameter whose DEFAULT binds the 
same temporary function, is still created and returns the persistent function's 
value.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/command/CreateSQLFunctionCommand.scala:
##########
@@ -174,8 +175,8 @@ case class CreateSQLFunctionCommand(
         checkCyclicFunctionReference(catalog, name, plan)
 
         // Check the function body can be analyzed correctly.
-        val (analyzed, referredTempVarsUnderIdentifier) =
-          analyzer.executeWithReferredTempVariablesUnderIdentifier(plan)
+        val (analyzed, referredTempFuncs, referredTempVarsUnderIdentifier) =

Review Comment:
   **Non-blocking (P2):** Analysis now follows the real binding, but 
`checkCyclicFunctionReference` just above still uses `lookupFunctionInfo` / 
`lookupFunction`, which try built-in and temporary functions before the current 
schema and ignore `sessionOrder` and the SQL path. Reading the code, with 
`spark.sql.functionResolution.sessionOrder=last` (or `SET PATH = 
spark_catalog.default, system.session, system.builtin`):
   
   ```sql
   CREATE FUNCTION a() RETURNS INT RETURN 1;
   CREATE FUNCTION pf() RETURNS INT RETURN a();
   CREATE TEMPORARY FUNCTION pf() RETURNS INT RETURN 42;
   CREATE OR REPLACE FUNCTION a() RETURNS INT RETURN pf();
   ```
   
   The cycle check expands the temporary `pf` and finds no cycle. Analysis 
binds the persistent `pf` and records nothing for the temporary one, so `a` is 
replaced and the stored functions form `a -> pf -> a`. The base branch failed 
this statement with INVALID_TEMP_OBJ_REFERENCE, and without the temporary `pf` 
it fails with CYCLIC_FUNCTION_REFERENCE. Now the working `a` is replaced, and 
every later call to `a` or `pf` recurses until analysis fails.
   
   **Verification:**
   - **Regression:** Under sessionOrder=last and under a SQL path that lists 
the persistent schema before system.session, replacing a function so that its 
body calls a persistent function that calls it back, while a same-named 
temporary function shadows the callee by name, fails with a cyclic function 
reference error for scalar and table function calls, and the previous 
definition still works afterwards.
   - **Compatibility:** A body whose call a persistent function owns ahead of a 
same-named temporary function, with no cycle, is still created and returns the 
persistent function's value.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionResolution.scala:
##########
@@ -390,6 +390,19 @@ class FunctionResolution(
     }
   }
 
+  /**
+   * Whether [[lookupBuiltinOrTempFunction]] finds the function. An 
unqualified name records no
+   * temp reference, see `SessionCatalog.builtinOrTempFunctionExists`.
+   */
+  def builtinOrTempFunctionExists(
+      nameParts: Seq[String],
+      unresolvedFunc: Option[UnresolvedFunction]): Boolean =
+    if (nameParts.length == 1 && !unresolvedFunc.exists(_.isInternal)) {
+      v1SessionCatalog.builtinOrTempFunctionExists(nameParts.head)
+    } else {
+      lookupBuiltinOrTempFunction(nameParts, unresolvedFunc).isDefined

Review Comment:
   **Blocking (P1):** This branch still records. For `session.f`, 
`lookupBuiltinOrTempFunction` maps the name to `system.session.f` and calls 
`lookupFunctionInfoByIdentifier`, whose `handleViewContext` adds `f` to 
`referredTempFunctionNames` before `ResolveFunctions` picks the owner. Under 
`spark.sql.legacy.persistentCatalogFirst=true`, `resolutionCandidates` tries 
the persistent `session.f` first. Reading the code, with the setup from 
FunctionQualificationSuite SECTION 16g:
   
   ```sql
   SET spark.sql.legacy.persistentCatalogFirst=true;
   CREATE DATABASE session;
   CREATE FUNCTION session.test_func() RETURNS STRING RETURN 'persistent';
   CREATE TEMPORARY FUNCTION test_func() RETURNS STRING RETURN 'temp';
   CREATE FUNCTION default.caller() RETURNS STRING RETURN session.test_func();
   ```
   
   The last statement binds only the persistent function, but it now fails with 
INVALID_TEMP_OBJ_REFERENCE on `test_func`. On the base branch it was created, 
because the old scan's `isTemporaryFunction(FunctionIdentifier(test_func, 
Some(session)))` is false without the `system` catalog. The new 
`LookupFunctions` comment and the new sentence in the CREATE FUNCTION and 
CREATE VIEW references both say a persistent owner is not a reference, which 
does not hold on this path. The PR defers fixing qualified calls; this is a new 
rejection of one that used to work.
   
   **Recommended change:** Make the session-qualified branch of 
FunctionResolution.builtinOrTempFunctionExists check existence without 
recording: map the name to its system.builtin or system.session identifier and 
test the scalar registry, applying the same stored-view visibility predicate 
used for unqualified temporary functions, as 
SessionCatalog.builtinOrTempFunctionExists already does for unqualified names. 
Keep the internal-function and other multi-part handling unchanged. Add SQL 
function and view tests under spark.sql.legacy.persistentCatalogFirst=true with 
a schema named session.
   
   **Why this works:** With the early check side-effect free for every name 
shape, the set holds only functions that binding chose. Under the legacy flag 
binding picks the persistent session.f and records nothing; under the default 
order it picks system.session.f and records it, so the rejection follows the 
owner and the LookupFunctions comment and the reference docs become true.
   
   **Scope:** The quick check stops recording for session-qualified names; 
tests cover function and view creation under both qualified-name orders.
   
   **Risks:** Persistent views and temporary view metadata under the legacy 
flag also change: a qualified call a persistent function owns is no longer 
rejected or recorded, which is the same correction the PR makes for unqualified 
calls; only a revert rolls it back.
   
   **Constraints:** The existence answer must stay identical to the recording 
lookup's isDefined for every name, so LookupFunctions takes the 
external-catalog path for exactly the same calls.
   
   **Exclusions:**
   - The cycle check's failure for 2-part session.f without a schema named 
session, and for 3-part system.session.f, is unchanged; the PR defers qualified 
calls in function bodies.
   
   **Success:** Under spark.sql.legacy.persistentCatalogFirst=true, with a 
schema named session holding f and a temporary f, CREATE FUNCTION c() RETURN 
session.f() is created and CREATE VIEW v AS SELECT session.f() succeeds. Under 
the default order with the same objects, persistent CREATE FUNCTION over 
session.f() still fails with INVALID_TEMP_OBJ_REFERENCE naming f. 
LookupFunctions records no temporary function for any name shape.
   
   **Verification:**
   - **Regression:** Under spark.sql.legacy.persistentCatalogFirst=true with a 
schema named session holding a persistent function and a same-named temporary 
function, creating a persistent function and a persistent view that call it 
session-qualified succeeds, both return the persistent function's value, and a 
temporary function created the same way stores no referred temporary function.
   - **Behavior:** Under the default qualified-name order with the same 
objects, a persistent function whose body calls the session-qualified name is 
rejected for the temporary function.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -603,25 +609,29 @@ class Analyzer(
   }
 
   /**
-   * Like [[execute]], but also returns the temporary variables recorded via 
IDENTIFIER clauses
-   * during this analysis 
(`AnalysisContext.referredTempVariableNamesUnderIdentifier`).
+   * Like [[execute]], but also returns the temporary functions the analysis 
bound
+   * (`AnalysisContext.referredTempFunctionNames`) and the temporary variables 
recorded via
+   * IDENTIFIER clauses 
(`AnalysisContext.referredTempVariableNamesUnderIdentifier`).
    *
    * SQL function creation analyzes the body, inspects it, and only then runs 
`checkAnalysis`, so
    * it cannot go through 
[[executeAndCheckReferredTempVariablesUnderIdentifier]]. It still needs
-   * the recorded variables, which [[execute]] discards with its analysis 
context: a persistent
-   * function must reject them and a temporary one stores them in its metadata.
+   * the recorded names, which [[execute]] discards with its analysis context: 
a persistent
+   * function must reject them and a temporary one stores the variables in its 
metadata.

Review Comment:
   **Nit (P3):** A temporary SQL function stores both returned lists: 
`generateFunctionProperties` keeps `referredTempFunctions.sorted` as 
`referredTempFunctionsNames` next to the variables, and the new test checks it. 
The base branch's "stores them" is accurate again:
   
   ```suggestion
      * function must reject them and a temporary one stores them in its 
metadata.
   ```
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -163,7 +163,8 @@ case class AnalysisContext(
     // 1. If we are resolving a view, this field will be restored from the 
view metadata,
     //    by calling `AnalysisContext.withAnalysisContext(viewDesc)`.
     // 2. If we are not resolving a view, this field will be updated everytime 
the analyzer
-    //    lookup a temporary function. And export to the view metadata.
+    //    lookup a temporary function. And export to the view metadata, or 
checked by persistent

Review Comment:
   **Nit (P3):** After this PR the `LookupFunctions` quick check no longer 
records an unqualified temporary function, so this field is written when 
resolution binds one. Temporary SQL function creation also reads it and stores 
it as `referredTempFunctionsNames`. The fragment is also hard to parse. 
Possible wording: "this field is updated each time the analyzer binds a 
temporary function, then exported to view or temporary SQL function metadata, 
or rejected by persistent SQL function creation." The word "binds" becomes 
fully accurate once the session-qualified quick check stops recording too.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/resources/sql-tests/inputs/sql-udf.sql:
##########
@@ -856,6 +856,14 @@ DROP FUNCTION foo3_5g;
 DROP FUNCTION foo3_5f;
 DROP TEMPORARY VARIABLE foo3_5_tbl;
 DROP TEMPORARY VARIABLE foo3_5_col;
+-- Expect error naming foo3_5a: referenced temporary functions are reported in 
sorted order

Review Comment:
   **Nit (P3):** `referredTempFunctionNames` is a `mutable.HashSet`. With 16 
buckets and the spread String hash, `foo3_5a` lands in bucket 4 and `foo3_5b` 
in bucket 5 (`temp_fn` and `temp_tvf` in the suite test land in 3 and 12), so 
the set already iterates alphabetically. Deleting `.sorted` at either site in 
`CreateSQLFunctionCommand` leaves this golden output and the metadata assertion 
unchanged. Names whose bucket order is the reverse of their alphabetical order, 
or more than two names, would make the tests fail without the sort. This case 
does still tell the new code apart from the old plan-order scan, which reported 
`foo3_5b`.
   
   **Verification:**
   - **Regression:** With names whose set iteration order is not alphabetical, 
the rejection reports the alphabetically first bound temporary function and the 
stored metadata lists the names alphabetically, and each assertion would fail 
if its sort were removed.



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