Registry Mirror
Skip to content

Conversation

@Alena0704

@Alena0704 Alena0704 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Bug fix (non-breaking change)

Breaking Changes

Test Plan

  • Integration tests added/updated

Impact

Performance:

  • For the ANALYZE underestimates ndistinct-by-segments of partitioned tables since 19b4ae07f8e; ORCA picks a useless two-stage aggregate #2407 reproduction, median execution time decreased from 7.33 s to 4.74 s across three runs (approximately 35% faster) by avoiding an unhelpful partial aggregation.
  • Full SF1 suites retained the same plan structures, with similar total execution times: TPC-H 19.99 → 20.10 s, TPC-DS 56.39 → 56.05 s. These were single-pass measurements, so small differences are not conclusive.
  • The additional calculation runs during root statistics merging in ANALYZE, with work proportional to the MCV list size. Performance effects depend on data distribution and the resulting plan.

Checklist

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
@Alena0704
Alena0704 requested a review from yjhjstz November 25, 2026 13:47
Comment thread src/backend/commands/analyze.c Outdated
Comment on lines +5055 to +5060
if (numsegments == 1 ||
(GpPolicyIsHashPartitioned(policy) && policy->nattrs == 1 &&
policy->attrs[0] == stats->attr->attnum))
estimate = root_ndistinct;
else
{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.
@Alena0704
Alena0704 marked this pull request as ready for review November 30, 2026 22:04
@Alena0704
Alena0704 requested a review from yjhjstz November 30, 2026 22:04
Comment thread src/backend/commands/analyze.c Outdated
Comment on lines +3177 to +3201
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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed but haven't checked on benchmarks yet

@Alena0704
Alena0704 requested a review from yjhjstz December 3, 2026 12:40
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.
@Alena0704
Alena0704 force-pushed the fix/ndv-by-segments-frequency branch from c926d33 to a2e4a7d Compare December 3, 2026 12:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ANALYZE underestimates ndistinct-by-segments of partitioned tables since 19b4ae07f8e; ORCA picks a useless two-stage aggregate

2 participants