LuciferYang commented on code in PR #60025:
URL: https://github.com/apache/spark/pull/60025#discussion_r4521869026


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -87,6 +88,26 @@ object EstimationUtils {
     expressions.collect {
       case alias @ Alias(attr: Attribute, _) if attributeStats.contains(attr) 
=>
         alias.toAttribute -> attributeStats(attr)
+      // Read-side CHAR padding wraps each CHAR column of a scan. With padding 
on, ANALYZE TABLE
+      // reads the table through it as well, so the statistics already 
describe padded values.
+      // Statistics collected otherwise (with padding off, or reported by a 
connector) can
+      // describe shorter values, and every non-null padded value has at least 
N characters.
+      // A distinct count of 0 or a null count covering every row means no 
non-null values, so
+      // there is nothing to pad (ANALYZE then stores the type's default size 
as the lengths).
+      // The distinct count is left as is.
+      // It is too high only when stored values differ just in trailing 
spaces, which the
+      // padding makes equal.
+      case alias @ Alias(CharVarcharUtils.ReadSidePadding(attr: Attribute, 
Literal(n: Int, _)), _)

Review Comment:
   Fixed in 78f799492c4. `computeCardinalityAndStats` now treats a key pair 
whose distinct counts are 0 on both sides as matching no rows before the 
interval check, so `computeByNdv` no longer divides by 0. `JoinEstimationSuite` 
covers inner and full outer joins on padded CHAR, CHAR with STRING, and STRING 
keys, and `StatisticsCollectionSuite` plans a full outer join of two analyzed 
all-null `CHAR(5)` columns under a cross join. Both failed with `Division by 
zero` before the fix. A pair where only one side has a distinct count of 0 
keeps its estimate.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala:
##########
@@ -163,6 +164,54 @@ class ProjectEstimationSuite extends 
StatsEstimationTestBase {
     assert(proj2.stats == expectedStats2)
   }
 
+  test("SPARK-60810: column stats of a CHAR column survive read-side padding") 
{
+    val c = 
DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      StructType(Seq(StructField("c", CharType(5))))).head)
+    val colStat = ColumnStat(distinctCount = Some(10), nullCount = Some(0),
+      avgLen = Some(5), maxLen = Some(5))
+    val child = StatsTestPlan(
+      outputList = Seq(c),
+      rowCount = 1000,
+      attributeStats = AttributeMap(Seq(c -> colStat)))
+
+    val padded = CharVarcharUtils.addPaddingForScan(c)
+    assert(padded != c, "expected a read-side padding expression for a CHAR 
column")
+    val proj = Project(Seq(Alias(padded, "c")()), child)
+    assert(proj.stats.attributeStats.get(proj.output.head).contains(colStat))
+
+    // Statistics of values shorter than N, e.g. collected with read-side 
padding off: every
+    // non-null padded value has at least N characters.
+    val shortStat = colStat.copy(avgLen = Some(3), maxLen = Some(4))

Review Comment:
   Done in 78f799492c4: lengths of 7 and 9 under `CHAR(5)` are kept.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala:
##########
@@ -163,6 +164,54 @@ class ProjectEstimationSuite extends 
StatsEstimationTestBase {
     assert(proj2.stats == expectedStats2)
   }
 
+  test("SPARK-60810: column stats of a CHAR column survive read-side padding") 
{
+    val c = 
DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      StructType(Seq(StructField("c", CharType(5))))).head)
+    val colStat = ColumnStat(distinctCount = Some(10), nullCount = Some(0),
+      avgLen = Some(5), maxLen = Some(5))
+    val child = StatsTestPlan(
+      outputList = Seq(c),
+      rowCount = 1000,
+      attributeStats = AttributeMap(Seq(c -> colStat)))
+
+    val padded = CharVarcharUtils.addPaddingForScan(c)
+    assert(padded != c, "expected a read-side padding expression for a CHAR 
column")
+    val proj = Project(Seq(Alias(padded, "c")()), child)
+    assert(proj.stats.attributeStats.get(proj.output.head).contains(colStat))
+
+    // Statistics of values shorter than N, e.g. collected with read-side 
padding off: every
+    // non-null padded value has at least N characters.
+    val shortStat = colStat.copy(avgLen = Some(3), maxLen = Some(4))
+    val shortChild = child.copy(attributeStats = AttributeMap(Seq(c -> 
shortStat)))
+    val shortProj = Project(Seq(Alias(padded, "c")()), shortChild)
+    
assert(shortProj.stats.attributeStats.get(shortProj.output.head).contains(colStat))
+    // The same without a distinct count, e.g. from a connector that reports 
only lengths.
+    val noNdvChild = child.copy(
+      attributeStats = AttributeMap(Seq(c -> shortStat.copy(distinctCount = 
None))))
+    val noNdvProj = Project(Seq(Alias(padded, "c")()), noNdvChild)
+    assert(noNdvProj.stats.attributeStats.get(noNdvProj.output.head)
+      .contains(colStat.copy(distinctCount = None)))
+
+    // An all-null column has no values to pad; ANALYZE stores the default 
size of the string
+    // type, 20, as its lengths, which a CHAR(30) floor must not raise.
+    val wide = 
DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      StructType(Seq(StructField("w", CharType(30))))).head)
+    val nullStat = ColumnStat(distinctCount = Some(0), nullCount = Some(1000),

Review Comment:
   Done in 78f799492c4: a distinct count of 0 with a null count of 200 in 1000 
rows keeps its lengths. The null-count check has since been removed (see the 
comment on `EstimationUtils`), and a null count scaled to cover every row now 
gets the floor.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -391,6 +391,22 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
     }.getOrElse(attr)
   }
 
+  /**
+   * Matches the read-side CHAR padding that [[addPaddingForScan]] wraps a 
column in (when
+   * standard semantics are off) and extracts the padded expression.
+   */
+  private[sql] object ReadSidePadding {

Review Comment:
   Noted for SPARK-60830: under first-class CHAR the filter unwrap also has to 
see through the cast to STRING, and it relies on the zero distinct count guard 
in 78f799492c4.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala:
##########
@@ -170,7 +173,11 @@ case class FilterEstimation(
    *         It returns None if the condition is not supported.
    */
   def calculateSingleCondition(condition: Expression, update: Boolean): 
Option[Double] = {
-    condition match {
+    val unpadded = condition.mapChildren {
+      case CharVarcharUtils.ReadSidePadding(attr: Attribute, _) => attr

Review Comment:
   Since this is what CBO already does for analyzed STRING partition columns, 
and the description covers it, I'd rather not add a migration guide entry: this 
PR stops CHAR columns from being the exception rather than introducing a new 
behavior. WDYT?



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