Repository navigation
HIVE-29625: Disambiguate ColStatistics.countDistinct "unknown" from "verified zero" - #6505
konstantinb wants to merge 29 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved statistics-estimation defects inflate multi-key group counts and mishandle all-NULL filters, producing incorrect cardinality estimates and potentially inappropriate aggregation choices.
3 open issues
What changed in this PR
This PR separates unknown distinct-value counts (-1) from verified zero in Hive’s statistics pipeline, allowing planner rules to apply different estimates for missing and empty domains.
Changes:
- Updates statistics producers, merging, and scaling to preserve unknown NDVs.
- Adjusts filter, join, grouping, and partition-planning consumers.
- Adds parameterized unit tests and join regressions, with two existing binary-column plan outputs updated.
| File | Description |
|---|---|
ql/src/test/results/clientpositive/llap/vector_binary_join_groupby.q.out |
Updates binary-key probe ratio. |
ql/src/test/results/clientpositive/llap/parquet_types_non_dictionary_encoding_vectorization.q.out |
Updates binary GROUP BY estimates. |
ql/src/test/results/clientpositive/llap/join_ndv_unknown_mixed.q.out |
Records mixed-NDV join estimates. |
ql/src/test/results/clientpositive/llap/join_ndv_unknown_mixed_multikey.q.out |
Records multi-key inner and outer join estimates. |
ql/src/test/queries/clientpositive/join_ndv_unknown_mixed.q |
Adds a mixed known/unknown join regression. |
ql/src/test/queries/clientpositive/join_ndv_unknown_mixed_multikey.q |
Adds correlated multi-key join regressions. |
ql/src/test/org/apache/hadoop/hive/ql/stats/TestStatsUtils.java |
Tests NDV production, merging, grouping, and scaling. |
ql/src/test/org/apache/hadoop/hive/ql/stats/estimator/TestPessimisticStatCombiner.java |
Tests unknown NDV propagation. |
ql/src/test/org/apache/hadoop/hive/ql/optimizer/TestSortedDynPartitionOptimizer.java |
Tests partition-cardinality handling. |
ql/src/test/org/apache/hadoop/hive/ql/optimizer/TestSetHashGroupByMinReduction.java |
Tests aggregation-reduction decisions. |
ql/src/test/org/apache/hadoop/hive/ql/optimizer/TestReduceSinkMapJoinProc.java |
Tests hash-join key-count estimates. |
ql/src/test/org/apache/hadoop/hive/ql/optimizer/stats/annotation/TestStatsRulesProcFactory.java |
Migrates to JUnit 5 and expands statistics-rule coverage. |
ql/src/test/org/apache/hadoop/hive/ql/optimizer/calcite/stats/TestHiveRelMdDistinctRowCount.java |
Tests distinct-row metadata boundaries. |
ql/src/java/org/apache/hadoop/hive/ql/stats/StatsUtils.java |
Introduces unknown-aware producers and shared helpers. |
ql/src/java/org/apache/hadoop/hive/ql/stats/estimator/PessimisticStatCombiner.java |
Uses unknown-aware maximum merging. |
ql/src/java/org/apache/hadoop/hive/ql/plan/Statistics.java |
Preserves unknown NDVs during merges. |
ql/src/java/org/apache/hadoop/hive/ql/optimizer/stats/annotation/StatsRulesProcFactory.java |
Updates filter, grouping, and join estimates. |
ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionOptimizer.java |
Treats negative NDVs as unavailable statistics. |
ql/src/java/org/apache/hadoop/hive/ql/optimizer/SetHashGroupByMinReduction.java |
Preserves configured reduction for unknown NDVs. |
ql/src/java/org/apache/hadoop/hive/ql/optimizer/ReduceSinkMapJoinProc.java |
Separates unknown and zero key counts. |
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/stats/HiveRelMdDistinctRowCount.java |
Prevents negative distinct-row metadata. |
Review effort: Balanced
| if (dvs == 0) { | ||
| return 0; |
There was a problem hiding this comment.
Fixed in dcaac90 for the case this PR introduced: a verified-zero NDV means every row is NULL, so col <=> NULL (either operand order) now keeps all rows. Unknown and known NDVs keep master's estimates; using numNulls there too would change master's behavior, so that's left for a follow-up.
| } | ||
| ndv = parentNumRows / 2; | ||
| } | ||
| numEstimatedRows = StatsUtils.safeMult(numEstimatedRows, ndv); |
There was a problem hiding this comment.
Agreed: this changed master's decision, including for a single unknown key on a large input. Fixed in d69875a: an unknown NDV now keeps master's outcome (unknown was stored as 0, so the estimated hash table was empty), and the known-NDV product, which predates this PR, is unchanged.
There was a problem hiding this comment.
Update: after a later review question (r4675031550), a90be13 replaces the master-parity guard described above. The table is now sized once with the GROUP BY's grouping cardinality, so the per-key parentNumRows / 2 inflation does not return, but an unknown key on a large input can now take the no-hash-aggregation branch, unlike master. Grouping-set expansion is still not counted in the memory check, as on master.
thomasrebele
left a comment
There was a problem hiding this comment.
Thank you for the PR, @konstantinb! Sorry for the late reply, this has been on my TODO list for a long time.
This PR doesn't seem to change FilterStatsRule itself. It's quite related, so I had a first look. I had a look at the non-test files, and the changes that I understood looked reasonable (I need to take another deeper look at StatsRulesProcFactory). I wonder whether this PR covers all parts of the code that need to be changed. I would still need to check that.
| return numRows / 2; | ||
| } | ||
| if (dvs == 0) { | ||
| // no non-null values: only col <=> NULL can match, and then every row does |
There was a problem hiding this comment.
Could you explain this? What does <=> mean? "not equals"? If that's the case I would prefer using !=.
There was a problem hiding this comment.
Could you explain this? What does
<=>mean? "not equals"? If that's the case I would prefer using!=.
<=> is Hive's null-safe equality operator (IS NOT DISTINCT FROM), not inequality; I've clarified the comment while retaining the SQL notation. This branch addresses Copilot's earlier finding: with a verified-zero NDV, every row is NULL, so col <=> NULL must keep every row.
okumin
left a comment
There was a problem hiding this comment.
I currently feel the intention is good and the regression is not disruptive; still checking file by file, but in my impression, so far so good.
| for (ColStatistics cStat : colStats) { | ||
| // unknown (< 0) or zero NDV yields 0; null (Calcite's | ||
| // "unknown") would need matching guards in | ||
| // HiveRelMdRowCount's PK-FK analysis |
There was a problem hiding this comment.
What if this returns null? Does it require major surgery, or do existing tests go wrong? Zero sounds better than negatives anyway, though.
There was a problem hiding this comment.
Done in 45c29a0: HiveRelMdDistinctRowCount now returns null for an unknown NDV. That was this PR's original design (bed032d), reverted in f5b19e9 as too intrusive. Null alone broke planning: explain cbo joincost with a filter on an unknown-NDV column hit an NPE in Calcite's RelMdUtil.estimateFilteredRows, and joins on RELY PK/FK constraints failed. So each reader got a guard, all following one rule: an unknown NDV never lowers an estimate below what the previous head of this PR estimated, and never discards a known value.
- PK-FK row count: unknown is the existing "not computed" -1; an unknown ratio means every FK row matches.
- Selectivity returned to Calcite: a predicate the statistics can't estimate keeps every row; unknown join keys are skipped, and the known ones still bound the join.
- A filter above an anti join that depends on an unknown NDV keeps every row. That filter is inverted, so the fallback values would otherwise turn into near-zero estimates.
FilterSelectivityEstimator: NOT and SEARCH propagate the unknown instead of unboxing it.
No existing golden changed (229 related qtests and the TPC-DS plan suites re-run). Two new qtests, cbo_ndv_unknown_estimates.q and cbo_ndv_unknown_pkfk.q, print each estimate next to the actual row count, and unit tests cover every changed line and branch.
Co-Authored-By: Treasure Work <291137728+treasure-work@users.noreply.github.com>
| if (cs.getCountDistint() < 0) { | ||
| // unknown NDV: the hash table cannot be sized. Keep the decision made when unknown | ||
| // was stored as 0: an empty estimated table, so only the memory budget matters. | ||
| return maxMemHashAgg > 0; |
There was a problem hiding this comment.
Does this condition make sense after we merge this PR? I suspect this formula is too influenced by the original implementation that abused NDV = 0 for two semantics.
There was a problem hiding this comment.
You're right: for an unknown NDV, return maxMemHashAgg > 0 only reproduced what NDV = 0 used to give (an empty estimated table). It was my answer to an earlier review comment (r4461508408) about applying parentNumRows / 2 per unknown key. In a90be13, checkMapSideAggregation sizes the table with the grouping cardinality the GROUP BY row estimate already uses (computeNDVGroupingColumns, with its parentNumRows / 2 fallback for unknown keys). Unknown keys count once, not per key, and a key with NULLs adds the NULL group, so an all-NULL key no longer makes the table look empty. Compared with master, estimates can only go up: when the table counted this way does not fit in the hash-aggregation memory, the map-side GROUP BY is estimated without reduction (rows instead of rows / 2). With unknown keys and the default memory settings, that happens above roughly 6-8 million input rows.
|
@konstantinb |
thomasrebele
left a comment
There was a problem hiding this comment.
During the second review round, I had a thought: wouldn't it be cleaner and more future-proof to use something more special than negative values to state that the NDV is unknown? E.g., OptionalLong?
| // if ndvProduct is 0 then column stats state must be partial and we are missing | ||
| // column stats for a group by column | ||
| if (ndvProduct == 0) { | ||
| if (ndvProduct < 0) { |
There was a problem hiding this comment.
The ndvProduct is calculated by computeNDVGroupingColumns which calls StatsUtils#safeMult, but the latter only handles positive saturation correctly.
long a = Integer.MIN_VALUE;
long b = 2000L * Integer.MAX_VALUE;
System.out.println(a + " * " + b + " = " + StatsUtils.safeMult(a, b) + " ?");
prints
-2147483648 * 4294967294000 = 9223372036854775807 ?
I think StatsUtils#safeMult should use LongMath.saturatedMultiply instead of catching the exception.
There was a problem hiding this comment.
Good catch on the helper itself: safeMult and safeAdd (from HIVE-8689) turn every overflow into Long.MAX_VALUE, so a negative overflow saturates the wrong way. It can't happen here: computeNDVGroupingColumns returns -1 as soon as a key's NDV is unknown, before multiplying, so safeMult only sees non-negative operands and ndvProduct < 0 still means only "unknown". The other callers combine row counts, data sizes, NDVs and null counts, which are non-negative, and for such quantities MAX_VALUE on any overflow matches the convention of StatsUtils.getMaxIfOverflow. LongMath.saturatedMultiply would instead return Long.MIN_VALUE where an operand has already wrapped negative, for example the 1L << 63 slot count in ConvertJoinMapJoin.computeOnlineDataSizeGeneric for very large row counts, which would make the hash table look tiny. So I'd rather keep it out of this PR; I can open a follow-up to document the non-negative contract.
|
Thank you for all the reviews; I am currently struggling with addressing full impact of the question #6505 (comment) It was in my original draft and was later decided against as "too intrusive", but digging deeper brings up more potential side effects/impacted queries. |
HiveRelMdDistinctRowCount returns null (Calcite's "no reliable estimate") for an unknown NDV instead of 0. The PK-FK row count, join and filter selectivity, NOT and SEARCH paths handle the null so that an unknown NDV never lowers an estimate below the previous one; a filter above an anti join that depends on an unknown NDV keeps every row. Removes an unreachable PK-FK block in getRowCountInt. Adds unit tests and two qtest files that print each estimate next to the actual row count.
calculateUnmatchedRowsForOuter: drop the redundant distinctVal <= 0 test. Once distinctUnmatched < 0 has returned, distinctUnmatched >= distinctVal already covers it. No behaviour change. TestStatsRulesProcFactory: remove the no-op (Number) casts on ColStatistics.Range.minValue/maxValue, which are already Number. This includes four assertions added by HIVE-29438 that the new ones were copied from.
…ardinality checkMapSideAggregation now uses the same group estimate as the GROUP BY row estimate: unknown keys fall back once to rows / 2 instead of short-circuiting to "fits", and the NULL group counts, so an all-NULL key no longer makes the table look empty. A GROUP BY with unknown-NDV keys on an input too large for the hash-aggregation memory is now estimated without map-side reduction.
@thomasrebele I agree it would be cleaner: with
I'd propose a follow-up JIRA that converts the four fields together, possibly keeping deprecated |
…ropagation NPE fix Regenerate nested_column_pruning, orc_nested_column_pruning and vector_orc_nested_column_pruning. Only EXPLAIN plan text changes: the AND conjuncts in the filter over t2 are reordered, and the vectorized variant renumbers the affected scratch columns. Cause: before 45c29a0, FilterSelectivityEstimator unboxed the null estimate for NOT over an operand with an unknown estimate and threw NullPointerException. HiveFilterSortPredicates caught it and returned the filter unsorted when column stats were reported missing. Now NOT returns null, sorting completes, and nullsLast places the unknown conjunct after IS NOT NULL. Query results are unchanged
| TableScan | ||
| alias: t2 | ||
| filterExpr: ((not s2.f8.f9) and s1.f6 is not null) (type: boolean) | ||
| filterExpr: (s1.f6 is not null and (not s2.f8.f9)) (type: boolean) |
There was a problem hiding this comment.
Consequence of the NOT null guard in 45c29a03e3. Estimating this nested boolean field returns null; previously NOT unboxed it and threw an NPE. With missing column stats, the sorter's exception fallback preserved the original order. Now NOT propagates null, sorting completes, and the existing nullsLast comparator places it after IS NOT NULL. Query results are unchanged; no runtime benefit is claimed.
| TableScan | ||
| alias: t2 | ||
| filterExpr: ((not s2.f8.f9) and s1.f6 is not null) (type: boolean) | ||
| filterExpr: (s1.f6 is not null and (not s2.f8.f9)) (type: boolean) |
There was a problem hiding this comment.
Same predicate-order change as in nested_column_pruning.q.out, caused by the NOT null guard in 45c29a03e3: sorting now completes instead of retaining the input order after the caught NPE, and the unknown-ranked NOT conjunct sorts last. Only EXPLAIN text changes; query results are unchanged.
| native: true | ||
| predicateExpression: FilterExprAndExpr(children: SelectColumnIsFalse(col 10:boolean)(children: VectorUDFStructField(col 9:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>, col 0:int)(children: VectorUDFStructField(col 2:struct<f7:string,f8:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>>, col 1:int) -> 9:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>) -> 10:boolean), SelectColumnIsNotNull(col 11:int)(children: VectorUDFStructField(col 1:struct<f1:boolean,f2:string,f3:struct<f4:int,f5:double>,f6:int>, col 3:int) -> 11:int)) | ||
| predicate: ((not s2.f8.f9) and s1.f6 is not null) (type: boolean) | ||
| predicateExpression: FilterExprAndExpr(children: SelectColumnIsNotNull(col 9:int)(children: VectorUDFStructField(col 1:struct<f1:boolean,f2:string,f3:struct<f4:int,f5:double>,f6:int>, col 3:int) -> 9:int), SelectColumnIsFalse(col 11:boolean)(children: VectorUDFStructField(col 10:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>, col 0:int)(children: VectorUDFStructField(col 2:struct<f7:string,f8:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>>, col 1:int) -> 10:struct<f9:boolean,f10:array<int>,f11:map<string,boolean>>) -> 11:boolean)) |
There was a problem hiding this comment.
Vectorized form of the same reorder caused by the NOT null guard in 45c29a03e3. The IS NOT NULL child now runs first. Scratch-column numbering follows expression order, including the reduce-sink key changing from col 10 to col 9 below; the computed values and query results are unchanged. Both conjuncts pass the single right-hand row in this fixture, so this does not demonstrate a runtime improvement.
| private final double childCardinality; | ||
| private final RelMetadataQuery mq; | ||
| private final RexBuilder rexBuilder; | ||
| private boolean unknownSeen; |
There was a problem hiding this comment.
This mutable state might add complexity. Once unknownSeen becomes true, it never resets, even when the visitor is used to estimate another expression (though that might not happen). I suspect this state was introduced because we sometimes (i.e., ANTI JOIN only) want to propagate unknown and sometimes do not; there is likely a workaround for the inconsistency, and it looks like we should fix the inconsistency ideally.
Fixing these inconsistencies may be out of scope for this ticket. If so, we could keep the previous implementation and have HiveRelMdDistinctRowCount return zero when the NDV is unknown. Compared with the existing Hive code, that would at least prevent negative NDVs from reaching Calcite. We could handle proper null propagation and consistent fallback behavior in a separate change.
Zero sounds better than negatives anyway, though.
There was a problem hiding this comment.
If it is already clear that only ANTI JOIN is a special case, we can add a new flag for the second mode to ensure referential transparency.
private Double computeConjunctionSelectivity(RexCall call) {
Double tmpSelectivity;
double selectivity = 1;
for (RexNode cje : call.getOperands()) {
tmpSelectivity = cje.accept(this);
if (tmpSelectivity != null) {
selectivity *= tmpSelectivity;
} else if (newFlag) {
return null;
}
}
return selectivity;
}
There was a problem hiding this comment.
Thanks, done in 3241f0c. unknownSeen is gone; FilterSelectivityEstimator now takes an immutable propagateUnknown flag. Only the filter-above-anti-join estimate in HiveRelMdSelectivity uses it, since that is the only place that inverts the estimate (1 - selectivity).
The flag also covers OR (multi-range SEARCH shares that code): OR treats an unknown part as 0.99, which the inversion turns into about 0.01. With only AND propagating, the existing LIMIT + OR case in cbo_ndv_unknown_estimates.q drops from 300 rows to 3 (actual 298). I added an AND case next to it: 300 rows, actual 296; without the AND branch it would be 1.2.
I kept null rather than zero: Calcite floors a 0 NDV to 1, so an unknown key would again look like a single distinct value (GROUP BY on an unknown key: 1 row with zero, 50 now, actual 309).
Agreed that the inversion itself is the real inconsistency. It is pre-existing on master (the disabled knownFilterAboveAntiJoinKeepsItsSelectivity test documents it), so I'd handle it in a separate JIRA.
There was a problem hiding this comment.
In this comment, I have two assumptions.
- No degradation would happen if
HiveRelMdDistinctRowCount#getDistinctRowCountreturned 0.0 where the original implementation returned zero or a negative number - We don't have clear evidence why we should handle only ANTI JOIN differently
I understand that inverting the fallback can produce very small estimates. My concern, however, is the asymmetry: the same AND/OR expression propagates unknown estimates only when used for a filter above an ANTI JOIN. The immutable flag removes the mutable state, but it does not resolve this inconsistency.
Let me explain how I see this as a reviewer.
- The earlier implementation returned zero for unknown NDVs. Calcite uses null to represent unknown, so zero is not ideal. However, returning zero at least prevents negative NDVs from reaching Calcite, and some existing callers assume a non-null result. My question was whether switching to null would require substantial changes or break existing tests. > "What if this returns null? Does it require major surgery, or do existing tests go wrong?"
- The revised implementation returns null, but handles its propagation differently depending on the caller. "If it is already clear that only ANTI JOIN is a special case" has not been satisfied at this point. The partial and incomplete patch introduces some tech debt; we have to read why only ANTI JOIN is specially handled.
If keeping that fallback does not introduce regressions relative to master, I would prefer to keep this PR focused on distinguishing unknown NDVs from verified zero. We could retain the zero fallback at the Calcite boundary temporarily and address consistent unknown propagation, including the ANTI JOIN behavior, in a separate ticket.
Please feel free to ask me if you would like me to clarify my expectations 👍
There was a problem hiding this comment.
Thanks, that clarifies it. To answer your original question ("Does it require major surgery, or do existing tests go wrong?") with what we found: yes to both. It took major surgery: null guards in four Calcite classes (PK-FK analysis, the selectivity entry points, NOT and SEARCH), two new test classes, and finally the anti-join-only mode you object to. Existing tests went wrong as well: three existing nested-column-pruning goldens changed, and five cases in this PR's own TestHiveRelMdDistinctRowCount that pinned 0.0 had to change. Without the guards, a PK-FK join on RELY constraints also failed with an NPE.
Before I change anything, let me confirm the plan:
- Revert the null work (45c29a0, 9cc9cfb, 85b3980, 3241f0c). The Calcite stats classes then match eda2c8d exactly:
HiveRelMdDistinctRowCountreturns 0.0 for an unknown or zero NDV, and there is no anti-join special case. - That also drops the null-safety fixes that came with it, including the NOT/SEARCH handling and the lateral-view NPE fix (that NPE also happens on master), and the tests added for them (
TestHiveRelMdRowCount,TestHiveRelMdSelectivity,cbo_ndv_unknown_estimates.q,cbo_ndv_unknown_pkfk.q). - Regressions vs master: in our earlier comparison of master with the zero-fallback revision, estimates matched in every measured case except one: an IN list on an int column with a stored
numDVs = -1fails on master with anAssertionErrorand is estimated normally with the fallback. I'll re-run the affected tests after the revert. - Consistent unknown propagation, including the anti-join behavior and the inversion of filters above anti joins, goes to a separate ticket.
Does that match what you had in mind, or would you like any part of the null work kept here?
There was a problem hiding this comment.
The list is aligned with me.
- Revert all or the vast majority and rework on another PR with proper subject-matter experts: 45c29a0, 9cc9cfb, 85b3980, 3241f0c
- Keep: ecb61df
That also drops the null-safety fixes that came with it, including the NOT/SEARCH handling and the lateral-view NPE fix (that NPE also happens on master), and the tests added for them (TestHiveRelMdRowCount, TestHiveRelMdSelectivity, cbo_ndv_unknown_estimates.q, cbo_ndv_unknown_pkfk.q).
Unless a degradation happens, it sounds fine.
I can also agree with (3) and (4).
| Sarg.of(RexUnknownAs.UNKNOWN, ImmutableRangeSet.of(Range.closed(BigDecimal.ONE, BigDecimal.TEN))), | ||
| inputRef0.getType()); | ||
| RexNode predicate = REX_BUILDER.makeCall(SqlStdOperatorTable.SEARCH, inputRef0, range); | ||
| Assert.assertNotNull(new FilterSelectivityEstimator(scan, mq).estimateSelectivity(predicate)); |
There was a problem hiding this comment.
If I understand correctly, this can assert a floating point with delta
| REX_BUILDER.makeCall(SqlStdOperatorTable.EQUALS, inputRef0, int1), | ||
| REX_BUILDER.makeCall(SqlStdOperatorTable.EQUALS, inputRef0, int2)); | ||
| Assert.assertNull(new FilterSelectivityEstimator(scan, mq, true).estimateSelectivity(predicate)); | ||
| Assert.assertNotNull(new FilterSelectivityEstimator(scan, mq).estimateSelectivity(predicate)); |
There was a problem hiding this comment.
ditto. This file includes both Assert.assertNotNull(...) and Assert.assertEquals(n, ..., DELTA). Please use the latter pattern for all so that we can ensure FilterSelectivityEstimator does not return undesirable values
| private final double childCardinality; | ||
| private final RelMetadataQuery mq; | ||
| private final RexBuilder rexBuilder; | ||
| private boolean unknownSeen; |
There was a problem hiding this comment.
In this comment, I have two assumptions.
- No degradation would happen if
HiveRelMdDistinctRowCount#getDistinctRowCountreturned 0.0 where the original implementation returned zero or a negative number - We don't have clear evidence why we should handle only ANTI JOIN differently
I understand that inverting the fallback can produce very small estimates. My concern, however, is the asymmetry: the same AND/OR expression propagates unknown estimates only when used for a filter above an ANTI JOIN. The immutable flag removes the mutable state, but it does not resolve this inconsistency.
Let me explain how I see this as a reviewer.
- The earlier implementation returned zero for unknown NDVs. Calcite uses null to represent unknown, so zero is not ideal. However, returning zero at least prevents negative NDVs from reaching Calcite, and some existing callers assume a non-null result. My question was whether switching to null would require substantial changes or break existing tests. > "What if this returns null? Does it require major surgery, or do existing tests go wrong?"
- The revised implementation returns null, but handles its propagation differently depending on the caller. "If it is already clear that only ANTI JOIN is a special case" has not been satisfied at this point. The partial and incomplete patch introduces some tech debt; we have to read why only ANTI JOIN is specially handled.
If keeping that fallback does not introduce regressions relative to master, I would prefer to keep this PR focused on distinguishing unknown NDVs from verified zero. We could retain the zero fallback at the Calcite boundary temporarily and address consistent unknown propagation, including the ANTI JOIN behavior, in a separate ticket.
Please feel free to ask me if you would like me to clarify my expectations 👍
I am supportive with this approach. If we updated all the methods here, the blast radius would be too big. If we updated it partially, we might see inconsistencies for a long and another drift might happen. |
|




Reviewer summary: the production change is +283/-153 across 11 files; the other 27 files (+5,546/-218) are tests and expected-output files. Two existing
.q.outgoldens change, both because binary columns, whose metastore stats carry no NDV, now report an unknown NDV (-1) instead of an implicit0that consumers took as a real value. Three nested-column-pruning goldens also change, in plan text only (AND conjunct order and vector scratch numbering); query results are unchanged. Suggested reading order:StatsUtils, thenStatisticsandPessimisticStatCombiner, thenStatsRulesProcFactory, then the Calcite metadata classes (HiveRelMdDistinctRowCount,HiveRelMdRowCount,HiveRelMdSelectivity,FilterSelectivityEstimator).What changes were proposed in this pull request?
HIVE-29625: Disambiguate
ColStatistics.countDistinct"unknown" from "verified zero".Establishes
-1as the "unknown" NDV sentinel forColStatistics.countDistinct, parallel tothe historical convention for
numNulls/numTrues/numFalses, which HIVE-29438 reinforced.Producers emit
-1when the NDV is genuinely unavailable:ColStatisticsconversion returns-1whennumDVsis unset (previously thethrift default
0);explicitly report
-1(tsltz likewise fornumNulls).Consumers of
getCountDistint()distinguish< 0(unknown),== 0(verified zero) and> 0(verified positive). Unknown triggers the same fallback the overloaded0used totrigger; verified zero flows through the math naturally. Two consumer rules are worth calling
out:
getDenominator) compute on the known values whenonly some inputs are unknown — the known NDVs bound the join-key domain from below, so this
reproduces the previous behavior (an unknown-as-
0lost the max for two relations and wasthe excluded least value for three or more) instead of collapsing to a cross-product
estimate. Only an all-unknown input makes the denominator itself unknown.
getDenominatorForUnmatchedRows) propagate unknown: an unknown mayresolve below every known value, so no known value is a safe bound.
Two small shared helpers consolidate previously duplicated logic:
StatsUtils.maxOrUnknown(five call sites:Statistics.addToColumnStatsplus all four fieldmerges in
PessimisticStatCombiner) andStatsUtils.scaleDownNDV(three call sites; alsounifies the row-count-ratio boundary at
< 1.0and keeps NDVs above 2^53 exact by skippingthe double round-trip when the row count does not shrink).
This also fixes HIVE-29556 (
extractNDVGroupingColumnsadjusting an unknown NDV of0to1).Unknown NDV at the Calcite boundary. Following review,
HiveRelMdDistinctRowCountreturnsnull, Calcite's "no reliable estimate" (BuiltInMetadata.DistinctRowCount), when a column's NDV is unknown; a verified 0 stays 0.nullalone breaks planning: Calcite'sRelMdUtil.estimateFilteredRowsunboxes a selectivity it declares@Nullable(NPE), and joins on RELY PK/FK constraints fail. So each reader is guarded, all by one rule: an unknown NDV never lowers an estimate below what the previous revision of this PR estimated, and never discards a known value.HiveRelMdRowCountPK-FK analysisHiveRelMdSelectivity, scan and join filter handoffHiveRelMdSelectivity, join keysHiveRelMdSelectivity, filter above an anti joinpropagateUnknownmode ofFilterSelectivityEstimator, used only here). This filter is inverted (1 - selectivity, pre-existing), so the fallback values would otherwise become near-zero estimatesFilterSelectivityEstimator, NOT and SEARCHAn unreachable block in
HiveRelMdRowCount.getRowCountIntis removed:analyzeJoinForPKFKreturnsnullfor every semi and anti join (since HIVE-8974), so its PK-FK branch never ran. Also fixed: an IN list on anintcolumn with a storednumDVs = -1failed on master with anAssertionErrorin Calcite (RelMdUtil.isNonNegative).Estimate changes in
cbo_ndv_unknown_estimates.qandcbo_ndv_unknown_pkfk.qagainst the previous revision of this PR (c84946b). Every case whose estimate differs is listed; all other cases have the same estimate (one of them, an aggregate feeding a three-way join, has a different join order). No estimate is lower. A later case, a filter above ORDER BY LIMIT over an anti join that ANDs an unknown-NDV part with a known one, is not part of this comparison: it estimates 300 rows (actual 296), and 1.2 without the AND propagation.Map-side GROUP BY hash-table sizing.
checkMapSideAggregationnow sizes the hash table with the same grouping cardinality as the GROUP BY row estimate (computeNDVGroupingColumns): unknown keys fall back once to rows / 2, and a key with NULLs counts the NULL group, so an all-NULL key no longer makes the table look empty. Before, an unknown NDV made the estimated table empty, so it always fit. Estimates can only go up compared with master: when the table does not fit in the hash-aggregation memory, the map-side GROUP BY is estimated without reduction (rows instead of rows / 2). With unknown-NDV keys and the default memory settings (hive.map.aggr.hash.percentmemory0.5,hive.map.aggr.hash.force.flush.memory.threshold0.9, 1,024 MB container), that happens above roughly 6 to 8 million input rows; this only changes the estimate, not whether map-side aggregation runs.Why are the changes needed?
ColStatistics.countDistinct == 0was overloaded to mean both "no distinct values" and"unknown NDV". The two states have opposite implications for cost-based planning — a real zero
supports tight estimates, while a genuinely-unknown NDV needs a conservative fallback. Treating
them identically led to inconsistent and sometimes severe cardinality estimates whenever a
column's NDV was unavailable: for example, a join between a table with a binary key (NDV always
unavailable) and a
castexpression with a known NDV could only be estimated as if no keystatistics existed at all. Disambiguating the sentinel lets each consumer apply the correct
logic.
@zabetak noted during review of #6359: "In fact, everything would be simpler if we could use -1
for NDV to declare unknown as it happens for the other stats. This is probably a bigger change to
digest so let's not go into this direction for now."
(#6359 (comment)) This PR takes up that bigger
change.
Does this PR introduce any user-facing change?
No. Query results, SQL syntax, and configuration are unchanged. Plan estimates in EXPLAIN output, the order of AND conjuncts in EXPLAIN output, and plans chosen from them (for example join order), may differ for queries reading columns whose NDV is unavailable, since the planner now distinguishes those from columns with
0distinct values. Two queries that failed during planning on master now run: a filter above a left outer join whose left input is a lateral view (NPE), and an IN list on anintcolumn with a storednumDVs = -1(AssertionError).How was this patch tested?
TestStatsUtils,TestStatsRulesProcFactory,TestPessimisticStatCombiner, plus the new optimizer tests underql/src/test/.../optimizer/), covering unknown / verified-zero / verified-positive for each site and the row-count-ratio boundary (including NDVs above 2^53).TestHiveRelMdDistinctRowCount,TestHiveRelMdRowCount,TestHiveRelMdSelectivityandTestFilterSelectivityEstimatorcover every changed line and branch of the Calcite-boundary change. Three disabled cases document pre-existing estimation bugs with their correct values..qregression tests:join_ndv_unknown_mixed.q(mixed known/unknown join-key NDVs),join_ndv_unknown_mixed_multikey.q(correlated multi-key inner and left-outer joins),groupby_ndv_unknown_multikey.q(map-side hash-table sizing with two unknown keys: one fallback, not one per key),filter_ndv_verified_zero_null_safe.q(null-safe equality against NULL with a verified-zero NDV), andcbo_ndv_unknown_estimates.q/cbo_ndv_unknown_pkfk.q, which print each CBO estimate next to the actual row count..q.outexpected-result files: two shift because of the binary NDV producer change (theprobeDecodeDetailsline invector_binary_join_groupby.qand the binary GROUP BY estimates inparquet_types_non_dictionary_encoding_vectorization.q). Three nested-column-pruning goldens (nested_column_pruning.q.out,orc_nested_column_pruning.q.out,vector_orc_nested_column_pruning.q.out) change in plan text only: the AND conjuncts overt2are reordered, and the vector variant renumbers scratch columns. This follows from the NOT null propagation inFilterSelectivityEstimator(45c29a0), which lets the predicate sorter complete instead of skipping after a NullPointerException. Query results are unchanged. The three tests pass locally without overwrite; the full CI run is pending. No runtime benefit is claimed.TestStatsRulesProcFactorynow uses JUnit 5 so it can host the parameterized cases. As part of that, its 16 existing min/max comparison tests were folded into four parameterized groups, with every case's operator, literal and expected row count preserved.