spark-test commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4580318547


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions.Expression
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Rejects optional references in the expressions of a statement that modifies 
table data and
+ * that was built without the SQL parser, which rejects them in SQL text (see
+ * `OptionalReferenceValidation`). A missing column must not silently change 
which rows a
+ * statement deletes or updates. The source of a MERGE is checked too, like 
the source query of
+ * the SQL statement: `Dataset.mergeInto` and the Spark Connect MERGE command 
put the unanalyzed
+ * plan of the source DataFrame there, so its references are resolved as part 
of the MERGE.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.sql("SELECT pk, is_deleted? FROM s").mergeInto("t", $"s.pk" === 
$"t.pk")...
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))
+        }
+        operator match {
+          case merge: MergeIntoTable =>
+            merge.sourceTable.foreach(_.expressions.foreach(checkExpression(_, 
"MERGE")))

Review Comment:
   **Blocking (P1):** This walk only finds expressions that are still 
unresolved and carry an optional marker 
(`OptionalReferences.unresolvedOptionalReference`), but a DataFrame-built 
source is unanalyzed only in some of its operations. On Spark Classic, 
`MergeIntoWriter` takes `df.queryExecution.logical`, and every earlier Dataset 
operation is the eagerly analyzed `logicalPlan` that the next one wraps, as 
`Dataset.as` does with `SubqueryAlias(alias, logicalPlan)`. On Spark Connect, 
the planner builds Project, Filter, and SubqueryAlias relations unanalyzed, but 
returns the analyzed plan for a `withColumns` relation 
(SparkConnectPlanner.scala:1381-1395) and for SQL that references DataFrames. 
In those analyzed subtrees an optional reference that matched nothing is 
already a resolved NULL, so nothing is raised.
   
   By the review's reading of the code, with optional references on and a 
source view without `archived`, `spark.table("source").selectExpr("pk", 
"archived? AS archived").as("s").mergeInto("t", $"s.pk" === 
col("t.pk")).whenMatched(expr("s.archived IS NULL")).delete().merge()` deletes 
every matched target row, and so does a Spark Connect source built with 
`withColumn("archived", expr("archived?"))`. Without `.as("s")`, in SQL, and 
with the same `selectExpr` program on Spark Connect, the source fails with 
IN_DML. The class doc above and the conf doc both say that MERGE rejects 
optional references. The second-round review called a classic step analyzed 
before the merge a case that keeps working and said that every `?` of a Connect 
source is checked; both statements were wrong. Any session can set the internal 
conf, and in those sessions a destructive write that the documented rule says 
must fail runs silently.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4570588628).
   
   **Recommended change:** Make CheckOptionalReferencesInDml also reject, in 
the source plan of a MergeIntoTable, a resolved NULL that an optional reference 
resolved to, recognized by OptionalReferences.isNullReference (the 
NULL_REFERENCE tag on the NULL and on the implicit alias that names it), except 
inside the subtrees of views and SQL functions, which resolve their own 
references as the PR intends, and raise the same IN_DML error with the MERGE 
context. Correct the class doc, which the second-review commit 1a9c3aff295 
wrote on the premise that the whole source DataFrame reaches the check 
unanalyzed, to describe how a source operation that was analyzed before the 
MERGE is covered. Add DataFrame MERGE tests for a source whose `?` is followed 
by another Dataset operation and for an aliased source that reads a view 
created with `?`, and a Spark Connect MERGE test for a source whose `?` is in a 
withColumn step.
   
   **Why this works:** An analyzed operation keeps a trace of every optional 
reference that matched nothing: the NULL, and the implicit alias of a top-level 
one, carry the NULL_REFERENCE tag that only the analyzer sets. Searching the 
MERGE source for that tag, outside the subtrees that views and SQL functions 
resolve on their own, rejects the source for every operation that was analyzed 
before the MERGE was built, a classic Dataset operation that another one 
follows or a Spark Connect relation that the planner analyzes eagerly, while 
the existing unresolved-reference search keeps covering the operations that are 
still unanalyzed.
   
   **Scope:** Extend the MERGE source check to recognize the NULL that a source 
operation analyzed before the MERGE resolved, correct its doc, and add 
DataFrame and Spark Connect MERGE tests.
   
   **Compatibility:** MERGE sources that read views or SQL functions using `?` 
keep running, and SQL MERGE, and DataFrame and Spark Connect sources whose `?` 
is still unanalyzed when the MERGE is built, keep failing with IN_DML.
   
   **Risks:** A MERGE source that ran with optional references on because its 
`?` sat in an operation analyzed before the MERGE, on Spark Classic or Spark 
Connect, now fails with IN_DML; the behavior is unreleased and behind an 
internal conf, and removing the new case rolls it back. The new case relies on 
the NULL_REFERENCE tag surviving the source's analysis; if a rule rebuilt the 
NULL or its alias without the tag, such a source would pass as it does today.
   
   **Constraints:** Search each subquery plan of the source once, so the added 
search does not repeat the duplicated traversal that the separate finding on 
the cost of the DML search describes. Do not reject the NULLs inside the 
subtrees of views and SQL functions, which resolve their own references.
   
   **Exclusions:**
   - An optional reference that matched an existing column in an earlier, 
already analyzed operation leaves no trace and behaves as without `?`; 
detecting it would need state the analyzer does not keep, so it is left out.
   - A `?` inside a DataFrame that Spark Connect SQL references by name stays 
under the temporary view that the planner registers for that DataFrame, and so 
outside this repair, like any view the source reads.
   
   **Success:** With optional references on, a classic DataFrame MERGE whose 
source has `?` in an operation before its last one, for example before 
`.as("s")`, fails with OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DML and the MERGE 
context. With optional references on, a Spark Connect MERGE whose source has 
`?` in a withColumn step fails with OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DML and 
the MERGE context. A classic MERGE source that reads a view or SQL function 
whose body uses `?` still runs, also when the source is aliased. The 
CheckOptionalReferencesInDml doc no longer says that every operation of a 
source DataFrame reaches the check unanalyzed.
   
   **Verification:**
   - **Regression:** With optional references on and a source without the 
column, a DataFrame MERGE whose source applies `.as("s")` or `filter` after a 
`selectExpr` with `archived? AS archived` fails with IN_DML and the MERGE 
context instead of deleting the matched rows.
   - **Regression:** With optional references on in a Spark Connect session and 
a source without the column, a MERGE whose source is built with 
`withColumn("archived", expr("archived?"))` fails with IN_DML and the MERGE 
context instead of deleting the matched rows.
   - **Compatibility:** With optional references on, a DataFrame MERGE whose 
aliased source reads a view created from a query with `?` still runs and uses 
the view's NULL, and a source without optional references merges as before.
   - **Behavior:** With optional references on, a DataFrame MERGE whose source 
has `?` in its last operation still fails with IN_DML and the fragment of the 
reference.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,360 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions.{
+  Attribute,
+  Expression,
+  LambdaFunction,
+  LateralColumnAliasReference,
+  NamedExpression,
+  PipeOperator,
+  SubqueryExpression,
+  UnaryExpression,
+  Unevaluable
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  Distinct,
+  Filter,
+  LateralJoin,
+  LogicalPlan,
+  RepartitionByExpression,
+  Sort,
+  SubqueryAlias,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Replaces the optional references that the fixed-point "Resolution" batch 
could not resolve
+ * with a static NULL, and then resolves the plan again with `resolveAgain`.
+ *
+ * {{{
+ *   -- `t` has no column `name`:
+ *   SELECT id, name? FROM t;
+ *   -- Project [id#1, 'name] becomes Project [id#1, null AS name#2]
+ * }}}
+ *
+ * Only the expressions of operators with resolved children are replaced, 
because a reference in
+ * an operator with unresolved children can still resolve once the children 
are resolved. The
+ * rule is meant to run in a fixed-point batch: every application replaces the 
references of the
+ * lowest operators that cannot be resolved, which can make the operators 
above them resolvable.
+ * References that a later resolution step is still waiting for, such as the 
body of an unbound
+ * lambda function or a lateral column alias reference, are left in place.
+ *
+ * The analyzer resolves the plan of a subquery expression on its own, while 
the operator of the
+ * subquery expression is still being resolved. A reference of the subquery 
that is unresolved at
+ * the end of that can still resolve later, e.g. once the outer query binds 
its parameter markers
+ * or resolves the alias of a generator. The rule therefore only replaces the 
references of a
+ * subquery plan after it could not resolve the operator of the subquery 
expression, which it
+ * signals by wrapping the subquery plan in 
[[ResolveOptionalReferencesInSubquery]].
+ *
+ * The rule never changes the plan that it is given, which can be analyzed 
again later, e.g. from a
+ * plan cache: its decisions are nodes of the plan that it returns.
+ */
+class ResolveOptionalReferences(resolveAgain: LogicalPlan => LogicalPlan)
+    extends Rule[LogicalPlan] {
+  import ResolveOptionalReferences._
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan match {
+    case subquery: ResolveOptionalReferencesInSubquery =>
+      val resolvedPlan = replaceAndResolveAgain(subquery.child)
+      if (resolvedPlan.fastEquals(subquery.child)) subquery.child else 
subquery.copy(resolvedPlan)
+    case _ if plan.resolved || isPlanOfSubquery || 
plan.containsPattern(PARAMETERIZED_QUERY) =>
+      plan
+    case _ if hasUnresolvedOptionalReferences(plan) =>
+      replaceAndResolveAgain(plan)
+    case _ =>
+      plan
+  }
+
+  private def replaceAndResolveAgain(plan: LogicalPlan): LogicalPlan = {
+    val replacedPlan = replaceUnresolvableOptionalReferences(plan)
+    val resolvedPlan = if (replacedPlan.fastEquals(plan)) {
+      plan
+    } else {
+      unwrapSubqueryPlans(resolveAgain(replacedPlan))
+    }
+    if (!resolvedPlan.fastEquals(plan)) {
+      resolvedPlan
+    } else {
+      val wrappedPlan = wrapOptionalFieldsAsLastResort(plan)
+      if (wrappedPlan.fastEquals(plan)) {
+        plan
+      } else {
+        unwrapLastResortExtractValues(resolveAgain(wrappedPlan))
+      }
+    }
+  }
+
+  /**
+   * Replaces the optional references of the lowest operators of `plan` that 
are not resolved, and
+   * wraps the unresolved plans of their subquery expressions for the analysis 
of these plans.
+   *
+   * The traversal is top-down so that an operator is only considered while 
its children are the
+   * ones that the "Resolution" batch resolved its references against. An 
operator above a
+   * replaced one waits for `resolveAgain`, which can still resolve its 
references in other ways,
+   * for example as lateral column aliases or as variables.
+   */
+  private def replaceUnresolvableOptionalReferences(plan: LogicalPlan): 
LogicalPlan = {
+    plan.resolveOperatorsDown {
+      case aggregate: Aggregate
+          if aggregate.childrenResolved && 
!aggregate.aggregateExpressions.forall(_.resolved) =>
+        replaceInAggregateExpressions(aggregate)
+      case lateralJoin: LateralJoin
+          if lateralJoin.left.resolved && !lateralJoin.right.plan.resolved =>
+        // The join condition can reference the output of the subquery, which 
is not known yet.
+        if (hasUnresolvedOptionalReferences(lateralJoin.right.plan)) {
+          lateralJoin.copy(right = wrapSubqueryPlan(lateralJoin.right))
+        } else {
+          lateralJoin
+        }
+      case operator if operator.childrenResolved && !operator.resolved =>
+        lazy val attributes = visibleAttributes(operator)
+        operator.mapExpressions(replace(_, attributes, isTopLevel = true))
+    }
+  }
+
+  /**
+   * Replaces the optional references in the aggregate expressions of 
`aggregate` only, because
+   * its grouping expressions can reference aliases of the aggregate 
expressions, which can only
+   * be resolved once all the aggregate expressions are resolved.
+   *
+   * {{{
+   *   -- `archived` in GROUP BY resolves to the alias `archived` of the 
SELECT list.
+   *   SELECT coalesce(archived?, false) AS archived FROM t GROUP BY archived?;
+   * }}}
+   */
+  private def replaceInAggregateExpressions(aggregate: Aggregate): Aggregate = 
{
+    lazy val attributes = visibleAttributes(aggregate)
+    aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { 
expression =>
+      replace(expression, attributes, isTopLevel = 
true).asInstanceOf[NamedExpression]
+    })
+  }
+
+  /**
+   * Replaces the optional references of `expression` that resolve to NULL 
against `attributes`.
+   * A top-level reference keeps its name through an [[Alias]] of its last 
name part.
+   */
+  private def replace(
+      expression: Expression,
+      attributes: => Seq[Attribute],
+      isTopLevel: Boolean): Expression = expression match {
+    case unresolvedAttribute: UnresolvedAttribute
+        if 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty &&
+        OptionalReferences.resolvesToNull(
+          nameParts = unresolvedAttribute.nameParts,
+          optionalNamePartIndices = 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute),
+          attributes = attributes,
+          resolver = conf.resolver,
+          isViewQuery = AnalysisContext.get.catalogAndNamespace.nonEmpty ||
+            AnalysisContext.get.isViewDefinition
+        ) =>
+      val nullReference = OptionalReferences.nullReference()
+      if (isTopLevel) {
+        OptionalReferences.implicitAlias(nullReference, 
unresolvedAttribute.nameParts.last)
+      } else {
+        nullReference
+      }
+    case namedParameter: NamedParameter if 
OptionalReferences.isOptional(namedParameter) =>
+      OptionalReferences.nullReference()
+    case lambdaFunction: LambdaFunction if !lambdaFunction.bound =>
+      lambdaFunction
+    case lateralColumnAliasReference: LateralColumnAliasReference =>
+      lateralColumnAliasReference
+    case subquery: SubqueryExpression if 
hasUnresolvedOptionalReferences(subquery.plan) =>
+      wrapSubqueryPlan(subquery)
+    case other if !other.resolved =>
+      other.mapChildren(replace(_, attributes, isTopLevel = false))
+    case other =>
+      other
+  }
+
+  private def wrapSubqueryPlan[T <: SubqueryExpression](subquery: T): T = 
subquery.plan match {
+    case _: ResolveOptionalReferencesInSubquery => subquery
+    case plan => 
subquery.withNewPlan(ResolveOptionalReferencesInSubquery(plan)).asInstanceOf[T]
+  }
+
+  /**
+   * Unwraps the subquery plans of `plan` that are still wrapped because the 
analyzer did not
+   * resolve them again.
+   */
+  private def unwrapSubqueryPlans(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
+      case subquery: SubqueryExpression =>
+        subquery.plan match {
+          case wrapped: ResolveOptionalReferencesInSubquery => 
subquery.withNewPlan(wrapped.child)
+          case _ => subquery
+        }
+    }
+  }
+
+  /**
+   * Wraps the optional field extractions of the lowest operators of `plan` 
that are not resolved
+   * in [[LastResortExtractValue]].
+   */
+  private def wrapOptionalFieldsAsLastResort(plan: LogicalPlan): LogicalPlan = 
{
+    plan.resolveOperatorsDown {
+      case operator if operator.childrenResolved && !operator.resolved =>
+        operator.mapExpressions(wrapOptionalFields)
+    }
+  }
+
+  private def wrapOptionalFields(expression: Expression): Expression = 
expression match {
+    case lastResort: LastResortExtractValue =>
+      lastResort
+    case extractValue: UnresolvedExtractValue if 
OptionalReferences.isOptional(extractValue) =>
+      // The children are wrapped first, so the wrapped extraction is still an 
extraction.
+      LastResortExtractValue(
+        
extractValue.mapChildren(wrapOptionalFields).asInstanceOf[UnresolvedExtractValue])
+    case other if !other.resolved =>
+      other.mapChildren(wrapOptionalFields)
+    case other =>
+      other
+  }
+
+  /** Unwraps the extractions of `plan` that the analyzer did not resolve. */
+  private def unwrapLastResortExtractValues(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressions {
+      case LastResortExtractValue(extractValue) => extractValue
+    }
+  }
+
+  /**
+   * Returns the attributes that the name resolution of `operator` can match a 
multipart name
+   * against: the output of its children, the attributes that `Sort`, 
`Filter`, HAVING, and
+   * QUALIFY can reference from below their child, the output of the subquery 
of a lateral join,
+   * and the attributes of the outer query of a subquery.
+   */
+  private def visibleAttributes(operator: LogicalPlan): Seq[Attribute] = {
+    val localAttributes = operator.children.flatMap(namedAttributes)
+    val attributesFromBelow = operator match {
+      case sort: Sort => attributesForMissingReferences(sort.child)
+      case filter: Filter => attributesForMissingReferences(filter.child)
+      case repartition: RepartitionByExpression =>
+        attributesForMissingReferences(repartition.child)
+      case qualify: UnresolvedQualify => 
attributesForMissingReferences(qualify.child)
+      case UnresolvedHaving(_, aggregate: Aggregate) => 
namedAttributes(aggregate.child)
+      case lateralJoin: LateralJoin => namedAttributes(lateralJoin.right.plan)
+      case _ => Seq.empty
+    }
+    val outerAttributes = AnalysisContext.get.outerPlan.toSeq.flatMap {
+      case having @ UnresolvedHaving(_, aggregate: Aggregate) =>
+        having.children.flatMap(namedAttributes) ++ 
namedAttributes(aggregate.child)
+      case outerPlan =>
+        outerPlan.children.flatMap(namedAttributes)
+    }
+    localAttributes ++ attributesFromBelow ++ outerAttributes
+  }
+
+  private def namedAttributes(plan: LogicalPlan): Seq[Attribute] =
+    plan.output ++ plan.metadataOutput
+
+  /**
+   * Returns the attributes below `plan` that a `Sort` or a `Filter` on top of 
`plan` can reference
+   * as missing attributes, mirroring 
`ColumnResolutionHelper.resolveExprsAndAddMissingAttrs`.
+   */
+  private def attributesForMissingReferences(plan: LogicalPlan): 
Seq[Attribute] = plan match {
+    case unary: UnaryNode
+        if !unary.isInstanceOf[Distinct] && !unary.isInstanceOf[SubqueryAlias] 
&&
+        !unary.isInstanceOf[PipeOperator] =>
+      namedAttributes(unary.child) ++ 
attributesForMissingReferences(unary.child)
+    case _ =>
+      Seq.empty
+  }
+}
+
+object ResolveOptionalReferences {
+
+  /**
+   * Returns true if `plan` or the plan of one of its subquery expressions has 
an optional
+   * reference that is not resolved and that the rule can still replace or 
wrap: an attribute, a
+   * named parameter marker, or a field extraction. Other unresolved nodes 
with an optional marker,
+   * such as a [[TempResolvedColumn]] that HAVING or ORDER BY tried, hold a 
reference that was
+   * found, and the rule leaves them to the rules that report their errors.
+   */
+  private def hasUnresolvedOptionalReferences(plan: LogicalPlan): Boolean = 
plan.exists {

Review Comment:
   **Nit (P3):** This `plan.exists` visits every operator and expression and 
recurses into every subquery plan without stopping at resolved subtrees, and 
`apply` runs it for every plan that is still unresolved after Resolution, also 
with `spark.sql.optionalReferences.enabled` off. `InsertIntoStatement` and the 
V1 `CreateTable` stay unresolved by construction until Post-Hoc Resolution, 
which runs after this batch, so a V1 `INSERT INTO ... SELECT`, `insertInto`, 
CTAS, or `saveAsTable` walks its whole written query, including an already 
analyzed DataFrame lineage, on every analysis. It is one linear pass, small 
next to optimizing the same plan, but it can be avoided without changing any 
answer, because a resolved operator or subquery plan cannot contain an 
unresolved optional reference.
   
   Suggested fix: return early from this walk for a resolved operator or a 
resolved subquery plan, and descend only into unresolved ones.
   
   **Verification:**
   - **Inspection:** The walk returns for a resolved operator or resolved 
subquery plan without visiting its expressions or children.
   - **Compatibility:** With optional references on, a missing optional 
reference in the query of an INSERT into a V1 table, and in a subquery of that 
query, is still replaced with NULL.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node; a rule that rebuilds a reference in another way 
forwards them with
+   * [[withOptionalNamePartsOf]]. This tag records a decision of one analysis, 
that a reference
+   * matched nothing, on the NULL and the alias that this analysis creates. 
Only the analyzer sets
+   * it, and only on these nodes: the plan that the analyzer receives can be 
analyzed again later,
+   * e.g. from a plan cache, against a relation that has the column by then. 
The other decision of
+   * an analysis, that no resolution step of an operator can resolve a field 
extraction, is a node
+   * of the plan that the analysis builds, see [[LastResortExtractValue]].
+   */
+  val NULL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceNull")
+
+  /** Qualifiers of session variables, which are valid prefixes of a variable 
reference. */
+  private val SESSION_VARIABLE_QUALIFIERS = Seq(
+    Seq(CatalogManager.SYSTEM_CATALOG_NAME, CatalogManager.SESSION_NAMESPACE),
+    Seq(CatalogManager.SESSION_NAMESPACE)
+  )
+
+  /** Returns the indices of the optional name parts of `expression`. */
+  def optionalNamePartIndices(expression: Expression): Set[Int] =
+    expression.getTagValue(OPTIONAL_NAME_PART_INDICES).getOrElse(Set.empty)
+
+  /** Marks the name parts at `indices` of the multipart name `expression` as 
optional. */
+  def markNamePartsOptional(expression: Expression, indices: Set[Int]): Unit = 
{
+    if (indices.nonEmpty) {
+      expression.setTagValue(
+        OPTIONAL_NAME_PART_INDICES,
+        optionalNamePartIndices(expression) ++ indices
+      )
+    }
+  }
+
+  /** Marks `expression` as a whole as optional. */
+  def markOptional(expression: Expression): Unit =
+    expression.setTagValue(OPTIONAL_REFERENCE, ())
+
+  /** Returns true if `expression` as a whole is marked optional. */
+  def isOptional(expression: Expression): Boolean =
+    expression.getTagValue(OPTIONAL_REFERENCE).isDefined
+
+  /** Returns true if `expression` or any of its name parts is marked 
optional. */
+  def hasOptionalMarker(expression: Expression): Boolean =
+    isOptional(expression) || optionalNamePartIndices(expression).nonEmpty
+
+  /**
+   * Gives `expression`, a multipart name that a rule rebuilt from `source`, 
the optional name
+   * parts of `source`, which a case class copy or a constructor does not keep.
+   */
+  def withOptionalNamePartsOf[T <: Expression](expression: T, source: 
Expression): T = {
+    markNamePartsOptional(expression, optionalNamePartIndices(source))
+    expression
+  }
+
+  /**
+   * Returns the first unresolved expression in `expression` that is an 
optional reference or has
+   * an optional name part, including in the plans of its subquery 
expressions, or None.
+   */
+  def unresolvedOptionalReference(expression: Expression): Option[Expression] 
= {
+    expression.find(e => !e.resolved && hasOptionalMarker(e)).orElse {
+      expression
+        .collect { case subquery: SubqueryExpression => subquery.plan }
+        .iterator
+        .flatMap(firstUnresolvedOptionalReference)
+        .nextOption()
+    }
+  }
+
+  /**
+   * Returns true if the parsed `plan` has an optional reference, including in 
the plans of its
+   * subquery expressions and in its common table expressions. Before the 
analysis, every optional
+   * reference of the statement is unresolved, so the answer does not depend 
on the data that the
+   * statement is analyzed against.
+   */
+  def hasOptionalReferences(plan: LogicalPlan): Boolean =
+    firstUnresolvedOptionalReference(plan).isDefined
+
+  /**
+   * Returns the first unresolved optional reference of the operators of 
`plan`, including in the
+   * plans of their subquery expressions and in the plans that an operator 
keeps outside of its
+   * children, such as the common table expressions of `UnresolvedWith`.
+   */
+  private def firstUnresolvedOptionalReference(plan: LogicalPlan): 
Option[Expression] = {
+    plan.expressions.iterator
+      .flatMap(unresolvedOptionalReference)
+      .nextOption()
+      .orElse {
+        plan.innerChildren.iterator
+          .collect { case innerPlan: LogicalPlan => innerPlan }
+          .flatMap(firstUnresolvedOptionalReference)
+          .nextOption()
+      }
+      
.orElse(plan.children.iterator.flatMap(firstUnresolvedOptionalReference).nextOption())
+  }
+
+  /** The static NULL of type VOID that an unresolvable optional reference 
resolves to. */
+  def nullReference(): Literal = {
+    val nullReference = Literal(null, NullType)
+    nullReference.setTagValue(NULL_REFERENCE, ())
+    nullReference
+  }
+
+  /**
+   * Returns true if `expression` is a [[nullReference]], i.e. the result of 
an optional reference

Review Comment:
   **Nit (P3):** `isNullReference` only reads the `NULL_REFERENCE` tag, and 
`markImplicitAlias` sets the same tag on the `Alias` that names a missing 
reference, so `isNullReference(implicitAlias(nullReference(), name))` is true 
as well; `isNullReferenceAlias` is the predicate that tells the alias apart. A 
caller that relies on this doc to mean only the literal, for example to decide 
that an expression is not a named output column, also matches that alias.
   
   Suggested fix: say that the implicit alias of such a NULL matches too, and 
point to `isNullReferenceAlias` for telling the two apart.
   
   **Verification:**
   - **Inspection:** The isNullReference doc describes both nodes that carry 
the tag and refers to isNullReferenceAlias for the alias.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node; a rule that rebuilds a reference in another way 
forwards them with

Review Comment:
   **Nit (P3):** `withOptionalNamePartsOf` only calls 
`markNamePartsOptional(expression, optionalNamePartIndices(source))`, so it 
forwards `OPTIONAL_NAME_PART_INDICES` and never `OPTIONAL_REFERENCE`, the 
marker of an optional field extraction, named parameter marker, or IDENTIFIER 
clause; the PR's own rebuild of an extraction keeps that marker with 
`copyTagsFrom` (`resolveExtractValue` in ColumnResolutionHelper). Because this 
paragraph is the tag contract that later rules follow, a rule that rebuilds 
`expr.f?` or `:p?` with a constructor and calls `withOptionalNamePartsOf` as 
told loses the marker, and the reference then raises FIELD_NOT_FOUND or 
UNBOUND_SQL_PARAMETER as if written without `?`.
   
   Suggested fix: say that `withOptionalNamePartsOf` forwards the optional name 
parts of a multipart name, and that `OPTIONAL_REFERENCE` is forwarded with 
`copyTagsFrom` or a generic tree transform.
   
   **Verification:**
   - **Inspection:** The tag-contract doc names withOptionalNamePartsOf only 
for the optional name parts and names copyTagsFrom or a generic tree transform 
for OPTIONAL_REFERENCE.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node; a rule that rebuilds a reference in another way 
forwards them with
+   * [[withOptionalNamePartsOf]]. This tag records a decision of one analysis, 
that a reference
+   * matched nothing, on the NULL and the alias that this analysis creates. 
Only the analyzer sets
+   * it, and only on these nodes: the plan that the analyzer receives can be 
analyzed again later,
+   * e.g. from a plan cache, against a relation that has the column by then. 
The other decision of
+   * an analysis, that no resolution step of an operator can resolve a field 
extraction, is a node
+   * of the plan that the analysis builds, see [[LastResortExtractValue]].
+   */
+  val NULL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceNull")
+
+  /** Qualifiers of session variables, which are valid prefixes of a variable 
reference. */
+  private val SESSION_VARIABLE_QUALIFIERS = Seq(
+    Seq(CatalogManager.SYSTEM_CATALOG_NAME, CatalogManager.SESSION_NAMESPACE),
+    Seq(CatalogManager.SESSION_NAMESPACE)
+  )
+
+  /** Returns the indices of the optional name parts of `expression`. */
+  def optionalNamePartIndices(expression: Expression): Set[Int] =
+    expression.getTagValue(OPTIONAL_NAME_PART_INDICES).getOrElse(Set.empty)
+
+  /** Marks the name parts at `indices` of the multipart name `expression` as 
optional. */
+  def markNamePartsOptional(expression: Expression, indices: Set[Int]): Unit = 
{
+    if (indices.nonEmpty) {
+      expression.setTagValue(
+        OPTIONAL_NAME_PART_INDICES,
+        optionalNamePartIndices(expression) ++ indices
+      )
+    }
+  }
+
+  /** Marks `expression` as a whole as optional. */
+  def markOptional(expression: Expression): Unit =
+    expression.setTagValue(OPTIONAL_REFERENCE, ())
+
+  /** Returns true if `expression` as a whole is marked optional. */
+  def isOptional(expression: Expression): Boolean =
+    expression.getTagValue(OPTIONAL_REFERENCE).isDefined
+
+  /** Returns true if `expression` or any of its name parts is marked 
optional. */
+  def hasOptionalMarker(expression: Expression): Boolean =
+    isOptional(expression) || optionalNamePartIndices(expression).nonEmpty
+
+  /**
+   * Gives `expression`, a multipart name that a rule rebuilt from `source`, 
the optional name
+   * parts of `source`, which a case class copy or a constructor does not keep.
+   */
+  def withOptionalNamePartsOf[T <: Expression](expression: T, source: 
Expression): T = {
+    markNamePartsOptional(expression, optionalNamePartIndices(source))
+    expression
+  }
+
+  /**
+   * Returns the first unresolved expression in `expression` that is an 
optional reference or has
+   * an optional name part, including in the plans of its subquery 
expressions, or None.
+   */
+  def unresolvedOptionalReference(expression: Expression): Option[Expression] 
= {
+    expression.find(e => !e.resolved && hasOptionalMarker(e)).orElse {
+      expression
+        .collect { case subquery: SubqueryExpression => subquery.plan }
+        .iterator
+        .flatMap(firstUnresolvedOptionalReference)
+        .nextOption()
+    }
+  }
+
+  /**
+   * Returns true if the parsed `plan` has an optional reference, including in 
the plans of its
+   * subquery expressions and in its common table expressions. Before the 
analysis, every optional
+   * reference of the statement is unresolved, so the answer does not depend 
on the data that the
+   * statement is analyzed against.
+   */
+  def hasOptionalReferences(plan: LogicalPlan): Boolean =
+    firstUnresolvedOptionalReference(plan).isDefined
+
+  /**
+   * Returns the first unresolved optional reference of the operators of 
`plan`, including in the
+   * plans of their subquery expressions and in the plans that an operator 
keeps outside of its
+   * children, such as the common table expressions of `UnresolvedWith`.
+   */
+  private def firstUnresolvedOptionalReference(plan: LogicalPlan): 
Option[Expression] = {
+    plan.expressions.iterator
+      .flatMap(unresolvedOptionalReference)
+      .nextOption()
+      .orElse {
+        plan.innerChildren.iterator

Review Comment:
   **Non-blocking (P2):** For ordinary operators `plan.innerChildren` is 
`QueryPlan.subqueries` (QueryPlan.scala:710), and the expression branch above 
has already searched those plans through `unresolvedOptionalReference`, so each 
subquery plan is searched twice per level and a plan d levels deep 2^(d-1) 
times. `CheckOptionalReferencesInDml` runs this on every DELETE, UPDATE, MERGE, 
and `DataFrameWriterV2.overwrite` plan in every analysis, also with 
`spark.sql.optionalReferences.enabled` off, when nothing can match and the 
search never stops early. By the review's reading of the code, a `DELETE FROM t 
WHERE a IN (SELECT ... WHERE b IN (SELECT ...))` with d nested subqueries 
therefore does about 2^d - 1 plan searches: negligible for a few levels, but by 
the review's estimate around a second near 20 levels and far longer beyond 
that, for statements that never use `?`. Results are unchanged.
   
   Suggested fix: search only the inner children that are not the operator's 
own subquery plans here, for example by skipping `plan.subqueries`, so that the 
common table expressions of `UnresolvedWith` and the analyzed children of an 
`AnalysisOnlyCommand` are still searched, each once.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4576517549).
   
   **Verification:**
   - **Regression:** With optional references off, analyzing a DELETE or a 
DataFrame MERGE whose condition nests about 25 IN subqueries visits each 
subquery plan once in the optional-reference search, with no exponential growth 
of analysis time.
   - **Compatibility:** A `?` inside a CTE of a subquery, and inside a subquery 
nested in another subquery, is still rejected in a DataFrame MERGE condition 
and in an AUTO CDC change argument, and the legacy binding mode still reports 
unused positional values for such a statement.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -155,7 +156,13 @@ trait ColumnResolutionHelper extends Logging with 
DataTypeErrorsBase {
             // Real columns from relations -- which don't carry the
             // SQL_FUNCTION_PARAMETER_ALIAS_METADATA_KEY -- continue to win as 
before.
             // Gated by a legacy kill-switch conf so the pre-fix behavior can 
be restored.
-            val column = resolveColumnByName(nameParts)
+            // A missing optional field is only NULL here if the error of the 
same name without

Review Comment:
   **Nit (P3):** This comment runs straight on from the comment about a 
parameterless built-in function taking precedence over a SQL UDF parameter, 
with no break, and the three lines below it now separate that comment from `val 
resolved = column match { case Some(c) if isSQLFunctionParameterAlias(c) ... 
}`, the code it explains; on the base branch the UDF comment sat directly above 
`resolveColumnByName` and that match. A reader of this central name-resolution 
path now sees one nine-line block above `optionalNamePartIndices`.
   
   Suggested fix: keep this optional-field comment as its own block above 
`optionalNamePartIndices`, and move the UDF precedence comment down so that it 
sits directly above `val resolved = column match`.
   
   **Verification:**
   - **Inspection:** The UDF-precedence comment directly precedes the match on 
SQL function parameter aliases, and the optional-field comment directly 
precedes the computation of the optional name parts.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to