cloud-fan commented on code in PR #60025:
URL: https://github.com/apache/spark/pull/60025#discussion_r4527648338


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -87,6 +88,23 @@ 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 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, n), 
_)

Review Comment:
   **Nit (P3):** This case covers only the default read-side padding. Under 
`spark.sql.charVarchar.standardSemantics.enabled`, `addPaddingForScan` wraps 
CHAR columns in `charTypeReadSideCheck` and VARCHAR columns in 
`varcharTypeReadSideCheck` instead. Those columns still lose their statistics 
here and in the `calculateSingleCondition` unwrap. Leaving them to SPARK-60830 
is fine, and this review no longer asks the PR to cover them. But only the PR 
description and the review replies record the deferral, and nothing in the code 
does, so a reader of the estimators sees what looks like a complete fix.
   
   A TODO here naming SPARK-60830 and the two check wrappers would mark it, 
with a pointer to it from the `calculateSingleCondition` unwrap. It could also 
record your note that the follow-up has to see through the cast to STRING. 
`ReadSidePadding` itself should stay padding-only, since `V2ExpressionBuilder` 
relies on it never matching the checks.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60025#discussion_r4449329581).
   
   **Verification:**
   - **Inspection:** The getAliasStats padding case carries a TODO that names 
SPARK-60830 and the charTypeReadSideCheck and varcharTypeReadSideCheck 
wrappers, the calculateSingleCondition unwrap points to it, and no code changes 
with it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -198,10 +198,14 @@ case class JoinEstimation(join: Join) extends Logging {
       val rightKeyStat = rightStats.attributeStats(rightKey)
       val lInterval = ValueInterval(leftKeyStat.min, leftKeyStat.max, 
leftKey.dataType)
       val rInterval = ValueInterval(rightKeyStat.min, rightKeyStat.max, 
rightKey.dataType)
-      if (ValueInterval.isIntersected(lInterval, rInterval)) {
+      // A distinct count of 0 on both sides means neither has a non-null key 
value.
+      val noValues = leftKeyStat.distinctCount.contains(BigInt(0)) &&
+        rightKeyStat.distinctCount.contains(BigInt(0))
+      if (!noValues && 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:
   **Non-blocking (P2):** `canEstimateWithHistogram` admits `BooleanType`, but 
`computeByHistogram` converts the intersected bounds with 
`newMin.get.toString.toDouble` rather than `EstimationUtils.toDouble`. For a 
Boolean key, `ValueInterval.intersect` returns the bounds through 
`fromDouble(_, BooleanType)`, which gives a Scala `Boolean`. The conversion 
then parses `"false"` or `"true"` and throws `NumberFormatException`. So with 
CBO on, an equi-join on Boolean keys whose statistics carry min, max and a 
histogram on both sides still fails during optimization. That is the failure 
this guard now prevents for STRING, BINARY and padded CHAR keys. `ANALYZE` 
never builds a Boolean histogram, but `DataSourceV2Relation.transformV2Stats` 
copies a connector's histogram for any type, the same route the new STRING and 
BINARY tests describe. The crash already happens on the base branch; the guard 
leaves it in place rather than introducing it.
   
   Converting the bounds with `EstimationUtils.toDouble(newMin.get, 
leftKey.dataType)` and `EstimationUtils.toDouble(newMax.get, leftKey.dataType)` 
would close it. For numeric, date and timestamp values that is the same 
`toString.toDouble`, so their estimates do not change, and for Boolean it gives 
1 or 0. The "Only numeric values have equi-height histograms" comment there 
would need to change to match.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60025#discussion_r4464484994), 
[2](https://github.com/apache/spark/pull/60025#discussion_r4515955354).
   
   **Verification:**
   - **Regression:** An equi-join on BOOLEAN keys whose statistics on both 
sides carry a distinct count, a null count, min, max and a histogram returns an 
estimated row count from the histogram path instead of throwing a 
NumberFormatException.
   - **Inspection:** The bounds the join histogram estimate passes to the 
overlapped-range computation go through the same toDouble conversion the filter 
histogram estimate uses, which is value.toString.toDouble for numeric, date and 
timestamp values, so their estimates cannot change.



##########
docs/sql-migration-guide.md:
##########
@@ -24,6 +24,7 @@ license: |
 
 ## Upgrading from Spark SQL 4.4 to 5.0
 
+- Since Spark 5.0, when `spark.sql.cbo.enabled` is `true`, the optimizer 
estimates plans over analyzed `CHAR` columns from their column statistics, as 
it does for `STRING` columns. Since Spark 3.4, read-side `CHAR` padding 
(`spark.sql.readSideCharPadding`, `true` by default) hid these statistics, so, 
for example, a filter on a `CHAR` partition column was estimated to keep every 
row. The estimate assumes evenly distributed values, so for a skewed partition 
it can now be smaller than the data, and the pruned relation can become small 
enough to be broadcast.

Review Comment:
   **Nit (P3):** This entry ties the change to `spark.sql.cbo.enabled`, but its 
own example, a filter on a CHAR partition column, also changes when only 
`spark.sql.cbo.planStats.enabled` is on. `PruneFileSourcePartitions` and 
`PruneHiveTablePartitions` run `FilterEstimation` with no CBO check and save 
its row count as the pruned relation's statistics. With either setting on, 
`CatalogStatistics.toPlanStats` then sizes that relation as row count times row 
size. A user who runs with plan statistics on and CBO off would read the note 
as not applying to them, although their pruned CHAR partitions can now be 
estimated small enough to broadcast.
   
   Filter, Project and DSv2 filter estimates still need 
`spark.sql.cbo.enabled`, so naming both settings for the whole entry would 
overstate it. Keeping `spark.sql.cbo.enabled` as the entry's condition and 
adding a sentence such as "This also applies to partition pruning when only 
`spark.sql.cbo.planStats.enabled` is `true`." would cover it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60025#discussion_r4515955342).
   
   **Verification:**
   - **Inspection:** The entry names spark.sql.cbo.planStats.enabled for the 
partition-pruning case and still ties the other estimate changes to 
spark.sql.cbo.enabled only.



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