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


##########
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 `PruneFileSourcePartitions` and `PruneHiveTablePartitions` store this 
estimate as the pruned relation's statistics, this unwrapping also changes 
their row counts for CHAR partition columns. With CBO on, 
`CatalogStatistics.toPlanStats` derives `sizeInBytes` from that row count. 
Previously, a filter on a padded CHAR partition column was estimated with 
selectivity 1.0.
   
   For example, for an analyzed `CHAR(5)` partition column `p` with 10 distinct 
values where 90% of rows are in `p = '3'`, `WHERE p = '3'` is now estimated as 
1/10 of the table instead of the whole table. If the estimate falls under 
`spark.sql.autoBroadcastJoinThreshold`, the 90% partition can be broadcast.
   
   I understand that this is the same as STRING partition columns, and the PR 
description mentions it. Since it can change join strategies for existing 
analyzed tables, shall we mention it in the SQL migration guide?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -128,6 +149,16 @@ object EstimationUtils {
     if (outputRowCount > 0) outputRowCount * getSizePerRow(attributes, 
attrStats) else 1
   }
 
+  /**
+   * Whether the histogram estimation paths apply to a column of this type. 
String and binary
+   * columns have no numeric bounds, which those paths need. ANALYZE TABLE 
builds no histogram for
+   * them, but a DSv2 connector can report one for any type.
+   */
+  def canEstimateWithHistogram(dataType: DataType): Boolean = dataType match {

Review Comment:
   This lists the types that don't work rather than the types that do. The 
histogram paths rely on `toDouble` and `fromDouble`, which support only 
`NumericType`, `DateType`, `TimestampType` and `BooleanType`, but this returns 
`true` for `TimestampNTZType`, `TimeType`, ANSI interval types and nested 
types. Note that `CommandUtils.supportsHistogram` builds histograms for 
`DatetimeType`, including `TimestampNTZType`.
   
   Since this helper is meant to state the rule, how about an allowlist that 
mirrors the domain of `toDouble`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala:
##########
@@ -366,7 +373,8 @@ case class FilterEstimation(
 
     if (!valueInRange) return Some(0.0)
 
-    val percent = if (colStat.histogram.isDefined) {
+    val useHistogram = colStat.histogram.isDefined && 
canEstimateWithHistogram(attr.dataType)

Review Comment:
   The PR description says that an equality on a column with a histogram but no 
min and max now uses the distinct count. However, `useHistogram` doesn't check 
`colStat.hasMinMaxStats`, so this is true only for STRING and BINARY columns.
   
   For example, if a DSv2 connector reports `distinctCount = 100` and a 
histogram for an INT column without min/max, `WHERE i = 5` still reaches the 
`None` branch below and is estimated with selectivity 1.0, while the same 
column without a histogram gets `1 / 100`. Shall we fold 
`colStat.hasMinMaxStats` into `useHistogram`, or narrow the PR description to 
STRING and BINARY columns?



##########
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, _)), _)
+          if attributeStats.contains(attr) =>
+        val stat = attributeStats(attr)
+        val noValues =
+          stat.distinctCount.contains(BigInt(0)) || stat.nullCount.exists(_ >= 
rowCount)

Review Comment:
   `nullCount` and `rowCount` don't always describe the same rows here. After a 
filter, `EstimationUtils.updateStat` scales `nullCount` with `ceil`, and 
`AggregateEstimation` passes its output row count as `rowCount`.
   
   For example, with 1000 rows and a `CHAR(100)` column with `nullCount = 10` 
and a connector-reported `avgLen = 3`, a filter on another column leaving 1 row 
gives `nullCount = ceil(10 * 1 / 1000) = 1` and `rowCount = 1`. Then, 
`noValues` becomes true and `avgLen` stays 3 instead of 100.
   
   The impact is limited to mostly-null columns with small row counts. However, 
since overestimating the size is the safer side, it might be better to skip the 
padding only when the column is known to have no values (e.g., `distinctCount 
== 0`). WDYT?



##########
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:
   This and `FilterEstimation.calculateSingleCondition` match one specific 
`StaticInvoke` by its function name inside generic CBO estimators. As the PR 
description mentions, `charTypeReadSideCheck` and `varcharTypeReadSideCheck` 
under the standard CHAR/VARCHAR semantics are not covered yet (SPARK-60830), 
and a future change in how the padding is expressed would silently drop the 
statistics again.
   
   For SPARK-60830, it might be worth considering a more generic way, e.g., a 
dedicated expression or a marker trait for stats-preserving read-side wrappers, 
instead of adding more name-based matches.



##########
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 and the 
length argument.
+   */
+  private[sql] object ReadSidePadding {
+    def unapply(e: Expression): Option[(Expression, Expression)] = e match {

Review Comment:
   nit. Four of the seven call sites (`getAliasStats` and the three char-pad 
helpers in `V2ExpressionBuilder`) destructure the length right away with 
`Literal(n: Int, _)`. If this extractor returned the `Int` length and matched 
only an `Int` literal, the callers wouldn't need to repeat it, and 
`V2ExpressionBuilder` could rebuild `Literal(n)` where it needs the expression.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -201,7 +201,8 @@ case class JoinEstimation(join: Join) extends Logging {
       if (ValueInterval.isIntersected(lInterval, rInterval)) {
         val (newMin, newMax) = ValueInterval.intersect(lInterval, rInterval, 
leftKey.dataType)
         val (card, joinStat) = (leftKeyStat.histogram, rightKeyStat.histogram) 
match {
-          case (Some(l: Histogram), Some(r: Histogram)) =>
+          case (Some(l: Histogram), Some(r: Histogram))
+              if canEstimateWithHistogram(leftKey.dataType) =>

Review Comment:
   This guards one consumer, but the histogram itself is kept. Line 214 below 
still copies `leftKeyStat.histogram` and `rightKeyStat.histogram` into the 
output stats, and the STRING/BINARY update path of 
`FilterEstimation.evaluateEquality` keeps it as well. So, every future 
histogram consumer has to remember this check.
   
   How about dropping unusable histograms once where they enter, e.g., in 
`DataSourceV2Relation.transformV2Stats` (and `CatalogColumnStat.toPlanStat`)?



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

Review Comment:
   nit. The same CHAR attribute construction, 
`DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(StructType(Seq(StructField(name,
 CharType(n))))).head)`, appears five times in four suites (twice here, and 
once each in `FilterEstimationSuite`, `JoinEstimationSuite` and 
`DataSourceV2RelationSuite`). How about adding a helper like `charAttr(name, 
n)` to `StatsEstimationTestBase`, which the three estimation suites already 
extend?



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