← Back to Pull requests

[SPARK-59243][SQL] Splice nested JSON constructors through routed/qualified calls #59828

Open
ganeshashree opened this pull request with 1971 lines diff across 20 files
View on GitHub
ganeshashree ganeshashree commented on Oct 27, 2026 11:45 UTC
Author

What changes were proposed in this pull request?

Follow-up to SPARK-59144. A nested JSON_ARRAY / JSON_OBJECT is now spliced as JSON instead of quoted as a string, however the outer constructor is called: plain, qualified (builtin.json_array(...)), or with clauses. Nested calls without clauses can now also be shadowed by a same-named function, like flat calls.

How it works:

  • The parser leaves a clause-free call with a nested constructor to function resolution, so the owner is decided there. Calls with a clause or FORMAT JSON always use the built-in.

  • The analyzer decides the owner once, and builds the built-in constructor once its arguments are resolved, deciding which arguments to splice from them. A small rule at the end of each iteration avoids extra analyzer passes when an argument resolves late.

  • ApplyDefaultCollation keeps the user-cast mark when it rebuilds a cast, so a user CAST(... AS STRING) still quotes the value.

  • The docs explain when a clause-free call can be shadowed and how to keep the built-in.
  • Why are the changes needed?

    After SPARK-59144, the result depended on how the constructor was written: builtin.json_object('a', json_object('b', 1)) returned {"a":"{\"b\":1}"} instead of {"a":{"b":1}}. SPARK-59144 left this, and routing of nested calls, to this ticket.

    Does this PR introduce _any_ user-facing change?

    Yes, but only compared to unreleased master (these constructors are not released yet):

  • Qualified, routed and clause-bearing calls splice nested constructors, e.g. builtin.json_array(json_array(1)) returns [[1]] instead of ["[1]"].

  • A nested clause-free call such as json_array(json_array(1)) can be shadowed by a same-named temporary or PATH function, like a flat call. As for flat calls, CREATE FUNCTION rejects such a body when a same-named temporary function exists; SPARK-60806 tracks improving that check.
  • How was this patch tested?

    New tests in JsonArraySuite, JsonObjectSuite, SparkSessionExtensionSuite, ResolverGuardSuite and parse-sql.sql. They cover splicing, shadowing, default collations, user casts, lambdas, subqueries, GROUP BY and analyzer iteration counts. Ran the JSON, collation, analyzer and SQL function suites, the related golden files, and scalastyle locally.

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

    Generated-by: Claude Code (Claude Opus 5.5)

    Diff: 1971 lines (+1728 / -243) across 20 files Reviewer: cloud-fan Review duration: 12140m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.72) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1971 lines diff across 20 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    91%
    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.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    35 items
    cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1720,6 +1760,100 @@ object JsonArray {
       }
     }
     
    +/**
    + * A parsed `JSON_ARRAY(...)` / `JSON_OBJECT(...)` whose splice flags are finalized after child
    + * resolution: parser flags keep explicit `FORMAT JSON` and lexical nested constructors, and the
    + * resolved children add qualified/routed nested constructors the parser cannot see.
    + *
    + * A clause-free call sets `routeThroughResolution` so a same-named routine (or an `injectFunction`
    + * replacement) can shadow it; it then resolves as a plain `prettyName(arguments...)` call. Other
    + * calls are owned by the stock built-in.
    + */
    +trait UnresolvedJsonConstructor
    +  extends Unevaluable
    +  with DefaultStringProducingExpression

    Blocking (P1): This wrapper claims DefaultStringProducingExpression with dataType = returning, which is the plain STRING type for every routed wrapper. Under a table or view default collation, the collation runner inside ResolveAliases (and ResolveReferences for view reads) wraps it in Cast(_, STRING COLLATE <default>) before ResolveJsonConstructors decides ownership. When a shadow or injectFunction replacement owns the name, the wrapper is replaced in place by an UnresolvedFunction, and the Cast stays around the owner's result. For example, with the INT-returning json_array replacement from SparkSessionExtensionSuite, CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS SELECT json_array(json_array(1)) AS c stores c as STRING COLLATE UTF8_LCASE with value '1' instead of INT 1, while SELECT json_array(1) keeps INT. The same applies to json_object('a', json_object('b', 1)), the VALUE/colon spellings, temporary/PATH/V2 owners, and every read of a view with a default collation. A STRING-returning owner is silently recolored. For the comma-form json_object with a nested producer, the merge target already routed this call without the Cast, so this is a regression there. Single-pass decides ownership first, so the two analyzers disagree on these plans.

    Recommended change: Stop routed SQL/JSON constructor wrappers (clause-free calls that contain a nested constructor) from presenting themselves as default-string-producing expressions, so collation rules treat them like the unresolved function call they stand for. Stock-owned wrappers keep reporting their RETURNING type. Add JSON_ARRAY and JSON_OBJECT tests in which a temporary function or an injected replacement owns the name, and analyze nested calls under a table default collation and a view default collation.

    Why this works: The default-collation pass casts only nodes that declare themselves default-string producers. Without that claim, the pass descends into a routed wrapper's children instead of casting the wrapper itself. When a routine owns the name, the call then resolves exactly like the flat call and keeps the routine's own type and collation. When the stock built-in owns it, the wrapper materializes to a JSON_ARRAY/JSON_OBJECT expression, which is itself a default-string producer, and the collation pass that runs in every analyzer iteration recolors it as before.

    Scope: Give routed constructor wrappers a representation that does not claim a default string type, and pin down shadowed calls under a default collation with tests.

    Compatibility: Default-collation recoloring of stock JSON_ARRAY and JSON_OBJECT results, and the exemption for an explicitly collated RETURNING type, must remain unchanged.

    Risks: A routed wrapper that waits for its children, for example inside a lambda, is recolored only after it materializes rather than while it is unresolved. Because the collation pass runs in every iteration the resolved plan should not change, and restoring the trait on routed wrappers rolls the change back.

    Constraints: Stock-owned wrappers must keep reporting their RETURNING type, so an explicit RETURNING STRING COLLATE c is still not recolored to the object or view default.

    Success: Under a table or view default collation, a nested clause-free JSON_ARRAY or JSON_OBJECT call owned by a temporary, PATH, persistent or V2 routine, or by an injected replacement, returns that owner's own result type and collation, the same as the equivalent flat call. Without a shadow, the same nested calls under a default collation still splice and still produce a result in the object or view default collation. The fixed-point and single-pass analyzers produce the same plan for these queries.

    Verification:

  • Regression: Under DEFAULT COLLATION UTF8_LCASE, both for a CTAS and for a view, json_array(json_array(1)) and json_object('a', json_object('b', 1)) owned by an injected replacement or a temporary function that returns a non-string keep that owner's result type and value, and an owner that returns STRING keeps its own collation.

  • Behavior: Without a shadow, the same nested calls under the same default collations still return spliced JSON whose type carries the default collation.

  • Compatibility: The view-based cases analyze identically in the fixed-point and single-pass analyzers when both run side by side.
  • cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:1
    @@ -709,6 +709,7 @@ class Analyzer(
           ResolveAliases ::
           ResolveSubquery ::
           ResolveSubqueryColumnAliases ::
    +      ResolveJsonConstructors ::

    Blocking (P1): Every clause-bearing, explicit-FORMAT-JSON, or nested JSON_ARRAY/JSON_OBJECT now reaches the analyzer as a wrapper that only this rule materializes. The rule runs after ResolveFunctions (702) and ResolveAliases (709), and only once all of the wrapper's children are resolved. In the merge target these were JsonArray/JsonObjectExpr nodes that ResolveTimeZone completed in iteration 1 regardless of their children, so one bottom-up ResolveFunctions pass finished any nesting. There are two consequences, both for queries with no qualified or shadowed constructor. First, an ordinary function between levels, as in JSON_ARRAY(upper(JSON_ARRAY(upper(JSON_ARRAY(1 RETURNING STRING)) RETURNING STRING)) RETURNING STRING), peels one level per iteration, so about 100 alternations exceed the default spark.sql.analyzer.maxIterations and fail analysis where master succeeds. Second, a single wrapper whose child resolves late in an iteration costs an extra full Resolution iteration; this happens with time-zone-aware children such as date_format or a CAST, with children that need type coercion, and with lambda bodies. For example, JSON_OBJECT('d' VALUE date_format(ts, 'yyyy') NULL ON NULL) gets its alias one iteration later than in master. The bounded-passes test covers only direct constructor-in-constructor nesting, which this rule's bottom-up traversal does handle in one pass. The single-pass resolver is unaffected.

    Recommended change: Route or materialize SQL/JSON constructor wrappers within the same bottom-up pass that resolves function calls, before alias assignment, rather than in a separate rule that runs after them. Add JSON_ARRAY and JSON_OBJECT analyzer tests that alternate ordinary functions with constructor levels under a low analyzer iteration limit.

    Why this works: When the function-resolution pass reaches a wrapper whose name a routine owns, it turns the wrapper into an ordinary call right away, without waiting for its children, as the current rule does, so the call resolves exactly like the flat call. A stock-owned wrapper still rejects a direct star, and once its children are resolved the pass materializes the stock built-in with the session time zone, so the constructor is already resolved when the pass reaches the call that encloses it. An alternating chain of functions and constructors then resolves in a single pass. A wrapper whose children became resolved in the previous iteration materializes before aliases are assigned, just as the merge target's parse-time node did.

    Scope: Move wrapper routing and materialization into the function-resolution traversal, and cover alternating nesting.

    Risks: Function resolution takes on wrapper handling, so a mistake there would affect every function call. The new handling must be pruned by its tree pattern and must not intercept ordinary function calls. Restoring the separate rule rolls the change back.

    Constraints: Ownership must still be decided once per wrapper, and the direct-star rejection and star-owner selection must stay as they are. Routing a routine-owned wrapper must not wait for its children, so a routine still receives the call while its arguments resolve, as it does for the flat call.

    Success: Alternating nesting of an ordinary function and a clause-bearing or nested JSON constructor, deeper than the analyzer iteration limit, analyzes successfully, and its iteration count does not grow with depth. A clause-bearing JSON_ARRAY or JSON_OBJECT whose child becomes resolved late in an iteration needs no more analyzer iterations than the merge target needed.

    Verification:

  • Regression: With spark.sql.analyzer.maxIterations deliberately set low, a chain of upper(JSON_ARRAY(... RETURNING STRING)) levels and a JSON_OBJECT VALUE ... NULL ON NULL chain, each nested deeper than that limit, analyze and return the expected JSON in fixed-point mode.

  • Behavior: Existing splice, shadowing, star, lambda, subquery, grouping, and default-collation behavior of both constructors is unchanged in both analyzers.

  • Regression: A clause-bearing JSON_OBJECT or JSON_ARRAY whose child is resolved only late in an iteration, such as JSON_OBJECT('d' VALUE date_format(ts, 'yyyy') NULL ON NULL) or a value under CAST(... AS STRING), needs no more Resolution-batch iterations than the merge target, checked through the per-rule invocation counts in QueryPlanningTracker.
  • cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1314,57 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`: under an object/view default collation,
    +   * `ApplyDefaultCollation` wraps a nested producer in a `Cast` to the default `StringType` before
    +   * the builder runs, which would otherwise hide the producer and quote it (unlike the direct
    +   * grammar path, which freezes the decision at parse time). Only a genuine collation change is
    +   * unwrapped (the cast recolors existing JSON text); a user `CAST(... AS STRING)` or the
    +   * `string(...)` alias still detaches, so the explicit-cast quoting is preserved.
    +   */
    +  @scala.annotation.tailrec
    +  def splicesThroughCollationCast(e: Expression): Boolean = e match {
    +    case c: Cast if isAnalyzerCollationCast(c) => splicesThroughCollationCast(c.child)
    +    case _ => isImplicitlyJson(e)

    Non-blocking (P2): This unwraps an analyzer collation Cast only when it is the outermost node, then defers to isImplicitlyJson, which sees through Collate but not Cast. Under a default collation, castDefaultStringExpressions descends through a user COLLATE and casts the producer below it, so a qualified or routed nested producer arrives as Collate(Cast(JsonArray, STRING COLLATE <default>), <c>) and is quoted. For example, CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS SELECT json_array(json_array(0), builtin.json_array(1) COLLATE UNICODE) AS b emits the second element as a quoted string, while the same SELECT without a default collation returns [[0],[1]]. builtin.json_array(json_array(1) COLLATE UNICODE) and builtin.json_object('a', json_object('b', 1) COLLATE UNICODE) behave the same way through the builders. Matching any interleaving of Collate and an analyzer collation Cast, while still stopping at user casts, would close this for every consumer of the predicate.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ResolverGuard.scala:1
    @@ -629,7 +629,8 @@ class ResolverGuard(
           // JSON
           case _: GetJsonObject | _: JsonTuple | _: JsonToStructs | _: StructsToJson |
               _: SchemaOfJson | _: JsonObjectKeys | _: LengthOfJsonArray | _: JsonArray |
    -          _: JsonExists | _: JsonQuery | _: JsonValue | _: JsonObjectExpr =>
    +          _: JsonExists | _: JsonQuery | _: JsonValue | _: JsonObjectExpr |
    +          _: UnresolvedJsonConstructor =>

    Nit (P3): A flat json_array(1) goes through checkUnresolvedFunction, which rejects it as a non-builtin function when a temporary function owns the name, so it stays on the fixed-point analyzer. A routed wrapper such as json_array(json_array(1)) or json_object('a' VALUE json_object('b' VALUE 1)) is admitted here with only its children checked, and ExpressionResolver then resolves it against the temporary owner. In tentative single-pass mode and in the dual-run comparison (enabled in tests), temp-function calls therefore reach the single-pass resolver, which the guard exists to prevent. This can surface spurious single-pass failures or plan mismatches for non-SQL temp functions. Strict single-pass and default production analysis are unaffected. For wrappers with routeThroughResolution, delegating to checkUnresolvedFunction(j.toUnresolvedFunction) would give them the same decision as the flat call, and stock-owned wrappers can stay in this arm.

    Verification:

  • Regression: The guard rejects a nested constructor call shadowed by a temporary function as a non-builtin function, matching the flat call.

  • Behavior: The guard still admits unshadowed nested, clause-bearing and explicit FORMAT JSON forms of both constructors.
  • cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1314,57 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`: under an object/view default collation,
    +   * `ApplyDefaultCollation` wraps a nested producer in a `Cast` to the default `StringType` before
    +   * the builder runs, which would otherwise hide the producer and quote it (unlike the direct
    +   * grammar path, which freezes the decision at parse time). Only a genuine collation change is

    Nit (P3): This contrasts the predicate with "the direct grammar path, which freezes the decision at parse time", but stock-owned grammar wrappers now run this same predicate in finalizeFlags. JsonArray's own docs make the same outdated claim. The class scaladoc says formatJson "is set once, at parse time" (1378), the field comment says both flags are "never re-derived from the child expression" (1415), and the eval comment calls needsValidation "the frozen parse-time" flag (1641). For JSON_ARRAY(builtin.json_array(1) NULL ON NULL), the element is spliced only because analysis re-derives the flag from the resolved child. The updated JsonObjectExpr comment already describes the actual lifecycle: flags are finalized before the node is built and frozen afterward.

    Verification:

  • Inspection: The JsonArray and splice-predicate comments describe parser flags plus analysis-time recovery from resolved children, frozen once the node is built, consistent with the JSON_OBJECT comment.
  • cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -954,6 +1226,23 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         }
       }
     
    +  test("SPARK-59243: routed/qualified nested JSON_ARRAY splices under a default collation") {
    +    // Both columns resolve through the built-in builder (not the direct grammar path): col a via
    +    // the qualified outer call, col b via the qualified nested call. `ApplyDefaultCollation` wraps
    +    // the nested producer in a collation Cast; the builder must still see through it (an analyzer
    +    // Cast, not a user one) and splice, so the result matches the UTF8_BINARY case rather than
    +    // quoting.
    +    withSQLConf(SQLConf.OBJECT_LEVEL_COLLATIONS_ENABLED.key -> "true") {
    +      withTable("t") {
    +        sql(
    +          """CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS

    Nit (P3): This test and its JsonObjectSuite counterpart check default-collation splicing only through CTAS followed by spark.table. ResolverGuard has no CreateTableAsSelect arm, so dual-run never runs these queries in single-pass, and reading the table returns persisted values without re-analysis. If the Cast that DefaultCollationTypeCoercion inserts in single-pass stopped matching isAnalyzerCollationCast, single-pass would quote builtin.json_array(json_array(1)) in a default-collation view while fixed-point still splices, and these tests would still pass. A CREATE VIEW ... DEFAULT COLLATION UTF8_LCASE variant read under dual-run, like the existing 'view default collation preserves an explicit collated RETURNING' test, would cover that path.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -549,11 +579,11 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
             checkAnswer(sql("SELECT json_array(*) FROM VALUES (1, 'x') AS t(a, b)"), Row("shadowed"))
             // The clause-bearing form is not a function call, so it stays the built-in constructor.
             checkAnswer(sql("SELECT json_array('x' NULL ON NULL)"), Row("""["x"]"""))
    -        // Nested JSON-producing children stay on the direct-construction path, so they are not
    -        // shadowed. This preserves JSON_ARRAY's parse-time splice decisions.
    -        checkAnswer(sql("SELECT json_array(json_array(1))"), Row("[[1]]"))
    +        // A nested clause-free call routes too, so it is shadowed like a flat call (see the
    +        // SPARK-59243 nested-shadowing test). Qualifying every level keeps the built-in splice.
    +        checkAnswer(sql("SELECT builtin.json_array(builtin.json_array(1))"), Row("[[1]]"))
             checkAnswer(
    -          sql("""SELECT json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    +          sql("""SELECT builtin.json_array(builtin.json_query('{"a":{"x":1}}', '$.a'))"""),

    Nit (P3): Before this change, the test asserted that json_array(json_query(...)) still splices the built-in json_query while temporary json_array and json_query routines are on the PATH. The replacement, builtin.json_array(builtin.json_query(...)), tests qualified routing rather than direct-argument ownership. That was the only assertion that a JSON_QUERY written as a direct constructor argument stays the stock built-in under a json_query shadow (the isDirectJsonConstructorArgument check in visitJsonQuery). If that rule regressed, the inner call would route to the temporary json_query, and the non-shadow tests would still pass because the builders recover the splice from a resolved stock JsonQuery. An assertion that keeps the outer call stock-owned, for example json_array(json_query(...) NULL ON NULL) as the neighboring json_value/json_exists cases do, would restore the signal.

    See Shared repair plan 2 in the review body.

    cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -646,23 +676,176 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         checkAnswer(sql("SELECT system.builtin.json_array(1, 'x')"), Row("""[1,"x"]"""))
       }
     
    -  test("a nested JSON-producing argument through a routed JSON_ARRAY call is quoted, not spliced") {
    -    // A routed call carries no lexical FORMAT JSON, so a nested JSON-producing argument (a JSON
    -    // constructor like json_array or a path function like json_query) is quoted as a plain value,
    -    // unlike the JSON_ARRAY(...) grammar which splices it (see the unqualified
    -    // `json_array(json_array(1))` -> `[[1]]` cases above). The outer call routes whenever it sees
    -    // no lexical implicit-JSON element: `JsonArray.isImplicitlyJson` recognizes only a
    -    // grammar-built nested JSON expression, so a qualified outer call and an unqualified call over
    -    // a qualified nested JSON expression (whose child is still unresolved) both route and quote.
    -    // Only a fully unqualified nested JSON expression stays on the direct grammar path; splicing
    -    // through a routed call is left as a follow-up.
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("""["[1]",2]"""))
    -    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("""["[1]"]"""))
    +  test("SPARK-59243: a nested JSON constructor through a routed JSON_ARRAY call is spliced") {
    +    // A routed or qualified built-in JSON_ARRAY splices a lexically-nested JSON constructor
    +    // argument, matching the JSON_ARRAY(...) grammar (`json_array(json_array(1))` -> `[[1]]`).
    +    // The built-in builder derives the FORMAT JSON flag from the resolved argument via
    +    // `ImplicitlyFormattedAsJson.splicesThroughCollationCast`, so a qualified outer call and an
    +    // unqualified call over a qualified nested constructor both splice, matching the fully
    +    // unqualified grammar form.
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("[[1],2]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(json_array(0), builtin.json_array(1))"), Row("[[0],[1]]"))
         checkAnswer(
           sql("""SELECT builtin.json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    -      Row("""["{\"x\":1}"]"""))
    +      Row("""[{"x":1}]"""))
    +    // A user CAST still detaches FORMAT JSON, so the element stays quoted (the routed splice check
    +    // sees through an analyzer collation Cast, but not a user `CAST(... AS STRING)`).
    +    checkAnswer(sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING))"), Row("""["[1]"]"""))
    +  }
    +
    +  test("SPARK-59243: clause-bearing JSON_ARRAY splices qualified nested constructors") {
    +    // Clause-bearing direct forms do not route through function resolution, but still need to
    +    // recover the qualified nested constructor after children resolve.
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) NULL ON NULL)"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) RETURNING STRING)"), Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)"),
    +      Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(CAST(builtin.json_array(1) AS STRING) NULL ON NULL)"),
    +      Row("""["[1]"]"""))
    +
    +    Seq(false, true).foreach { singlePass =>
    +      withSQLConf(
    +        SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> singlePass.toString) {
    +        val analyzed =
    +          sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)")
    +            .queryExecution.analyzed
    +        assert(analyzed.resolved, s"singlePass=$singlePass")
    +        val arrays = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j })
    +        val outer = arrays.find(_.nullBehavior == JsonConstructorNullBehavior.Null).get
    +        assert(outer.formatJson == Seq(true), s"singlePass=$singlePass")
    +        assert(outer.needsValidation == Seq(false), s"singlePass=$singlePass")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: routed JSON_ARRAY splice round-trips through canonical SQL") {
    +    // The analyzed expression's canonical SQL must reparse to the same spliced result.
    +    Seq(
    +      "SELECT builtin.json_array(json_array(1))",
    +      "SELECT json_array(builtin.json_array(1))").foreach { query =>
    +      val analyzed = sql(query).queryExecution.analyzed
    +      val jsonArray = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j }).head
    +      checkAnswer(sql(s"SELECT ${jsonArray.sql}"), Row("[[1]]"))
    +    }
    +  }
    +
    +  test("SPARK-59243: spliced nested JSON_ARRAY canonical SQL stays built-in under a shadow") {
    +    // Canonical SQL of a resolved built-in must reparse to the built-in even under a shadow: the
    +    // nested splice now routes, so each clause-free level carries an ownership clause.
    +    val inner = JsonArray(
    +      Seq(Literal(1)), Seq(false), Seq(false), JsonConstructorNullBehavior.Absent, StringType)
    +    val canonical = JsonArray(
    +      Seq(inner), Seq(true), Seq(false), JsonConstructorNullBehavior.Absent, StringType).sql
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        checkAnswer(sql(s"SELECT $canonical"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: an explicit collation-changing string() cast detaches splicing") {
    +    // `string(... COLLATE c)` is an explicit cast (via the cast alias) that detaches FORMAT JSON,
    +    // so the nested constructor is quoted, not spliced. The analyzer-collation-cast unwrap in
    +    // `splicesThroughCollationCast` must not treat it as an `ApplyDefaultCollation` cast.
    +    checkAnswer(
    +      sql("SELECT builtin.json_array(string(json_array(1) COLLATE UTF8_LCASE))"),
    +      Row("""["[1]"]"""))
    +    // Also when the cast itself changes the collation: it is still a user cast, not a
    +    // default-collation recoloring, on both the routed and the direct grammar paths.
    +    val nested = "string(json_array(1 RETURNING STRING COLLATE UTF8_LCASE))"
    +    checkAnswer(sql(s"SELECT builtin.json_array($nested)"), Row("""["[1]"]"""))
    +    checkAnswer(sql(s"SELECT json_array($nested NULL ON NULL)"), Row("""["[1]"]"""))
    +  }
    +
    +  test("SPARK-59243: a nested clause-free JSON_ARRAY call is shadowed like a flat call") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        // The inner json_array(1) is a grammar element (built-in) producing "[1]"; the outer
    +        // clause-free call routes, so the temp shadows it.
    +        checkAnswer(sql("SELECT json_array(json_array(1))"), Row("shadowed"))
    +        // Strict single-pass routes the outer clause-free call to the shadow owner too, but the
    +        // owner is a SQL function, which the single-pass analyzer does not yet resolve: it reaches
    +        // that owner (proving the routing) and then aborts with an
    +        // ExplicitlyUnsupportedResolverFeature on the SQL function body. The guard-gated modes fall
    +        // back to fixed-point, which produces the shadow result asserted above.
    +        withSQLConf(SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> "true") {
    +          intercept[ExplicitlyUnsupportedResolverFeature] {
    +            sql("SELECT json_array(json_array(1))").queryExecution.analyzed
    +          }
    +        }
    +        // Qualifying every level selects Spark's constructor and splices.
    +        checkAnswer(sql("SELECT builtin.json_array(builtin.json_array(1))"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: nested constructors splice in subqueries, grouping, and INSERT VALUES") {
    +    // The finalization rule runs over every operator, not just a top-level Project.
    +    checkAnswer(sql("SELECT (SELECT builtin.json_array(json_array(1)))"), Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT 1 WHERE '[[1]]' IN (SELECT json_array(builtin.json_array(1)))"),
    +      Row(1))
    +    checkAnswer(
    +      sql("SELECT json_array(json_array(count(*))) FROM VALUES (1), (2) AS t(a)"),
    +      Row("[[2]]"))
    +    // HAVING and ORDER BY are checked separately: combining them with GROUP BY hits an unrelated
    +    // dual-run plan mismatch for any select-list expression.
    +    val grouped = "FROM VALUES (1), (2), (2) AS t(a) GROUP BY a"
    +    checkAnswer(
    +      sql(s"SELECT builtin.json_array(json_array(a)) AS j $grouped " +
    +        "HAVING builtin.json_array(json_array(count(*))) = '[[2]]'"),
    +      Row("[[2]]"))
    +    checkAnswer(
    +      sql(s"SELECT builtin.json_array(json_array(a)) AS j $grouped " +
    +        "ORDER BY json_array(builtin.json_array(a))"),
    +      Seq(Row("[[1]]"), Row("[[2]]")))
    +    withTable("t") {
    +      sql("CREATE TABLE t (j STRING) USING parquet")
    +      sql("INSERT INTO t VALUES (builtin.json_array(json_array(1))), (json_object('a', " +
    +        "builtin.json_object('b', 1)))")
    +      checkAnswer(sql("SELECT j FROM t"), Seq(Row("[[1]]"), Row("""{"a":{"b":1}}""")))
    +    }
    +  }
    +
    +  test("SPARK-59243: a persistent function cannot reference a temp shadow via a nested call") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        // The routed nested call is a reference to the temp shadow, like the flat call.
    +        Seq("json_array(1)", "json_array(json_array(1))").foreach { body =>
    +          val e = intercept[AnalysisException] {
    +            sql(s"CREATE FUNCTION perm_json_fn() RETURNS STRING RETURN $body")

    Nit (P3): The new CreateSQLFunctionCommand case excludes stock-owned wrappers only through its routeThroughResolution check. This test and its JsonObjectSuite counterpart cover only routed bodies that must fail. In master, stock-owned forms parsed to resolved JsonArray/JsonObjectExpr and were never inspected. If that check were dropped, CREATE FUNCTION perm() RETURNS STRING RETURN json_array(1 NULL ON NULL) would start failing with INVALID_TEMP_OBJ_REFERENCE whenever a temporary json_array exists, and no test would notice. Accepted cases such as json_array(1 NULL ON NULL), json_array(json_array(1) NULL ON NULL), and json_object('id' VALUE '[1]' FORMAT JSON) next to the rejected ones would pin it down.

    See Shared repair plan 2 in the review body.

    cloud-fan cloud-fan commented on code on Oct 29, 2026 21:51 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -646,23 +676,176 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         checkAnswer(sql("SELECT system.builtin.json_array(1, 'x')"), Row("""[1,"x"]"""))
       }
     
    -  test("a nested JSON-producing argument through a routed JSON_ARRAY call is quoted, not spliced") {
    -    // A routed call carries no lexical FORMAT JSON, so a nested JSON-producing argument (a JSON
    -    // constructor like json_array or a path function like json_query) is quoted as a plain value,
    -    // unlike the JSON_ARRAY(...) grammar which splices it (see the unqualified
    -    // `json_array(json_array(1))` -> `[[1]]` cases above). The outer call routes whenever it sees
    -    // no lexical implicit-JSON element: `JsonArray.isImplicitlyJson` recognizes only a
    -    // grammar-built nested JSON expression, so a qualified outer call and an unqualified call over
    -    // a qualified nested JSON expression (whose child is still unresolved) both route and quote.
    -    // Only a fully unqualified nested JSON expression stays on the direct grammar path; splicing
    -    // through a routed call is left as a follow-up.
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("""["[1]",2]"""))
    -    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("""["[1]"]"""))
    +  test("SPARK-59243: a nested JSON constructor through a routed JSON_ARRAY call is spliced") {
    +    // A routed or qualified built-in JSON_ARRAY splices a lexically-nested JSON constructor
    +    // argument, matching the JSON_ARRAY(...) grammar (`json_array(json_array(1))` -> `[[1]]`).
    +    // The built-in builder derives the FORMAT JSON flag from the resolved argument via
    +    // `ImplicitlyFormattedAsJson.splicesThroughCollationCast`, so a qualified outer call and an
    +    // unqualified call over a qualified nested constructor both splice, matching the fully
    +    // unqualified grammar form.
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("[[1],2]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(json_array(0), builtin.json_array(1))"), Row("[[0],[1]]"))
         checkAnswer(
           sql("""SELECT builtin.json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    -      Row("""["{\"x\":1}"]"""))
    +      Row("""[{"x":1}]"""))
    +    // A user CAST still detaches FORMAT JSON, so the element stays quoted (the routed splice check
    +    // sees through an analyzer collation Cast, but not a user `CAST(... AS STRING)`).
    +    checkAnswer(sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING))"), Row("""["[1]"]"""))

    Nit (P3): isAnalyzerCollationCast relies on !c.containsTag(Cast.USER_SPECIFIED_CAST) to keep a user cast that changes the collation from being unwrapped and spliced. This test and the other user-cast tests all cast to the plain STRING type with no default collation, so to != from rejects the cast before the tag is read. The string(...) tests are rejected earlier by the Collate-child and explicitly-collated-child conditions. If the tag check were removed, builtin.json_array(CAST(json_array(1) AS STRING COLLATE UTF8_LCASE)) would splice to [[1]] instead of quoting, as would CAST(json_array(1) AS STRING) inside a DEFAULT COLLATION UTF8_LCASE CTAS, and nothing would fail. A case where the tag alone decides the outcome would cover this guard.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on Oct 29, 2026 21:51 UTC
    Reviewer

    Review summary

    The most serious issues are two defects in fixed-point analysis of the new constructor wrappers. First, under a table or view default collation, a nested clause-free JSON_ARRAY/JSON_OBJECT call owned by a shadowing or injected routine returns the owner's result cast to the default-collated STRING, while the flat call with the same owner keeps its own type. The single-pass resolver produces a different plan for the same query. Second, because wrappers are materialized only after ResolveFunctions and ResolveAliases, ordinary clause-bearing constructor queries now need extra Resolution iterations. They need one per function/constructor alternation level, so deep generated SQL can exceed maxIterations where master succeeded, and one more whenever a child such as date_format or a CAST resolves late in an iteration.

    The splice predicate also misses one shape: under a default collation, a COLLATE-annotated qualified or routed nested producer is still quoted, although the same expression splices without a default collation. ResolverGuard admits routed wrappers without the owner check the equivalent flat call gets, which matters only in tentative and dual-run single-pass modes.

    The remaining findings are smaller. Some JsonArray and splice-predicate comments still describe parse-time-only flags. Four test gaps leave new behavior without a failure signal: single-pass default-collation splicing, the USER_SPECIFIED_CAST check in the splice predicate, direct-argument JSON_QUERY ownership under a json_query shadow, and acceptance of stock-owned bodies in persistent functions.

    Review-level concerns

  • Shared problem: The new SQL/JSON constructor wrapper does not behave like the flat call or the parse-time node it replaces until a separate rule late in the Resolution batch routes or materializes it, and three consumers see it in that in-between state. Default-collation rules cast a routed wrapper as if it were a string producer before its owner is known, so a shadowing routine's or injected replacement's result is forced to the default-collated STRING. ResolverGuard admits a routed wrapper as a JSON expression and skips the owner check a flat call gets. Enclosing calls and aliases wait an extra iteration per wrapper level, so alternating function and constructor nesting grows analyzer iterations with depth. Patching each symptom in its own consumer would leave the wrapper's meaning spread across the collation rules, the guard and rule placement. The coherent response is to route or materialize wrappers in the same bottom-up function-resolution pass that resolves the calls around them, and to present a routed wrapper to the collation rules and to ResolverGuard as the unresolved call it stands for until its owner is decided. The collation-cast and iteration-scaling defects are blocking.
  • Cross-cutting observations

  • Both wrong results this change can produce appear only under a table or view default collation. In one, a nested call owned by a shadowing routine takes on the default-collated STRING type. In the other, a COLLATE-annotated qualified producer is quoted instead of spliced. The current default-collation tests go through CTAS with explicit aliases, which covers neither shape and never runs the single-pass resolver. A shared view-based default-collation test matrix covering shadows, COLLATE annotations and both analyzers would therefore serve both fixes.
  • Separation: The two defects have different owners, the wrapper's default-string claim and the splice predicate's handling of collation wrappers, and each is fixed independently. The shared trigger only affects which tests to write, not repair scope or coordination.

    Findings

    9 total: 0 P0, 2 P1, 1 P2, 6 P3.

    Blocking (P1)

  • Shadowed nested JSON constructor calls keep a default-collation cast — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1774 — see inline.

  • ResolveJsonConstructors adds Resolution iterations for ordinary constructor queries — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:712 — see inline.
  • Non-blocking (P2)

  • COLLATE over a qualified nested producer is still quoted under a default collation — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1349 — see inline.
  • Nit (P3)

  • ResolverGuard skips the owner check for routed JSON constructor calls — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ResolverGuard.scala:633 — see inline.

  • JsonArray flag comments still say the flags are fixed at parse time — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1342 — see inline.

  • Default-collation splice tests never run the single-pass resolver — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1238 — see inline.

  • Direct-argument JSON_QUERY shadow assertion was replaced — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:586 — see inline.

  • No test that stock-owned bodies are still accepted in persistent functions — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:839 — see inline.

  • USER_SPECIFIED_CAST check in the splice predicate is untested — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:696 — see inline.
  • Shared repair plans

    Shared repair plan 1

    Covered findings:

  • COLLATE over a qualified nested producer is still quoted under a default collation — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1349

  • Default-collation splice tests never run the single-pass resolver — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1238

  • USER_SPECIFIED_CAST check in the splice predicate is untested — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:696
  • Verification:

  • Regression: For both constructors, COLLATE-annotated qualified and routed nested producers splice under a table default collation and under a view default collation.

  • Regression: A user cast that changes the collation of a nested producer keeps the value quoted, in at least one case where the user-specified-cast marker is the only condition that decides it.

  • Compatibility: The view-based default-collation splice cases produce the same plans and results in the fixed-point and single-pass analyzers.
  • Shared repair plan 2

    Covered findings:

  • Direct-argument JSON_QUERY shadow assertion was replaced — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:586

  • No test that stock-owned bodies are still accepted in persistent functions — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:839
  • Verification:

  • Regression: Routing a direct-argument JSON_QUERY to the shadowing routine makes the shadowing test fail.

  • Regression: Treating stock-owned constructor wrappers as temporary-function references makes the persistent-function tests fail.
  • <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"93c872156ae4a947885a","id":"pass-a:routed-wrapper-default-collation-cast"},{"delivery":"inline","fingerprint":"139adae459ce6a74b8fe","id":"pass-a:finalization-adds-analyzer-iterations"},{"delivery":"inline","fingerprint":"1657e43576c47db0d129","id":"pass-a:collate-over-collation-cast-not-spliced"},{"delivery":"inline","fingerprint":"7f0fccdeb34e94b3fcf6","id":"pass-a:resolver-guard-routed-wrapper-owner-check"},{"delivery":"inline","fingerprint":"c0d5b9928bfba76120e4","id":"pass-b:jsonarray-docs-claim-parse-time-only-flags"},{"delivery":"inline","fingerprint":"88b6635e2259cf27af6c","id":"pass-b:tests-default-collation-splice-single-pass-gap"},{"delivery":"inline","fingerprint":"2699f3dd38f1dec156a3","id":"pass-b:tests-direct-json-query-shadow-coverage-removed"},{"delivery":"inline","fingerprint":"7c90d0a0ccad92938f54","id":"pass-b:tests-stock-owned-wrapper-temp-reference-negative-missing"},{"delivery":"inline","fingerprint":"89a5cfa72b4cd06671e1","id":"pass-b:tests-user-cast-collation-tag-unexercised"}],"head_sha":"8cdc5125c3c5c2633ee90418222b6a274f53b284","verdict_sha256":"d254a1b16133fd9b3db28d22fd1ed14c256cdb7de00a2ed84b1448cb8785843d"} -->

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1720,6 +1760,100 @@ object JsonArray {
       }
     }
     
    +/**
    + * A parsed `JSON_ARRAY(...)` / `JSON_OBJECT(...)` whose splice flags are finalized after child
    + * resolution: parser flags keep explicit `FORMAT JSON` and lexical nested constructors, and the
    + * resolved children add qualified/routed nested constructors the parser cannot see.
    + *
    + * A clause-free call sets `routeThroughResolution` so a same-named routine (or an `injectFunction`
    + * replacement) can shadow it; it then resolves as a plain `prettyName(arguments...)` call. Other
    + * calls are owned by the stock built-in.
    + */
    +trait UnresolvedJsonConstructor
    +  extends Unevaluable
    +  with DefaultStringProducingExpression

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:1
    @@ -709,6 +709,7 @@ class Analyzer(
           ResolveAliases ::
           ResolveSubquery ::
           ResolveSubqueryColumnAliases ::
    +      ResolveJsonConstructors ::

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1314,57 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`: under an object/view default collation,
    +   * `ApplyDefaultCollation` wraps a nested producer in a `Cast` to the default `StringType` before
    +   * the builder runs, which would otherwise hide the producer and quote it (unlike the direct
    +   * grammar path, which freezes the decision at parse time). Only a genuine collation change is
    +   * unwrapped (the cast recolors existing JSON text); a user `CAST(... AS STRING)` or the
    +   * `string(...)` alias still detaches, so the explicit-cast quoting is preserved.
    +   */
    +  @scala.annotation.tailrec
    +  def splicesThroughCollationCast(e: Expression): Boolean = e match {
    +    case c: Cast if isAnalyzerCollationCast(c) => splicesThroughCollationCast(c.child)
    +    case _ => isImplicitlyJson(e)

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/ResolverGuard.scala:1
    @@ -629,7 +629,8 @@ class ResolverGuard(
           // JSON
           case _: GetJsonObject | _: JsonTuple | _: JsonToStructs | _: StructsToJson |
               _: SchemaOfJson | _: JsonObjectKeys | _: LengthOfJsonArray | _: JsonArray |
    -          _: JsonExists | _: JsonQuery | _: JsonValue | _: JsonObjectExpr =>
    +          _: JsonExists | _: JsonQuery | _: JsonValue | _: JsonObjectExpr |
    +          _: UnresolvedJsonConstructor =>

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1314,57 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`: under an object/view default collation,
    +   * `ApplyDefaultCollation` wraps a nested producer in a `Cast` to the default `StringType` before
    +   * the builder runs, which would otherwise hide the producer and quote it (unlike the direct
    +   * grammar path, which freezes the decision at parse time). Only a genuine collation change is

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -954,6 +1226,23 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         }
       }
     
    +  test("SPARK-59243: routed/qualified nested JSON_ARRAY splices under a default collation") {
    +    // Both columns resolve through the built-in builder (not the direct grammar path): col a via
    +    // the qualified outer call, col b via the qualified nested call. `ApplyDefaultCollation` wraps
    +    // the nested producer in a collation Cast; the builder must still see through it (an analyzer
    +    // Cast, not a user one) and splice, so the result matches the UTF8_BINARY case rather than
    +    // quoting.
    +    withSQLConf(SQLConf.OBJECT_LEVEL_COLLATIONS_ENABLED.key -> "true") {
    +      withTable("t") {
    +        sql(
    +          """CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -549,11 +579,11 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
             checkAnswer(sql("SELECT json_array(*) FROM VALUES (1, 'x') AS t(a, b)"), Row("shadowed"))
             // The clause-bearing form is not a function call, so it stays the built-in constructor.
             checkAnswer(sql("SELECT json_array('x' NULL ON NULL)"), Row("""["x"]"""))
    -        // Nested JSON-producing children stay on the direct-construction path, so they are not
    -        // shadowed. This preserves JSON_ARRAY's parse-time splice decisions.
    -        checkAnswer(sql("SELECT json_array(json_array(1))"), Row("[[1]]"))
    +        // A nested clause-free call routes too, so it is shadowed like a flat call (see the
    +        // SPARK-59243 nested-shadowing test). Qualifying every level keeps the built-in splice.
    +        checkAnswer(sql("SELECT builtin.json_array(builtin.json_array(1))"), Row("[[1]]"))
             checkAnswer(
    -          sql("""SELECT json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    +          sql("""SELECT builtin.json_array(builtin.json_query('{"a":{"x":1}}', '$.a'))"""),

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -646,23 +676,176 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         checkAnswer(sql("SELECT system.builtin.json_array(1, 'x')"), Row("""[1,"x"]"""))
       }
     
    -  test("a nested JSON-producing argument through a routed JSON_ARRAY call is quoted, not spliced") {
    -    // A routed call carries no lexical FORMAT JSON, so a nested JSON-producing argument (a JSON
    -    // constructor like json_array or a path function like json_query) is quoted as a plain value,
    -    // unlike the JSON_ARRAY(...) grammar which splices it (see the unqualified
    -    // `json_array(json_array(1))` -> `[[1]]` cases above). The outer call routes whenever it sees
    -    // no lexical implicit-JSON element: `JsonArray.isImplicitlyJson` recognizes only a
    -    // grammar-built nested JSON expression, so a qualified outer call and an unqualified call over
    -    // a qualified nested JSON expression (whose child is still unresolved) both route and quote.
    -    // Only a fully unqualified nested JSON expression stays on the direct grammar path; splicing
    -    // through a routed call is left as a follow-up.
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("""["[1]",2]"""))
    -    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("""["[1]"]"""))
    +  test("SPARK-59243: a nested JSON constructor through a routed JSON_ARRAY call is spliced") {
    +    // A routed or qualified built-in JSON_ARRAY splices a lexically-nested JSON constructor
    +    // argument, matching the JSON_ARRAY(...) grammar (`json_array(json_array(1))` -> `[[1]]`).
    +    // The built-in builder derives the FORMAT JSON flag from the resolved argument via
    +    // `ImplicitlyFormattedAsJson.splicesThroughCollationCast`, so a qualified outer call and an
    +    // unqualified call over a qualified nested constructor both splice, matching the fully
    +    // unqualified grammar form.
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("[[1],2]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(json_array(0), builtin.json_array(1))"), Row("[[0],[1]]"))
         checkAnswer(
           sql("""SELECT builtin.json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    -      Row("""["{\"x\":1}"]"""))
    +      Row("""[{"x":1}]"""))
    +    // A user CAST still detaches FORMAT JSON, so the element stays quoted (the routed splice check
    +    // sees through an analyzer collation Cast, but not a user `CAST(... AS STRING)`).
    +    checkAnswer(sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING))"), Row("""["[1]"]"""))
    +  }
    +
    +  test("SPARK-59243: clause-bearing JSON_ARRAY splices qualified nested constructors") {
    +    // Clause-bearing direct forms do not route through function resolution, but still need to
    +    // recover the qualified nested constructor after children resolve.
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) NULL ON NULL)"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) RETURNING STRING)"), Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)"),
    +      Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(CAST(builtin.json_array(1) AS STRING) NULL ON NULL)"),
    +      Row("""["[1]"]"""))
    +
    +    Seq(false, true).foreach { singlePass =>
    +      withSQLConf(
    +        SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> singlePass.toString) {
    +        val analyzed =
    +          sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)")
    +            .queryExecution.analyzed
    +        assert(analyzed.resolved, s"singlePass=$singlePass")
    +        val arrays = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j })
    +        val outer = arrays.find(_.nullBehavior == JsonConstructorNullBehavior.Null).get
    +        assert(outer.formatJson == Seq(true), s"singlePass=$singlePass")
    +        assert(outer.needsValidation == Seq(false), s"singlePass=$singlePass")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: routed JSON_ARRAY splice round-trips through canonical SQL") {
    +    // The analyzed expression's canonical SQL must reparse to the same spliced result.
    +    Seq(
    +      "SELECT builtin.json_array(json_array(1))",
    +      "SELECT json_array(builtin.json_array(1))").foreach { query =>
    +      val analyzed = sql(query).queryExecution.analyzed
    +      val jsonArray = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j }).head
    +      checkAnswer(sql(s"SELECT ${jsonArray.sql}"), Row("[[1]]"))
    +    }
    +  }
    +
    +  test("SPARK-59243: spliced nested JSON_ARRAY canonical SQL stays built-in under a shadow") {
    +    // Canonical SQL of a resolved built-in must reparse to the built-in even under a shadow: the
    +    // nested splice now routes, so each clause-free level carries an ownership clause.
    +    val inner = JsonArray(
    +      Seq(Literal(1)), Seq(false), Seq(false), JsonConstructorNullBehavior.Absent, StringType)
    +    val canonical = JsonArray(
    +      Seq(inner), Seq(true), Seq(false), JsonConstructorNullBehavior.Absent, StringType).sql
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        checkAnswer(sql(s"SELECT $canonical"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: an explicit collation-changing string() cast detaches splicing") {
    +    // `string(... COLLATE c)` is an explicit cast (via the cast alias) that detaches FORMAT JSON,
    +    // so the nested constructor is quoted, not spliced. The analyzer-collation-cast unwrap in
    +    // `splicesThroughCollationCast` must not treat it as an `ApplyDefaultCollation` cast.
    +    checkAnswer(
    +      sql("SELECT builtin.json_array(string(json_array(1) COLLATE UTF8_LCASE))"),
    +      Row("""["[1]"]"""))
    +    // Also when the cast itself changes the collation: it is still a user cast, not a
    +    // default-collation recoloring, on both the routed and the direct grammar paths.
    +    val nested = "string(json_array(1 RETURNING STRING COLLATE UTF8_LCASE))"
    +    checkAnswer(sql(s"SELECT builtin.json_array($nested)"), Row("""["[1]"]"""))
    +    checkAnswer(sql(s"SELECT json_array($nested NULL ON NULL)"), Row("""["[1]"]"""))
    +  }
    +
    +  test("SPARK-59243: a nested clause-free JSON_ARRAY call is shadowed like a flat call") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        // The inner json_array(1) is a grammar element (built-in) producing "[1]"; the outer
    +        // clause-free call routes, so the temp shadows it.
    +        checkAnswer(sql("SELECT json_array(json_array(1))"), Row("shadowed"))
    +        // Strict single-pass routes the outer clause-free call to the shadow owner too, but the
    +        // owner is a SQL function, which the single-pass analyzer does not yet resolve: it reaches
    +        // that owner (proving the routing) and then aborts with an
    +        // ExplicitlyUnsupportedResolverFeature on the SQL function body. The guard-gated modes fall
    +        // back to fixed-point, which produces the shadow result asserted above.
    +        withSQLConf(SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> "true") {
    +          intercept[ExplicitlyUnsupportedResolverFeature] {
    +            sql("SELECT json_array(json_array(1))").queryExecution.analyzed
    +          }
    +        }
    +        // Qualifying every level selects Spark's constructor and splices.
    +        checkAnswer(sql("SELECT builtin.json_array(builtin.json_array(1))"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: nested constructors splice in subqueries, grouping, and INSERT VALUES") {
    +    // The finalization rule runs over every operator, not just a top-level Project.
    +    checkAnswer(sql("SELECT (SELECT builtin.json_array(json_array(1)))"), Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT 1 WHERE '[[1]]' IN (SELECT json_array(builtin.json_array(1)))"),
    +      Row(1))
    +    checkAnswer(
    +      sql("SELECT json_array(json_array(count(*))) FROM VALUES (1), (2) AS t(a)"),
    +      Row("[[2]]"))
    +    // HAVING and ORDER BY are checked separately: combining them with GROUP BY hits an unrelated
    +    // dual-run plan mismatch for any select-list expression.
    +    val grouped = "FROM VALUES (1), (2), (2) AS t(a) GROUP BY a"
    +    checkAnswer(
    +      sql(s"SELECT builtin.json_array(json_array(a)) AS j $grouped " +
    +        "HAVING builtin.json_array(json_array(count(*))) = '[[2]]'"),
    +      Row("[[2]]"))
    +    checkAnswer(
    +      sql(s"SELECT builtin.json_array(json_array(a)) AS j $grouped " +
    +        "ORDER BY json_array(builtin.json_array(a))"),
    +      Seq(Row("[[1]]"), Row("[[2]]")))
    +    withTable("t") {
    +      sql("CREATE TABLE t (j STRING) USING parquet")
    +      sql("INSERT INTO t VALUES (builtin.json_array(json_array(1))), (json_object('a', " +
    +        "builtin.json_object('b', 1)))")
    +      checkAnswer(sql("SELECT j FROM t"), Seq(Row("[[1]]"), Row("""{"a":{"b":1}}""")))
    +    }
    +  }
    +
    +  test("SPARK-59243: a persistent function cannot reference a temp shadow via a nested call") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        // The routed nested call is a reference to the temp shadow, like the flat call.
    +        Seq("json_array(1)", "json_array(json_array(1))").foreach { body =>
    +          val e = intercept[AnalysisException] {
    +            sql(s"CREATE FUNCTION perm_json_fn() RETURNS STRING RETURN $body")

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 02:25 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -646,23 +676,176 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         checkAnswer(sql("SELECT system.builtin.json_array(1, 'x')"), Row("""[1,"x"]"""))
       }
     
    -  test("a nested JSON-producing argument through a routed JSON_ARRAY call is quoted, not spliced") {
    -    // A routed call carries no lexical FORMAT JSON, so a nested JSON-producing argument (a JSON
    -    // constructor like json_array or a path function like json_query) is quoted as a plain value,
    -    // unlike the JSON_ARRAY(...) grammar which splices it (see the unqualified
    -    // `json_array(json_array(1))` -> `[[1]]` cases above). The outer call routes whenever it sees
    -    // no lexical implicit-JSON element: `JsonArray.isImplicitlyJson` recognizes only a
    -    // grammar-built nested JSON expression, so a qualified outer call and an unqualified call over
    -    // a qualified nested JSON expression (whose child is still unresolved) both route and quote.
    -    // Only a fully unqualified nested JSON expression stays on the direct grammar path; splicing
    -    // through a routed call is left as a follow-up.
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("""["[1]",2]"""))
    -    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("""["[1]"]"""))
    +  test("SPARK-59243: a nested JSON constructor through a routed JSON_ARRAY call is spliced") {
    +    // A routed or qualified built-in JSON_ARRAY splices a lexically-nested JSON constructor
    +    // argument, matching the JSON_ARRAY(...) grammar (`json_array(json_array(1))` -> `[[1]]`).
    +    // The built-in builder derives the FORMAT JSON flag from the resolved argument via
    +    // `ImplicitlyFormattedAsJson.splicesThroughCollationCast`, so a qualified outer call and an
    +    // unqualified call over a qualified nested constructor both splice, matching the fully
    +    // unqualified grammar form.
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("[[1],2]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(json_array(0), builtin.json_array(1))"), Row("[[0],[1]]"))
         checkAnswer(
           sql("""SELECT builtin.json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    -      Row("""["{\"x\":1}"]"""))
    +      Row("""[{"x":1}]"""))
    +    // A user CAST still detaches FORMAT JSON, so the element stays quoted (the routed splice check
    +    // sees through an analyzer collation Cast, but not a user `CAST(... AS STRING)`).
    +    checkAnswer(sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING))"), Row("""["[1]"]"""))

    Done

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1315,60 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`, in any interleaving with `Collate`: under an
    +   * object/view default collation, `ApplyDefaultCollation` wraps a nested producer (also one under
    +   * a user `COLLATE`) in a `Cast` to the default `StringType` before the builder runs, which would
    +   * otherwise hide the producer and quote it. The stock-owned grammar wrappers apply the same
    +   * predicate when they finalize their flags. Only a genuine collation change is unwrapped (the
    +   * cast recolors existing JSON text); a user `CAST(... AS STRING)` or the `string(...)` alias
    +   * still detaches, so the explicit-cast quoting is preserved.
    +   */
    +  @scala.annotation.tailrec
    +  def splicesThroughCollationCast(e: Expression): Boolean = e match {
    +    case c: Collate => splicesThroughCollationCast(c.child)
    +    case c: Cast if isAnalyzerCollationCast(c) => splicesThroughCollationCast(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  private def isAnalyzerCollationCast(c: Cast): Boolean = {
    +    // `ApplyDefaultCollation` / `DefaultCollationTypeCoercion` wrap only a companion-`StringType`
    +    // `DefaultStringProducingExpression` (they skip explicitly collated ones), so only that shape
    +    // is an analyzer recoloring. User detachments stay quoted: `string(json_array(1) COLLATE c)`
    +    // (child is a `Collate`), `string(json_array(1 RETURNING STRING COLLATE c))` (explicitly
    +    // collated child), and `CAST(... AS STRING)` (`USER_SPECIFIED_CAST`). Requiring a real
    +    // collation change leaves the no-op `string(...)` cast alone.
    +    if (!c.child.isInstanceOf[DefaultStringProducingExpression]) return false
    +    (c.dataType, c.child.dataType) match {
    +      case (to: StringType, from: StringType) =>
    +        from.eq(StringType) && to != from && !c.containsTag(Cast.USER_SPECIFIED_CAST)

    Blocking (P1): This predicate tells a user CAST(... AS STRING) from an analyzer collation cast only by USER_SPECIFIED_CAST, but the fixed-point ApplyDefaultCollation drops that tag in a reachable shape. Under a non-UTF8_BINARY table, view, or SQL-function default collation, the already-cast arm of castDefaultStringExpressions rebuilds a retargeted user cast with cast.copy(...) whenever a default-string producer below it gets its own collation cast, and withNewChildren installs the untagged copy. Any splice decision made after that pass, in the builders or in finalizeFlags, then splices the value the user cast in order to quote it.

    For example, CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS SELECT builtin.json_array(CAST(json_array(json_array(1)) AS STRING), (SELECT 1)) AS j stores [[[1]],1] instead of ["[[1]]",1]. The scalar-subquery sibling defers the outer call past the first ApplyDefaultCollation pass; without it the same expression is decided earlier and stays quoted. The unqualified json_array(...) call, the clause-bearing forms, and JSON_OBJECT behave the same way. The single-pass analyzer keeps the tag (CoercesExpressionTypes copies tags onto the coercion result) and quotes, so the two analyzers also disagree for views.

    Recommended change: Make the default-collation rule re-apply the user-specified cast marker when it rebuilds an already-retargeted user cast around recolored children, as the collation type-coercion rule does when it retargets a cast. Copy only that marker, not every tag, because that rule notes that a stale collation-context tag must not be carried over. Add JSON_ARRAY and JSON_OBJECT default-collation tests in which the enclosing constructor's splice decision is deferred by a sibling argument.

    Why this works: With the marker preserved, a user CAST, TRY_CAST, or :: around a nested JSON producer keeps reading as a user cast, so the splice predicate quotes it no matter which analyzer iteration makes the decision.

    Scope: Marker-preserving cast rebuild in the default-collation rule, plus deferred-decision regression coverage for the JSON constructors.

    Compatibility: Default-collation recoloring of JSON constructor results, and splicing through casts the analyzer inserts for the default collation.

    Risks: Auto-generated column names read the same marker, so a deferred un-aliased column of this shape is renamed to include the user's CAST, which is the name the same column already gets when nothing is deferred and in the single-pass analyzer. This applies to any such column under a non-UTF8_BINARY object or view default collation, not only to JSON constructors. A view created on Spark 4.2.0 or later with such a column stored the old name, and reading a view matches its stored column names against the query output, so it can fail with an incompatible view schema error until it is recreated or the column is aliased. CHAR/VARCHAR truncation is unaffected because only casts already retargeted to the default STRING collation reach this rebuild. Reverting the change restores the current behavior.

    Constraints: Casts that the default-collation rules insert must stay unmarked, so qualified and routed nested producers keep splicing under an object or view default collation. Re-apply only the user-specified cast marker; do not copy the collation-context tag.

    Exclusions:

  • Resolution rules outside the analysis package and rules injected through session extensions, which the targeted search for marker-dropping cast rebuilds did not cover.
  • Success: Under a table, view, or SQL-function default collation, a user cast to STRING around a nested JSON producer stays quoted in JSON_ARRAY and JSON_OBJECT whether the enclosing splice decision is made in the same analyzer iteration or a later one. Qualified and routed nested producers without a user cast still splice under a default collation. A deferred un-aliased column whose user cast was rebuilt gets the same auto-generated name as when nothing defers it, in both analyzers.

    Verification:

  • Regression: Under a table default collation and a view default collation, an unqualified, a qualified, and a clause-bearing JSON_ARRAY whose user-cast nested-constructor argument has a scalar-subquery sibling return the quoted value in both analyzers, matching the same query without the sibling. The same holds for JSON_OBJECT.

  • Compatibility: Existing default-collation results stay the same for qualified, routed, COLLATE-annotated, string(), and plain user-cast cases of both constructors.

  • Compatibility: Under a view default collation, a deferred un-aliased column whose user cast wraps a default-string producer with such a descendant gets the same auto-generated name in the fixed-point analyzer as without the deferring sibling, and as in the single-pass analyzer.

  • Behavior: A user cast that the default-collation rule rebuilds around recolored children still carries the user-specified marker, and an analyzer-inserted cast it rebuilds stays unmarked.
  • cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:1
    @@ -2594,18 +2621,39 @@ class Analyzer(
     
           case q: LogicalPlan =>
             q.transformExpressionsUpWithPruning(
    -          _.containsAnyPattern(UNRESOLVED_FUNCTION, GENERATOR),
    +          _.containsAnyPattern(UNRESOLVED_FUNCTION, GENERATOR, UNRESOLVED_JSON_CONSTRUCTOR),
               ruleId) {
    -          case u @ UnresolvedFunction(nameParts, arguments, _, _, _, _, _, _)
    -              if functionResolution.hasLambdaAndResolvedArguments(arguments) => withPosition(u) {
    -            functionResolution.resolveFunction(u) match {
    -              case func: HigherOrderFunction => func
    -              case other => other.failAnalysis(
    -                errorClass = "INVALID_LAMBDA_FUNCTION_CALL.NON_HIGHER_ORDER_FUNCTION",
    -                messageParameters = Map(
    -                  "class" -> other.getClass.getCanonicalName))
    +          case u @ UnresolvedFunction(_, arguments, _, _, _, _, _, _)
    +              if functionResolution.hasLambdaAndResolvedArguments(arguments) =>
    +            resolveHigherOrderFunction(u)
    +
    +          // Decide a SQL/JSON constructor's owner in this same bottom-up pass, so an enclosing call
    +          // and its alias see the result without an extra iteration per nesting level.
    +          case j: UnresolvedJsonConstructor
    +              if functionResolution.routesJsonConstructorToFunction(j) =>

    Non-blocking (P2): The ownership probe in this guard runs before the !j.childrenResolved wait below, so a routed wrapper that the built-in owns repeats the SQL PATH walk each time ResolveFunctions revisits it while its children are unresolved (for example inside a lambda, or with outer or lateral references), and once more when it finalizes. A wrapper that a routine owns walks the PATH here and again in resolveFunction. The equivalent flat call is skipped until its children resolve, and LookupFunctions resolves the single-part built-in name in memory, so it walks the PATH once.

    With SET PATH = cat.fns, system.builtin, transform(arr, x -> json_array(json_array(x))) makes two uncached functionExists calls on cat.fns, where transform(arr, x -> json_array(x)) makes one loadFunction call. This only costs analysis time, and under the default PATH each walk stops at system.builtin in memory.

    Recommended change: When the ownership check finds that the built-in owns a routed nested JSON_ARRAY or JSON_OBJECT call, replace the routed wrapper with its stock-owned counterpart, carrying the same values, splice flags, and clause-free defaults. Later iterations then finalize it without checking the SQL PATH again. Routine-owned wrappers still become an ordinary call right away.

    Why this works: Ownership is decided once per routed call, as in the direct-star path and the single-pass resolver. The stock-owned counterpart then waits for its children without touching the catalog.

    Scope: One-time ownership decision for routed JSON constructor wrappers in fixed-point function resolution.

    Compatibility: Routine and injected-replacement ownership of nested clause-free JSON constructor calls.

    Risks: While it waits for its children, the stock-owned counterpart reports its RETURNING type to default-collation rules, as clause-bearing stock wrappers already do. That is correct only because the built-in has already been chosen as owner. Reverting the change restores per-iteration checking.

    Constraints: A routine-owned or injected-replacement-owned wrapper must still become an ordinary call without waiting for its children. A routed wrapper must not be presented as a default-string producer before its owner is decided.

    Exclusions:

  • The second PATH walk when a routine owns the call. Removing it would need resolution to reuse the owner the probe found, which would change the flat call's fallback to the built-in when a shadow disappears between the probe and resolution.
  • Success: A routed nested call owned by the built-in checks the SQL PATH once per analysis, however many iterations its children take to resolve. Routine-owned and injected-replacement-owned nested calls resolve exactly as before.

    Verification:

  • Regression: With a SQL PATH that lists a lookup-counting function catalog ahead of system.builtin, a nested clause-free JSON_ARRAY that the built-in owns, inside a lambda body, makes no more catalog function lookups (existence checks and loads combined) than the equivalent flat call.

  • Compatibility: Existing splice, shadowing, direct-star, lambda, and default-collation results for routed nested calls are unchanged in both analyzers.
  • cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:1
    @@ -4391,25 +4391,32 @@ class AstBuilder extends DataTypeAstBuilder
        */
       override def visitJsonArray(ctx: JsonArrayContext): Expression = withOrigin(ctx) {
         val arrayValues = ctx.values.asScala.map(v => expression(v.value)).toSeq
    -    // Route a flat, clause-free call through routine resolution so it can be shadowed. Cheap
    -    // clause/nesting checks come first to skip the recursive per-value FORMAT scans when a clause
    -    // already forces direct construction.
    -    val routeThroughResolution =
    +    // A clause-free call (no RETURNING, no ON NULL, not a direct JSON constructor argument, and no
    +    // explicit FORMAT JSON on any value) routes through routine resolution so a routine can shadow
    +    // it. The cheap clause/nesting checks come first so the recursive per-value implicit-JSON scan
    +    // runs only when routing is still possible.
    +    val clauseFree =
           ctx.returning == null && ctx.nullBehavior == null && !isDirectJsonConstructorArgument(ctx) &&
    -        !ctx.values.asScala.exists(_.FORMAT() != null) &&
    -        !arrayValues.exists(JsonArray.isImplicitlyJson)
    -    if (routeThroughResolution) {
    +        !ctx.values.asScala.exists(_.FORMAT() != null)
    +    if (clauseFree && !arrayValues.exists(ImplicitlyFormattedAsJson.isImplicitlyJson)) {
           UnresolvedFunction("json_array", arrayValues, isDistinct = false)
    +    } else if (clauseFree) {
    +      // Nested clause-free call: route so a routine can shadow it, but carry the per-value splice
    +      // decision, frozen now from the lexical argument, through resolution (see

    Nit (P3): This says the per-value splice decision is "frozen now from the lexical argument", and the direct-branch comment just below says a later rewrite that wraps or swaps the child cannot change the flags. Both wrappers now finalize through StockJsonConstructor.finalizeFlags, which ORs each parser flag with splicesThroughCollationCast on the resolved child, so analysis can still add a splice, for example to the second element of json_array(json_array(1), builtin.json_array(2)). The parser flags are a lower bound, as the updated JsonArray comments already say.

    This extends an existing discussion.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -2411,14 +2582,14 @@ case class JsonObjectKeyGuard(child: Expression) extends UnaryExpression with No
      *   JSON_OBJECT('id': 7, 'v': NULL ABSENT ON NULL)     -> '{"id":7}'
      *   JSON_OBJECT()                                       -> '{}'
      *
    - * A clause-free call that is not itself lexically nested in an enclosing constructor's *value*
    - * position routes through function resolution and is rebuilt by `JsonObjectExpressionBuilder`, so a
    - * same-named routine can shadow the built-in `json_object`: always for the comma form (a nested
    - * producer value routes too, carrying its raw-splice eligibility via `JsonImplicitFormatCarrier`),
    - * but for the `VALUE` / `:` forms only when no member carries a raw value (`rawJson.contains(true)`
    - * -- an explicit `FORMAT JSON` or a nested producer in *value* position -- keeps it direct).
    - * Otherwise it is built directly from the grammar (clause-bearing, or value-nested); a nested
    - * *key*-position call stays routable (see `AstBuilder.visitJsonObject`).
    + * A clause-free call without explicit `FORMAT JSON`, and not itself lexically nested in an
    + * enclosing constructor's *value* position, routes through function resolution so a same-named
    + * routine can shadow the built-in `json_object`. A parser-visible nested producer value keeps its
    + * raw-splice eligibility in an [[UnresolvedJsonObject]]; a shadow receives plain key/value

    Nit (P3): On the routed, shadowable path the parser builds UnresolvedRoutedJsonObject(members, rawJson) in AstBuilder.visitJsonObject, not UnresolvedJsonObject, which is the stock-owned wrapper that never routes. As written, the sentence points a reader at the wrong class while describing the call a shadow can own.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1720,6 +1765,144 @@ object JsonArray {
       }
     }
     
    +/**
    + * A parsed `JSON_ARRAY(...)` / `JSON_OBJECT(...)` whose splice flags are finalized after child
    + * resolution: parser flags keep explicit `FORMAT JSON` and lexical nested constructors, and the
    + * resolved children add qualified/routed nested constructors the parser cannot see.
    + *
    + * [[StockJsonConstructor]]s are owned by the stock built-in. [[RoutedJsonConstructor]]s are
    + * clause-free calls a same-named routine (or an `injectFunction` replacement) can shadow; they then
    + * resolve as a plain `prettyName(arguments...)` call.
    + */
    +sealed trait UnresolvedJsonConstructor extends Unevaluable with ImplicitlyFormattedAsJson {
    +  def routeThroughResolution: Boolean
    +  /** The flattened argument list a routed call passes to a same-named routine. */
    +  def arguments: Seq[Expression] = children
    +  /** The stock built-in over the current children, with splice flags finalized. */
    +  def toBuiltin: TimeZoneAwareExpression
    +  /** The ordinary call a routed constructor resolves as when a routine owns the name. */
    +  def toUnresolvedFunction: UnresolvedFunction = CurrentOrigin.withOrigin(origin) {
    +    UnresolvedFunction(prettyName, arguments, isDistinct = false)
    +  }
    +
    +  override def dataType: DataType = throw new UnresolvedException("dataType")
    +  override def nullable: Boolean = throw new UnresolvedException("nullable")
    +  override lazy val resolved: Boolean = false
    +  final override val nodePatterns: Seq[TreePattern] = Seq(UNRESOLVED_JSON_CONSTRUCTOR)
    +}
    +
    +/** An [[UnresolvedJsonConstructor]] the stock built-in owns (clause-bearing or `FORMAT JSON`). */

    Nit (P3): The parser also builds a stock wrapper for a clause-free call written directly as another constructor's value, such as the inner JSON_ARRAY(1) in JSON_ARRAY(JSON_ARRAY(1)), because visitJsonArray and visitJsonObject route only when !isDirectJsonConstructorArgument(ctx). The routing comment in FunctionRegistry has the same gap and also leaves out json_array with explicit FORMAT JSON. A reader working out shadow ownership, or the temp-function and cyclic-reference checks, from these lists would conclude that value-nested calls can be shadowed, which they cannot.

    See Shared repair plan 1 in the review body.

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1720,6 +1765,144 @@ object JsonArray {
       }
     }
     
    +/**
    + * A parsed `JSON_ARRAY(...)` / `JSON_OBJECT(...)` whose splice flags are finalized after child
    + * resolution: parser flags keep explicit `FORMAT JSON` and lexical nested constructors, and the
    + * resolved children add qualified/routed nested constructors the parser cannot see.
    + *
    + * [[StockJsonConstructor]]s are owned by the stock built-in. [[RoutedJsonConstructor]]s are
    + * clause-free calls a same-named routine (or an `injectFunction` replacement) can shadow; they then
    + * resolve as a plain `prettyName(arguments...)` call.
    + */
    +sealed trait UnresolvedJsonConstructor extends Unevaluable with ImplicitlyFormattedAsJson {
    +  def routeThroughResolution: Boolean
    +  /** The flattened argument list a routed call passes to a same-named routine. */
    +  def arguments: Seq[Expression] = children
    +  /** The stock built-in over the current children, with splice flags finalized. */
    +  def toBuiltin: TimeZoneAwareExpression
    +  /** The ordinary call a routed constructor resolves as when a routine owns the name. */
    +  def toUnresolvedFunction: UnresolvedFunction = CurrentOrigin.withOrigin(origin) {
    +    UnresolvedFunction(prettyName, arguments, isDistinct = false)
    +  }
    +
    +  override def dataType: DataType = throw new UnresolvedException("dataType")
    +  override def nullable: Boolean = throw new UnresolvedException("nullable")
    +  override lazy val resolved: Boolean = false
    +  final override val nodePatterns: Seq[TreePattern] = Seq(UNRESOLVED_JSON_CONSTRUCTOR)
    +}
    +
    +/** An [[UnresolvedJsonConstructor]] the stock built-in owns (clause-bearing or `FORMAT JSON`). */
    +sealed trait StockJsonConstructor
    +  extends UnresolvedJsonConstructor
    +  with DefaultStringProducingExpression {
    +  def returning: DataType
    +  final override def routeThroughResolution: Boolean = false
    +  // Report the actual RETURNING type (not the default from `DefaultStringProducingExpression`) so
    +  // `ApplyDefaultCollation` sees an explicit `RETURNING STRING COLLATE c` on this still-unresolved
    +  // node and does not recolor it to the object/view default.
    +  override def dataType: DataType = returning
    +
    +  // A parser flag stays set; a resolved child that splices through a collation cast adds one.
    +  // An added splice is a trusted constructor, so it never needs validation.
    +  protected def finalizeFlags(
    +      parserFlags: Seq[Boolean],
    +      needsValidation: Seq[Boolean],
    +      values: Seq[Expression]): (Seq[Boolean], Seq[Boolean]) = {
    +    val splices = values.map(ImplicitlyFormattedAsJson.splicesThroughCollationCast)
    +    (parserFlags.lazyZip(splices).map(_ || _), needsValidation.lazyZip(splices).map(_ && !_))
    +  }
    +}
    +
    +/**
    + * An [[UnresolvedJsonConstructor]] whose owner is not known until resolution. Deliberately not a
    + * `DefaultStringProducingExpression`: until a routine is ruled out it stands for an ordinary call,
    + * so default-collation rules must not cast it (a shadow keeps its own result type).
    + */
    +sealed trait RoutedJsonConstructor extends UnresolvedJsonConstructor {
    +  final override def routeThroughResolution: Boolean = true
    +}
    +
    +case class UnresolvedJsonArray(
    +    values: Seq[Expression],
    +    formatJson: Seq[Boolean],
    +    needsValidation: Seq[Boolean],
    +    nullBehavior: JsonConstructorNullBehavior,
    +    returning: DataType)
    +  extends StockJsonConstructor {
    +  assert(values.length == formatJson.length && values.length == needsValidation.length,
    +    "UnresolvedJsonArray requires one formatJson and one needsValidation flag per value")
    +  assert(needsValidation.lazyZip(formatJson).forall((nv, fj) => !nv || fj),
    +    "UnresolvedJsonArray needsValidation implies formatJson")
    +  override def children: Seq[Expression] = values
    +  override def prettyName: String = "json_array"
    +  // Only the values are children, so `withNewChildren` (e.g. a default-collation `Cast` wrapping a
    +  // child) preserves the parse-time flags.
    +  override protected def withNewChildrenInternal(
    +      newChildren: IndexedSeq[Expression]): UnresolvedJsonArray = copy(values = newChildren)
    +
    +  override def toBuiltin: JsonArray = {
    +    val (finalFormatJson, finalNeedsValidation) = finalizeFlags(formatJson, needsValidation, values)
    +    JsonArray(values, finalFormatJson, finalNeedsValidation, nullBehavior, returning)
    +  }
    +}
    +
    +/** A clause-free `JSON_ARRAY(...)` with a lexically nested constructor (see [[JsonArray]]). */
    +case class UnresolvedRoutedJsonArray(values: Seq[Expression], formatJson: Seq[Boolean])
    +  extends RoutedJsonConstructor {
    +  assert(values.length == formatJson.length,
    +    "UnresolvedRoutedJsonArray requires one formatJson flag per value")
    +  override def children: Seq[Expression] = values
    +  override def prettyName: String = "json_array"
    +  override protected def withNewChildrenInternal(
    +      newChildren: IndexedSeq[Expression]): UnresolvedRoutedJsonArray = copy(values = newChildren)
    +
    +  override def toBuiltin: JsonArray = UnresolvedJsonArray(
    +    values, formatJson, values.map(_ => false), JsonConstructorNullBehavior.Absent, StringType

    Nit (P3): The routed wrappers now supply their own clause-free null defaults: ABSENT ON NULL here and NULL ON NULL in UnresolvedRoutedJsonObject.toBuiltin. Both are correct, but no test in JsonArraySuite, JsonObjectSuite, or the JSON SQL tests runs a nested clause-free call with a NULL value. A swapped default would turn json_array(json_array(1), NULL) into [[1],null], or drop the "c" key from json_object('a' VALUE json_object('b' VALUE 1), 'c' VALUE NULL), without any test failing.

    Verification:

  • Regression: A clause-free JSON_ARRAY with a nested constructor and a NULL element returns the array without the null, and a clause-free JSON_OBJECT VALUE form with a nested constructor and a NULL value returns the key with null, in both analyzers.
  • cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -954,6 +1283,77 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         }
       }
     
    +  test("SPARK-59243: routed/qualified nested JSON_ARRAY splices under a default collation") {
    +    // Both columns resolve through the built-in builder (not the direct grammar path): col a via

    Nit (P3): The CTAS below now selects four columns. Column c, json_array(json_array(0), builtin.json_array(1) COLLATE UNICODE), parses to UnresolvedRoutedJsonArray and is finalized through toBuiltin/finalizeFlags, not through JsonArrayExpressionBuilder, so the comment misstates which splice-predicate consumers this test covers.

    See Shared repair plan 2 in the review body.

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1
    @@ -646,23 +681,197 @@ class JsonArraySuite extends QueryTest with SharedSparkSession {
         checkAnswer(sql("SELECT system.builtin.json_array(1, 'x')"), Row("""[1,"x"]"""))
       }
     
    -  test("a nested JSON-producing argument through a routed JSON_ARRAY call is quoted, not spliced") {
    -    // A routed call carries no lexical FORMAT JSON, so a nested JSON-producing argument (a JSON
    -    // constructor like json_array or a path function like json_query) is quoted as a plain value,
    -    // unlike the JSON_ARRAY(...) grammar which splices it (see the unqualified
    -    // `json_array(json_array(1))` -> `[[1]]` cases above). The outer call routes whenever it sees
    -    // no lexical implicit-JSON element: `JsonArray.isImplicitlyJson` recognizes only a
    -    // grammar-built nested JSON expression, so a qualified outer call and an unqualified call over
    -    // a qualified nested JSON expression (whose child is still unresolved) both route and quote.
    -    // Only a fully unqualified nested JSON expression stays on the direct grammar path; splicing
    -    // through a routed call is left as a follow-up.
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("""["[1]"]"""))
    -    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("""["[1]",2]"""))
    -    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("""["[1]"]"""))
    +  test("SPARK-59243: a nested JSON constructor through a routed JSON_ARRAY call is spliced") {
    +    // A routed or qualified built-in JSON_ARRAY splices a lexically-nested JSON constructor
    +    // argument, matching the JSON_ARRAY(...) grammar (`json_array(json_array(1))` -> `[[1]]`).
    +    // The built-in builder derives the FORMAT JSON flag from the resolved argument via
    +    // `ImplicitlyFormattedAsJson.splicesThroughCollationCast`, so a qualified outer call and an
    +    // unqualified call over a qualified nested constructor both splice, matching the fully
    +    // unqualified grammar form.
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT system.builtin.json_array(json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT builtin.json_array(json_array(1), 2)"), Row("[[1],2]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1))"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(json_array(0), builtin.json_array(1))"), Row("[[0],[1]]"))
         checkAnswer(
           sql("""SELECT builtin.json_array(json_query('{"a":{"x":1}}', '$.a'))"""),
    -      Row("""["{\"x\":1}"]"""))
    +      Row("""[{"x":1}]"""))
    +    // A user CAST still detaches FORMAT JSON, so the element stays quoted (the routed splice check
    +    // sees through an analyzer collation Cast, but not a user `CAST(... AS STRING)`).
    +    checkAnswer(sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING))"), Row("""["[1]"]"""))
    +    // A user cast that changes the collation is told apart from an analyzer collation Cast only by
    +    // its USER_SPECIFIED_CAST tag, and must still detach.
    +    checkAnswer(
    +      sql("SELECT builtin.json_array(CAST(json_array(1) AS STRING COLLATE UTF8_LCASE))"),
    +      Row("""["[1]"]"""))
    +    withSQLConf(SQLConf.OBJECT_LEVEL_COLLATIONS_ENABLED.key -> "true") {
    +      withTable("t") {
    +        sql("CREATE TABLE t DEFAULT COLLATION UTF8_LCASE AS " +
    +          "SELECT builtin.json_array(CAST(json_array(1) AS STRING)) AS a")
    +        checkAnswer(spark.table("t"), Row("""["[1]"]"""))
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: clause-bearing JSON_ARRAY splices qualified nested constructors") {
    +    // Clause-bearing direct forms do not route through function resolution, but still need to
    +    // recover the qualified nested constructor after children resolve.
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) NULL ON NULL)"), Row("[[1]]"))
    +    checkAnswer(sql("SELECT json_array(builtin.json_array(1) RETURNING STRING)"), Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)"),
    +      Row("[[1]]"))
    +    checkAnswer(
    +      sql("SELECT json_array(CAST(builtin.json_array(1) AS STRING) NULL ON NULL)"),
    +      Row("""["[1]"]"""))
    +
    +    Seq(false, true).foreach { singlePass =>
    +      withSQLConf(
    +        SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> singlePass.toString) {
    +        val analyzed =
    +          sql("SELECT json_array(builtin.json_array(1) FORMAT JSON NULL ON NULL)")
    +            .queryExecution.analyzed
    +        assert(analyzed.resolved, s"singlePass=$singlePass")
    +        val arrays = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j })
    +        val outer = arrays.find(_.nullBehavior == JsonConstructorNullBehavior.Null).get
    +        assert(outer.formatJson == Seq(true), s"singlePass=$singlePass")
    +        assert(outer.needsValidation == Seq(false), s"singlePass=$singlePass")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: routed JSON_ARRAY splice round-trips through canonical SQL") {
    +    // The analyzed expression's canonical SQL must reparse to the same spliced result.
    +    Seq(
    +      "SELECT builtin.json_array(json_array(1))",
    +      "SELECT json_array(builtin.json_array(1))").foreach { query =>
    +      val analyzed = sql(query).queryExecution.analyzed
    +      val jsonArray = analyzed.expressions.flatMap(_.collect { case j: JsonArray => j }).head
    +      checkAnswer(sql(s"SELECT ${jsonArray.sql}"), Row("[[1]]"))
    +    }
    +  }
    +
    +  test("SPARK-59243: spliced nested JSON_ARRAY canonical SQL stays built-in under a shadow") {
    +    // Canonical SQL of a resolved built-in must reparse to the built-in even under a shadow: the
    +    // nested splice now routes, so each clause-free level carries an ownership clause.
    +    val inner = JsonArray(
    +      Seq(Literal(1)), Seq(false), Seq(false), JsonConstructorNullBehavior.Absent, StringType)
    +    val canonical = JsonArray(
    +      Seq(inner), Seq(true), Seq(false), JsonConstructorNullBehavior.Absent, StringType).sql
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        checkAnswer(sql(s"SELECT $canonical"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: an explicit collation-changing string() cast detaches splicing") {
    +    // `string(... COLLATE c)` is an explicit cast (via the cast alias) that detaches FORMAT JSON,
    +    // so the nested constructor is quoted, not spliced. The analyzer-collation-cast unwrap in
    +    // `splicesThroughCollationCast` must not treat it as an `ApplyDefaultCollation` cast.
    +    checkAnswer(
    +      sql("SELECT builtin.json_array(string(json_array(1) COLLATE UTF8_LCASE))"),
    +      Row("""["[1]"]"""))
    +    // Also when the cast itself changes the collation: it is still a user cast, not a
    +    // default-collation recoloring, on both the routed and the direct grammar paths.
    +    val nested = "string(json_array(1 RETURNING STRING COLLATE UTF8_LCASE))"
    +    checkAnswer(sql(s"SELECT builtin.json_array($nested)"), Row("""["[1]"]"""))
    +    checkAnswer(sql(s"SELECT json_array($nested NULL ON NULL)"), Row("""["[1]"]"""))
    +  }
    +
    +  test("SPARK-59243: a nested clause-free JSON_ARRAY call is shadowed like a flat call") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_array(a STRING) RETURNS STRING RETURN 'shadowed'")
    +        sql("SET PATH = system.session, system.builtin")
    +        // The inner json_array(1) is a grammar element (built-in) producing "[1]"; the outer
    +        // clause-free call routes, so the temp shadows it.
    +        checkAnswer(sql("SELECT json_array(json_array(1))"), Row("shadowed"))
    +        // Strict single-pass routes the outer clause-free call to the shadow owner too, but the
    +        // owner is a SQL function, which the single-pass analyzer does not yet resolve: it reaches
    +        // that owner (proving the routing) and then aborts with an
    +        // ExplicitlyUnsupportedResolverFeature on the SQL function body. The guard-gated modes fall
    +        // back to fixed-point, which produces the shadow result asserted above.
    +        withSQLConf(SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> "true") {
    +          intercept[ExplicitlyUnsupportedResolverFeature] {
    +            sql("SELECT json_array(json_array(1))").queryExecution.analyzed
    +          }
    +        }
    +        // Qualifying every level selects Spark's constructor and splices.
    +        checkAnswer(sql("SELECT builtin.json_array(builtin.json_array(1))"), Row("[[1]]"))
    +      } finally {
    +        sql("SET PATH = DEFAULT_PATH")
    +        sql("DROP TEMPORARY FUNCTION IF EXISTS json_array")
    +      }
    +    }
    +  }
    +
    +  test("SPARK-59243: nested constructors splice in subqueries, grouping, and INSERT VALUES") {
    +    // The finalization rule runs over every operator, not just a top-level Project.

    Nit (P3): There is no longer a separate finalization rule: ResolveJsonConstructors was removed, and ResolveFunctions (and ExpressionResolver in the single-pass analyzer) now route or finalize the wrappers. A reader looking for the rule this comment names will not find it.

    See Shared repair plan 2 in the review body.

    cloud-fan cloud-fan commented on code on Oct 30, 2026 08:26 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala:1
    @@ -1350,6 +1604,59 @@ world'))"""))
         }
       }
     
    +  test("invalid: a direct star in VALUE/colon JSON_OBJECT forms is not expanded") {
    +    // Clause-free VALUE / colon forms route through function resolution, but the stock built-in
    +    // still rejects a direct member value `*`; only a shadowing routine may receive it expanded.
    +    Seq(
    +      "SELECT json_object('a' VALUE *, 'b' VALUE json_object('c' VALUE 1)) " +
    +        "FROM VALUES ('id', 7) AS t(a, b)",
    +      "SELECT json_object('a': *, 'b': json_object('c': 1)) " +
    +        "FROM VALUES ('id', 7) AS t(a, b)"
    +    ).foreach { query =>
    +      Seq(false, true).foreach { singlePass =>
    +        withSQLConf(SQLConf.ANALYZER_SINGLE_PASS_RESOLVER_ENABLED.key -> singlePass.toString) {
    +          val e = intercept[AnalysisException] {
    +            sql(query).queryExecution.analyzed
    +          }
    +          assert(e.getCondition == "INVALID_USAGE_OF_STAR_OR_REGEX",
    +            s"singlePass=$singlePass for $query")
    +        }
    +      }
    +    }
    +  }
    +
    +  test("VALUE/colon JSON_OBJECT star expands for a shadow owner") {
    +    withSQLConf(
    +      SQLConf.PATH_ENABLED.key -> "true",
    +      SQLConf.SESSION_FUNCTION_RESOLUTION_ORDER.key -> "second") {
    +      try {
    +        sql("CREATE TEMPORARY FUNCTION json_object(k1 STRING, v1 STRING, v2 INT, " +
    +          "k2 STRING, v3 STRING) RETURNS STRING RETURN 'shadowed-5'")
    +        sql("SET PATH = system.session, system.builtin")
    +        Seq(
    +          "SELECT json_object('a' VALUE *, 'b' VALUE json_object('c' VALUE 1)) " +
    +            "FROM VALUES ('id', 7) AS t(a, b)",
    +          "SELECT json_object('a': *, 'b': json_object('c': 1)) " +
    +            "FROM VALUES ('id', 7) AS t(a, b)"
    +        ).foreach { query =>
    +          checkAnswer(sql(query), Row("shadowed-5"))
    +          // Strict single-pass expands the nested star and routes to the shadow owner too, but the

    Nit (P3): In both queries the is a direct member value of the outer call, which the previous test calls "a direct member value ". Elsewhere in this PR, "nested star" means a star that belongs to an inner call such as array(*) (for example in the single-pass: routed JSON_OBJECT resolves and expands a nested star test below), and that star expands whoever owns the JSON constructor. Calling this one "the nested star" makes the test read as covering that case, rather than a direct star whose expansion depends on a shadow owning the call.

    See Shared repair plan 2 in the review body.

    cloud-fan cloud-fan commented on Oct 30, 2026 08:26 UTC
    Reviewer

    Review summary

    Since the previous review, all nine earlier findings have been addressed. Routed wrappers no longer take the default-collation cast before their owner is known, wrappers are finalized inside ResolveFunctions without extra Resolution iterations, COLLATE over an analyzer collation cast now splices, ResolverGuard checks routed wrappers the way it checks the flat call, and the requested tests were added. The JsonArray and splice-predicate comments flagged earlier are fixed, but the same parse-time-only claim remains in two AstBuilder comments, reported below.

    The main remaining issue is a wrong result in the default fixed-point analyzer. Under a table, view, or SQL-function default collation, a user CAST(... AS STRING) around a nested JSON constructor can lose its user-cast marker in ApplyDefaultCollation before a later iteration makes the splice decision, so the value the user cast in order to quote it is spliced raw. This happens only when a sibling argument such as a scalar subquery defers that decision, so the same expression quotes or splices depending on its siblings. The single-pass analyzer keeps the marker and quotes.

    Routed nested calls also make more catalog lookups at analysis time than the equivalent flat call when a custom PATH lists persistent schemas ahead of system.builtin. The cost is bounded and does not affect execution.

    The rest are small. Three production comments and three test comments describe the routing or the splice-flag lifecycle inaccurately, and no test pins the clause-free null defaults on the new routed-wrapper path. Two questions for the author about routing nested calls like flat calls follow.

    Cross-cutting observations

  • Both decision challenges come from one choice in this PR: nested clause-free JSON_ARRAY and JSON_OBJECT calls are now handled like flat function calls, so every flat-call rule about same-named routines now also applies to SQL that previously always meant the built-in constructor.
  • Each can be settled on its own, because accepting routine ownership for nested calls at query time does not decide whether the temporary-function check for persistent function bodies should consider PATH order.

    Findings

    9 total: 0 P0, 1 P1, 1 P2, 7 P3.

    Blocking (P1)

  • User CAST around a nested JSON constructor is spliced when the splice decision is deferred — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1366 — see inline.
  • Non-blocking (P2)

  • Routed nested constructors walk the SQL PATH more often than the flat call — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:2633 — see inline.
  • Nit (P3)

  • visitJsonArray comments still say splice flags are fixed at parse time — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:4405 — see inline.

  • JsonObjectExpr scaladoc names the stock wrapper for the routed path — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:2588 — see inline.

  • Stock-owned form lists omit clause-free calls in a constructor's value position — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1794 — see inline.

  • No test covers the clause-free null defaults on the routed-wrapper path — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1860 — see inline.

  • Default-collation test comment describes two builder columns, but the CTAS has four — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1287 — see inline.

  • Test comment refers to a finalization rule that was removed — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:819 — see inline.

  • Shadow-owner star test calls a direct member star a nested star — sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala:1643 — see inline.
  • Shared repair plans

    Shared repair plan 1

    Covered findings:

  • visitJsonArray comments still say splice flags are fixed at parse time — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:4405

  • JsonObjectExpr scaladoc names the stock wrapper for the routed path — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:2588

  • Stock-owned form lists omit clause-free calls in a constructor's value position — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1794
  • Verification:

  • Inspection: The JsonObjectExpr, StockJsonConstructor, FunctionRegistry, and visitJsonArray comments describe the direct-argument stock rule, the routed wrapper classes, and the analysis-time splice extension consistently with the parser and finalization code.
  • Shared repair plan 2

    Covered findings:

  • Default-collation test comment describes two builder columns, but the CTAS has four — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:1287

  • Test comment refers to a finalization rule that was removed — sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala:819

  • Shadow-owner star test calls a direct member star a nested star — sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala:1643
  • Verification:

  • Inspection: The three comments name the code paths their assertions exercise, do not refer to a separate finalization rule, and call a bare member * a direct star.
  • Re-review status

    Prior AI findings: 9 no longer raised, 0 still raised; additional unresolved findings in this review: 9.

    New attribution: 6 newly introduced, 3 late catch, 0 previously raised, 0 unattributed.

    PR description suggestions

  • The Analyzer bullet describes a new ResolveJsonConstructors rule placed just before ApplyDefaultCollation. At the reviewed head that rule no longer exists: ResolveFunctions routes or finalizes the wrappers in its bottom-up pass, and ExpressionResolver does the same in the single-pass analyzer. The Parser bullet also describes one UnresolvedJsonArray / UnresolvedJsonObject that sets routeThroughResolution, while the head builds separate UnresolvedRoutedJsonArray / UnresolvedRoutedJsonObject wrappers for clause-free calls with a nested constructor and keeps UnresolvedJsonArray / UnresolvedJsonObject for stock-owned forms. Update both bullets to match the code.
  • Decision challenges

    Nested clause-free JSON_ARRAY/JSON_OBJECT calls now bind to a same-named routine

    On the base branch, a clause-free call that lexically nests a constructor, such as json_array(json_array(1)) or json_object('a' VALUE json_object('b' VALUE 1)), always meant the built-in constructor; only the comma-form json_object already routed. With this PR such a call resolves through function resolution like a flat call, so any same-named temporary, PATH, V2-catalog, or injected routine ahead of system.builtin owns it, even one written for a different signature. With the existing shadow test's json_array(a INT, b STRING) ahead of system.builtin, SELECT json_array(json_array(1)) returned [[1]] before and now fails argument binding, and the PR removed that assertion. With a json_object(a STRING, b INT) shadow, the VALUE form now casts the nested JSON text to INT. The inner call stays the built-in because it is a direct constructor argument, so a shadow receives the built-in's JSON text as an ordinary argument.

    Flat calls already behave this way, and the constructors are unreleased, so only builds whose PATH puts such a routine first are affected. Is this the intended consistency with flat calls? If so, consider documenting on the JSON_ARRAY and JSON_OBJECT reference pages that a clause-free call, nested or not, can be shadowed, and that qualifying it (builtin.json_array) or adding a clause keeps the built-in. If not, nested clause-free calls could keep binding to the built-in.

    CREATE FUNCTION rejects nested constructor bodies whenever a same-named temporary function exists

    CreateSQLFunctionCommand now counts a routed nested constructor as a temporary-function reference whenever a temporary function with the same name exists, using the same existence-only check as the flat call, without considering whether that temporary function would own the call. Under the default session order (second: built-in functions first, then session functions), a temporary json_array never owns json_array(json_array(1)) at runtime, yet CREATE FUNCTION perm() RETURNS STRING RETURN json_array(json_array(1)) now fails with INVALID_TEMP_OBJ_REFERENCE. On the base branch that body was the built-in constructor and was accepted. A flat json_array(1) body is already rejected the same way. The new tests only use SET PATH = system.session, system.builtin, where the temporary function does own the call.

    Is the existence-only check intended for nested bodies, to match flat calls, or should the routed-wrapper check consider whether the temporary function would actually own the call under the session's resolution order?

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"5a714d4f0c89025f9420","id":"pass-a:pass-a:user-cast-tag-lost-deferred-splice"},{"delivery":"inline","fingerprint":"9d363713bb7d7fe04f69","id":"pass-b:pass-b:routed-owner-probe-repeats"},{"delivery":"inline","fingerprint":"35af054e40ca9797db7c","id":"pass-b:pass-b:astbuilder-flags-frozen-comment"},{"delivery":"inline","fingerprint":"4b44e847fea57191b3ce","id":"pass-b:pass-b:json-object-doc-wrong-wrapper"},{"delivery":"inline","fingerprint":"48c6db9306ed28e34be5","id":"pass-b:pass-b:stock-owned-doc-omits-direct-arguments"},{"delivery":"inline","fingerprint":"9d6aed3152e81b4930d7","id":"pass-b:pass-b:routed-null-default-untested"},{"delivery":"inline","fingerprint":"53d38572cd5a24ff9642","id":"pass-b:pass-b:test-comment-both-columns"},{"delivery":"inline","fingerprint":"41ffe46e91eda6473606","id":"pass-b:pass-b:test-comment-finalization-rule"},{"delivery":"inline","fingerprint":"e9f788b43aa28776d966","id":"pass-b:pass-b:test-comment-nested-star"}],"head_sha":"d72f76007d671cbd267d2d2f757b420b92075fa7","verdict_sha256":"f499a188170122e0091c4031e7a113fbbc670624b9f8933bbcb0a60d23dde7e4"} -->

    ganeshashree ganeshashree commented on code on Oct 30, 2026 09:04 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1
    @@ -1314,6 +1315,60 @@ trait ImplicitlyFormattedAsJson extends Expression {
       def emitsImplicitJsonText: Boolean = true
     }
     
    +object ImplicitlyFormattedAsJson {
    +  /**
    +   * Whether `e` lexically emits JSON text -- i.e. carries an implicit SQL/JSON `FORMAT JSON` and
    +   * should be spliced raw rather than quoted (a nested JSON constructor, or `JSON_QUERY` under
    +   * `KEEP QUOTES`; see [[ImplicitlyFormattedAsJson]]). Sees through a value-preserving `Collate`
    +   * (a postfix `... COLLATE c` only annotates the collation of the JSON text, e.g.
    +   * `JSON_ARRAY(JSON_ARRAY(1) COLLATE UTF8_LCASE)`), but deliberately NOT through a `Cast`:
    +   * `AstBuilder`/`JsonArray.sql` use a `CAST(... AS STRING)` wrapper specifically to detach a value
    +   * from implicit `FORMAT JSON`, so unwrapping it would defeat that neutralization. The routed/
    +   * qualified builders use [[splicesThroughCollationCast]], which additionally sees through an
    +   * analyzer collation `Cast`.
    +   */
    +  @scala.annotation.tailrec
    +  def isImplicitlyJson(e: Expression): Boolean = e match {
    +    case c: Collate => isImplicitlyJson(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  /**
    +   * The routed/qualified splice decision made by `JsonArrayExpressionBuilder` /
    +   * `JsonObjectExpressionBuilder` on a resolved argument. Like [[isImplicitlyJson]], but also sees
    +   * through an analyzer-inserted collation `Cast`, in any interleaving with `Collate`: under an
    +   * object/view default collation, `ApplyDefaultCollation` wraps a nested producer (also one under
    +   * a user `COLLATE`) in a `Cast` to the default `StringType` before the builder runs, which would
    +   * otherwise hide the producer and quote it. The stock-owned grammar wrappers apply the same
    +   * predicate when they finalize their flags. Only a genuine collation change is unwrapped (the
    +   * cast recolors existing JSON text); a user `CAST(... AS STRING)` or the `string(...)` alias
    +   * still detaches, so the explicit-cast quoting is preserved.
    +   */
    +  @scala.annotation.tailrec
    +  def splicesThroughCollationCast(e: Expression): Boolean = e match {
    +    case c: Collate => splicesThroughCollationCast(c.child)
    +    case c: Cast if isAnalyzerCollationCast(c) => splicesThroughCollationCast(c.child)
    +    case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
    +    case _ => false
    +  }
    +
    +  private def isAnalyzerCollationCast(c: Cast): Boolean = {
    +    // `ApplyDefaultCollation` / `DefaultCollationTypeCoercion` wrap only a companion-`StringType`
    +    // `DefaultStringProducingExpression` (they skip explicitly collated ones), so only that shape
    +    // is an analyzer recoloring. User detachments stay quoted: `string(json_array(1) COLLATE c)`
    +    // (child is a `Collate`), `string(json_array(1 RETURNING STRING COLLATE c))` (explicitly
    +    // collated child), and `CAST(... AS STRING)` (`USER_SPECIFIED_CAST`). Requiring a real
    +    // collation change leaves the no-op `string(...)` cast alone.
    +    if (!c.child.isInstanceOf[DefaultStringProducingExpression]) return false
    +    (c.dataType, c.child.dataType) match {
    +      case (to: StringType, from: StringType) =>
    +        from.eq(StringType) && to != from && !c.containsTag(Cast.USER_SPECIFIED_CAST)

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 09:04 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:1
    @@ -2594,18 +2621,39 @@ class Analyzer(
     
           case q: LogicalPlan =>
             q.transformExpressionsUpWithPruning(
    -          _.containsAnyPattern(UNRESOLVED_FUNCTION, GENERATOR),
    +          _.containsAnyPattern(UNRESOLVED_FUNCTION, GENERATOR, UNRESOLVED_JSON_CONSTRUCTOR),
               ruleId) {
    -          case u @ UnresolvedFunction(nameParts, arguments, _, _, _, _, _, _)
    -              if functionResolution.hasLambdaAndResolvedArguments(arguments) => withPosition(u) {
    -            functionResolution.resolveFunction(u) match {
    -              case func: HigherOrderFunction => func
    -              case other => other.failAnalysis(
    -                errorClass = "INVALID_LAMBDA_FUNCTION_CALL.NON_HIGHER_ORDER_FUNCTION",
    -                messageParameters = Map(
    -                  "class" -> other.getClass.getCanonicalName))
    +          case u @ UnresolvedFunction(_, arguments, _, _, _, _, _, _)
    +              if functionResolution.hasLambdaAndResolvedArguments(arguments) =>
    +            resolveHigherOrderFunction(u)
    +
    +          // Decide a SQL/JSON constructor's owner in this same bottom-up pass, so an enclosing call
    +          // and its alias see the result without an extra iteration per nesting level.
    +          case j: UnresolvedJsonConstructor
    +              if functionResolution.routesJsonConstructorToFunction(j) =>

    Done

    ganeshashree ganeshashree commented on code on Oct 30, 2026 09:04 UTC
    Code Review
    sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:1
    @@ -4391,25 +4391,32 @@ class AstBuilder extends DataTypeAstBuilder
        */
       override def visitJsonArray(ctx: JsonArrayContext): Expression = withOrigin(ctx) {
         val arrayValues = ctx.values.asScala.map(v => expression(v.value)).toSeq
    -    // Route a flat, clause-free call through routine resolution so it can be shadowed. Cheap
    -    // clause/nesting checks come first to skip the recursive per-value FORMAT scans when a clause
    -    // already forces direct construction.
    -    val routeThroughResolution =
    +    // A clause-free call (no RETURNING, no ON NULL, not a direct JSON constructor argument, and no
    +    // explicit FORMAT JSON on any value) routes through routine resolution so a routine can shadow
    +    // it. The cheap clause/nesting checks come first so the recursive per-value implicit-JSON scan
    +    // runs only when routing is still possible.
    +    val clauseFree =
           ctx.returning == null && ctx.nullBehavior == null && !isDirectJsonConstructorArgument(ctx) &&
    -        !ctx.values.asScala.exists(_.FORMAT() != null) &&
    -        !arrayValues.exists(JsonArray.isImplicitlyJson)
    -    if (routeThroughResolution) {
    +        !ctx.values.asScala.exists(_.FORMAT() != null)
    +    if (clauseFree && !arrayValues.exists(ImplicitlyFormattedAsJson.isImplicitlyJson)) {
           UnresolvedFunction("json_array", arrayValues, isDistinct = false)
    +    } else if (clauseFree) {
    +      // Nested clause-free call: route so a routine can shadow it, but carry the per-value splice
    +      // decision, frozen now from the lexical argument, through resolution (see

    Done

    cloud-fan cloud-fan commented on Nov 01, 2026 05:46 UTC
    Reviewer

    Review summary

    All nine findings from the previous review have been addressed. ApplyDefaultCollation now restores the user-cast mark, so a user CAST around a nested constructor stays quoted when a sibling defers the splice decision; a routed nested call that the built-in owns checks the SQL PATH only once; the JSON_ARRAY, JsonObjectExpr and stock-wrapper comments were corrected; and the routed null defaults and the three test comments are now covered or fixed.

    One blocking issue remains in the fixed-point analyzer. A JSON_ARRAY or JSON_OBJECT call with a clause or explicit FORMAT JSON, or one written directly as another constructor's value, is now materialized only inside ResolveFunctions. When one of its children is completed later in the same iteration (a time-zone-aware function or cast, a scalar subquery, a lambda variable, or a child fixed by type coercion) and the call is explicitly aliased or outside the select list, analysis takes one more Resolution iteration than on the base branch. This affects ordinary constructor queries with no qualified or routed producer, and every read of a view with such a body; the single-pass resolver and the executed plan are unaffected. The earlier move into ResolveFunctions removed the depth scaling and fixed the un-aliased case, but not this position.

    The remaining findings are smaller. A GROUP BY alias of a JSON producer used as a constructor argument is quoted by the fixed-point analyzer and spliced by the single-pass resolver, so the two build different plans for the same query. ResolverGuardSuite no longer reaches the resolved JsonArray and JsonObjectExpr allowlist arms. Four comments are inaccurate: the function registry note says direct JSON_VALUE and JSON_EXISTS values always mean the built-in, the routed JSON_ARRAY docs name only a nested constructor as the trigger, the splice predicate's scaladoc claims it accepts Collate and casts in any order, and the visitJsonObject comment still says the splice flags are frozen at parse time.

    The two questions for the author raised in the previous review are still unanswered and follow below.

    Cross-cutting observations

  • Both decision challenges come from one choice in this PR: nested clause-free JSON_ARRAY and JSON_OBJECT calls now follow every flat-call rule about same-named routines, so SQL that always meant the built-in constructor can now bind to a routine or be rejected as a temporary-function reference.
  • Each can be settled on its own, because accepting routine ownership of nested calls at query time does not decide whether the CREATE FUNCTION check should follow resolution order.

  • Four comment findings share one pattern: text written while the routing design changed across revisions still describes an earlier or broader rule than the final code.
  • Each is a small, separate comment fix, so they can be done together in one pass and in any order.

    Findings

    7 total: 0 P0, 1 P1, 0 P2, 6 P3.

    Blocking (P1)

  • Clause-bearing JSON constructors with a late-resolving child need an extra Resolution iteration — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:2654 — see inline.
  • Nit (P3)

  • A GROUP BY alias of a JSON producer is spliced by single-pass but quoted by fixed-point — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1334 — see inline.

  • Registry comment says direct JSON_VALUE and JSON_EXISTS values always mean the built-in — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala:947 — see inline.

  • ResolverGuardSuite no longer exercises the resolved JsonArray and JsonObjectExpr arms — sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/ResolverGuardSuite.scala:155 — see inline.

  • Routed JSON_ARRAY comments describe the trigger as a nested constructor — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1827 — see inline.

  • splicesThroughCollationCast scaladoc says it accepts Collate and casts in any order — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:1331 — see inline.

  • visitJsonObject comment still says splice flags are frozen from the lexical argument — sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:4500 — see inline.
  • Re-review status

    Prior AI findings: 9 no longer raised, 0 still raised; additional unresolved findings in this review: 7.

    New attribution: 1 newly introduced, 6 late catch, 0 previously raised, 0 unattributed.

    PR description suggestions

  • The Analyzer bullet still describes a new ResolveJsonConstructors rule placed just before ApplyDefaultCollation. That rule no longer exists: ResolveFunctions routes or materializes the wrappers in its bottom-up pass, and ExpressionResolver does the same in the single-pass analyzer. The Parser bullet still describes a single UnresolvedJsonArray / UnresolvedJsonObject that sets routeThroughResolution, while the code builds UnresolvedRoutedJsonArray / UnresolvedRoutedJsonObject for clause-free calls with a nested JSON producer and keeps UnresolvedJsonArray / UnresolvedJsonObject for the forms the built-in always owns. Update both bullets to match the code.

  • Consider mentioning that ApplyDefaultCollation now restores the user-cast mark when it rebuilds an already-retargeted cast. Besides keeping a user CAST around a nested constructor quoted, this changes the auto-generated name of a deferred, un-aliased column whose user cast it rebuilds under an object or view default collation, for any expression and not only the JSON constructors, so the user-facing section's statement that the changes concern only the unreleased constructors does not cover it.
  • Decision challenges

    CREATE FUNCTION rejects nested JSON constructor bodies whenever a same-named temporary function exists

    CreateSQLFunctionCommand now counts a routed nested constructor as a temporary-function reference whenever a temporary function with the same name exists, using the same name-based check as the flat call, without asking whether that temporary function would own the call. Under the default session order (second: built-in functions before session functions), a temporary json_array never owns json_array(json_array(1)), so creation-time analysis and invocation both use the built-in. Yet CREATE FUNCTION perm() RETURNS STRING RETURN json_array(json_array(1)) now fails with INVALID_TEMP_OBJ_REFERENCE, naming a temporary function the body never calls; the base branch accepted it. The VALUE and colon json_object spellings behave the same way, and qualifying only the outer call does not help, because the inner json_array(1) then becomes a flat routed call.

    A flat json_array(1) body and the comma-form nested json_object body are already rejected this way on the base branch, so the change keeps nested and flat calls consistent. Under SET PATH = system.session, system.builtin, which every new test uses, the temporary function does own the call and the rejection is correct, while the new cyclic-reference check already resolves the name in session order through lookupFunctionInfo. Should the routed-wrapper arm keep the name-based check for nested bodies, or count a routed call only when the temporary function would actually own it under the session's resolution order, which would make nested bodies more permissive than flat ones?

    Nested clause-free JSON_ARRAY and JSON_OBJECT calls now bind to a same-named routine

    On the base branch, a clause-free call that nests a constructor, such as json_array(json_array(1)) or json_object('a' VALUE json_object('b' VALUE 1)), always meant the built-in constructor; only the comma-form json_object already routed. With this change such a call resolves like a flat call, so any same-named temporary, PATH, persistent, V2-catalog or injected routine ahead of system.builtin owns it, including one written for a different signature. With the existing shadow test's json_array(a INT, b STRING) ahead of system.builtin, SELECT json_array(json_array(1)) returned [[1]] before and now fails argument binding; the test now asserts only the fully qualified form. With a json_object(a STRING, b INT) shadow, the VALUE form now casts the nested JSON text to INT. The inner call stays the built-in because it is a direct constructor argument, so even a matching shadow receives the built-in's JSON text and the call means shadow(builtin(1)), not the shadow(shadow(1)) of a flat f(f(1)).

    Only sessions whose PATH, persistent schemas or extensions put such a routine first are affected, clause-bearing and explicit FORMAT JSON forms stay with the built-in, and the constructors are unreleased. Is this consistency with flat calls intended? If so, consider documenting on the JSON_ARRAY and JSON_OBJECT reference pages that a clause-free call, nested or not, can be shadowed, and that qualifying every level (builtin.json_array) or adding a clause keeps the built-in. If not, nested clause-free calls could keep binding to the built-in.

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"dd4455f7f629639c1323","id":"pass-b:pass-b:stock-wrapper-late-child-extra-iteration"},{"delivery":"inline","fingerprint":"cbb18d08186d5b0ca8e6","id":"pass-a:pass-a:groupby-alias-splice-diverges-across-analyzers"},{"delivery":"inline","fingerprint":"c7abab09b102fb738cef","id":"pass-b:pass-b:function-registry-direct-value-overstated"},{"delivery":"inline","fingerprint":"511bbbaf9a9470d43ff7","id":"pass-b:pass-b:resolver-guard-resolved-json-arms-untested"},{"delivery":"inline","fingerprint":"d53ecdfff44b78a028c3","id":"pass-b:pass-b:routed-array-trigger-described-as-constructor"},{"delivery":"inline","fingerprint":"a5a032c05fce370a64b4","id":"pass-b:pass-b:splice-predicate-any-order-overstated"},{"delivery":"inline","fingerprint":"22b43050d9469ee1af2f","id":"pass-b:pass-b:visit-json-object-lexical-freeze-comment-stale"}],"head_sha":"1e13591f1940da8b1a54f59202a9ae85235e7340","verdict_sha256":"45cc9ffd5b74fb8a2016514ecfb13ff624805cb3c0e41ac0bd1b802d5e7d806d"} -->

    ganeshashree ganeshashree commented on Nov 02, 2026 07:02 UTC
    Author

    Thanks for the review. On the two decision challenges:

  • CREATE FUNCTION and a same-named temporary function: kept the name-based check, so nested bodies follow the same rule as flat calls. That check is too strict for every function (on master, a temporary abs already blocks RETURN abs(-1)), so it is tracked in SPARK-60806. SPARK-60805 covers bodies that call qualified functions.

  • Shadowing nested clause-free calls: intended, for consistency with flat calls. The JSON_ARRAY and JSON_OBJECT pages now document it and how to keep the built-in.
  • PR description updated.

    Reviewers
    Assignees
    ganeshashree ganeshashree
    Labels
    risk: low confidence: 91.4% 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: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    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: 91.4% · Lower = rushed or shallow review
    91.4%
    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: 6.2% · Safe to merge
    6.2%
    Repository