This is an automated email from the ASF dual-hosted git repository.
englefly pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new 3acad412154 [fix](stats) Scale column null counts when estimating
filter predicates (#69817)
3acad412154 is described below
commit 3acad412154ed50c973dc1acc540aed994b30042
Author: minghong <[email protected]>
AuthorDate: Mon Nov 23 17:05:17 2026 +0800
[fix](stats) Scale column null counts when estimating filter predicates
(#69817)
### What problem does this PR solve?
Issue Number: N/A
Related PR: N/A
Problem Summary:
`FilterEstimation` reduces the row count of the estimated `Statistics`
for every conjunct, but the
null counts of the columns were only clamped to the new row count
instead of being scaled with it.
The column statistics then no longer matched the row count they were
combined with, and predicates
that estimate from the absolute null count produced wrong results.
Concrete plan (TPCDS store_sales, 28.8B rows): both `ss_customer_sk` and
`ss_sold_date_sk` have
about 4.5% nulls (1,296,000,270 and 1,296,010,052). For
ss_customer_sk is null and not (ss_sold_date_sk is null)
`visitIsNull` estimates the first conjunct as 1,296,000,270 rows
(`visitAnd` then clamps
`ss_sold_date_sk.numNulls` to `rowCount - ndv` = 1,295,998,441), and
`visitNot` estimates the second
conjunct as `rowCount - numNulls` = 1,296,000,270 - 1,295,998,441 =
1829, i.e. exactly the NDV of
`ss_sold_date_sk`. The filter was estimated to output 1829 rows instead
of about 1.24B rows, which
made the join build the 648M-row side and capped the runtime filter NDV
at 1829.
The same inconsistency made a following `is null` predicate use the
base-table null count after an
`in`, a `not`, a `like` or a column-to-column comparison had already
reduced the row count: for
example `a in (1..10) and b is null` was estimated 10x too large.
Fix: scale the null counts of the other columns with the selectivity of
the predicate whenever it
reduces the row count. It is applied to `visitIsNull` (including the
unknown-stats path),
`visitInPredicate` (including the unknown-stats path), `visitNot`,
`visitLike`,
`estimateColumnEqualToColumn`, `estimateColumnLessThanColumn` and the
default/unknown selectivity
paths. The two `visitOr` calls that normalized the children a second
time are removed, because the
children already return statistics consistent with their own row count.
The scaled statistics keep
`numNulls` consistent with `Statistics.rowCount`, so predicates that
combine a null count with the
row count (is-null, not, not-in, not-null selectivity) no longer cancel
each other.
The `Statistics.normalizeColumnStatistics(inputRowCount, boolean)` API
is split into
`enforceValid()` and `rescaleNumNulls(inputRowCount)`: the boolean was
easy to get wrong (the two
modes differ only in whether the null counts are rescaled, and
`inputRowCount` was unused when the
flag was false). `enforceValid` only clamps invalid `ndv`/`numNulls` and
is used after an operator
or a predicate has finished estimating (filter/join/scan/agg);
`rescaleNumNulls` scales the null
counts by `rowCount / inputRowCount` and is used where a predicate just
reduced the row count.
### Release note
None
### Check List (For Author)
- Test: Unit Test
- `FilterEstimationTest#testIsNullAndIsNotNull` reproduces the TPCDS
numbers above: without the
fix the filter is estimated to output 1829 rows, with the fix
1,237,679,772 rows.
- `FilterEstimationTest#testInPredicateScalesNumNulls`,
`#testNotPredicateScalesNumNulls`, `#testLikePredicateScalesNumNulls`
and
`#testColumnToColumnScalesNumNulls` verify that the null count is scaled
by the predicate
selectivity; without the fix the following `is null` predicate is 10x
too large.
- `StatisticsTest#testEnforceValid` and `#testRescaleNumNulls` cover the
split API.
- `FilterEstimationTest` (69), `ExpressionEstimationTest` (17),
`JoinEstimateTest` (3),
`StatsCalculatorTest` (20), `MemoStatsAndCostRecomputerTest` (12) and
`StatisticsTest` (3)
pass, 124 tests in total.
- checkstyle passes.
- `shape_check/tpcds_sf100/shape` (98 suites) produces byte-identical
plan shapes on this
branch and on origin/master (the suite itself fails against the stale
in-repo goldens, which
predate the base commit and are unrelated to this change).
- Behavior changed: No (statistics estimation only)
- Does this need documentation: No
---
.../doris/nereids/stats/FilterEstimation.java | 106 +++++---
.../apache/doris/nereids/stats/JoinEstimation.java | 18 +-
.../doris/nereids/stats/StatsCalculator.java | 4 +-
.../apache/doris/statistics/model/Statistics.java | 66 +++--
.../doris/nereids/stats/FilterEstimationTest.java | 272 ++++++++++++++++++++-
.../doris/statistics/model/StatisticsTest.java | 41 ++++
6 files changed, 434 insertions(+), 73 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/FilterEstimation.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/FilterEstimation.java
index 5507d42c318..ad8a2823af4 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/FilterEstimation.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/FilterEstimation.java
@@ -117,13 +117,15 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
}
outputStats = builder.build();
}
- outputStats.normalizeColumnStatistics();
+ outputStats.enforceValid();
return outputStats;
}
@Override
public Statistics visit(Expression expr, EstimationContext context) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
@Override
@@ -136,7 +138,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
}
for (Expression child : children) {
outputStats = child.accept(this, new
EstimationContext(inputStats));
- outputStats.normalizeColumnStatistics(inputStats.getRowCount(),
false);
+ outputStats.enforceValid();
inputStats = outputStats;
}
return outputStats;
@@ -147,7 +149,13 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
List<Expression> children = or.children();
Set<Slot> leftInputSlots =
Sets.newHashSet(children.get(0).getInputSlots());
Statistics leftStats = children.get(0).accept(this, context);
- leftStats.normalizeColumnStatistics(context.statistics.getRowCount(),
true);
+ // A predicate can return key column statistics whose ndv is larger
than its output row count.
+ // For example `a = b` on 1000 rows with ndv 1000 estimates one row
but keeps ndv 1000 from the
+ // intersected range. The children already scaled their null counts
with their own selectivity, so
+ // only repair the validity here instead of rescaling the null counts
a second time; otherwise the
+ // overlap estimated below, which uses the left child's ndv, is far
too small and the union is
+ // overestimated.
+ leftStats.enforceValid();
Statistics outputStats = leftStats;
Preconditions.checkArgument(children.size() > 1, "and expression
abnormal: " + or);
for (int i = 1; i < children.size(); i++) {
@@ -158,9 +166,15 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
// for the results of derivation. The lower limit may cause
andStats.row > leftStats.row.
double andStatsRowCount = Math.min(andStats.getRowCount(),
leftStats.getRowCount());
Statistics rightStats = child.accept(this, context);
-
rightStats.normalizeColumnStatistics(context.statistics.getRowCount(), true);
+ rightStats.enforceValid();
double rowCount = leftStats.getRowCount() +
rightStats.getRowCount() - andStatsRowCount;
Statistics orStats = context.statistics.withRowCount(rowCount);
+ // A child of the OR may be compound (nested AND/OR) and restore
the input null counts of the
+ // columns it does not touch. Scale them with the selectivity of
this union before the key
+ // columns merged below get their own null counts, otherwise a
following predicate which
+ // estimates from the absolute null count (e.g. `c is null`) uses
the null count of the whole
+ // input and overestimates the overlap with this branch.
+ orStats.rescaleNumNulls(context.statistics.getRowCount());
Set<Slot> rightInputSlots = child.getInputSlots();
for (Slot slot : context.keyColumns) {
@@ -180,6 +194,10 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
orStats.addColumnStats(slot, colBuilder.build());
}
}
+ // The key column statistics merged above use the distinct values
of the union range, which is
+ // not bounded by the union row count. Repair them so the next
child of this OR (and the
+ // returned statistics) work on valid statistics.
+ orStats.enforceValid();
leftStats = orStats;
outputStats = orStats;
leftInputSlots.addAll(child.getInputSlots());
@@ -216,7 +234,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic leftStats, ColumnStatistic rightStats,
EstimationContext context) {
Preconditions.checkArgument(cp.right().isConstant(), "right hand
should be const: " + cp.right());
if (leftStats.isUnKnown || rightStats.isUnKnown) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
Preconditions.checkArgument(rightStats.minValue == rightStats.maxValue,
"stats for const is not valid: " + rightStats);
@@ -266,7 +286,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic leftStats, ColumnStatistic rightStats,
EstimationContext context) {
Preconditions.checkArgument(cp.right().isConstant(), "right hand
should be const: " + cp.right());
if (leftStats.isUnKnown || rightStats.isUnKnown) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
double selectivity;
@@ -318,7 +340,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic leftStats, ColumnStatistic rightStats,
EstimationContext context) {
Preconditions.checkArgument(cp.right().isConstant(), "right hand
should be const: " + cp.right());
if (leftStats.isUnKnown || rightStats.isUnKnown) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
Preconditions.checkArgument(rightStats.minValue == rightStats.maxValue,
"stats for const is not valid: " + rightStats);
@@ -369,7 +393,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic leftStats, ColumnStatistic rightStats,
EstimationContext context) {
Preconditions.checkArgument(cp.right().isConstant(), "right hand
should be const: " + cp.right());
if (leftStats.isUnKnown || rightStats.isUnKnown) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
Preconditions.checkArgument(rightStats.minValue == rightStats.maxValue,
"stats for const is not valid: " + rightStats);
@@ -458,7 +484,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
Statistics filterStatistics = context.statistics.withSel(selectivity);
filterStatistics.addColumnStats(cp.left(),
filterKeyColStatsBuilder.build());
-
filterStatistics.normalizeColumnStatistics(context.statistics.getRowCount(),
true);
+ filterStatistics.rescaleNumNulls(context.statistics.getRowCount());
return filterStatistics;
}
@@ -466,7 +492,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic statsForLeft =
ExpressionEstimation.estimate(cp.left(), context.statistics);
ColumnStatistic statsForRight =
ExpressionEstimation.estimate(cp.right(), context.statistics);
if (statsForLeft.isUnKnown) {
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
// A > cast (1 as xxx), min/max of cast is +infinity/-infinity
// regard the stats for cast as UNKNOWN
@@ -680,7 +708,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
left.accept(new ColumnStatsAdjustVisitor(), equalStats);
}
// normalize column statistics here to sync numNulls by proportion and
ndv by current row count
- equalStats.normalizeColumnStatistics(context.statistics.getRowCount(),
true);
+ equalStats.rescaleNumNulls(context.statistics.getRowCount());
return equalStats;
}
@@ -818,7 +846,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
Expression compareExpr = inPredicate.getCompareExpr();
ColumnStatistic compareExprStats =
ExpressionEstimation.estimate(compareExpr, context.statistics);
if (compareExprStats.isUnKnown || compareExpr instanceof Function) {
- return context.statistics.withSel(DEFAULT_IN_COEFFICIENT);
+ Statistics outputStats =
context.statistics.withSel(DEFAULT_IN_COEFFICIENT);
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
List<Expression> options = inPredicate.getOptions();
@@ -850,6 +880,8 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
selectivity = getNotNullSelectivity(compareExprStats.numNulls,
estimated.getRowCount(),
compareExprStats.ndv, selectivity);
estimated = estimated.withSel(selectivity);
+ estimated.rescaleNumNulls(context.statistics.getRowCount());
+ // add the statistics of the in predicate column after the null counts
are scaled
estimated.addColumnStats(compareExpr, newCompareExprStats);
context.addKeyIfSlot(compareExpr);
return estimated;
@@ -867,7 +899,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
}
Expression child = not.child();
Statistics childStats = child.accept(this, context);
- childStats.normalizeColumnStatistics();
+ childStats.enforceValid();
double rowCount = context.statistics.getRowCount() -
childStats.getRowCount();
if (child instanceof InPredicate
&& Precision.equals(childStats.getRowCount(),
context.statistics.getRowCount(), 0.000001)) {
@@ -948,7 +980,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
}
}
- return statisticsBuilder.build();
+ Statistics outputStats = statisticsBuilder.build();
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
private boolean doubleNearlyEqual(double a, double b) {
@@ -970,7 +1004,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatistic childColStats =
ExpressionEstimation.estimate(isNull.child(), context.statistics);
if (childColStats.isUnKnown()) {
double row = context.statistics.getRowCount() *
DEFAULT_ISNULL_SELECTIVITY;
- return new
StatisticsBuilder(context.statistics).setRowCount(row).build();
+ Statistics outputStats = new
StatisticsBuilder(context.statistics).setRowCount(row).build();
+ outputStats.rescaleNumNulls(context.statistics.getRowCount());
+ return outputStats;
}
double outputRowCount = Math.min(childColStats.numNulls,
context.statistics.getRowCount());
if (!isOnBase(isNull.child(), context)) {
@@ -978,7 +1014,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
// nulls will be generated such as outer join and then we do a
protection
Expression child = isNull.child();
Statistics childStats = child.accept(this, context);
- childStats.normalizeColumnStatistics();
+ childStats.enforceValid();
outputRowCount = Math.max(childStats.getRowCount() *
DEFAULT_ISNULL_SELECTIVITY, outputRowCount);
outputRowCount = Math.max(outputRowCount,
Math.min(1, childStats.getRowCount()));
@@ -990,11 +1026,12 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
.setMinValue(Double.NEGATIVE_INFINITY)
.setNdv(0)
.setHotValues(null);
- StatisticsBuilder builder = new StatisticsBuilder(context.statistics);
- builder.setRowCount(outputRowCount);
- builder.putColumnStatistics(isNull.child(), colBuilder.build());
+ Statistics filterStatistics = new StatisticsBuilder(context.statistics)
+ .setRowCount(outputRowCount).build();
+ filterStatistics.rescaleNumNulls(context.statistics.getRowCount());
+ filterStatistics.addColumnStats(isNull.child(), colBuilder.build());
context.addKeyIfSlot(isNull.child());
- return builder.build();
+ return filterStatistics;
}
static class EstimationContext {
@@ -1047,6 +1084,7 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
* (keepNull ? 1 : leftNotNullSel * rightNotNullSel);
Statistics updatedStatistics = context.statistics.withSel(notNullSel,
numNull);
+ updatedStatistics.rescaleNumNulls(context.statistics.getRowCount());
// update hot values
if (leftStats.getHotValues() != null && rightStats.getHotValues() !=
null) {
Map<Literal, Float> newHotValues = Maps.newHashMap();
@@ -1086,9 +1124,10 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
Statistics statistics;
// Left always less than Right
if (leftRange.getHigh() < rightRange.getLow()) {
- statistics =
-
context.statistics.withRowCount(Math.min(context.statistics.getRowCount() -
leftStats.numNulls,
- context.statistics.getRowCount() -
rightStats.numNulls));
+ statistics = context.statistics.withRowCount(Math.min(
+ context.statistics.getRowCount() - leftStats.numNulls,
+ context.statistics.getRowCount() -
rightStats.numNulls));
+ statistics.rescaleNumNulls(context.statistics.getRowCount());
statistics.addColumnStats(leftExpr, new
ColumnStatisticBuilder(leftStats).setNumNulls(0.0).build());
statistics.addColumnStats(rightExpr, new
ColumnStatisticBuilder(rightStats).setNumNulls(0.0).build());
context.addKeyIfSlot(leftExpr);
@@ -1140,8 +1179,9 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
}
context.addKeyIfSlot(leftExpr);
context.addKeyIfSlot(rightExpr);
- return context.statistics.withSel(sel)
- .addColumnStats(leftExpr, leftColumnStatistic)
+ statistics = context.statistics.withSel(sel);
+ statistics.rescaleNumNulls(context.statistics.getRowCount());
+ return statistics.addColumnStats(leftExpr, leftColumnStatistic)
.addColumnStats(rightExpr, rightColumnStatistic);
} else {
ColumnStatistic leftColumnStatistic = new
ColumnStatisticBuilder(leftStats)
@@ -1158,17 +1198,19 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
.build();
context.addKeyIfSlot(leftExpr);
context.addKeyIfSlot(rightExpr);
- return context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT)
- .addColumnStats(leftExpr, leftColumnStatistic)
+ Statistics filteredStatistics =
context.statistics.withSel(DEFAULT_INEQUALITY_COEFFICIENT);
+
filteredStatistics.rescaleNumNulls(context.statistics.getRowCount());
+ return filteredStatistics.addColumnStats(leftExpr,
leftColumnStatistic)
.addColumnStats(rightExpr, rightColumnStatistic);
}
}
@Override
public Statistics visitLike(Like like, EstimationContext context) {
- StatisticsBuilder statsBuilder = new
StatisticsBuilder(context.statistics);
double rowCount = context.statistics.getRowCount() *
DEFAULT_LIKE_COMPARISON_SELECTIVITY;
- statsBuilder.setRowCount(rowCount);
+ Statistics likeStatistics = new StatisticsBuilder(context.statistics)
+ .setRowCount(rowCount).build();
+ likeStatistics.rescaleNumNulls(context.statistics.getRowCount());
if (like.left() instanceof Slot) {
ColumnStatistic origin =
context.statistics.findColumnStatistics(like.left());
Preconditions.checkArgument(origin != null,
@@ -1177,10 +1219,10 @@ public class FilterEstimation extends
ExpressionVisitor<Statistics, EstimationCo
ColumnStatisticBuilder colBuilder = new
ColumnStatisticBuilder(origin);
colBuilder.setNdv(origin.ndv *
DEFAULT_LIKE_COMPARISON_SELECTIVITY).setNumNulls(0);
colBuilder.setHotValues(null);
- statsBuilder.putColumnStatistics(like.left(), colBuilder.build());
+ likeStatistics.addColumnStats(like.left(), colBuilder.build());
context.addKeyIfSlot(like.left());
}
- return statsBuilder.build();
+ return likeStatistics;
}
private double getNotNullSelectivity(double origNumNulls, double
origRowCount, double origNdv, double origSel) {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/JoinEstimation.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/JoinEstimation.java
index 54548e9d22b..24008b3ddea 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/JoinEstimation.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/JoinEstimation.java
@@ -60,10 +60,6 @@ public class JoinEstimation {
||
connectContext.getSessionVariable().isEnableLowConfidenceEqJoinRemainingConditionDecay();
}
- private static void normalizeColumnStatistics(Statistics outputStats,
Statistics inputStats) {
- outputStats.normalizeColumnStatistics(inputStats.getRowCount(), false);
- }
-
private static EqualPredicate
normalizeEqualPredJoinCondition(EqualPredicate equal, Statistics rightStats) {
boolean changeOrder = equal.left().getInputSlots().stream()
.anyMatch(slot -> rightStats.findColumnStatistics(slot) !=
null);
@@ -359,8 +355,7 @@ public class JoinEstimation {
.putColumnStatistics(rightStats.columnStatistics())
.build();
}
- normalizeColumnStatistics(result,
- join.getJoinType().isLeftSemiOrAntiJoin() ? leftStats :
rightStats);
+ result.enforceValid();
return result;
}
double rowCount = Double.POSITIVE_INFINITY;
@@ -406,7 +401,7 @@ public class JoinEstimation {
}
builder.setRowCount(outputRowCount);
Statistics outputStats = builder.build();
- outputStats.normalizeColumnStatistics();
+ outputStats.enforceValid();
return outputStats;*/
StatisticsBuilder builder;
if (join.getJoinType().isLeftSemiOrAntiJoin()) {
@@ -418,8 +413,7 @@ public class JoinEstimation {
builder.setRowCount(rowCount);
}
Statistics outputStats = builder.build();
- normalizeColumnStatistics(outputStats,
- join.getJoinType().isLeftSemiOrAntiJoin() ? leftStats :
rightStats);
+ outputStats.enforceValid();
return outputStats;
}
}
@@ -441,8 +435,7 @@ public class JoinEstimation {
.putColumnStatistics(rightStats.columnStatistics())
.build();
}
- normalizeColumnStatistics(result,
- join.getJoinType().isAsofLeftInnerJoin() ? leftStats :
rightStats);
+ result.enforceValid();
return result;
}
double rowCount = Double.POSITIVE_INFINITY;
@@ -469,8 +462,7 @@ public class JoinEstimation {
}
builder.setRowCount(rowCount);
Statistics outputStats = builder.build();
- normalizeColumnStatistics(outputStats,
- join.getJoinType().isAsofLeftInnerJoin() ? leftStats :
rightStats);
+ outputStats.enforceValid();
return outputStats;
}
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
index f52d9737517..44becf747b5 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/stats/StatsCalculator.java
@@ -305,7 +305,7 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
newStats = ((GroupPlan) plan.child(0)).getStats();
}
}
- newStats.normalizeColumnStatistics();
+ newStats.enforceValid();
// We ensure that the rowCount remains unchanged in order to make the
cost of each plan comparable.
if (groupExpression.getOwnerGroup().getStatistics() == null) {
@@ -1473,7 +1473,7 @@ public class StatsCalculator extends
DefaultPlanVisitor<Statistics, Void> {
slotToColumnStats.put(outputExpression.toSlot(), columnStat);
}
Statistics aggOutputStats = new Statistics(rowCount, 1,
slotToColumnStats);
- aggOutputStats.normalizeColumnStatistics();
+ aggOutputStats.enforceValid();
return aggOutputStats;
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/statistics/model/Statistics.java
b/fe/fe-core/src/main/java/org/apache/doris/statistics/model/Statistics.java
index 50e1057f29f..943328dbcb4 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/statistics/model/Statistics.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/statistics/model/Statistics.java
@@ -104,7 +104,7 @@ public class Statistics {
public Statistics withRowCountAndEnforceValid(double rowCount) {
Statistics statistics = new Statistics(rowCount, widthInJoinCluster,
expressionToColumnStats, 0, isFromHbo);
- statistics.normalizeColumnStatistics(this.rowCount, false);
+ statistics.enforceValid();
return statistics;
}
@@ -114,39 +114,55 @@ public class Statistics {
return statistics;
}
- // IMPORTANT: it is suggested to do this action after each estimation
critical visiting,
- // since statistics will have serious deviation during the partial
deriving.
- public void normalizeColumnStatistics() {
- normalizeColumnStatistics(this.rowCount);
- }
-
- public void normalizeColumnStatistics(double inputRowCount) {
- normalizeColumnStatistics(inputRowCount, false);
+ /**
+ * Repair the column statistics which are not valid for the current row
count: clamp ndv to the row
+ * count and numNulls to `rowCount - ndv`. The null proportions are not
changed, so this is the method
+ * to call after the estimation of an operator or a predicate, where the
null counts have already been
+ * scaled by the operator or the predicate itself.
+ */
+ public void enforceValid() {
+ for (Entry<Expression, ColumnStatistic> entry :
expressionToColumnStats.entrySet()) {
+ ColumnStatistic columnStatistic = entry.getValue();
+ if (!columnStatistic.isUnKnown() &&
!checkColumnStatsValid(columnStatistic, rowCount)) {
+ entry.setValue(buildValidColumnStatistic(columnStatistic,
columnStatistic.numNulls));
+ }
+ }
}
- public void normalizeColumnStatistics(double inputRowCount, boolean
isNumNullsDecreaseByProportion) {
- double factor = isNumNullsDecreaseByProportion ? rowCount /
inputRowCount : 1.0;
+ /**
+ * Scale the null counts of the columns with `rowCount / inputRowCount`,
i.e. with the selectivity of
+ * the predicate which produced these statistics, and then repair invalid
statistics.
+ *
+ * <p>A null count which is not scaled together with the row count no
longer matches the row count it
+ * is combined with, and a following predicate which estimates from the
absolute null count produces a
+ * wrong result. For example, for `a is null and not b is null`, when both
columns have about 4.5%
+ * nulls, the base-table null count of `b` is almost equal to the row
count left by `a is null`, so
+ * the `not b is null` estimation (`rowCount - numNulls`) cancels all the
remaining rows.
+ */
+ public void rescaleNumNulls(double inputRowCount) {
+ if (inputRowCount <= 0) {
+ enforceValid();
+ return;
+ }
+ double factor = rowCount / inputRowCount;
for (Entry<Expression, ColumnStatistic> entry :
expressionToColumnStats.entrySet()) {
ColumnStatistic columnStatistic = entry.getValue();
- // the following columnStatistic.isUnKnown() judgment is loop
inside since current doris
- // supports partial stats deriving, i.e, allowing part of tables
have stats and other parts don't,
- // or part of columns have stats but other parts don't, especially
join and filter estimation.
if (!columnStatistic.isUnKnown() &&
(!checkColumnStatsValid(columnStatistic, rowCount)
- || isNumNullsDecreaseByProportion &&
columnStatistic.numNulls != 0)) {
- ColumnStatisticBuilder columnStatisticBuilder = new
ColumnStatisticBuilder(columnStatistic);
- double ndv = Math.min(columnStatistic.ndv, rowCount);
- double numNulls = columnStatistic.numNulls;
- if (numNulls > 0) {
- numNulls = Math.max(1, Math.min(columnStatistic.numNulls *
factor, rowCount - ndv));
- }
- columnStatisticBuilder.setNumNulls(numNulls);
- columnStatisticBuilder.setNdv(ndv);
- columnStatistic = columnStatisticBuilder.build();
- expressionToColumnStats.put(entry.getKey(), columnStatistic);
+ || columnStatistic.numNulls != 0)) {
+ double numNulls = columnStatistic.numNulls > 0 ?
columnStatistic.numNulls * factor : 0;
+ entry.setValue(buildValidColumnStatistic(columnStatistic,
numNulls));
}
}
}
+ private ColumnStatistic buildValidColumnStatistic(ColumnStatistic
columnStatistic, double numNulls) {
+ double ndv = Math.min(columnStatistic.ndv, rowCount);
+ if (numNulls > 0) {
+ numNulls = Math.max(1, Math.min(numNulls, rowCount - ndv));
+ }
+ return new
ColumnStatisticBuilder(columnStatistic).setNumNulls(numNulls).setNdv(ndv).build();
+ }
+
public boolean checkColumnStatsValid(ColumnStatistic columnStatistic,
double rowCount) {
return columnStatistic.ndv <= rowCount && columnStatistic.numNulls <=
rowCount - columnStatistic.ndv;
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/FilterEstimationTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/FilterEstimationTest.java
index 115f6786a28..024b83d3f1b 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/FilterEstimationTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/stats/FilterEstimationTest.java
@@ -29,6 +29,7 @@ import org.apache.doris.nereids.trees.expressions.InPredicate;
import org.apache.doris.nereids.trees.expressions.IsNull;
import org.apache.doris.nereids.trees.expressions.LessThan;
import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Like;
import org.apache.doris.nereids.trees.expressions.Not;
import org.apache.doris.nereids.trees.expressions.NullSafeEqual;
import org.apache.doris.nereids.trees.expressions.Or;
@@ -58,6 +59,7 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
class FilterEstimationTest {
@@ -1073,6 +1075,223 @@ class FilterEstimationTest {
Assertions.assertEquals(result.getRowCount(), 90);
}
+ /**
+ * `ss_customer_sk is null and ss_sold_date_sk is not null`
+ *
+ * <p>The first predicate keeps the rows whose `ss_customer_sk` is null,
the second one keeps the rows
+ * whose `ss_sold_date_sk` is not null among them. The null count of
`ss_sold_date_sk` must be scaled
+ * down together with the row count, otherwise the two almost equal
base-table null counts cancel each
+ * other and the filter is estimated to output only a few rows.
+ */
+ @Test
+ public void testIsNullAndIsNotNull() {
+ double rowCount = 28_799_983_563D;
+ SlotReference customer = new SlotReference("ss_customer_sk",
IntegerType.INSTANCE);
+ SlotReference soldDate = new SlotReference("ss_sold_date_sk",
IntegerType.INSTANCE);
+ ColumnStatistic customerStats = new ColumnStatisticBuilder(rowCount)
+
.setNdv(66_253_740).setAvgSizeByte(4).setNumNulls(1_296_000_270D)
+ .setMinValue(1).setMaxValue(65_000_000).build();
+ ColumnStatistic soldDateStats = new ColumnStatisticBuilder(rowCount)
+ .setNdv(1_829).setAvgSizeByte(4).setNumNulls(1_296_010_052D)
+ .setMinValue(2_450_816).setMaxValue(2_452_642).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(rowCount)
+ .putColumnStatistics(customer, customerStats)
+ .putColumnStatistics(soldDate, soldDateStats)
+ .build();
+
+ Expression predicate = new And(new IsNull(customer), new Not(new
IsNull(soldDate)));
+ Statistics outputStats = new FilterEstimation().estimate(predicate,
inputStats);
+
+ double rowsAfterIsNull = customerStats.numNulls;
+ double expected = rowsAfterIsNull * (1 - soldDateStats.numNulls /
rowCount);
+ Assertions.assertEquals(expected, outputStats.getRowCount(), expected
* 0.001);
+ }
+
+ /**
+ * `a in (1, ..., 10) and b is null`
+ *
+ * <p>The in predicate keeps 10% of the rows, so the null count of `b`
must be scaled by the same ratio
+ * before the is-null predicate uses it. Otherwise `b is null` is
estimated with the null count of the
+ * base relation and is 10x too large.
+ */
+ @Test
+ public void testInPredicateScalesNumNulls() {
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic bStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(500)
+ .setMinValue(1).setMaxValue(1_000).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(10_000)
+ .putColumnStatistics(a, aStats)
+ .putColumnStatistics(b, bStats)
+ .build();
+
+ List<Expression> options = new ArrayList<>();
+ for (int i = 1; i <= 10; i++) {
+ options.add(new IntegerLiteral(i));
+ }
+ Statistics inStats = new FilterEstimation().estimate(new
InPredicate(a, options), inputStats);
+ Assertions.assertEquals(1_000, inStats.getRowCount(), 0.01);
+ // only 10% of the 500 nulls are expected within the rows kept by the
in predicate
+ Assertions.assertEquals(50, inStats.findColumnStatistics(b).numNulls,
0.01);
+
+ Statistics result = new FilterEstimation().estimate(new IsNull(b),
inStats);
+ Assertions.assertEquals(50, result.getRowCount(), 0.01);
+ }
+
+ /**
+ * `not (a in (1, ..., 90)) and b is null`
+ *
+ * <p>The not predicate keeps 10% of the rows, so the null count of `b`
must be scaled by the same
+ * ratio before the is-null predicate uses it.
+ */
+ @Test
+ public void testNotPredicateScalesNumNulls() {
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic bStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(500)
+ .setMinValue(1).setMaxValue(1_000).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(10_000)
+ .putColumnStatistics(a, aStats)
+ .putColumnStatistics(b, bStats)
+ .build();
+
+ List<Expression> options = new ArrayList<>();
+ for (int i = 1; i <= 90; i++) {
+ options.add(new IntegerLiteral(i));
+ }
+ Statistics notStats = new FilterEstimation().estimate(
+ new Not(new InPredicate(a, options)), inputStats);
+ Assertions.assertEquals(1_000, notStats.getRowCount(), 0.01);
+ Assertions.assertEquals(50, notStats.findColumnStatistics(b).numNulls,
0.01);
+
+ Statistics result = new FilterEstimation().estimate(new IsNull(b),
notStats);
+ Assertions.assertEquals(50, result.getRowCount(), 0.01);
+ }
+
+ /**
+ * `a like 'x%' and b is null`
+ *
+ * <p>The like predicate keeps 20% of the rows, so the null count of `b`
must be scaled by the same
+ * ratio before the is-null predicate uses it.
+ */
+ @Test
+ public void testLikePredicateScalesNumNulls() {
+ SlotReference a = new SlotReference("a", new VarcharType(10));
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(8).setNumNulls(0).build();
+ ColumnStatistic bStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(500)
+ .setMinValue(1).setMaxValue(1_000).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(10_000)
+ .putColumnStatistics(a, aStats)
+ .putColumnStatistics(b, bStats)
+ .build();
+
+ Statistics likeStats = new FilterEstimation().estimate(
+ new Like(a, new StringLiteral("x%")), inputStats);
+ Assertions.assertEquals(2_000, likeStats.getRowCount(), 0.01);
+ Assertions.assertEquals(100,
likeStats.findColumnStatistics(b).numNulls, 0.01);
+
+ Statistics result = new FilterEstimation().estimate(new IsNull(b),
likeStats);
+ Assertions.assertEquals(100, result.getRowCount(), 0.01);
+ }
+
+ /**
+ * `a = b and c is null`
+ *
+ * <p>The equality of two columns keeps only `1 / max(ndv)` of the rows,
so the null count of `c` must
+ * be scaled by the same ratio before the is-null predicate uses it.
+ */
+ @Test
+ public void testColumnToColumnScalesNumNulls() {
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ SlotReference c = new SlotReference("c", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic bStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic cStats = new ColumnStatisticBuilder(10_000)
+ .setNdv(10).setAvgSizeByte(4).setNumNulls(500)
+ .setMinValue(1).setMaxValue(1_000).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(10_000)
+ .putColumnStatistics(a, aStats)
+ .putColumnStatistics(b, bStats)
+ .putColumnStatistics(c, cStats)
+ .build();
+
+ Statistics equalStats = new FilterEstimation().estimate(new EqualTo(a,
b), inputStats);
+ Assertions.assertEquals(100, equalStats.getRowCount(), 0.01);
+ Assertions.assertEquals(5,
equalStats.findColumnStatistics(c).numNulls, 0.01);
+
+ Statistics result = new FilterEstimation().estimate(new IsNull(c),
equalStats);
+ Assertions.assertEquals(5, result.getRowCount(), 0.01);
+ }
+
+ /**
+ * `((a in (1, 2) or b in (1, 2)) and e is not null) or c is null`
+ *
+ * <p>The left child of the outer OR is compound and reduces the row count
while restoring the input
+ * null count of `c`, which it does not touch. The outer `c is null` then
estimates its overlap with
+ * the base-table null count and the union is wrong. The null count
inherited by the OR output has to
+ * be scaled with the OR selectivity.
+ */
+ @Test
+ public void testNestedOrScalesInheritedNumNulls() {
+ double rowCount = 1_000_000;
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ SlotReference c = new SlotReference("c", IntegerType.INSTANCE);
+ SlotReference e = new SlotReference("e", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new ColumnStatisticBuilder(rowCount)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic bStats = new ColumnStatisticBuilder(rowCount)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic cStats = new ColumnStatisticBuilder(rowCount)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(20_000)
+ .setMinValue(1).setMaxValue(100).build();
+ ColumnStatistic eStats = new ColumnStatisticBuilder(rowCount)
+ .setNdv(100).setAvgSizeByte(4).setNumNulls(0)
+ .setMinValue(1).setMaxValue(100).build();
+ Statistics inputStats = new StatisticsBuilder()
+ .setRowCount(rowCount)
+ .putColumnStatistics(a, aStats)
+ .putColumnStatistics(b, bStats)
+ .putColumnStatistics(c, cStats)
+ .putColumnStatistics(e, eStats)
+ .build();
+
+ List<Expression> options = Lists.newArrayList(new IntegerLiteral(1),
new IntegerLiteral(2));
+ Or innerOr = new Or(new InPredicate(a, options), new InPredicate(b,
options));
+ Statistics innerStats = new FilterEstimation().estimate(innerOr,
inputStats);
+ Assertions.assertEquals(39_600, innerStats.getRowCount(), 0.01);
+ // 20,000 * 39,600 / 1,000,000: the null count of `c` follows the rows
kept by the inner OR
+ Assertions.assertEquals(792,
innerStats.findColumnStatistics(c).numNulls, 0.01);
+
+ Expression predicate = new Or(new And(innerOr, new Not(new
IsNull(e))), new IsNull(c));
+ Statistics result = new FilterEstimation().estimate(predicate,
inputStats);
+ // 39,600 + 20,000 - 792
+ Assertions.assertEquals(58_808, result.getRowCount(), 0.01);
+ }
+
/**
* a = 1
*/
@@ -1390,6 +1609,57 @@ class FilterEstimationTest {
Assertions.assertEquals(7, resultNse.getRowCount() -
resultEq.getRowCount());
}
+ /**
+ * `(a = b) or (a <=> b)`
+ *
+ * <p>`a = b` is a subset of `a <=> b`, so the OR has to be estimated like
the null-safe equality:
+ * 1000 rows with ndv 1000 give one row. The equality leaves key
statistics whose ndv (1000) is larger
+ * than its output row count (1); if they are not repaired before the
overlap is estimated, the
+ * overlap becomes 1/1000 row and the union is estimated as 1.999 rows.
+ */
+ @Test
+ public void testOrEqualAndNullSafeEqualOverlap() {
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new
ColumnStatisticBuilder(1000).setNdv(1000).setAvgSizeByte(4)
+
.setNumNulls(0).setDataSize(0).setMinValue(1).setMaxValue(1000).build();
+ ColumnStatistic bStats = new
ColumnStatisticBuilder(1000).setNdv(1000).setAvgSizeByte(4)
+
.setNumNulls(0).setDataSize(0).setMinValue(1).setMaxValue(1000).build();
+ StatisticsBuilder statsBuilder = new StatisticsBuilder();
+ statsBuilder.setRowCount(1000);
+ statsBuilder.putColumnStatistics(a, aStats);
+ statsBuilder.putColumnStatistics(b, bStats);
+
+ Or or = new Or(new EqualTo(a, b), new NullSafeEqual(a, b));
+ Statistics result = new FilterEstimation().estimate(or,
statsBuilder.build());
+ Assertions.assertEquals(1.0, result.getRowCount(), 0.01);
+ }
+
+ /**
+ * `(a < b) or (a = 5)`
+ *
+ * <p>The column-to-column comparison leaves the ndv of `a` (1000) larger
than the 500 rows it
+ * estimates. The following `a = 5` has to be estimated with the valid ndv
(500), otherwise the
+ * overlap is 0.5 row instead of one row and the union is estimated as
500.5 rows.
+ */
+ @Test
+ public void testOrColumnComparisonUsesValidKeyStatistics() {
+ SlotReference a = new SlotReference("a", IntegerType.INSTANCE);
+ SlotReference b = new SlotReference("b", IntegerType.INSTANCE);
+ ColumnStatistic aStats = new
ColumnStatisticBuilder(1000).setNdv(1000).setAvgSizeByte(4)
+
.setNumNulls(0).setDataSize(0).setMinValue(1).setMaxValue(1000).build();
+ ColumnStatistic bStats = new
ColumnStatisticBuilder(1000).setNdv(1000).setAvgSizeByte(4)
+
.setNumNulls(0).setDataSize(0).setMinValue(1).setMaxValue(1000).build();
+ StatisticsBuilder statsBuilder = new StatisticsBuilder();
+ statsBuilder.setRowCount(1000);
+ statsBuilder.putColumnStatistics(a, aStats);
+ statsBuilder.putColumnStatistics(b, bStats);
+
+ Or or = new Or(new LessThan(a, b), new EqualTo(a, new
IntegerLiteral(5)));
+ Statistics result = new FilterEstimation().estimate(or,
statsBuilder.build());
+ Assertions.assertEquals(500.0, result.getRowCount(), 0.01);
+ }
+
/**
* for string literal, min-max range is only used for coverage, not for
percentage
*/
@@ -1695,7 +1965,7 @@ class FilterEstimationTest {
* estimated output rows is zero.
* But after 2020-01-01, some rows are inserted, called delta rows.
* we will estimate output based on deltaRows, and assume all column stats
are unknown.
- * after estimation, we will put col stats back except A, and run
Statistics.normalizeColumnStatistics().
+ * after estimation, we will put col stats back except A, and run
Statistics.enforceValid().
*/
@Test
void testDeltaRow() {
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/statistics/model/StatisticsTest.java
b/fe/fe-core/src/test/java/org/apache/doris/statistics/model/StatisticsTest.java
index d50e15c973b..8adcd2ed504 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/statistics/model/StatisticsTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/statistics/model/StatisticsTest.java
@@ -17,6 +17,7 @@
package org.apache.doris.statistics.model;
+import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.SlotReference;
import org.apache.doris.nereids.types.IntegerType;
@@ -25,6 +26,9 @@ import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import java.util.HashMap;
+import java.util.Map;
+
public class StatisticsTest {
@Test
public void testAvgSizeAbnormal() {
@@ -50,4 +54,41 @@ public class StatisticsTest {
tupleSize = stats.computeTupleSize(ImmutableList.of(slot));
Assertions.assertEquals(1, tupleSize);
}
+
+ @Test
+ public void testEnforceValid() {
+ SlotReference slot = SlotReference.of("a", IntegerType.INSTANCE);
+ ColumnStatistic columnStatistic = new ColumnStatisticBuilder(1000)
+ .setNdv(80).setNumNulls(50).setAvgSizeByte(4).build();
+ Statistics stats = statisticsOf(slot, columnStatistic, 100);
+ stats.enforceValid();
+ ColumnStatistic result = stats.findColumnStatistics(slot);
+ Assertions.assertEquals(80, result.ndv, 0.01);
+ // numNulls is clamped to `rowCount - ndv`, but not scaled by the row
count change
+ Assertions.assertEquals(20, result.numNulls, 0.01);
+ }
+
+ @Test
+ public void testRescaleNumNulls() {
+ SlotReference slot = SlotReference.of("a", IntegerType.INSTANCE);
+ ColumnStatistic columnStatistic = new ColumnStatisticBuilder(1000)
+ .setNdv(10).setNumNulls(200).setAvgSizeByte(4).build();
+ Statistics stats = statisticsOf(slot, columnStatistic, 100);
+ // 100 / 1000 of the input rows are kept
+ stats.rescaleNumNulls(1000);
+ Assertions.assertEquals(20, stats.findColumnStatistics(slot).numNulls,
0.01);
+
+ // a non-positive input row count only repairs the statistics and does
not produce NaN
+ ColumnStatistic zeroInput = new ColumnStatisticBuilder(1000)
+ .setNdv(10).setNumNulls(200).setAvgSizeByte(4).build();
+ Statistics zeroInputStats = statisticsOf(slot, zeroInput, 100);
+ zeroInputStats.rescaleNumNulls(0);
+ Assertions.assertEquals(90,
zeroInputStats.findColumnStatistics(slot).numNulls, 0.01);
+ }
+
+ private static Statistics statisticsOf(SlotReference slot, ColumnStatistic
columnStatistic, double rowCount) {
+ Map<Expression, ColumnStatistic> columnStats = new HashMap<>();
+ columnStats.put(slot, columnStatistic);
+ return new Statistics(rowCount, 1, columnStats);
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]