dongjoon-hyun commented on code in PR #60560:
URL: https://github.com/apache/spark/pull/60560#discussion_r4645650014


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,24 +67,117 @@ private[sql] object RowLevelAssignmentResolution {
     Assignment(cleanedKey, finalValue)
   }
 
+  /**
+   * Fills omitted generated-column assignments for UPDATE and MERGE actions, 
including INSERT
+   * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+   *
+   * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must 
assign
+   * g = (old.b + 1) * 2. Resolve the generation expression against attributes 
for the new values,
+   * then substitute the aligned assignments while preserving their references 
to the original row.
+   * UPDATE and projection-based insert-only MERGE project shared assignment 
values in the rewrite.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan,
+      shareAssignedValues: Boolean = true): Seq[Assignment] = {
+    if 
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+      return assignments
+    }
+
+    val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+    val generationExpressions = GeneratedColumn.expressionReaders(relation)
+    // For the example above, pair a with Alias(old.b + 1, "a") and b with 
Alias(100, "b").
+    // Each alias has a fresh attribute ID, distinct from the original table 
column.
+    val assigned = assignments.collect {
+      case Assignment(attr: Attribute, value)
+          if !value.isInstanceOf[GeneratedColumnAssignmentValue] =>
+        attr -> Alias(value, attr.name)()
+    }
+    // input exposes the new a and b; valuesByAttribute maps them to old.b + 1 
and 100.
+    // When sharing is enabled, preserve each alias ID in a marker for the 
rewrite.
+    val input = assigned.map(_._2.toAttribute)
+    val valuesByAttribute = AttributeMap(assigned.map { case (_, alias) =>
+      val value = if (shareAssignedValues) {
+        GeneratedColumnSharedAssignmentValue(alias.child, alias.exprId)

Review Comment:
   **[2] Following up on @spark-test's 
[thread](https://github.com/apache/spark/pull/60560#discussion_r4594657910), 
which was moved to #60559: the shared markers hide failing constants from the 
trial fold of #60559, so its fix does not reach generated values.** 
`GeneratedColumnSharedAssignmentValue` is Unevaluable, so it is never foldable. 
After the rebase, with `projectAssignmentValues` on the Project branch, take `g 
INT GENERATED ALWAYS AS (100 DIV a)` and a lone `WHEN NOT MATCHED THEN INSERT 
(pk, part, a) VALUES (s.pk, 'p', 0)`, where every source row matches. The trial 
fold in `tryBuildInsertOnlyMergeProject` sees `a = marker(0)` and `g = CAST(100 
DIV marker(0) AS INT)`, folds nothing, and picks the Project plan. 
`projectAssignmentValues` then projects `0` once, CollapseProject inlines it 
into `100 DIV v`, and ConstantFolding throws DIVIDE_BY_ZERO at planning, 
although no row is inserted. Without the marker, the trial fold would see `100 
DIV 0` and keep MergeRows. Could the trial
  fold run on a copy with the markers replaced by their children, and could a 
test cover this example?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala:
##########
@@ -62,25 +66,28 @@ object ResolveRowLevelCommandAssignments extends 
Rule[LogicalPlan] {
       validateStoreAssignmentPolicy()
       val coerceNestedTypes = conf.coerceMergeNestedTypes && 
m.withSchemaEvolution
       val castCheck = ansiStoreAssignmentCastCheck(m.targetTable)
+      val generatedColumns = generatedColumnNames(m.targetTable)
       val (newTargetTable, metadataAttrMap) = cleanAttrMetadata(m.targetTable)
       val padded = padTargetReferences(m, m.targetTable)
       padded.copy(
         targetTable = newTargetTable,
         matchedActions = RowLevelAssignmentResolution.alignActions(
-          m.targetTable.output,
+          m.targetTable,
           padded.matchedActions,
           coerceNestedTypes,
-          castCheck),
+          castCheck, generatedColumns, analyze),
         notMatchedActions = RowLevelAssignmentResolution.alignActions(
-          m.targetTable.output,
+          m.targetTable,
           padded.notMatchedActions,
           coerceNestedTypes,
-          castCheck),
+          castCheck, generatedColumns, analyze,
+          shareAssignedValues = m.matchedActions.isEmpty && 
m.notMatchedActions.size == 1 &&

Review Comment:
   **[1] After the rebase on the latest #60559, a single NOT MATCHED clause can 
be planned as MergeRows, where these markers are never replaced.** 
`shareAssignedValues` is true here for a lone NOT MATCHED clause, which assumes 
that the rewrite always takes the case that calls `projectAssignmentValues` 
(RewriteMergeIntoTable.scala:72). This branch carries an older copy of #60559 
(ae2c393). At its current head (abe7bd7), that case is gone, and 
`tryBuildInsertOnlyMergeProject(...).getOrElse(mergeRows)` keeps MergeRows when 
the trial fold throws or the clause condition holds a deferred failure. For 
example, with `g INT GENERATED ALWAYS AS (a * 2)`:
   
   ```sql
   MERGE INTO t USING s ON t.pk = s.pk
   WHEN NOT MATCHED AND IF(s.a > 0, true, 1 DIV 0 = 1)
     THEN INSERT (pk, part, a) VALUES (s.pk, 'p', s.a)
   ```
   
   The condition keeps a deferred failure, so this goes to MergeRows, and its 
`Keep(Insert, ...)` outputs still hold the Unevaluable 
`GeneratedColumnSharedAssignmentValue`. A source row with `s.a > 0` then fails 
with an internal error instead of being inserted. Turning sharing off for that 
fallback is not enough either: #60559 lets a single-insert MergeRows keep 
nondeterministic values, so `id = reflect('java.util.UUID', 'randomUUID')` with 
`g = upper(id)` would evaluate the UUID twice and fail with 
CHECK_CONSTRAINT_VIOLATION. Could the sharing follow the plan that the rewrite 
actually builds, so that the MergeRows branch also replaces the markers, and 
could a test cover that fallback with a generated column?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -198,7 +198,8 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
 
     // the plan output may include immutable metadata columns at the end
     // that's why the number of assignments may not match the number of plan 
output columns
-    val assignedValues = assignments.map(_.value).toIndexedSeq
+    val (projectedPlan, projectedAssignments) = projectAssignmentValues(plan, 
assignments)

Review Comment:
   **[4] In delta and split UPDATE, a valid constant assignment can fail 
planning through a generated column even when no row matches, while group-based 
UPDATE accepts it.** Here the shared value and the generated expression sit in 
plain Projects above `Filter(cond, readRelation)` (L179), with no guard. For `g 
INT GENERATED ALWAYS AS (100 DIV a)`, take `UPDATE t SET a = 0 WHERE pk = 999` 
with no matching row. CollapseProject, or FoldablePropagation into the `Expand` 
of a split update, inlines the projected `0` into `100 DIV v`, and 
ConstantFolding throws DIVIDE_BY_ZERO during optimization. In group mode the 
same statement succeeds, because `buildReplaceDataUpdateProjection` guards the 
values with `If(cond, ...)` (L135 and L140), so the failed fold is deferred. 
Could the delta paths defer it the same way, or could a test pin down the 
intended behavior in all three modes?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -142,11 +143,23 @@ private[sql] class TableConstraintResolution(
             s"${col.name} <=> $genExprSql")
           // Analyze the check under the settings an auto-filled value is 
analyzed under, so that a
           // row Spark auto-filled passes it when a later write carries it.
-          reader.analyze(
+          val invariant = reader.analyze(
             check(catalystExpr),
             
check(reader.toCatalyst(StoredExpressionText.parseWithSessionAnsi)),
             v2Write.query.output,
             analyze)
+          v2Write match {
+            // MERGE and split UPDATE deltas also contain deletes, whose row 
values may be null.
+            case _: WriteDelta =>
+              val isDelete = EqualTo(
+                UnresolvedAttribute.quoted(OPERATION_COLUMN), 
Literal(DELETE_OPERATION))

Review Comment:
   **[6] Minor: the operation column is looked up by name here and at L159, 
although `RowLevelWrite.operationResolved` already pins it as 
`query.output.head` (v2Commands.scala:361-364).** 
`UnresolvedAttribute.quoted(OPERATION_COLUMN)` matches every attribute named 
`__row_operation` in the query output, so a table with a data column of that 
name gets AMBIGUOUS_REFERENCE here instead of a check bound to the operation 
column. The attribute also stays unresolved until a later analyzer iteration. 
Could both use `v2Write.query.output.head`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala:
##########
@@ -122,6 +129,12 @@ object ResolveRowLevelCommandAssignments extends 
Rule[LogicalPlan] {
     !m.schemaEvolutionEnabled || (m.schemaEvolutionReady && 
m.pendingSchemaChanges.isEmpty)
   }
 
+  private def generatedColumnNames(table: LogicalPlan): Set[String] = {

Review Comment:
   **[9] Nit: `generatedColumnNames` repeats the lookup that this PR adds to 
the MERGE star expansion (Analyzer.scala:1821-1824).** Both decide which 
generated columns Spark computes for the target, and they must agree: if one 
later gets a gate that the other lacks, such as the `m.rewritable` that only 
the Analyzer copy has, or case-insensitive names, a star action can omit a 
column that alignment then fills from its default, or the other way around. 
Could both call one helper on `GeneratedColumn` that takes the target plan?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,24 +67,117 @@ private[sql] object RowLevelAssignmentResolution {
     Assignment(cleanedKey, finalValue)
   }
 
+  /**
+   * Fills omitted generated-column assignments for UPDATE and MERGE actions, 
including INSERT
+   * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+   *
+   * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must 
assign
+   * g = (old.b + 1) * 2. Resolve the generation expression against attributes 
for the new values,
+   * then substitute the aligned assignments while preserving their references 
to the original row.
+   * UPDATE and projection-based insert-only MERGE project shared assignment 
values in the rewrite.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan,
+      shareAssignedValues: Boolean = true): Seq[Assignment] = {
+    if 
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+      return assignments
+    }
+
+    val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+    val generationExpressions = GeneratedColumn.expressionReaders(relation)
+    // For the example above, pair a with Alias(old.b + 1, "a") and b with 
Alias(100, "b").
+    // Each alias has a fresh attribute ID, distinct from the original table 
column.
+    val assigned = assignments.collect {
+      case Assignment(attr: Attribute, value)
+          if !value.isInstanceOf[GeneratedColumnAssignmentValue] =>
+        attr -> Alias(value, attr.name)()
+    }
+    // input exposes the new a and b; valuesByAttribute maps them to old.b + 1 
and 100.
+    // When sharing is enabled, preserve each alias ID in a marker for the 
rewrite.
+    val input = assigned.map(_._2.toAttribute)
+    val valuesByAttribute = AttributeMap(assigned.map { case (_, alias) =>
+      val value = if (shareAssignedValues) {
+        GeneratedColumnSharedAssignmentValue(alias.child, alias.exprId)
+      } else {
+        alias.child
+      }
+      alias.toAttribute -> value
+    })
+
+    val generatedAssignments = assignments.map {
+      case Assignment(attr: Attribute, _: GeneratedColumnAssignmentValue) =>
+        // Bind g's a * 2 to input's new a, not the table's original a.
+        val resolved = generationExpressions(attr.name).resolve(input, 
analyze) { expr =>
+          Cast(expr, attr.dataType, Some(conf.sessionLocalTimeZone), 
ansiEnabled = true)
+        }
+        // Substitute once to get (old.b + 1) * 2, with a shared marker if 
enabled.
+        val generated = resolved.transform {
+          case a: AttributeReference if valuesByAttribute.contains(a) => 
valuesByAttribute(a)
+        }
+        resolveAssignment(Assignment(attr, generated))
+      case assignment => assignment
+    }
+
+    // Only a needs sharing in this example. Match its assignment to the 
marker used by g,
+    // so the rewrite can project old.b + 1 once and use the result for both a 
and g.
+    val sharedIds = generatedAssignments.flatMap(_.value.collect {
+      case value: GeneratedColumnSharedAssignmentValue => value.id
+    }).toSet
+    val sharedByTarget = AttributeMap(assigned.collect {

Review Comment:
   **[7] Minor: `sharedByTarget` also wraps the self-assignments that alignment 
adds for unassigned columns, so an unchanged column looks assigned.** With row 
ID `pk` and `g INT GENERATED ALWAYS AS (pk * 2)`, `UPDATE t SET b = 1` in delta 
(non-split) mode aligns `pk = pk`, which becomes `pk = marker(pk)` here. 
`buildOriginalRowIdValues` (RewriteRowLevelCommand.scala:383, called from 
RewriteUpdateTable.scala:219) then sees `!key.semanticEquals(value)` and adds 
an `__original_row_id_pk` column to every updated row, and 
`projectAssignmentValues` projects a redundant copy of `pk`. The result is 
correct, but every such UPDATE pays for the extra columns. Could the marker be 
skipped when the value is the key attribute itself, so that `g` reads `pk` 
directly?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -42,7 +42,6 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
 
       EliminateSubqueryAliases(aliasedTable) match {
         case r @ ExtractV2Table(tbl: SupportsRowLevelOperations) =>
-          checkNoGeneratedColumns(r, UPDATE)

Review Comment:
   **[3] This guard also covered tables that accept any schema, which 
`ResolveRowLevelCommandAssignments` skips.** That rule aligns only targets with 
`!skipSchemaResolution` (ResolveRowLevelCommandAssignments.scala:50 and :125), 
so for an `ACCEPT_ANY_SCHEMA` table with `GENERATE_COLUMN_VALUES_ON_WRITE`, 
nothing computes the generated values now. Such a table relies on an injected 
rule for alignment, like `ResolveMergeIntoTableAcceptingAnySchema` in the 
tests, which passes `generatedColumns = Set.empty`. Before this PR, `UPDATE t 
SET a = 5` with `g = a * 2` failed at analysis with 
UNSUPPORTED_FEATURE.TABLE_OPERATION. Now `g = g` keeps the old value, and the 
write fails at runtime with CHECK_CONSTRAINT_VIOLATION on `g`, a column the 
statement never set, after the scan has run. A MERGE INSERT that omits `g` gets 
NULL and fails the same way. The three removed calls in 
RewriteMergeIntoTable.scala are the same. Could the guard stay for 
`skipSchemaResolution` targets?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,24 +67,117 @@ private[sql] object RowLevelAssignmentResolution {
     Assignment(cleanedKey, finalValue)
   }
 
+  /**
+   * Fills omitted generated-column assignments for UPDATE and MERGE actions, 
including INSERT
+   * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+   *
+   * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must 
assign
+   * g = (old.b + 1) * 2. Resolve the generation expression against attributes 
for the new values,
+   * then substitute the aligned assignments while preserving their references 
to the original row.
+   * UPDATE and projection-based insert-only MERGE project shared assignment 
values in the rewrite.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan,
+      shareAssignedValues: Boolean = true): Seq[Assignment] = {
+    if 
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+      return assignments
+    }
+
+    val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+    val generationExpressions = GeneratedColumn.expressionReaders(relation)

Review Comment:
   **[8] Minor: the expression readers are rebuilt for every action.** This 
method runs once for each UPDATE or INSERT action that omits a generated 
column, and each call builds `GeneratedColumn.expressionReaders(relation)` 
again, which calls `Table.columns()` and converts the modeled expressions again 
in fresh `ExpressionReader`s. A MERGE with K such actions makes 1 + K 
`Table.columns()` calls in alignment, counting `generatedColumnNames` 
(ResolveRowLevelCommandAssignments.scala:132), and `TableConstraintResolution` 
builds the readers once more. After the rebase, SPARK-62110 also makes 
`ExpressionReader.analyze` call `relation.table.columns()` on each analysis. 
Could `ResolveRowLevelCommandAssignments` build the readers once per command 
and pass a `Map[String, ExpressionReader]` instead of the `Set[String]`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -96,15 +97,16 @@ private[sql] class TableConstraintResolution(
       catalogManager.v1SessionCatalog.parser.parseExpression(c.predicateSql))
 
   /**
-   * For each generated column whose value was provided by the write, add a 
CheckInvariant that
-   * validates the column value matches the generation expression. Generated 
columns Spark
-   * auto-filled are excluded: ResolveOutputRelation marks them in the table 
output and their
-   * values are correct by construction.
+   * Validates generated values against their generation expressions. For 
INSERT,
+   * WriteOutputResolution marks auto-filled columns so their checks can be 
skipped. UPDATE and
+   * MERGE validate every generated column in updated or inserted rows, 
including computed values.
+   * DELETE, delta delete records and unchanged rows copied by group-based 
writes are exempt.

Review Comment:
   **[5] Following up on @spark-test's 
[thread](https://github.com/apache/spark/pull/60560#discussion_r4619979878), 
which also names a DELETE-only MERGE: the DELETE early return at L114-L118 does 
not cover a MERGE whose actions are all DELETE.** Such a MERGE writes no new 
generated value either, since every row is a delta delete or a group copy, but 
it still builds and analyzes a check for each generated column inside 
`If(isDelete, true, ...)` or `If(isCopy, true, ...)`. So on a table whose 
modeled expression fails analysis, as in the suite's "DML does not fall back to 
SQL after modeled expression analysis fails" case, `DELETE FROM t WHERE pk = 1` 
succeeds, but `MERGE INTO t USING s ON t.pk = s.pk WHEN MATCHED THEN DELETE` 
fails with INVALID_GENERATED_COLUMN_EXPRESSION. L114-L118 are outside this 
diff, so I left this on the scaladoc line. Could the early return also cover a 
MERGE whose actions are all DELETE?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,24 +67,117 @@ private[sql] object RowLevelAssignmentResolution {
     Assignment(cleanedKey, finalValue)
   }
 
+  /**
+   * Fills omitted generated-column assignments for UPDATE and MERGE actions, 
including INSERT
+   * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+   *
+   * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must 
assign
+   * g = (old.b + 1) * 2. Resolve the generation expression against attributes 
for the new values,
+   * then substitute the aligned assignments while preserving their references 
to the original row.
+   * UPDATE and projection-based insert-only MERGE project shared assignment 
values in the rewrite.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan,
+      shareAssignedValues: Boolean = true): Seq[Assignment] = {

Review Comment:
   **[10] Design: the fix chains two placeholders across rules, and the default 
here opts every new caller in to the second one.** Alignment emits 
`GeneratedColumnAssignmentValue`, this method turns the values into 
`GeneratedColumnSharedAssignmentValue`, and every rewrite that receives one 
must call `projectAssignmentValues`, or the Unevaluable marker reaches 
execution, as in item 1. `shareAssignedValues` defaults to `true` here but to 
`false` in `alignActions` (L147). The MergeRows paths also still evaluate each 
substituted value once per reference, the part of @spark-test's 
[thread](https://github.com/apache/spark/pull/60560#discussion_r4594657893) 
that sharing does not cover. INSERT avoids both by resolving the generated 
values over a projection of the stored values 
(TableOutputResolver.scala:202-209). Could the rewrites compute the generated 
values over a projection of the aligned values in the same way, which would 
cover every plan shape? Short of that, could the default be `fal
 se` here, so that sharing is opt-in?



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