Skip to content

HIVE-29625: Disambiguate ColStatistics.countDistinct "unknown" from "verified zero" - #6505

Open
konstantinb wants to merge 29 commits into
apache:masterfrom
konstantinb:HIVE-29625
Open

konstantinb wants to merge 29 commits into
apache:masterfrom
konstantinb:HIVE-29625

Conversation

@konstantinb

@konstantinb konstantinb commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

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.out goldens change, both because binary columns, whose metastore stats carry no NDV, now report an unknown NDV (-1) instead of an implicit 0 that 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, then Statistics and PessimisticStatCombiner, then StatsRulesProcFactory, 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 -1 as the "unknown" NDV sentinel for ColStatistics.countDistinct, parallel to
the historical convention for numNulls/numTrues/numFalses, which HIVE-29438 reinforced.

Producers emit -1 when the NDV is genuinely unavailable:

  • proto-to-ColStatistics conversion returns -1 when numDVs is unset (previously the
    thrift default 0);
  • binary and timestamp-with-local-time-zone columns, whose stats data carries no NDV, now
    explicitly report -1 (tsltz likewise for numNulls).

Consumers of getCountDistint() distinguish < 0 (unknown), == 0 (verified zero) and
> 0 (verified positive). Unknown triggers the same fallback the overloaded 0 used to
trigger; verified zero flows through the math naturally. Two consumer rules are worth calling
out:

  • Max/product-style join denominators (getDenominator) compute on the known values when
    only some inputs are unknown — the known NDVs bound the join-key domain from below, so this
    reproduces the previous behavior (an unknown-as-0 lost the max for two relations and was
    the 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.
  • Min-style combines (getDenominatorForUnmatchedRows) propagate unknown: an unknown may
    resolve 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.addToColumnStats plus all four field
merges in PessimisticStatCombiner) and StatsUtils.scaleDownNDV (three call sites; also
unifies the row-count-ratio boundary at < 1.0 and keeps NDVs above 2^53 exact by skipping
the double round-trip when the row count does not shrink).

This also fixes HIVE-29556 (extractNDVGroupingColumns adjusting an unknown NDV of 0 to 1).

Unknown NDV at the Calcite boundary. Following review, HiveRelMdDistinctRowCount returns null, Calcite's "no reliable estimate" (BuiltInMetadata.DistinctRowCount), when a column's NDV is unknown; a verified 0 stays 0. null alone breaks planning: Calcite's RelMdUtil.estimateFilteredRows unboxes 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.

Where Guard
HiveRelMdRowCount PK-FK analysis null is the existing "not computed" -1; an unknown ratio means every FK row matches (upper bound)
HiveRelMdSelectivity, scan and join filter handoff a predicate the statistics can't estimate keeps every row
HiveRelMdSelectivity, join keys an unknown key is skipped; the known keys still bound the join
HiveRelMdSelectivity, filter above an anti join a filter that depends on an unknown NDV keeps every row, including an unknown part inside AND, OR or a multi-range SEARCH (an immutable propagateUnknown mode of FilterSelectivityEstimator, used only here). This filter is inverted (1 - selectivity, pre-existing), so the fallback values would otherwise become near-zero estimates
FilterSelectivityEstimator, NOT and SEARCH an unknown operand stays unknown instead of being unboxed

An unreachable block in HiveRelMdRowCount.getRowCountInt is removed: analyzeJoinForPKFK returns null for every semi and anti join (since HIVE-8974), so its PK-FK branch never ran. Also fixed: an IN list on an int column with a stored numDVs = -1 failed on master with an AssertionError in Calcite (RelMdUtil.isNonNegative).

Estimate changes in cbo_ndv_unknown_estimates.q and cbo_ndv_unknown_pkfk.q against 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.

Case Previous revision This PR Actual
GROUP BY an unknown-NDV key 1 50 309
GROUP BY an unknown-NDV key and a known one 1 50 309
OR with a known-NDV predicate 1.629 495 4
Equality between an unknown-NDV column and a known-NDV expression 1.629 500 500
GROUP BY an integer column with unknown NDV 1 50 309
Dedup (rn = 1) over an anti join, window partitioned by an unknown-NDV column 498 500 252
Filter above ORDER BY LIMIT over an anti join, OR with an unselective unknown-NDV part 298.8 300 298
Integer point and range in one SEARCH, numDVs = -1, 3-way join 429.5 1280 875
A filter above a left outer join that reads columns from both sides (selectivity unknown) 4.336 1313 0
A non-deterministic filter on an unknown-NDV column, kept above an anti join 1 500 0
NOT over a boolean function of an unknown-NDV column 1 500 498
A filter above a left outer join whose left input is a lateral view fails (NPE), also on master 1290 0
Only the primary key side has column statistics: PK NDV unknown, FK NDV estimated 1 166.7 271
Both sides have column statistics: PK and FK NDVs unknown, PK side filtered on its key 55.56 166.7 271

