dongjoon-hyun commented on code in PR #60168:
URL: https://github.com/apache/spark/pull/60168#discussion_r4571285170
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/ValueInterval.scala:
##########
@@ -80,9 +81,14 @@ object ValueInterval {
*/
def intersect(r1: ValueInterval, r2: ValueInterval, dt: DataType):
(Option[Any], Option[Any]) = {
(r1, r2) match {
- case (_, _: DefaultValueInterval) | (_: DefaultValueInterval, _) =>
- // binary/string types don't support intersecting.
+ case (_: DefaultValueInterval, _: DefaultValueInterval) =>
Review Comment:
**[2] `intersect` now throws for an unknown range paired with a null-only
one.**
Before, `case (_, _: DefaultValueInterval) | (_: DefaultValueInterval, _)`
returned `(None, None)` for any pair with an unknown range, including
`(Default, Null)` and `(Null, Default)`. The new arms accept only
`DefaultValueInterval` and `NumericValueInterval`, so those two pairs now fall
to `case _ => throw pairUnsupportedAtFunctionError`.
This is not reachable today: `JoinEstimation` calls `intersect` only after
`isIntersected`, which now rejects any null-only interval first. But nothing
enforces "This is only for two overlapped intervals". A caller that skips
`isIntersected`, or a change to its arm order, would then fail optimization
where it used to get `(None, None)`. Could the null-only pairs get an explicit
arm, or the doc say that callers must check `isIntersected` first?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -196,16 +196,22 @@ case class JoinEstimation(join: Join) extends Logging {
// Check if the two sides are disjoint
val leftKeyStat = leftStats.attributeStats(leftKey)
val rightKeyStat = rightStats.attributeStats(rightKey)
- val lInterval = ValueInterval(leftKeyStat.min, leftKeyStat.max,
leftKey.dataType)
- val rInterval = ValueInterval(rightKeyStat.min, rightKeyStat.max,
rightKey.dataType)
+ val lInterval = keyInterval(leftKey, leftKeyStat)
+ val rInterval = keyInterval(rightKey, rightKeyStat)
// 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)
+ // If only one key has a known range, the joined keys take it. The
histogram of the other
+ // key may not cover that range, so it is neither used nor propagated.
+ def keepsHistogram(interval: ValueInterval): Boolean =
+ newMin.isEmpty || interval.isInstanceOf[NumericValueInterval]
Review Comment:
**[3] No test covers two numeric keys that both lack min/max.**
This is the plain case of joining two DSv2 tables that report distinct and
null counts but no min/max. There, `intersect` returns `(None, None)`,
`newMin.isEmpty` makes `keepsHistogram` true for both keys, and both histograms
are passed on without min/max.
The new tests cover a key with min/max against one without (the first four),
and a null-only key against one without (the last one), but not this pair. It
was estimated at 0 rows before this PR. A test with two keys like
`key-no-min-max`, with and without histograms, would pin the estimate (`rows *
rows / max(ndv)`) and the stats passed on.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala:
##########
@@ -628,6 +628,120 @@ class JoinEstimationSuite extends StatsEstimationTestBase
{
}
}
+ test("SPARK-61002: a join key without min/max is not taken as holding only
nulls") {
+ // table1 (key-1-5 int, key-5-9 int): (1, 9), (2, 8), (3, 7), (4, 6), (5,
5)
+ // A data source can report the distinct and null counts of a column but
not its min/max.
+ val (noMinMax, noMinMaxStat) = (attr("key-no-min-max"),
+ ColumnStat(distinctCount = Some(3), min = None, max = None,
+ nullCount = Some(0), avgLen = Some(4), maxLen = Some(4)))
+ val noMinMaxTable = StatsTestPlan(
+ outputList = Seq(noMinMax),
+ rowCount = 3,
+ attributeStats = AttributeMap(Seq(noMinMax -> noMinMaxStat)))
+ val join = Join(table1, noMinMaxTable, Inner,
+ Some(EqualTo(nameToAttr("key-1-5"), noMinMax)), JoinHint.NONE)
+ // Estimated by ndv: 5 * 3 / max(5, 3) = 3. The joined keys keep the range
of key-1-5.
+ val joinedColStat = ColumnStat(distinctCount = Some(3), min = Some(1), max
= Some(5),
+ nullCount = Some(0), avgLen = Some(4), maxLen = Some(4))
+ val expectedStats = Statistics(
+ sizeInBytes = 3 * (8 + 4 * 3),
+ rowCount = Some(3),
+ attributeStats = AttributeMap(Seq(
+ nameToAttr("key-1-5") -> joinedColStat, noMinMax -> joinedColStat,
+ nameToAttr("key-5-9") ->
nameToColInfo("key-5-9")._2.copy(distinctCount = Some(3)))))
+ assert(join.stats == expectedStats)
+ }
+
+ test("SPARK-61002: join keys with histograms but without min/max are
estimated by ndv") {
+ val histogram = Histogram(height = 10, Array(
+ HistogramBin(lo = 1, hi = 5, ndv = 5), HistogramBin(lo = 5, hi = 9, ndv
= 4)))
+ val (col1, col2) = (attr("key1"), attr("key2"))
+ val withMinMax = generateJoinChild(col1, histogram, 1, 9)
+ val noMinMax = StatsTestPlan(
+ outputList = Seq(col2),
+ rowCount = 20,
+ attributeStats = AttributeMap(Seq(
+ col2 -> inferColumnStat(histogram, 1, 9).copy(min = None, max =
None))))
+ val join = Join(withMinMax, noMinMax, Inner, Some(EqualTo(col1, col2)),
JoinHint.NONE)
+ // 20 * 20 / max(9, 9), rounded up.
+ assert(join.stats.rowCount == Some(45))
+ }
+
+ test("SPARK-61002: a join key without min/max drops its histogram for the
range of the other") {
+ // The joined keys take the range [1, 5] of `known`. The histogram of
`unknown` covers only
+ // [2, 4], so it is dropped, while the histogram of `known` is kept.
+ val knownHistogram = Histogram(height = 5, Array(
+ HistogramBin(lo = 1, hi = 3, ndv = 3), HistogramBin(lo = 3, hi = 5, ndv
= 3)))
+ val unknownHistogram = Histogram(height = 5, Array(
+ HistogramBin(lo = 2, hi = 3, ndv = 2), HistogramBin(lo = 3, hi = 4, ndv
= 2)))
+ val (known, unknown) = (attr("known"), attr("unknown"))
+ def table(key: AttributeReference, stat: ColumnStat): StatsTestPlan =
+ StatsTestPlan(Seq(key), rowCount = 10, attributeStats =
AttributeMap(Seq(key -> stat)))
+ val knownTable = table(known, ColumnStat(distinctCount = Some(5), min =
Some(1),
+ max = Some(5), nullCount = Some(0), avgLen = Some(4), maxLen = Some(4),
+ histogram = Some(knownHistogram)))
+ val unknownTable = table(unknown, ColumnStat(distinctCount = Some(3), min
= None,
+ max = None, nullCount = Some(0), avgLen = Some(4), maxLen = Some(4),
+ histogram = Some(unknownHistogram)))
+ // 10 * 10 / max(5, 3), rounded up.
+ val joinedColStat = ColumnStat(distinctCount = Some(3), min = Some(1), max
= Some(5),
+ nullCount = Some(0), avgLen = Some(4), maxLen = Some(4))
+ Seq(
+ Join(knownTable, unknownTable, Inner, Some(EqualTo(known, unknown)),
JoinHint.NONE),
+ Join(unknownTable, knownTable, Inner, Some(EqualTo(unknown, known)),
JoinHint.NONE)
+ ).foreach { join =>
+ assert(join.stats.rowCount == Some(20))
+ assert(join.stats.attributeStats(known) ==
+ joinedColStat.copy(histogram = Some(knownHistogram)))
+ assert(join.stats.attributeStats(unknown) == joinedColStat)
+ // A filter estimated with the histogram of `unknown` would read it
outside of its bins.
+ assert(Filter(EqualTo(unknown, Literal(3)),
join).stats.rowCount.isDefined)
Review Comment:
**[5] The filter checks pass with any estimate.**
L696 already checks that `unknown` has no histogram, so these two lines only
check that the estimate does not fail. After the join, `unknown` has 3 distinct
values in `[1, 5]` over 20 rows:
- `unknown = 3` should give ceil(20 / 3) = 7 rows.
- `unknown > 3` should give 20 * (5 - 3) / (5 - 1) = 10 rows.
Asserting `== Some(7)` and `== Some(10)` would also check that the filter
uses the joined min/max and distinct count.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -228,6 +236,19 @@ case class JoinEstimation(join: Join) extends Logging {
(joinCard, AttributeMap(keyStatsAfterJoin))
}
+ /**
+ * Returns the value range of a join key. A key with distinct values but no
min/max (a data
+ * source may not report them, and a union drops them for some types) has an
unknown range, not
+ * only nulls, so it overlaps the other key unless that key holds only nulls.
Review Comment:
**[1] A STRING or BINARY key that holds only nulls still overlaps the other
key.**
This says that a key without min/max overlaps the other key "unless that key
holds only nulls". The description also says "A key with no distinct values
still makes the join empty". Both hold for numeric keys, but not for STRING,
BINARY or CHAR keys:
- For them, `keyInterval` falls through to `ValueInterval.apply`, which
returns a `DefaultValueInterval` even when the distinct count is 0.
- So `isIntersected` returns true, and `noValues` only catches the case
where both keys have a distinct count of 0.
For example, `l.s` (STRING, 10 rows, 10 distinct values) joined with `r.s`
(STRING, 10 rows, a distinct count of 0 and 10 nulls) is estimated at 10 * 10 /
10 = 10 rows. The same stats on INT keys give 0 rows. This extends the [earlier
thread](https://github.com/apache/spark/pull/60168#discussion_r4500569105): the
qualifier added there is accurate only for non-string keys.
In SQL, the `IsNotNull` filter inferred from the join condition usually
empties the null side first. On 4.3.0, a join with an analyzed all-null STRING
column is estimated at 0 rows. So this matters mostly for the doc. Still,
checking the distinct count first would make the doc hold for every type, and
`noValues` would no longer be needed:
```scala
private def keyInterval(key: AttributeReference, keyStat: ColumnStat):
ValueInterval = {
if (keyStat.distinctCount.contains(BigInt(0))) {
new NullValueInterval()
} else if (!keyStat.hasMinMaxStats) {
new DefaultValueInterval()
} else {
ValueInterval(keyStat.min, keyStat.max, key.dataType)
}
}
```
`computeByNdv` would then only see keys with a positive distinct count on
both sides, so it cannot divide by zero.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -228,6 +236,19 @@ case class JoinEstimation(join: Join) extends Logging {
(joinCard, AttributeMap(keyStatsAfterJoin))
}
+ /**
+ * Returns the value range of a join key. A key with distinct values but no
min/max (a data
+ * source may not report them, and a union drops them for some types) has an
unknown range, not
+ * only nulls, so it overlaps the other key unless that key holds only nulls.
+ */
+ private def keyInterval(key: AttributeReference, keyStat: ColumnStat):
ValueInterval = {
Review Comment:
**[6] `ValueInterval.apply` still takes a missing min/max as a column of
nulls.**
`ValueInterval.apply` keeps `case _ if min.isEmpty || max.isEmpty => new
NullValueInterval()`, and this helper works around it for join keys only.
SPARK-56485 did the same in `FilterEstimation`, with a `hasMinMaxStats` check
before each call. So the next caller of `apply` gets the same bug back.
`apply` could take the distinct count (or the `ColumnStat`), and return a
`NullValueInterval` only for a distinct count of 0 and a `DefaultValueInterval`
for a missing min/max. Then `keyInterval` and `noValues` would not be needed.
The `FilterEstimation` callers already check `hasMinMaxStats` before they call
it, so their behavior would not change. This is optional; the helper is fine as
a narrower fix.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala:
##########
@@ -628,6 +628,120 @@ class JoinEstimationSuite extends StatsEstimationTestBase
{
}
}
+ test("SPARK-61002: a join key without min/max is not taken as holding only
nulls") {
Review Comment:
**[4] No test covers an outer join on a key without min/max.**
Before this PR, such a join took the `numInnerJoinedRows == 0` branch: the
outer side kept its stats, and the other side got `nullColumnStat`. Now it goes
through `updateOutputStats`. For example, in `t1 LEFT JOIN t2 ON t1.k = t2.k`
where `t2.k` has no min/max, `t2.k` now takes the range of `t1.k` and the row
count changes. `LeftOuter`, `RightOuter` and `FullOuter` cases would pin which
side gets the joined stats.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -196,16 +196,22 @@ case class JoinEstimation(join: Join) extends Logging {
// Check if the two sides are disjoint
val leftKeyStat = leftStats.attributeStats(leftKey)
val rightKeyStat = rightStats.attributeStats(rightKey)
- val lInterval = ValueInterval(leftKeyStat.min, leftKeyStat.max,
leftKey.dataType)
- val rInterval = ValueInterval(rightKeyStat.min, rightKeyStat.max,
rightKey.dataType)
+ val lInterval = keyInterval(leftKey, leftKeyStat)
+ val rInterval = keyInterval(rightKey, rightKeyStat)
// 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)
+ // If only one key has a known range, the joined keys take it. The
histogram of the other
+ // key may not cover that range, so it is neither used nor propagated.
+ def keepsHistogram(interval: ValueInterval): Boolean =
+ newMin.isEmpty || interval.isInstanceOf[NumericValueInterval]
val (card, joinStat) = (leftKeyStat.histogram, rightKeyStat.histogram)
match {
+ // Histograms are trimmed to the intersected range, so both keys
need a known range.
case (Some(l: Histogram), Some(r: Histogram))
- if canEstimateWithHistogram(leftKey.dataType) =>
+ if canEstimateWithHistogram(leftKey.dataType) &&
newMin.isDefined &&
Review Comment:
**[7] Nit: the histogram guard is the same as "both keys have a known
range".**
`intersect` fills both bounds whenever one key has a known range. With
bounds, `keepsHistogram` rejects the key without one. So `newMin.isDefined &&
newMax.isDefined && keepsHistogram(lInterval) && keepsHistogram(rInterval)` is
the same as:
```scala
lInterval.isInstanceOf[NumericValueInterval] &&
rInterval.isInstanceOf[NumericValueInterval]
```
That says directly what the comment above says.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -214,8 +220,10 @@ case class JoinEstimation(join: Join) extends Logging {
// Histograms are propagated as unchanged. During future estimation,
they should be
Review Comment:
**[8] Nit: this comment no longer matches the code below it.**
It says "Histograms are propagated as unchanged. During future estimation,
they should be truncated by the updated max/min." Now the histogram of a key
without a known range is dropped. When neither key has min/max, the histograms
are passed on with no max/min to truncate them. Could it be merged with the new
comment at L206-L207?
--
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]