gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4652060894


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,160 @@
+/*
+ * 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 scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper, 
CTERelationRef, Except, Intersect, LogicalPlan, Project, SetOperation, Union, 
UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length 
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of 
different lengths at
+ * the same position, this pads the values of the shorter children to the 
widest length, in a
+ * Project over each child that needs it, as 
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from 
its first child,
+ * then has the widest length. Like read-side padding, the padding does not 
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children 
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length 
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after 
the widening of
+ * their types and the deduplication of their output: in 
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass 
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+  /**
+   * Whether the CHAR lengths of the children of a set operation are the same 
at each position, so
+   * that it needs no padding. Only analysis pads the children, so outside of 
it this is true, as
+   * an optimizer rule can make the metadata of the children differ again, 
such as one that pushes
+   * an alias with explicit metadata through a union. True if the children are 
not resolved yet.
+   */
+  def isAligned(children: Seq[LogicalPlan]): Boolean = {
+    !AnalysisHelper.isInAnalyzer || !needsPadding(children)
+  }
+
+  /** Whether the resolved children of a set operation have CHAR lengths to 
pad. */
+  def needsPadding(children: Seq[LogicalPlan]): Boolean = {

Review Comment:
   **[P1] Set-operation CHAR padding ignores 
spark.sql.legacy.charVarcharAsString**
   
   `needsPadding` / `padChildren` (used by `isAligned`, 
`PadSetOperationCharLengths` and `SetOperationLikeResolver`) never check 
`conf.charVarcharAsString && !conf.charVarcharStandardSemantics`. 
`ApplyCharTypePadding.apply` deliberately returns the plan untouched in that 
mode. Even in legacy mode the catalog keeps `CHAR(n)` for tables, and 
`SessionCatalog.getTableMetadata` / `LogicalRelation` attach the CHAR raw-type 
metadata through `replaceCharVarcharWithStringInSchema`, whatever the flag 
says. So the new rule now pads CHAR values in the legacy CHAR-as-STRING mode, 
which promises no padding. Since `readSideCharPadding` defaults to true, 
`alwaysPad` is false: only the shorter children are padded, while the widest 
child's unpadded values are left alone. Gate `needsPadding` (or 
`widerCharRawTypes`) on the same legacy check as `ApplyCharTypePadding`.
   
   **Failure scenario:** With spark.sql.legacy.charVarcharAsString=true: CREATE 