Map-side GROUP BY hash-table sizing. checkMapSideAggregation now 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.percentmemory 0.5, hive.map.aggr.hash.force.flush.memory.threshold 0.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 == 0 was 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 cast expression with a known NDV could only be estimated as if no key
statistics 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 0 distinct 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 an int column with a stored numDVs = -1 (AssertionError).

How was this patch tested?

  • Parameterized unit-test matrices for every producer branch and consumer rule (TestStatsUtils, TestStatsRulesProcFactory, TestPessimisticStatCombiner, plus the new optimizer tests under ql/src/test/.../optimizer/), covering unknown / verified-zero / verified-positive for each site and the row-count-ratio boundary (including NDVs above 2^53).
  • Calcite metadata: TestHiveRelMdDistinctRowCount, TestHiveRelMdRowCount, TestHiveRelMdSelectivity and TestFilterSelectivityEstimator cover every changed line and branch of the Calcite-boundary change. Three disabled cases document pre-existing estimation bugs with their correct values.
  • Six new .q regression 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), and cbo_ndv_unknown_estimates.q / cbo_ndv_unknown_pkfk.q, which print each CBO estimate next to the actual row count.
  • Existing .q.out expected-result files: two shift because of the binary NDV producer change (the probeDecodeDetails line in vector_binary_join_groupby.q and the binary GROUP BY estimates in parquet_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 over t2 are reordered, and the vector variant renumbers scratch columns. This follows from the NOT null propagation in FilterSelectivityEstimator (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.
  • TestStatsRulesProcFactory now 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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment on lines +1391 to +1392
if (dvs == 0) {
return 0;

@konstantinb konstantinb Nov 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 thomasrebele left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain this? What does <=> mean? "not equals"? If that's the case I would prefer using !=.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 okumin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@okumin okumin Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if this returns null? Does it require major surgery, or do existing tests go wrong? Zero sounds better than negatives anyway, though.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@konstantinb konstantinb Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@okumin

okumin commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

@konstantinb
I checked all the usage of ColStatistics#getCountDistint, and I think the current patch covers all required points. Could you please check a couple of my comments

@thomasrebele thomasrebele left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@konstantinb

Copy link
Copy Markdown
Contributor Author

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.
@konstantinb

Copy link
Copy Markdown
Contributor Author

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?

@thomasrebele I agree it would be cleaner: with OptionalLong the compiler forces every reader to handle the unknown case, and the bugs this PR fixes are exactly arithmetic on the sentinel. I'd still keep -1 here:

  • numNulls, numTrues and numFalses in the same class already use negative = unknown (HIVE-29438); switching only countDistinct would make ColStatistics inconsistent.
  • Converting all four is a refactor of its own: about 140 reads in 21 files in ql, and ColStatistics is part of the public StatEstimator interface that UDFs implement (including in iceberg-handler), so it changes an extension API.
  • The metastore keeps a sentinel anyway: Thrift numDVs is a required i64, and stored -1 values exist.
  • Where an API defines a special value, this PR uses it: unknown is now null at the Calcite boundary.

I'd propose a follow-up JIRA that converts the four fields together, possibly keeping deprecated long getters for a while.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this comment, I have two assumptions.

  • No degradation would happen if HiveRelMdDistinctRowCount#getDistinctRowCount returned 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.

  1. 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?"
  2. 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 👍

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Revert the null work (45c29a0, 9cc9cfb, 85b3980, 3241f0c). The Calcite stats classes then match eda2c8d exactly: HiveRelMdDistinctRowCount returns 0.0 for an unknown or zero NDV, and there is no anti-join special case.
  2. 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).
  3. 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 = -1 fails on master with an AssertionError and is estimated normally with the fallback. I'll re-run the affected tests after the revert.
  4. 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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The list is aligned with me.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this comment, I have two assumptions.

  • No degradation would happen if HiveRelMdDistinctRowCount#getDistinctRowCount returned 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.

  1. 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?"
  2. 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 👍

@okumin

okumin commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@thomasrebele I agree it would be cleaner: with OptionalLong the compiler forces every reader to handle the unknown case, and the bugs this PR fixes are exactly arithmetic on the sentinel. I'd still keep -1 here:
I'd propose a follow-up JIRA that converts the four fields together, possibly keeping deprecated long getters for a while.

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.

@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants