← Back to Pull requests

[SPARK-59970][SQL] Reject a temporary variable read through an IDENTIFIER clause in a persistent SQL function #59226

Closed
unknown closed this pull request without merging on Nov 06, 2026 08:31 UTC
View on GitHub
unknown unknown commented on Oct 03, 2026 09:13 UTC
Author

What changes were proposed in this pull request?

CreateSQLFunctionCommand now captures the temporary variables that the function body reads only inside IDENTIFIER clauses and treats them like any other temporary variable reference: a persistent function is rejected with INVALID_TEMP_OBJ_REFERENCE, and a temporary function records them in its referredTempVariableNames property.

The names are recorded by ResolveIdentifierClause in AnalysisContext.referredTempVariableNamesUnderIdentifier (SPARK-59323), but the command analyzed the body with Analyzer.execute, which opens a fresh AnalysisContext and discards the accumulator on exit. A new Analyzer.executeWithReferredTempVariablesUnderIdentifier runs the same fixed-point analysis in a context it owns and returns the recorded names alongside the analyzed plan. It is the sibling of executeAndCheckReferredTempVariablesUnderIdentifier, minus checkAnalysis, because the function command inspects the analyzed body (return type inference, aggregate/window checks) before checking it. Both analysis sites (scalar and table function) use it, and the names are unioned into verifyTemporaryObjectsNotExists and generateFunctionProperties.

Only the variables read by the function body itself are attributed to it. A SQL function that the body calls is expanded in a context of its own (a new AnalysisContext flag, shareIdentifierVariablesWithNestedSQLFunctions, which the function-creation entry point turns off), so a variable that an existing function reads through an IDENTIFIER clause stays that function's dependency: CREATE FUNCTION g(x) RETURN f2(x) is not rejected for f2's variable.
View bodies keep sharing the accumulator with the functions they expand, as SPARK-59323 designed.

spark.sql.legacy.allowSessionVariableInPersistedView is honored for functions as it is for views: with it set, a persistent function may read the variable through an IDENTIFIER clause. As with persisted views, the dependency is not stored (a persistent function records no temporary variable names at all), so the function only resolves while the variable exists.

Bodies without IDENTIFIER clauses are unaffected.

Why are the changes needed?

A persistent SQL function could capture a session-scoped dependency and then fail in another session:

DECLARE OR REPLACE VARIABLE col STRING DEFAULT 'a';
CREATE FUNCTION f(x INT) RETURNS INT RETURN (SELECT IDENTIFIER(col) FROM VALUES (1) AS T(a));
-- succeeds; in a new session:
SELECT f(1);
-- [NOT_A_CONSTANT_STRING.NOT_CONSTANT] The expression col used for the routine or clause
-- IDENTIFIER must be a constant STRING which is NOT NULL.

A direct reference (RETURN x + length(col)) was already rejected, because ViewHelper.collectTemporaryVariables sees the VariableReference in the analyzed plan. Under an IDENTIFIER clause the reference is gone by then: the placeholder is replaced by the expression or plan built from the evaluated name.

SPARK-59323 (#58606) fixed the same gap for CREATE VIEW, ALTER VIEW, CACHE TABLE AS SELECT and metric views; its review noted the SQL function path as pre-existing and to be tracked separately.

Does this PR introduce _any_ user-facing change?

Yes. CREATE FUNCTION (persistent) whose body reads a temporary variable only through an IDENTIFIER clause now fails with INVALID_TEMP_OBJ_REFERENCE at creation, matching a direct variable reference, instead of succeeding and failing later when the function is called from a session where the variable does not exist. Setting
spark.sql.legacy.allowSessionVariableInPersistedView restores the previous behavior; a migration-guide entry is added under 4.3 to 4.4 (branch-4.3 predates the SPARK-59323 mechanism this builds on). Temporary functions are unchanged in behavior; their stored referredTempVariableNames now also lists such variables.

How was this patch tested?

New cases in sql-udf.sql (regenerated through SQLQueryTestSuite), in the existing "permanent functions with temp objects" section:

  • a direct temporary variable reference, as the baseline rejection;

  • a variable read through IDENTIFIER in a scalar function body and in a table function body,

  • both rejected with INVALID_TEMP_OBJ_REFERENCE naming the variable (both were accepted before
    this change);
  • a temporary function reading the variable through IDENTIFIER is created and evaluates;

  • the variable naming a relation (FROM IDENTIFIER(v)), a session.-qualified variable name,

  • and two variables in one body, all rejected;
  • with the legacy flag set, a persistent function reading the variable is created and evaluates;

  • with the flag off again, a function calling it is created and evaluates (the callee's variable
    is not attributed to the caller).

    SQLFunctionSuite gains two tests: the nested case (the callee is created under the legacy flag; the caller, created with the flag off, is accepted because the callee’s variable is not attributed to it; a direct IDENTIFIER read in the caller’s own body is rejected) and one that reads the stored function properties to pin that a temporary function records the variable in referredTempVariableNames while a persistent function created under the legacy flag stores none.

    SPARK_GENERATE_GOLDEN_FILES=1 build/sbt "sql/testOnly org.apache.spark.sql.SQLQueryTestSuite -- -z sql-udf.sql"
    build/sbt "sql/testOnly org.apache.spark.sql.SQLQueryTestSuite -- -z sql-udf.sql -z identifier-clause" "sql/testOnly org.apache.spark.sql.execution.SQLFunctionSuite org.apache.spark.sql.execution.SimpleMetricViewSuite org.apache.spark.sql.connector.DataSourceV2MetadataViewSuite"
    

    Was this patch authored or co-authored using generative AI tooling?

    Generated-by: Claude claude-opus-4-8

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: stevomitric Review duration: 48918m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #59226"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository