dongjoon-hyun commented on code in PR #60616:
URL: https://github.com/apache/spark/pull/60616#discussion_r4604563234
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -96,21 +96,17 @@ object EstimationUtils {
// 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.
- // TODO(SPARK-60830): under
spark.sql.charVarchar.standardSemantics.enabled the scan wraps
- // CHAR and VARCHAR columns in charTypeReadSideCheck and
varcharTypeReadSideCheck instead,
- // so they still lose their statistics here and in
FilterEstimation.calculateSingleCondition.
- // They need an extractor of their own, because V2ExpressionBuilder
relies on
- // ReadSidePadding never matching the checks. Under first-class CHAR
types the filter unwrap
- // also has to see through the cast to STRING.
case alias @ Alias(CharVarcharUtils.ReadSidePadding(attr: Attribute, n),
_)
if attributeStats.contains(attr) =>
+ alias.toAttribute -> padToCharLength(attributeStats(attr), n)
+ // Under standard CHAR/VARCHAR semantics the scan wraps CHAR and VARCHAR
columns in
+ // read-side checks instead, and ANALYZE TABLE reads through those as
well. The CHAR check
+ // pads like the padding above. The VARCHAR check never makes a value
longer, so its
+ // lengths are kept.
+ case alias @ Alias(CharVarcharUtils.ReadSideCheck(attr: Attribute, n,
isChar), _)
Review Comment:
The cast is stripped in `FilterEstimation` and `JoinEstimation` only, so
`getAliasStats`, which `Project` and `Aggregate` share, still drops the stats
for the same cast under an `Alias`.
For example, with either conf on, `SELECT c FROM t UNION ALL SELECT s FROM
u` (`c CHAR(5)`, `s STRING`) gets `cast(c AS STRING) AS c` from
`WidenSetOperationTypes`, which becomes `Alias(Cast(charTypeReadSideCheck(c,
5), StringType))` after `CollapseProject`. None of the cases here match it, so
the union output loses the distinct count of `c`, and a filter, join, or
aggregate above it falls back to the default estimate. An explicit `SELECT
CAST(c AS STRING) AS k FROM t` behaves the same way.
Could we strip the cast here as well, e.g. by matching the cases above on
`stripCastToPlainString` of the `Alias` child? Or is this intentionally left
for a follow-up?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -123,6 +119,26 @@ object EstimationUtils {
}
}
+ /** Raises the lengths of a column with values to the length N of the CHAR
it is padded to. */
+ private def padToCharLength(stat: ColumnStat, n: Int): ColumnStat = {
+ if (stat.distinctCount.contains(BigInt(0))) {
+ stat
+ } else {
+ stat.copy(avgLen = stat.avgLen.map(_.max(n)), maxLen =
stat.maxLen.map(_.max(n)))
+ }
+ }
+
+ /**
+ * Strips a cast of a CHAR, VARCHAR or STRING value to a STRING of the same
collation, such as
+ * the one a comparison with a STRING adds when CHAR and VARCHAR are
first-class types. Such a
+ * cast returns the value unchanged.
+ */
+ def stripCastToPlainString(e: Expression): Expression = e match {
Review Comment:
`stripCastToPlainString` does not depend on either conf, so it also applies
in the default mode. There, `SimplifyCasts` intentionally keeps an explicit
`CAST(c AS STRING)` on a CHAR/VARCHAR column (the annotated STRING case in
`optimizer/expressions.scala`), and this PR now strips it for estimation.
For example, with CBO on and the default confs, `t JOIN u ON CAST(t.c AS
STRING) = u.s` (`c CHAR(5)`) goes from the cartesian estimate (1000000) to
100000, and `WHERE CAST(v AS STRING) = 'x'` on a `VARCHAR` column goes from all
rows to 1/ndv. The new estimates look reasonable to me since the cast keeps the
value, but the PR description says plans can change "with CBO on and either
conf enabled", and the migration guide entry only mentions those confs. Could
we mention the default mode as well?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -59,8 +59,10 @@ case class JoinEstimation(join: Join) extends Logging {
case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right,
_) =>
// 1. Compute join selectivity
val joinKeyPairs = extractJoinKeysWithColStats(leftKeys, rightKeys)
- val leftSideUniqueness =
left.distinctKeys.exists(_.subsetOf(ExpressionSet(leftKeys)))
- val rightSideUniqueness =
right.distinctKeys.exists(_.subsetOf(ExpressionSet(rightKeys)))
+ val leftSideUniqueness = left.distinctKeys.exists(
+ _.subsetOf(ExpressionSet(leftKeys.map(stripCastToPlainString))))
Review Comment:
`DistinctKeyVisitor.visitJoin` performs the same uniqueness check on the raw
keys (`ExpressionSet(leftKeys)` / `ExpressionSet(rightKeys)`).
So for `(SELECT c FROM t GROUP BY c) a JOIN u ON a.c = u.s` under either
conf, this estimator treats the left side as unique on `cast(a.c AS STRING)`,
while `DistinctKeyVisitor` does not, and the join output does not get the
distinct keys that a join above it could use. Is it intended to keep them apart
(e.g. because `DistinctKeyVisitor` also drives optimizer rules such as
`RemoveRedundantAggregates`), or should they be aligned here or in a follow-up?
##########
sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala:
##########
@@ -287,6 +288,63 @@ class StatisticsCollectionSuite extends
StatisticsCollectionTestBase with Shared
}
}
+ // Both make CHAR and VARCHAR first-class types, which a comparison with a
STRING casts.
+ private val firstClassCharVarcharConfs = Seq(
+ SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS,
SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO)
+
+ test("SPARK-60830: CBO keeps CHAR/VARCHAR column statistics as first-class
types") {
+ for (mode <- firstClassCharVarcharConfs; colType <- Seq("CHAR(5)",
"VARCHAR(5)")) {
+ withSQLConf(SQLConf.CBO_ENABLED.key -> "true", mode.key -> "true") {
+ val tableName = "char_varchar_first_class_stats"
+ val stringTable = "char_varchar_first_class_strings"
+ withTable(tableName, stringTable) {
+ sql(s"CREATE TABLE $tableName(c $colType) USING parquet")
+ sql(s"CREATE TABLE $stringTable(s STRING) USING parquet")
+ Seq(tableName, stringTable).foreach { t =>
+ sql(s"INSERT INTO $t SELECT CAST(id % 10 AS STRING) FROM
range(1000)")
+ }
+ sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS c")
+ sql(s"ANALYZE TABLE $stringTable COMPUTE STATISTICS FOR COLUMNS s")
+
+ val clue = s"${mode.key}, $colType"
+ assert(estimatedRows(s"SELECT c, count(*) FROM $tableName GROUP BY
c") {
+ case a: Aggregate => a
+ }.contains(BigInt(10)), clue)
+ Seq("c = '3'" -> 100, "c IN ('3', '4')" -> 200, "c IS NULL" ->
0).foreach {
Review Comment:
If I read it correctly, for `CHAR(5)` these predicates match no rows, so the
test pins the estimates of predicates that are actually empty.
Under either conf, `c = '3'` is analyzed as `cast(c AS STRING) = '3'`.
`ApplyCharTypePadding` runs after type coercion and pads the literal only when
it is compared with a bare attribute, so `'3'` is not padded, while the stored
and read value is `'3 '`. This is the expected behavior under standard
semantics: `SPARK-58942: CHAR column vs string literal under standardSemantics`
in `CharVarcharTestSuite` asserts that `WHERE code = 'ab'` and `code IN ('ab',
'cd')` on a `CHAR(4)` column return no rows, for both a regular and a
partitioned table. Under `preserveCharVarcharTypeInfo`,
`StringHelper.tightestCommonString` also picks `STRING` for `CHAR(5)` vs
`STRING`, so the cast keeps the padding there too.
The same applies to `c IN ('3', '4')`, the join with the STRING column (`'3
'` vs `'3'`), and `p = '3'` in the partition pruning test below, whose
`rowCount` comes from `FilterEstimation` rather than from the partitions that
are actually kept. `VARCHAR(5)` is fine because its values are not padded. So
the `same data as STRING` column in the PR description and "the stats describe
the values the predicates compare" do not hold for `CHAR(5)`.
How about inserting 5-character values so that `CHAR(5)` and `VARCHAR(5)`
store the same values, e.g. `CAST(10000 + id % 10 AS STRING)` with `c =
'10003'`, and asserting the actual row count next to each estimate (e.g.
`checkAnswer` or `count()`)?
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/FilterEstimationSuite.scala:
##########
@@ -999,6 +1000,50 @@ class FilterEstimationSuite extends
StatsEstimationTestBase {
expectedRowCount = 9)
}
+ test("SPARK-60830: predicates on a CHAR/VARCHAR column under a read-side
check") {
Review Comment:
`unwrapCharVarcharRead` handles three shapes, but this test covers only
`Cast(readSideCheck(attr))` (standard semantics). Under
`preserveCharVarcharTypeInfo` alone, a CHAR column becomes
`Cast(readSidePadding(attr))`, which relies on stripping the cast before
unwrapping the padding, and a VARCHAR column becomes `Cast(attr)`, which relies
on the `case attr: Attribute` branch. Both are covered only by the end-to-end
test in `StatisticsCollectionSuite`. Could we add these two shapes here (and to
`JoinEstimationSuite`) so that a regression shows up in `catalyst` tests?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -354,7 +356,9 @@ case class JoinEstimation(join: Join) extends Logging {
private def extractJoinKeysWithColStats(
leftKeys: Seq[Expression],
rightKeys: Seq[Expression]): Seq[(AttributeReference,
AttributeReference)] = {
- leftKeys.zip(rightKeys).collect {
+ leftKeys.zip(rightKeys).map { case (lk, rk) =>
+ (stripCastToPlainString(lk), stripCastToPlainString(rk))
Review Comment:
nit: Each join key goes through `stripCastToPlainString` twice, once for the
uniqueness check (L62-65) and once here, which also splits this helper into a
`map` followed by a `collect`. How about stripping the keys once in
`estimateInnerOuterJoin` and passing the stripped keys to both, so this can
stay a single `collect`?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala:
##########
@@ -258,6 +255,20 @@ case class FilterEstimation(
}
}
+ /**
+ * Returns the column under the read-side padding or check that a scan wraps
a CHAR or VARCHAR
+ * column in, and under the cast to STRING that a comparison adds when CHAR
and VARCHAR are
+ * first-class types (see `EstimationUtils.stripCastToPlainString`).
+ */
+ private def unwrapCharVarcharRead(e: Expression): Expression = {
Review Comment:
nit: The `ReadSidePadding` / `ReadSideCheck` pair is matched separately both
here (L265-266) and in `EstimationUtils.getAliasStats` (L99 and L106). Since
`ReadSidePadding` has to stay as is for `V2ExpressionBuilder`, how about a
stats-only extractor in `CharVarcharUtils` (e.g. returning the column, the
length, and whether it pads to the length)? Then each site needs a single case,
and a new read-side wrapper only has to be added in one place.
--
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]