TABLE t3(c CHAR(3)) and t5(c CHAR(5)), and INSERT 'a' into each (stored 
unpadded, because legacy mode skips write-side padding). `SELECT c FROM t3 
UNION SELECT c FROM t5` used to return one row 'a'. Now t3's value is padded 
with readSidePadding to 'a    ' while t5's stays 'a', so UNION returns two 
rows. length(c) changes, and CTAS or views of the union store padded values, 
all in a mode that promises no CHAR padding.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TypeCoercion.scala:
##########
@@ -49,6 +49,7 @@ object TypeCoercion extends TypeCoercionBase {
   override def typeCoercionRules: List[Rule[LogicalPlan]] =
     UnpivotCoercion ::
     WidenSetOperationTypes ::
+    PadSetOperationCharLengths ::

Review Comment:
   **[P1] PadSetOperationCharLengths also runs on optimized V2 write plans**
   
   `PadSetOperationCharLengths` is added to `typeCoercionRules`, which 
`DistributionAndOrderingUtils.prepareQuery` (called from the optimizer rule 
`V2Writes`) also runs through `TypeCoercionExecutor` on the optimized query. 
The rule's guard (`resolvedExceptCharLengths && needsPadding`) doesn't check 
`AnalysisHelper.isInAnalyzer`. The PR's own design says only analysis pads, 
because optimizer rules can misalign the children's metadata. Optimizer-created 
Union and Project nodes are not marked analyzed, so 
`resolveOperatorsUpWithNewOutput` visits them and pads children based on 
metadata that the optimizer misaligned. Gate the rule on `isInAnalyzer`, as 
`isAligned` is, or keep it out of the list that V2Writes reuses.
   
   **Failure scenario:** `t5.union(t5).select(col("c").as("c", <metadata with 
CHAR(10) raw type>))` (the PR's own test case) is written with writeTo() into a 
V2 table that requires a distribution or ordering. PushProjectionThroughUnion 
keeps the explicit CHAR(10) metadata only on the first child; pushToRight's 
`Alias(child, alias)()` leaves the second at CHAR(5). TypeCoercionExecutor then 
pads only the second branch to 10 characters, while the first keeps 5. The 
written data differs from what the same DataFrame returns when read, where both 
rows are 'a    '.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,160 @@
+/*
+ * 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 scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper, 
CTERelationRef, Except, Intersect, LogicalPlan, Project, SetOperation, Union, 
UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length 
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of 
different lengths at
+ * the same position, this pads the values of the shorter children to the 
widest length, in a
+ * Project over each child that needs it, as 
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from 
its first child,
+ * then has the widest length. Like read-side padding, the padding does not 
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children 
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length 
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after 
the widening of
+ * their types and the deduplication of their output: in 
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass 
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+  /**
+   * Whether the CHAR lengths of the children of a set operation are the same 
at each position, so
+   * that it needs no padding. Only analysis pads the children, so outside of 
it this is true, as
+   * an optimizer rule can make the metadata of the children differ again, 
such as one that pushes
+   * an alias with explicit metadata through a union. True if the children are 
not resolved yet.
+   */
+  def isAligned(children: Seq[LogicalPlan]): Boolean = {
+    !AnalysisHelper.isInAnalyzer || !needsPadding(children)

Review Comment:
   **[P2] Design: Set-op `resolved` now depends on a nested-analyzer 
thread-local counter that doesn't match the phase that pads**
   
   `isAligned` (SetOperationCharPadding.scala:52-54) now feeds `Union.resolved` 
and `SetOperation.resolved` (basicLogicalOperators.scala:416-417, 727-728). It 
reads `AnalysisHelper.inAnalyzer` through the new `isInAnalyzer` 
(AnalysisHelper.scala:422).
   
   Until now, this thread-local's only reader was the test-only check 
`assertNotAnalysisRule` (AnalysisHelper.scala:342-347, gated by 
`Utils.isTesting`). Every other `resolved` in plans/logical depends only on the 
node, its children and the conf, which is the contract in 
LogicalPlan.scala:113-119.
   
   The counter does not track "the phase that pads" in either direction:
   - `markInAnalyzer` is opened only by `Analyzer.executeAndCheck` 
(Analyzer.scala:490, 498) and by 
`executeAndCheckReferredTempVariablesUnderIdentifier` (Analyzer.scala:584). 
`Analyzer.execute` (Analyzer.scala:549) still runs 
`PadSetOperationCharLengths`, because the TypeCoercion.scala:52 and 
AnsiTypeCoercion.scala:80 rule lists include it, and that rule guards on 
`needsPadding`, not on the flag. Production code calls `Analyzer.execute` 
directly: ExpressionEncoder.scala:278, ResolveDefaultColumnsUtil.scala:295, 
RelationalGroupedDataset.scala:649, classic/SparkSession.scala:482, 
execution/datasources/ddl.scala:114. On that path a set operation is already 
resolved before its children are padded, which is the state the gate exists to 
prevent.
   - A query execution started from an analyzer rule runs its optimizer while 
the counter is still above zero. For example, `EvalSubqueriesForTimeTravel` 
(sql/core/.../EvalSubqueriesForTimeTravel.scala:42-43) calls 
`executePlan(...).executedPlan`. In that optimizer the CHAR gate applies again, 
though the PR says it must not apply to optimizer output.
   
   So the description's premise ("Outside of analysis, which is the only phase 
that pads, the CHAR lengths don't affect `resolved`") is not what the code does.
   
   What to change: tie the padding rule and the gate to the same signal. One 
option is to open `markInAnalyzer` in `Analyzer.execute`/`executeSameContext`, 
so every analyzer run sets it, and to clear the counter for query executions 
nested inside analyzer rules. The other is to keep `resolved` structural and 
have the rules that resolve parent operators wait for 
`PadSetOperationCharLengths`. In either case, document `isInAnalyzer` as a real 
phase signal rather than leaving it as a reuse of a test-assertion counter.
   
   **Why it matters:** `resolved` is a cached lazy val that every analyzer rule 
and CheckAnalysis read. Tying it to a call-stack counter makes the same Union 
resolved or not depending on which entry point, or which nested execution, 
reads it first. Every current and future caller of `Analyzer.execute`, and 
every nested QueryExecution, inherits that hidden behavior. Bugs like this are 
hard to diagnose, and once more code relies on `resolved` changing by phase, 
the dependency is hard to remove.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +89,95 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          narrowCharColumns(newPlan), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        narrowCharColumns(plan),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+    }
+  }
+
+  /**
+   * Set operations of CHAR columns of different lengths have the widest 
length, see
+   * [[SetOperationCharPadding]]. This narrows the values of recursive CTEs 
and views, whose
+   * columns keep shorter lengths, to those lengths.
+   */
+  private def narrowCharColumns(plan: LogicalPlan): LogicalPlan =
+    narrowViewColumns(narrowRecursiveTerms(plan))
+
+  /**
+   * The columns of a recursive CTE have the CHAR lengths of its anchor. This 
narrows values of the
+   * recursive term with longer CHAR lengths, such as those of a set operation 
in it, to them, as
+   * [[narrowViewColumns]] does for a view.
+   */
+  private def narrowRecursiveTerms(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveOperatorsUp {
+      case loop: UnionLoop if loop.resolved =>
+        val recursion = loop.recursion
+        val projectList = recursion.output.zip(loop.anchor.output).map { case 
(attr, anchorAttr) =>
+          (for {
+            rawType <- CharVarcharUtils.getRawType(attr.metadata, 
attr.dataType)
+            anchorType <- CharVarcharUtils.getRawType(anchorAttr.metadata, 
anchorAttr.dataType)
+            narrowed <- narrowToLength(attr, rawType, anchorType)
+          } yield Alias(narrowed, attr.name)(
+            qualifier = attr.qualifier,
+            explicitMetadata = 
Some(CharVarcharUtils.withRawType(attr.metadata, anchorType))
+          )).getOrElse(attr)
+        }
+        if (projectList == recursion.output) {
+          loop
+        } else {
+          loop.copy(recursion = Project(projectList, recursion))
+        }
+    }
+  }
+
+  // The value narrowed to the CHAR lengths of `toType`, with the data type of 
the value. A rebuilt
+  // struct loses the metadata of its fields, which holds their raw types.
+  private def narrowToLength(
+      expr: Expression,
+      fromType: DataType,
+      toType: DataType): Option[Expression] = {
+    CharVarcharUtils.narrowCharToLength(expr, fromType, toType).map { narrowed 
=>
+      if (narrowed.dataType == expr.dataType) {
+        narrowed
+      } else {
+        Cast(narrowed, expr.dataType, Some(conf.sessionLocalTimeZone))
+      }
+    }
+  }
+
+  /**
+   * A view stores the CHAR types of its columns, and keeps them for the 
values of its query. A view
+   * of a set operation created before the output had the widest length of its 
children stores the
+   * length of the first child. This narrows the values back to that length, 
as the stored type
+   * says, so that comparisons padded to it still match them. The columns keep 
their expression IDs
+   * and metadata.
+   */
+  private def narrowViewColumns(plan: LogicalPlan): LogicalPlan = {
+    def queryAttr(e: Expression): Option[Attribute] = e match {
+      case a: Attribute => Some(a)
+      case c: Cast => queryAttr(c.child)
+      case _ => None
+    }
+    plan.resolveOperatorsUp {
+      case v @ View(_, _, p @ Project(projectList, _), _) =>
+        val newProjectList = projectList.map {
+          case a @ Alias(child, _) =>
+            (for {
+              viewType <- CharVarcharUtils.getRawType(a.metadata, a.dataType)
+              attr <- queryAttr(child)
+              queryType <- CharVarcharUtils.getRawType(attr.metadata, 
attr.dataType)
+              narrowed <- narrowToLength(child, queryType, viewType)

Review Comment:
   **[P2] View narrowing hides read-side padding from V2 pushdown and stats**
   
   `narrowViewColumns` wraps the view's columns in a `charTypeNarrowing` 
StaticInvoke. `CharVarcharUtils.ReadSidePadding`, `V2ExpressionBuilder` 
(CHAR_READ_SIDE_PADDING translation) and `EstimationUtils` / `FilterEstimation` 
don't recognize it. Filters on existing views over unions of CHAR columns of 
different lengths therefore lose V2/JDBC predicate pushdown and ColumnStat 
propagation, even for the first child, whose filter was pushed before. Let 
`ReadSidePadding` (or the V2 builder) see through a narrowing back to the 
scan's length, or narrow in a form that these matchers recognize.
   
   **Failure scenario:** A view v created before this change over `t3 UNION ALL 
t5`, on a JDBC/V2 source that supports CHAR_READ_SIDE_PADDING, stores CHAR(3). 
`SELECT * FROM v WHERE c = 'a'` used to push `CHAR_READ_SIDE_PADDING(c, 3) = 'a 
 '` to the t3 scan. The pushed-down predicate is now 
`charTypeNarrowing(readSidePadding(readSidePadding(c,3),5),3) = 'a  '`, which 
isn't translatable, so the source does a full scan and filter estimation loses 
the column stats.



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