Conversation
The average number of segments holding a value can differ between a leaf partition and the whole table. Applying the leaf ratio to the root NDV underestimates NDV_BY_SEGMENTS when a value occurs on different segments across partitions, which can make ORCA choose unhelpful partial aggregation. Estimate root segment occupancy from MCV frequencies and a uniform frequency for the remaining non-null values. Use log1p/expm1 for numerical stability, retain colocation for a sole hash distribution key, and bound the result by the leaf sum, root NDV times the segment count, and non-null row count. Remove the now-unused leaf ndistinct sum. The idea for the frequency-based segment occupancy estimator was proposed by Jianghua Yang <yjhjstz@gmail.com>. Add incremental_analyze coverage for sparse values spanning segments across partitions with a multi-column distribution key. The existing low-cardinality and sole-distribution-key cases remain covered. Fixes apache#2407
| if (numsegments == 1 || | ||
| (GpPolicyIsHashPartitioned(policy) && policy->nattrs == 1 && | ||
| policy->attrs[0] == stats->attr->attnum)) | ||
| estimate = root_ndistinct; | ||
| else | ||
| { |
There was a problem hiding this comment.
Only the sole hash distribution key is treated as colocated; every other column is assumed to be placed independently. Columns that are functionally dependent on the distribution key (denormalized dimension attributes, derived ids, a copy of the key, ...) are colocated too, and the leaf ratio used to capture that. The leaf-sum upper bound does not help once a value appears in >= numsegments partitions.
Repro (3 segments): create table h1 (a int, pk int, b int) distributed by (a) partition by range (pk) (start (0) end (6) every (1)); insert into h1 select v, p, v from generate_series(0,5) p, generate_series(1,100) v, generate_series(1,10) k; analyze h1; -> NDV_BY_SEGMENTS for b is 300 on this PR, actual count(distinct (gp_segment_id, b)) is 100, and main gives 100. In the worst case this overestimates by numsegments, which skews ORCA's local/partial aggregate costing.
Suggestion: keep the leaf information as a colocation correction, e.g. compute the independent-placement expectation E_leaf per leaf with the same formula, derive a factor clamp((observed_leaf - ndv_leaf) / (E_leaf - ndv_leaf), 0, 1), and use it to interpolate between root_ndistinct and the root's independent estimate. Please also add a regression case for a colocated non-distribution-key column. (verified: SQL above on PR vs base)
There was a problem hiding this comment.
Thanks for pointing this out. I reproduced the problem and fixed it in separate last commit, now it uses:
leaf bounds → inherited sample if ambiguous → bounded root estimate
A sample already needed for other statistics is reused; otherwise, one sample serves all affected columns. This handles both stable colocation and values whose segment changes between partitions. The corresponding examples now estimate 100 and 275, matching the actual counts.
All 22 TPC-H queries and 103 TPC-DS statements pass at SF1, with unchanged plan structures and execution totals within 1% of unpatched main.
The tradeoff is additional work during ANALYZE: root analysis took approximately 28–32% longer in the single-pass measurements.
A copy of the distribution key can have 100 distinct segment/value pairs where the independent-placement estimator predicts 300. Leaf colocation ratios also cannot distinguish stable placement from a segment changing between partitions, and singleton leaves provide no colocation evidence. Use leaf bounds to identify ambiguous root estimates and resolve them with one inherited sample for all affected columns, reusing an existing sample. Keep the bounded frequency estimate if no non-null NDV was sampled. Make QEs compute local NDV from that sample instead of merging leaf statistics. Handle empty/all-null leaves, missing or invalid slots, crossing bounds, custom typanalyze routines and single-segment policies. Add regression coverage for these cases and for sample reuse. Validate incremental_analyze, bfv_aggregate, olap_plans and subselect_gp with both optimizers, including plan comparisons.
| if (!sampled) | ||
| { | ||
| MemoryContext old_context; | ||
| HeapTuple *sample_rows; | ||
| double totalrows; | ||
| double deadrows; | ||
|
|
||
| /* The dispatcher must request at least one row from each segment. */ | ||
| targrows = Max(targrows, onerel->rd_cdbpolicy->numsegments); | ||
| sample_context = AllocSetContextCreate(CurrentMemoryContext, | ||
| "Analyze root NDV sample", | ||
| ALLOCSET_DEFAULT_SIZES); | ||
| old_context = MemoryContextSwitchTo(sample_context); | ||
| sample_rows = palloc(targrows * sizeof(HeapTuple)); | ||
| colndv = palloc0(onerel->rd_att->natts * sizeof(double)); | ||
|
|
||
| Assert(acquire_func_colLargeRowIndexes == NULL); | ||
| Assert(acquire_func_colLargeRowLength == NULL); | ||
| Assert(acquire_func_colNDVBySeg == NULL); | ||
| acquire_func_colNDVBySeg = colndv; | ||
| pgstat_progress_update_param(PROGRESS_ANALYZE_PHASE, | ||
| PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS_INH); | ||
| PG_TRY(); | ||
| { | ||
| (void) acquire_inherited_sample_rows(onerel, elevel, sample_rows, |
There was a problem hiding this comment.
When ndvbs_lower < ndvbs_upper, sample_merged_ndv_by_segments() dispatches acquire_inherited_sample_rows() (gp_acquire_sample_rows) across all segments and all leaf partitions. For most multi-partition tables, virtually any non-distribution-key column whose values recur across partitions without saturating every segment in a single leaf will satisfy ndvbs_lower < ndvbs_upper. This turns every incremental ANALYZE and ANALYZE ROOTPARTITION—whose main purpose is to avoid scanning already-analyzed historical leaves—into a full inherited sample over all partitions, computing stats for all columns on every QE (ignoring va_cols) and shipping targrows full tuples back to QD only to discard them. (The PR Impact section still describes only MCV-proportional work from commit 1.)
Consider gating this fallback behind a GUC or tightening when sampling is triggered (e.g., avoiding a full inherited scan by default during incremental merge, or using a lightweight/column-scoped QE estimator that does not transfer full sample rows or re-analyze unaffected columns), and benchmark ANALYZE / ANALYZE ROOTPARTITION on tables with hundreds of partitions. (not verified)
There was a problem hiding this comment.
Thanks, yes, I noticed this overhead too when measured it on benchmarks: root ANALYZE was about 47% slower on TPC-H SF1 and 34% slower on TPC-DS SF1. I haven’t settled on a solution yet, but your suggestion to compute NDV only for the required columns on the QEs and return estimates without sending full sample rows looks reasonable. I’ll try implementing that and repeat the measurements.
There was a problem hiding this comment.
Fixed but haven't checked on benchmarks yet
When leaf statistics leave root NDV_BY_SEGMENTS ambiguous, the inherited sampler computes statistics for unrelated columns and transfers full sample tuples to the coordinator, although this path only needs local NDV estimates. Dispatch a helper for the ambiguous attributes and return one float8 array per segment. Keep sample tuples on the segments, derive the sample budget from the requested attributes, and reuse an existing sample when available. Preserve the NDV bounds and inherited overrides without updating segment catalog statistics. Historical partitions are still sampled. Cover column subsets, reversed attribute order, dropped-column gaps and n_distinct_inherited in incremental_analyze. Add the internal catalog helper and bump the catalog version; a fresh initdb is required.
c926d33 to
a2e4a7d
Compare
Leaf statistics cannot determine whether a value stays on the same segment across partitions. Use them to derive bounds for root NDV_BY_SEGMENTS. When those bounds leave the result ambiguous, estimate local NDV from an inherited sample on each QE, sum the estimates on the dispatcher, and clamp the result to the bounds.
One sample serves all affected columns, reusing an existing sample when available. Global NDV, MCV, and histogram statistics continue to be merged from the leaves.
The frequency-based segment occupancy estimator, retained as a fallback when sampling provides no usable non-null NDV estimate, was proposed by Jianghua Yang yjhjstz@gmail.com.
Extend incremental_analyze coverage for colocated non-distribution-key columns, values whose segment changes across partitions, sparse leaves, and multi-column distribution keys. Add cases for sample reuse, NULL and empty leaves, and missing or invalid NDV_BY_SEGMENTS slots. The existing low-cardinality and sole-distribution-key cases remain covered.
Fixes #2407
Type of Change
Breaking Changes
Test Plan
Impact
Performance:
Checklist