Skip to content

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

In review

Description

@yjhjstz

Apache Cloudberry version

main, including 19b4ae0 ("Fix ndistinct-by-segments for partitioned tables").

What happened

Since 19b4ae0, ANALYZE stores a much too small STATISTIC_KIND_NDV_BY_SEGMENTS on the root of a partitioned table when the column is neither the partitioning key nor the distribution key and has high cardinality.

ORCA uses this value as the output size of a partial (local) aggregate. With the low value, it believes the partial aggregate removes most rows and picks Partial HashAggregate -> Redistribute -> Finalize HashAggregate. In reality the partial aggregate removes almost nothing, so the two-stage plan is slower than the one-stage plan.

We first saw this in TPC-DS Q23: the max_store_sales subquery (group by c_customer_sk over a partitioned store_sales) switched from a one-stage to a two-stage aggregate.

Cause. merge_leaf_stats() now caps the summed leaf value at root_ndistinct * segs_per_value, where segs_per_value = sum(leaf NDV_BY_SEGMENTS) / sum(leaf ndistinct). The comment says this average "does not depend on the partitioning". It does: for a non-distribution-key column, the number of segments a value lands on grows with the number of rows that value has. Within one leaf a value has few rows and sits on 1-2 segments. Across the whole table the same value sits on most segments. The ratio measured on leaves is therefore far below the table-wide ratio, and the cap cuts the statistic well below the true value.

Runtime values captured with gdb at analyze.c (merge_leaf_stats, column ss_customer_sk) in the reproduction below:

root_ndistinct           = 1,822,479
sum(leaf NDV_BY_SEGMENTS)= 4,434,219   (value stored before 19b4ae07f8e)
sum(leaf ndistinct)      = 4,309,708
segs_per_value           = 1.0289      (numsegments = 3)
stored NDV_BY_SEGMENTS   = 1,875,132   (true sum of per-segment distinct counts: 3,541,120)

ORCA then uses 1,875,132 directly as the group count of the partial aggregate (CStatisticsUtils::AddNdvForAllGrpCols, is_partial = true): 1,875,132 / 3 = 625,044 rows per segment in the plan below.

What you think should happen instead

The root's NDV_BY_SEGMENTS should not fall below the true sum of per-segment distinct counts for this kind of column. ORCA should then keep the one-stage aggregate, as it did before 19b4ae0.

Reverting 19b4ae0 fixes this case (details under "Anything else").

How to reproduce

3-segment demo cluster, optimizer = on, default settings.

CREATE TABLE customer (c_customer_sk int NOT NULL, c_name text) DISTRIBUTED BY (c_customer_sk);
INSERT INTO customer SELECT g, 'c'||g FROM generate_series(1, 3000000) g;

CREATE TABLE store_sales (
  ss_sold_date_sk int, ss_item_sk int NOT NULL, ss_customer_sk int,
  ss_ticket_number bigint NOT NULL, ss_quantity int, ss_sales_price numeric(7,2))
DISTRIBUTED BY (ss_item_sk, ss_ticket_number)
PARTITION BY RANGE (ss_sold_date_sk) (START (0) END (30) EVERY (1));

-- 4.5M rows, 30 partitions, ss_customer_sk uniform over 3M values
INSERT INTO store_sales
SELECT g % 30, ((g::bigint * 7919) % 200000 + 1)::int,
       (hashint4(g) & 2147483647) % 3000000 + 1, g,
       (g % 100) + 1, ((g % 1000) / 10.0)::numeric(7,2)
FROM generate_series(1, 4500000) g;

ANALYZE customer;
ANALYZE store_sales;

-- NDV_BY_SEGMENTS is stakind 8
SELECT c.relname,
       CASE 8 WHEN s.stakind1 THEN s.stavalues1::text WHEN s.stakind2 THEN s.stavalues2::text
              WHEN s.stakind3 THEN s.stavalues3::text WHEN s.stakind4 THEN s.stavalues4::text
              WHEN s.stakind5 THEN s.stavalues5::text END AS ndv_by_segments
FROM pg_statistic s
JOIN pg_class c ON c.oid = s.starelid
JOIN pg_attribute a ON a.attrelid = s.starelid AND a.attnum = s.staattnum
WHERE c.relname = 'store_sales' AND a.attname = 'ss_customer_sk';

-- true value
SELECT sum(n) FROM (SELECT gp_segment_id, count(DISTINCT ss_customer_sk) n
                    FROM store_sales GROUP BY 1) t;

SET optimizer = on;
EXPLAIN ANALYZE
SELECT c_customer_sk, sum(ss_quantity * ss_sales_price) csales
FROM store_sales, customer
WHERE ss_customer_sk = c_customer_sk
GROUP BY c_customer_sk;

Result on main:

value
root NDV_BY_SEGMENTS ~1.9M (true: 3,541,120)
Partial HashAggregate, estimated vs actual rows/segment 632,252 vs 1,476,738 (input: 1,500,930)
two-stage cost (chosen) vs one-stage cost 1696.60 vs 1844.16
 Gather Motion 3:1  (slice1; segments: 3)
   ->  Finalize HashAggregate
         Group Key: customer.c_customer_sk
         ->  Hash Join
               Hash Cond: (store_sales.ss_customer_sk = customer.c_customer_sk)
               ->  Redistribute Motion 3:3  (slice2; segments: 3)
                     Hash Key: store_sales.ss_customer_sk
                     ->  Streaming Partial HashAggregate  (rows=632252) (actual rows=1476738)
                           Group Key: store_sales.ss_customer_sk
                           ->  Dynamic Seq Scan on store_sales  (rows=1500000) (actual rows=1500930)
               ->  Hash
                     ->  Seq Scan on customer

The same data in a non-partitioned table gets NDV_BY_SEGMENTS ~2.9M, so the gap comes from the partitioned-root merge.

Operating System

Rocky Linux 9.7 (Blue Onyx)

Anything else

Reverting 19b4ae0 fixes the case above. The revert applies cleanly to main.

  • Root NDV_BY_SEGMENTS: 4,436,064, the plain sum of the leaves (true value: 3,541,120).
  • ORCA picks the one-stage HashAggregate by default (cost 1842.93).
  • Run time: one-stage ~3.86 s vs two-stage (forced with optimizer_force_multistage_agg) ~6.0 s.
  • incremental_analyze, bfv_aggregate, olap_plans and subselect_gp pass with optimizer=on and optimizer=off. incremental_analyze passes because the revert also removes the test cases that 19b4ae0 added.

Trade-off. The revert brings back the overestimate that 19b4ae0 was meant to fix. For low-cardinality columns repeated in every partition (the ndvbs_part test case: 8 partitions, g % 53 and g % 3), NDV_BY_SEGMENTS becomes 1272 and 72 instead of 159 and 9. group by a, c then goes back to a one-stage aggregate.

Possible fix that handles both cases (not implemented yet). Do not derive segments-per-value from the leaves. Estimate the root value from root-level statistics. For a column that is not the distribution key, rows are placed on segments essentially at random, so the expected sum of per-segment distinct counts is the Cardenas/Yao occupancy formula:

NDV_BY_SEGMENTS ≈ sum over values v of  S * (1 - (1 - 1/S)^k_v)

where k_v is the row count of v, taken from the MCVs plus a uniform split of the rest over root_ndistinct. Use root_ndistinct for a single-column distribution key, and clamp the result to [root_ndistinct, min(sum of leaves, S * root_ndistinct, N)]. In the cases above this gives 3.46M (true value 3.54M), 159 and 9. A simpler alternative is to cap at root_ndistinct * numsegments, as the commit message describes.

Are you willing to submit PR?

  • Yes, I am willing to submit a PR!

Code of Conduct

  • I agree to follow this project's Code of Conduct.

Activity

  1. github-actions commented on Nov 24, 2026

    @github-actions

    Hi, @yjhjstz welcome!🎊 Thanks for taking the time to point this out.🙌

  2. Alena0704 commented on Nov 25, 2026

    @Alena0704
    Collaborator

    I compared your frequency-based occupancy formula with the simpler conservative cap:

    min(sum(leaf NDV_BY_SEGMENTS), root_ndistinct * numsegments)
    

    The cap avoids transferring the leaves’ average segments-per-value ratio to the whole table. A segment cannot contain more distinct values than the table as a whole. For a column that is the sole hash distribution key, the bound is root_ndistinct, since equal values are colocated on one segment.

    After comparing both compiled approaches, I support using your frequency-based formula for this fix. It estimates the sum of per-segment distinct counts from value frequencies, while the cap provides an upper limit. Both fix the reproduction in this issue and preserve the original low-cardinality fix.

    In the original ndvbs_part regression case, both fixes preserve NDV_BY_SEGMENTS=159 and 9 and the intended two-stage aggregate. In the separate #2407 reproduction, both remove the ineffective partial aggregate. The frequency-based estimate is much closer to the actual NDV there: 3,572,053 versus 3,541,120. Median execution time across three runs falls from 7.33 s on current main to 4.74 s with the frequency-based formula and 4.77 s with the cap. The two fixes select the same plan, so their small timing difference does not establish that one is faster.

    Original regression case and issue reproduction: estimates and plans

    The original ndvbs_part case has eight partitions and 24,000 rows, with grouping columns g % 53 and g % 3. The old uncapped leaf sums are 1272 and 72; in the earlier statistics-level check these selected:

    Gather Motion
      -> HashAggregate
           -> Redistribute Motion
                -> Dynamic Seq Scan
    

    Both compiled fixes store 159 and 9 and preserve:

    Gather Motion
      -> Finalize HashAggregate
           -> Redistribute Motion
                -> Streaming Partial HashAggregate
                     -> Dynamic Seq Scan
    

    The sole hash distribution-key case also remains at 53 with its explicit special case.

    For the #2407 reproduction (4.5M fact rows, 30 partitions), the actual NDV_BY_SEGMENTS is 3,541,120:

    Variant Estimated NDV_BY_SEGMENTS Median execution time, 3 runs
    Current main 2,032,046 7.33 s
    Conservative cap 4,431,267 4.77 s
    Frequency-based occupancy estimate 3,572,053 4.74 s

    Current main selects:

    Gather Motion
      -> Finalize HashAggregate
           -> Hash Join
                -> Redistribute Motion
                     -> Streaming Partial HashAggregate
                          -> Dynamic Seq Scan on store_sales
                -> Hash
                     -> Seq Scan on customer
    

    Both fixes select:

    Gather Motion
      -> HashAggregate
           -> Hash Join
                -> Redistribute Motion
                     -> Dynamic Seq Scan on store_sales
                -> Hash
                     -> Seq Scan on customer
    

    The result row count and aggregate checksums agree across the three variants. Both fixes select the same plan; their small timing difference does not establish that one is faster.

    I also constructed three additional cases, labelled A, B and C below. These show that neither formula always selects the fastest plan. The cap is faster in B, where every value is deliberately present on all three segments (298 ms versus 899 ms). The frequency-based formula is faster in C, where both copies of each value are on the same segment and the join produces 16 matches per key (831 ms versus 1072 ms). These are medians of 10 executions per binary, including a second batch with the two fixes run in reverse order. Query results match across variants.

    Additional cases: estimation accuracy and median times

    I then constructed additional examples to see what happens when the formulas select different plans. All three examples contain 150,000 different values in the fact table:

    • A — Independent placement (independent_4 joined to dim): each value occurs four times, and its copies can land on different segments. There are 600,000 fact rows. Each key matches one row in the joined table.
    • B — Forced spread (spread_4 joined to dim): each value also occurs four times, but the copies are deliberately placed so that every value is present on all three segments. Again, there are 600,000 fact rows and one joined row per key.
    • C — Colocated copies and a multiplying join (colocated_2 joined to dim_dup16): each value occurs twice, with both copies on the same segment. There are 300,000 fact rows. Each key matches 16 rows in the joined table, which contains 2.4M rows.

    For these examples I used default_statistics_target=1000 and counted the actual distinct values on each segment directly. NDV_BY_SEGMENTS is the sum of those per-segment counts. A value present on all three segments contributes three, so 150,000 different values can produce NDV_BY_SEGMENTS=450,000.

    The table below compares the observed count with the two estimates:

    Example Actual sum of per-segment distinct counts Cap estimate Frequency-based estimate
    A — Independent placement 361,190 441,891 357,163
    B — Every value on all three segments 450,000 442,011 357,222
    C — Both copies on one segment 150,000 300,000 248,396

    I also measured the query in each example 10 times per binary. The following numbers are median times for one query, rather than totals for a suite. I repeated the measurements in a second batch with the two fixes run in reverse order. Query results matched in all variants.

    Example Current main Cap Frequency-based estimate
    A — Independent placement 557 ms 326 ms 545 ms
    B — Every value on all three segments 868 ms 298 ms 899 ms
    C — Both copies on one segment; 16 joined rows per key 914 ms 1072 ms 831 ms

    In A, the frequency-based formula estimates NDV more accurately, but the cap selects the faster plan under the current ORCA costing. More accurate statistics alone do not guarantee a faster plan.

    In B, the cap is closer to the actual NDV and avoids a partial aggregate whose cost does not pay off. Its small remaining estimation error comes from the root ndistinct estimate itself.

    In C, the frequency-based estimate preserves useful partial aggregation before the join. Fewer rows enter the join that multiplies them by 16, so this plan is faster. Both formulas overestimate NDV here, but they lead to different plans.

    These examples show a tradeoff: neither alternative consistently produces the fastest plan. The SQL for A/B/C and the contrasting plans for B/C follow below.

    SQL for cases A, B and C

    The script creates case A as independent_4, case B as spread_4, and case C as colocated_2 joined to dim_dup16. It rolls back all test objects at the end.

    -- Run on a three-segment cluster with current main or one of the two patches.
    -- The transaction rolls back all test objects. Estimates can vary with ANALYZE.
    BEGIN;
    SET LOCAL optimizer = on;
    SET LOCAL default_statistics_target = 1000;
    SET LOCAL gp_autostats_mode = 'none';
    SET LOCAL statement_mem = '125MB';
    SET LOCAL work_mem = '32MB';
    SET LOCAL jit = off;
    CREATE SCHEMA ndv2407_tradeoff_demo;
    SET LOCAL search_path = ndv2407_tradeoff_demo, public;
    
    CREATE TABLE mapping(dk int) DISTRIBUTED BY(dk);
    INSERT INTO mapping SELECT g FROM generate_series(1,100) g;
    CREATE TABLE dim(v int NOT NULL) DISTRIBUTED BY(v);
    INSERT INTO dim SELECT g FROM generate_series(1,150000) g;
    CREATE TABLE dim_dup16(v int NOT NULL) DISTRIBUTED BY(v);
    INSERT INTO dim_dup16 SELECT v FROM dim, generate_series(1,16) x;
    ANALYZE dim;
    ANALYZE dim_dup16;
    
    -- Four occurrences per value, with independent hash placement.
    CREATE TABLE independent_4
      (id bigint, pk int, dk int, v int, quantity int, price numeric(7,2))
    DISTRIBUTED BY(dk)
    PARTITION BY RANGE(pk) (START(0) END(4) EVERY(1));
    INSERT INTO independent_4
    SELECT p::bigint*150000+g, p, p*150000+g, g, g%100+1,
           (g%1000/10.0)::numeric(7,2)
    FROM generate_series(0,3) p, generate_series(1,150000) g;
    ANALYZE independent_4;
    
    -- Four occurrences per value, deliberately present on all three segments.
    CREATE TABLE spread_4
      (id bigint, pk int, dk int, v int, quantity int, price numeric(7,2))
    DISTRIBUTED BY(dk)
    PARTITION BY RANGE(pk) (START(0) END(4) EVERY(1));
    INSERT INTO spread_4
    SELECT p::bigint*150000+g, p, m.dk, g, g%100+1,
           (g%1000/10.0)::numeric(7,2)
    FROM generate_series(0,3) p, generate_series(1,150000) g,
         (SELECT gp_segment_id AS seg, min(dk) AS dk FROM mapping GROUP BY 1) m
    WHERE m.seg=p%3;
    ANALYZE spread_4;
    
    -- Two occurrences per value, both on the same segment.
    CREATE TABLE colocated_2
      (id bigint, pk int, dk int, v int, quantity int, price numeric(7,2))
    DISTRIBUTED BY(dk)
    PARTITION BY RANGE(pk) (START(0) END(2) EVERY(1));
    INSERT INTO colocated_2
    SELECT p::bigint*150000+g, p, g+1000, g, g%100+1,
           (g%1000/10.0)::numeric(7,2)
    FROM generate_series(0,1) p, generate_series(1,150000) g;
    ANALYZE colocated_2;
    
    -- Actual NDV_BY_SEGMENTS, independent of the stored estimates.
    SELECT 'independent_4' AS layout, sum(n) AS actual_ndv_by_segments
    FROM (SELECT gp_segment_id,count(DISTINCT v) n FROM independent_4 GROUP BY 1) s
    UNION ALL
    SELECT 'spread_4',sum(n)
    FROM (SELECT gp_segment_id,count(DISTINCT v) n FROM spread_4 GROUP BY 1) s
    UNION ALL
    SELECT 'colocated_2',sum(n)
    FROM (SELECT gp_segment_id,count(DISTINCT v) n FROM colocated_2 GROUP BY 1) s
    ORDER BY 1;
    -- colocated_2: 150000; independent_4: 361190; spread_4: 450000.
    
    SELECT c.relname,
           CASE 8 WHEN s.stakind1 THEN s.stavalues1::text
                  WHEN s.stakind2 THEN s.stavalues2::text
                  WHEN s.stakind3 THEN s.stavalues3::text
                  WHEN s.stakind4 THEN s.stavalues4::text
                  WHEN s.stakind5 THEN s.stavalues5::text END AS ndv_by_segments
    FROM pg_statistic s
    JOIN pg_class c ON c.oid=s.starelid
    JOIN pg_attribute a ON a.attrelid=c.oid AND a.attnum=s.staattnum
    WHERE c.relnamespace='ndv2407_tradeoff_demo'::regnamespace
      AND c.relkind='p' AND a.attname='v'
    ORDER BY 1;
    
    EXPLAIN (ANALYZE, TIMING OFF)
    SELECT d.v,sum(t.quantity*t.price)
    FROM independent_4 t JOIN dim d ON t.v=d.v GROUP BY d.v;
    
    EXPLAIN (ANALYZE, TIMING OFF)
    SELECT d.v,sum(t.quantity*t.price)
    FROM spread_4 t JOIN dim d ON t.v=d.v GROUP BY d.v;
    
    EXPLAIN (ANALYZE, TIMING OFF)
    SELECT d.v,sum(t.quantity*t.price)
    FROM colocated_2 t JOIN dim_dup16 d ON t.v=d.v GROUP BY d.v;
    ROLLBACK;
    Plans for cases B and C: where each alternative wins

    Case B — the cap wins: 298 ms versus 899 ms for occupancy (about 3x faster).

    This case has 600,000 fact rows, four partitions, and 150,000 distinct values deliberately present on all three segments. The actual NDV_BY_SEGMENTS is 450,000; the cap estimates 442,011 and occupancy estimates 357,222.

    Query:

    SELECT d.v, sum(t.quantity * t.price)
    FROM spread_4 t
    JOIN dim d ON t.v = d.v
    GROUP BY d.v;

    The cap chooses one-stage aggregation; occupancy chooses partial aggregation before the join.

    Conservative cap, EXPLAIN:

    Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..971.33 rows=145328 width=12)
      ->  HashAggregate  (cost=0.00..964.83 rows=48443 width=12)
            Group Key: d.v
            ->  Hash Join  (cost=0.00..940.23 rows=200000 width=14)
                  Hash Cond: (t.v = d.v)
                  ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..452.01 rows=200000 width=14)
                        Hash Key: t.v
                        ->  Dynamic Seq Scan on spread_4 t  (cost=0.00..438.04 rows=200000 width=14)
                              Number of partitions to scan: 4 (out of 4)
                  ->  Hash  (cost=432.05..432.05 rows=50000 width=4)
                        ->  Seq Scan on dim d  (cost=0.00..432.05 rows=50000 width=4)
    Optimizer: GPORCA
    

    Occupancy + MCV, EXPLAIN:

    Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..964.19 rows=145328 width=12)
      ->  Finalize HashAggregate  (cost=0.00..957.69 rows=48443 width=12)
            Group Key: d.v
            ->  Hash Join  (cost=0.00..942.92 rows=119075 width=12)
                  Hash Cond: (t.v = d.v)
                  ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..474.39 rows=119075 width=12)
                        Hash Key: t.v
                        ->  Streaming Partial HashAggregate  (cost=0.00..469.92 rows=119075 width=12)
                              Group Key: t.v
                              ->  Dynamic Seq Scan on spread_4 t  (cost=0.00..438.04 rows=200000 width=14)
                                    Number of partitions to scan: 4 (out of 4)
                  ->  Hash  (cost=432.05..432.05 rows=50000 width=4)
                        ->  Seq Scan on dim d  (cost=0.00..432.05 rows=50000 width=4)
    Optimizer: GPORCA
    

    Case C — occupancy wins: 831 ms versus 1072 ms for the cap (about 22% less execution time).

    This case has 300,000 fact rows and 150,000 distinct values, each occurring twice on one segment. The dimension contains 16 matching rows per key. The actual NDV_BY_SEGMENTS is 150,000; the cap estimates 300,000 and occupancy estimates 248,396.

    Query:

    SELECT d.v, sum(t.quantity * t.price)
    FROM colocated_2 t
    JOIN dim_dup16 d ON t.v = d.v
    GROUP BY d.v;

    Here the partial aggregate selected by occupancy reduces the rows entering the multiplying join; the cap chooses one-stage aggregation.

    Conservative cap, EXPLAIN:

    Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..1345.92 rows=145153 width=12)
      ->  HashAggregate  (cost=0.00..1339.43 rows=48385 width=12)
            Group Key: d.v
            ->  Hash Join  (cost=0.00..1144.60 rows=1602961 width=14)
                  Hash Cond: (t.v = d.v)
                  ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..441.51 rows=100000 width=14)
                        Hash Key: t.v
                        ->  Dynamic Seq Scan on colocated_2 t  (cost=0.00..434.52 rows=100000 width=14)
                              Number of partitions to scan: 2 (out of 2)
                  ->  Hash  (cost=447.72..447.72 rows=800000 width=4)
                        ->  Seq Scan on dim_dup16 d  (cost=0.00..447.72 rows=800000 width=4)
    Optimizer: GPORCA
    

    Occupancy + MCV, EXPLAIN:

    Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..1298.96 rows=145153 width=12)
      ->  Finalize HashAggregate  (cost=0.00..1292.47 rows=48385 width=12)
            Group Key: d.v
            ->  Hash Join  (cost=0.00..1131.09 rows=1327230 width=12)
                  Hash Cond: (t.v = d.v)
                  ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..454.04 rows=82799 width=12)
                        Hash Key: t.v
                        ->  Streaming Partial HashAggregate  (cost=0.00..450.93 rows=82799 width=12)
                              Group Key: t.v
                              ->  Dynamic Seq Scan on colocated_2 t  (cost=0.00..434.52 rows=100000 width=14)
                                    Number of partitions to scan: 2 (out of 2)
                  ->  Hash  (cost=447.72..447.72 rows=800000 width=4)
                        ->  Seq Scan on dim_dup16 d  (cost=0.00..447.72 rows=800000 width=4)
    Optimizer: GPORCA
    

    There are separate limitations to consider. ANALYZE sampling and the limited MCV list can produce imperfect frequency estimates; an error caused by those inputs does not, by itself, establish a flaw in the occupancy formula. Treating the values outside the MCV list as uniformly frequent is another approximation.

    The placement assumption can also fail even with exact frequencies. I checked this in a separate small example with 53 distinct values, 24,000 rows, and no join: DISTRIBUTED BY (dk) with v = dk + 1000. Both alternatives estimate 159 instead of the actual 53. The tested GROUP BY v query still retains the same two-stage plan and returns identical results. This is a different test from case C above; its SQL and captured output follow immediately below.

    Separate small correlation example: 53 distinct values, 24,000 rows, GROUP BY without a join
    -- Run on a three-segment Cloudberry cluster. Everything is rolled back.
    BEGIN;
    CREATE TABLE ndvbs_corr_example (id int, pk int, dk int, v int)
    DISTRIBUTED BY (dk)
    PARTITION BY RANGE (pk) (START (1) END (9) EVERY (1));
    
    INSERT INTO ndvbs_corr_example
    SELECT g, (g % 8) + 1, g % 53, (g % 53) + 1000
    FROM generate_series(1, 24000) g;
    ANALYZE ndvbs_corr_example;
    
    -- v determines dk, so all occurrences of each v are on a single segment.
    WITH per_value AS (
      SELECT v, count(*) AS k FROM ndvbs_corr_example GROUP BY v
    ), leaf_pairs AS (
      SELECT tableoid, gp_segment_id, v
      FROM ndvbs_corr_example GROUP BY 1, 2, 3
    ), segment_pairs AS (
      SELECT gp_segment_id, v FROM ndvbs_corr_example GROUP BY 1, 2
    ), inputs AS (
      SELECT count(*)::float8 AS d, sum(k)::float8 AS n,
             sum(3 * (1 - power(2.0 / 3, k::float8))) AS occupancy,
             (SELECT count(*)::float8 FROM leaf_pairs) AS leaf_sum,
             (SELECT count(*) FROM segment_pairs) AS actual
      FROM per_value
    )
    SELECT d AS root_distinct, leaf_sum, actual,
           least(leaf_sum, 3 * d) AS conservative_cap,
           round(least(leaf_sum, 3 * d, n, greatest(d, occupancy))::numeric, 3)
             AS author_occupancy
    FROM inputs;
    -- Expected: 53 | 424 | 53 | 159 | 159.000
    
    -- Inspect the estimate actually stored by the installed server variant.
    SELECT CASE 8
             WHEN s.stakind1 THEN s.stavalues1::text
             WHEN s.stakind2 THEN s.stavalues2::text
             WHEN s.stakind3 THEN s.stavalues3::text
             WHEN s.stakind4 THEN s.stavalues4::text
             WHEN s.stakind5 THEN s.stavalues5::text
           END AS stored_ndv_by_segments
    FROM pg_statistic s
    JOIN pg_attribute a ON a.attrelid = s.starelid AND a.attnum = s.staattnum
    WHERE s.starelid = 'ndvbs_corr_example'::regclass AND a.attname = 'v';
    -- Current main: {53}; either patched binary: {159}.
    
    SET LOCAL optimizer = on;
    EXPLAIN (ANALYZE, TIMING OFF)
    SELECT v, count(*) FROM ndvbs_corr_example GROUP BY v;
    -- All three compiled variants retained the same two-stage aggregate shape.
    ROLLBACK;

    Actual output from the SQL calculation, identical on all three binaries (this calculation uses exact value counts):

     root_distinct | leaf_sum | actual | conservative_cap | author_occupancy 
    ---------------+----------+--------+------------------+------------------
                53 |      424 |     53 |              159 |          159.000
    (1 row)
    

    The stored statistic produced by ANALYZE differs:

    Binary stored_ndv_by_segments
    Current main {53}
    Conservative cap {159}
    Occupancy + MCV {159}

    Current main, EXPLAIN ANALYZE excerpt:

     Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..432.26 rows=53 width=12) (actual rows=53 loops=1)
       ->  Finalize HashAggregate  (cost=0.00..432.25 rows=18 width=12) (actual rows=20 loops=1)
             Group Key: v
             ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..432.25 rows=18 width=12) (actual rows=20 loops=1)
                   Hash Key: v
                   ->  Streaming Partial HashAggregate  (cost=0.00..432.25 rows=18 width=12) (actual rows=19 loops=1)
                         Group Key: v
                         ->  Dynamic Seq Scan on ndvbs_corr_example  (cost=0.00..431.22 rows=8000 width=4) (actual rows=8605 loops=1)
                               Number of partitions to scan: 8 (out of 8)
    

    Both patched binaries produced the following EXPLAIN ANALYZE excerpt (memory diagnostics and timing summaries omitted):

     Gather Motion 3:1  (slice1; segments: 3)  (cost=0.00..432.26 rows=53 width=12) (actual rows=53 loops=1)
       ->  Finalize HashAggregate  (cost=0.00..432.26 rows=18 width=12) (actual rows=20 loops=1)
             Group Key: v
             ->  Redistribute Motion 3:3  (slice2; segments: 3)  (cost=0.00..432.25 rows=53 width=12) (actual rows=20 loops=1)
                   Hash Key: v
                   ->  Streaming Partial HashAggregate  (cost=0.00..432.25 rows=53 width=12) (actual rows=19 loops=1)
                         Group Key: v
                         ->  Dynamic Seq Scan on ndvbs_corr_example  (cost=0.00..431.22 rows=8000 width=4) (actual rows=8605 loops=1)
                               Number of partitions to scan: 8 (out of 8)
    

    The partial-aggregate estimate increases from 18 to 53 rows per segment, while the two-stage structure and final 53 result rows remain unchanged.

    I also completed the full SF1 TPC-H and TPC-DS suites for current main and both fixes: 22 TPC-H queries and 103 SQL statements from the 99 TPC-DS templates per variant.

    The fixes did change statistics: for example, the stored NDV_BY_SEGMENTS estimate for TPC-DS store_sales.ss_customer_sk increased from 235,953 on current main to 269,541 with the cap and 269,540 with the frequency-based estimate. Q23a and Q23b nevertheless retained the same partial-aggregation plan structures.

    This SF1 dataset contains 100,000 customer rows and 2,880,404 store_sales rows, whereas the #2407 reproduction contains 3,000,000 customer rows and 4,500,000 store_sales rows. The number of possible customer keys relative to sales rows is therefore very different. The SF1 run did not reproduce the bad plan switch from the issue; the separate issue reproduction above demonstrates the fix. I also verified that the related regression tests pass with both optimizers.

    Test environment and validation details

    The compiled comparison used main 8bfa4cd2b83eab464221bc57c37c6aa01c0b0350 on the provided Ubuntu 22.04.5 LTS test VM: x86_64, Linux 6.8.0-106-generic, 8 reported logical CPUs, an AMD Ryzen 7 3750H processor, and approximately 13.6 GiB RAM. One coordinator and three primary segments ran on the same machine. The build used -O2 -g, debug support, and assertions.

    The full SF1 TPC-H and TPC-DS runs used partitioned fact tables, optimizer=on, statement_mem=125MB, work_mem=32MB, default_statistics_target=100, and jit=off. I kept the data and leaf statistics identical, reanalyzed only the partition roots after switching binaries, and verified that the other root statistics were unchanged.

    All 22 TPC-H queries used GPORCA. TPC-DS queries 10, 35, and 69 fell back to the PostgreSQL planner in every variant; the other 100 TPC-DS statements used GPORCA.

    For the full suites, I first ran each query to verify its result, then measured one EXPLAIN ANALYZE execution. These are sums of query execution times for each suite, excluding data loading, ANALYZE, query planning, and the earlier result-checking executions:

    Query Main Cap Frequency
    Q1 2780.699 2796.542 2866.688
    Q2 222.649 209.082 214.149
    Q3 542.484 544.470 553.725
    Q4 932.336 917.856 901.948
    Q5 751.623 712.287 722.594
    Q6 97.050 98.539 100.621
    Q7 414.878 440.299 439.790
    Q8 703.551 731.520 699.008
    Q9 1370.270 1438.375 1430.047
    Q10 573.531 573.127 576.186
    Q11 147.555 111.725 118.783
    Q12 529.832 527.671 531.888
    Q13 592.848 610.576 679.751
    Q14 71.710 65.169 80.883
    Q15 97.180 96.137 95.254
    Q16 208.575 171.022 180.285
    Q17 3889.763 4074.543 3877.849
    Q18 2441.561 2471.018 2542.988
    Q19 544.550 442.394 448.079
    Q20 570.314 569.905 585.081
    Q21 2128.406 1970.176 2082.752
    Q22 374.243 380.701 373.172
    Summary 19985.608 19953.134 20101.521
    Query Main Cap Frequency
    Q1 126.413 108.508 121.360
    Q2 748.409 768.697 758.225
    Q3 311.232 300.868 303.103
    Q4 1815.389 1898.920 1933.881
    Q5 168.028 175.524 174.479
    Q6 83.296 73.128 82.943
    Q7 196.251 220.113 187.194
    Q8 83.188 92.512 86.245
    Q9 1725.387 1718.119 1713.995
    Q10 257.916 304.697 293.163
    Q11 1091.873 1066.919 1162.227
    Q12 19.999 23.633 30.905
    Q13 258.140 248.072 247.236
    Q14a 1706.776 1683.845 1648.895
    Q14b 1529.467 1513.354 1538.558
    Q15 62.827 46.065 54.703
    Q16 412.609 427.659 411.814
    Q17 101.220 91.942 91.183
    Q18 516.052 503.659 522.998
    Q19 71.589 65.408 64.550
    Q20 37.053 34.931 42.450
    Q21 67.190 67.423 74.857
    Q22 1804.747 1800.075 1767.584
    Q23a 3921.763 3989.636 3865.021
    Q23b 3965.093 3998.266 3794.941
    Q24a 372.685 373.930 364.352
    Q24b 440.081 376.089 421.756
    Q25 128.024 124.514 122.136
    Q26 207.117 267.448 211.084
    Q27 237.922 226.128 205.936
    Q28 897.826 908.525 905.547
    Q29 152.716 150.998 157.401
    Q30 84.621 80.352 80.287
    Q31 237.041 241.277 240.551
    Q32 39.879 45.520 43.322
    Q33 126.766 125.851 132.790
    Q34 178.885 181.500 188.481
    Q35 419.119 391.776 389.749
    Q36 507.829 531.470 493.048
    Q37 12.379 14.511 14.015
    Q38 584.373 574.529 588.103
    Q39a 261.215 251.178 238.644
    Q39b 264.266 246.415 232.742
    Q40 37.885 37.485 47.675
    Q41 7.732 9.974 10.492
    Q42 40.468 30.577 41.268
    Q43 234.667 263.735 297.730
    Q44 729.814 659.848 670.739
    Q45 51.506 57.046 52.066
    Q46 462.567 465.149 479.127
    Q47 859.662 885.859 799.276
    Q48 308.538 279.381 285.791
    Q49 145.887 142.431 146.184
    Q50 319.155 317.084 326.307
    Q51 1215.515 1356.889 1281.564
    Q52 41.654 33.811 43.963
    Q53 96.090 67.606 64.458
    Q54 99.924 99.457 93.309
    Q55 47.213 39.047 46.678
    Q56 111.182 101.131 119.292
    Q57 434.656 436.876 388.138
    Q58 147.705 137.891 129.236
    Q59 969.378 985.013 1018.869
    Q60 202.352 188.339 187.159
    Q61 73.921 71.114 71.747
    Q62 177.666 174.589 153.754
    Q63 91.142 88.966 73.139
    Q64 1079.200 1163.862 1214.628
    Q65 550.301 511.609 576.749
    Q66 154.945 154.619 152.126
    Q67 4593.778 4625.868 4438.069
    Q68 247.050 232.520 237.867
    Q69 252.014 239.388 243.156
    Q70 589.491 535.305 516.892
    Q71 91.839 95.918 87.158
    Q72 4289.959 4241.465 4228.227
    Q73 154.285 164.337 158.571
    Q74 826.399 843.675 806.900
    Q75 653.956 642.962 675.027
    Q76 355.706 350.030 380.962
    Q77 132.532 136.862 128.338
    Q78 1180.735 1178.304 1144.541
    Q79 461.154 486.200 445.480
    Q80 214.600 211.175 220.704
    Q81 69.125 88.202 68.297
    Q82 269.379 265.532 286.916
    Q83 318.601 330.684 336.728
    Q84 191.580 170.336 186.267
    Q85 342.526 319.428 381.595
    Q86 112.974 114.093 119.965
    Q87 586.346 583.076 573.381
    Q88 1365.192 1352.159 1418.547
    Q89 125.941 113.043 96.809
    Q90 138.532 134.829 139.135
    Q91 150.449 152.966 149.410
    Q92 27.540 28.261 31.292
    Q93 371.725 371.327 427.006
    Q94 250.072 253.597 261.267
    Q95 2061.593 2009.878 1978.317
    Q96 272.435 267.174 273.597
    Q97 423.850 431.169 509.307
    Q98 60.778 66.636 44.574
    Q99 283.399 293.249 286.760
    Summary 56390.911 56423.020 56054.980

    The incremental_analyze, bfv_aggregate, olap_plans, and subselect_gp regression tests pass for all three binaries with both optimizer=on and optimizer=off.

    On balance, I support the frequency-based approach, while keeping these limitations explicit. I’m now preparing a PR implementing this fix, including the single-column distribution-key special case, the bounds on the estimate, and regression coverage for values that can occupy different segments across partitions.

    Draft patch implementing the conservative cap
    diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
    index 194f49ee164..3a4952de3b4 100644
    --- a/src/backend/commands/analyze.c
    +++ b/src/backend/commands/analyze.c
    @@ -5018,12 +5018,10 @@ merge_leaf_stats(VacAttrStatsP stats,
     		old_context = MemoryContextSwitchTo(stats->anl_context);
     		bool valid;
     		double ndinstinct_by_segs = 0;
    -		double leaf_ndistinct_sum = 0;
     		Datum *ndvbs;
     
     		valid = aggregate_leaf_partition_ndvbs(
    -			numPartitions, heaptupleStats, relTuples, &ndinstinct_by_segs,
    -			&leaf_ndistinct_sum);
    +			numPartitions, heaptupleStats, relTuples, &ndinstinct_by_segs);
     
     		if (valid)
     		{
    @@ -5034,17 +5032,17 @@ merge_leaf_stats(VacAttrStatsP stats,
     			 * with the number of partitions and ORCA overestimates the output of
     			 * a local aggregate.
     			 *
    -			 * This statistic counts a distinct value once per segment holding
    -			 * it, so it is the column's ndistinct times the average number of
    -			 * segments a value sits on.  That average does not depend on the
    -			 * partitioning, so take it from the leaves, where the sums are free
    -			 * of the double counting, and apply it to the root's ndistinct.
    -			 * For a partitioning key, whose values belong to one leaf each, the
    -			 * result is the plain sum as before.
    +			 * A segment cannot contain more distinct values than the whole
    +			 * table, so cap the sum at the root's ndistinct times the number of
    +			 * segments.  Do not use the average number of segments per value
    +			 * from the leaves: a value can occur on different segments in
    +			 * different leaves, making that average too small for the root.
     			 *
    -			 * The average is between one and the number of segments.  Keeping
    -			 * the sum as an upper bound guards against the root's ndistinct and
    -			 * the leaves' one disagreeing, as they are estimated separately.
    +			 * If this column is the sole hash distribution key, equal values
    +			 * are confined to one segment and the cap is just root ndistinct.
    +			 * A column belonging to a multi-column key has no such guarantee.
    +			 * Retain the leaf sum as a cap too, since the root and leaf
    +			 * statistics are estimated separately.
     			 */
     			double		root_ndistinct = stats->stadistinct < 0 ?
     				-stats->stadistinct * totalTuples : stats->stadistinct;
    @@ -5054,16 +5052,14 @@ merge_leaf_stats(VacAttrStatsP stats,
     				GpPolicy   *policy = GpPolicyFetch(stats->attr->attrelid);
     				int			numsegments = policy->numsegments > 0 ?
     					policy->numsegments : getgpsegmentCount();
    -				double		segs_per_value;
     
    -				pfree(policy);
    -
    -				segs_per_value = leaf_ndistinct_sum > 0 ?
    -					ndinstinct_by_segs / leaf_ndistinct_sum : numsegments;
    -				segs_per_value = Min(Max(segs_per_value, 1.0), numsegments);
    +				if (GpPolicyIsHashPartitioned(policy) && policy->nattrs == 1 &&
    +					policy->attrs[0] == stats->attr->attnum)
    +					numsegments = 1;
     
     				ndinstinct_by_segs = Min(ndinstinct_by_segs,
    -										 root_ndistinct * segs_per_value);
    +										 root_ndistinct * numsegments);
    +				pfree(policy);
     			}
     
     			ndvbs = (Datum *) palloc(sizeof(Datum));
    diff --git a/src/backend/commands/analyzeutils.c b/src/backend/commands/analyzeutils.c
    index 7d8db5d1d1f..332097b7221 100644
    --- a/src/backend/commands/analyzeutils.c
    +++ b/src/backend/commands/analyzeutils.c
    @@ -1361,13 +1361,11 @@ bool
     aggregate_leaf_partition_ndvbs(int nParts,
     							   HeapTuple *heaptupleStats,
     							   float4 *relTuples,
    -							   float8 *result,
    -							   float8 *ndistinct_sum)
    +							   float8 *result)
     {
     	bool valid;
     	Assert(nParts > 0);
     	Assert(result);
    -	Assert(ndistinct_sum);
     
     	AttStatsSlot **ndvbsSlots = (AttStatsSlot **) palloc0((nParts) * sizeof(AttStatsSlot *));
     	valid = getNdvBySegHeapTuple(ndvbsSlots, heaptupleStats, relTuples, nParts);
    @@ -1375,22 +1373,10 @@ aggregate_leaf_partition_ndvbs(int nParts,
     		for (int i = 0; i < nParts; i++)
     		{
     			if (ndvbsSlots[i]) {
    -				Form_pg_statistic stat;
    -
     				*result += DatumGetFloat8(ndvbsSlots[i]->values[0]);
    -
    -				/*
    -				 * Sum the leaves' own ndistinct as well.  Both sums are over
    -				 * the same leaves and on the same (absolute) scale, so their
    -				 * ratio tells how many segments a distinct value of this
    -				 * column sits on, on average.  See merge_leaf_stats().
    -				 */
    -				stat = (Form_pg_statistic) GETSTRUCT(heaptupleStats[i]);
    -				*ndistinct_sum += stat->stadistinct < 0 ?
    -					-stat->stadistinct * relTuples[i] : stat->stadistinct;
     			}
     		}
     	}
     
     	return valid;
    -}
    \ No newline at end of file
    +}
    diff --git a/src/include/commands/analyzeutils.h b/src/include/commands/analyzeutils.h
    index 8f936b9b6fe..33ca85d458a 100644
    --- a/src/include/commands/analyzeutils.h
    +++ b/src/include/commands/analyzeutils.h
    @@ -64,6 +64,5 @@ extern bool leaf_parts_analyzed(Oid attrelid, Oid relid_exclude, List *va_cols,
     extern bool aggregate_leaf_partition_ndvbs(int nParts,
     								HeapTuple *heaptupleStats,
     								float4 *relTuples,
    -								float8 *result,
    -								float8 *ndistinct_sum);
    +								float8 *result);
     #endif  /* ANALYZEUTILS_H */
    diff --git a/src/test/regress/sql/incremental_analyze.sql b/src/test/regress/sql/incremental_analyze.sql
    index c326ca2d893..1f3adc67209 100644
    --- a/src/test/regress/sql/incremental_analyze.sql
    +++ b/src/test/regress/sql/incremental_analyze.sql
    @@ -931,3 +931,30 @@ select c.relname, a.attname,
      order by 2, 1;
     reset default_statistics_target;
     drop table ndvbs_part_seg;
    +
    +-- A value occurring once in each leaf can land on different segments in
    +-- different leaves.  The leaf segments-per-value ratio is one, but must not
    +-- limit the root to one segment per value.  Being part of a multi-column
    +-- distribution key does not make a column's values colocated either.
    +set default_statistics_target = 100;
    +create table ndvbs_sparse (id int, pk int, v int) distributed by (id, v)
    +  partition by range (pk) (start (0) end (3) every (1));
    +insert into ndvbs_sparse
    +  select p * 100 + v, p, v
    +  from generate_series(0, 2) p, generate_series(1, 100) v;
    +analyze ndvbs_sparse;
    +select ndv_by_segments > 1.5 * ndistinct as spans_segments,
    +       ndv_by_segments <= least(300, 3 * ndistinct) as bounded
    +from (
    +  select ((case 8 when s.stakind1 then s.stavalues1::text when s.stakind2 then s.stavalues2::text
    +                 when s.stakind3 then s.stavalues3::text when s.stakind4 then s.stavalues4::text
    +                 when s.stakind5 then s.stavalues5::text end)::float8[])[1] as ndv_by_segments,
    +         case when s.stadistinct < 0 then -s.stadistinct * c.reltuples
    +              else s.stadistinct end as ndistinct
    +    from pg_statistic s
    +    join pg_class c on c.oid = s.starelid
    +    join pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
    +   where s.starelid = 'ndvbs_sparse'::regclass and a.attname = 'v'
    +) s;
    +reset default_statistics_target;
    +drop table ndvbs_sparse;
    diff --git a/src/test/regress/expected/incremental_analyze.out b/src/test/regress/expected/incremental_analyze.out
    index 5786403d1bb..78604f03dc2 100644
    --- a/src/test/regress/expected/incremental_analyze.out
    +++ b/src/test/regress/expected/incremental_analyze.out
    @@ -2136,3 +2136,34 @@ select c.relname, a.attname,
     
     reset default_statistics_target;
     drop table ndvbs_part_seg;
    +-- A value occurring once in each leaf can land on different segments in
    +-- different leaves.  The leaf segments-per-value ratio is one, but must not
    +-- limit the root to one segment per value.  Being part of a multi-column
    +-- distribution key does not make a column's values colocated either.
    +set default_statistics_target = 100;
    +create table ndvbs_sparse (id int, pk int, v int) distributed by (id, v)
    +  partition by range (pk) (start (0) end (3) every (1));
    +insert into ndvbs_sparse
    +  select p * 100 + v, p, v
    +  from generate_series(0, 2) p, generate_series(1, 100) v;
    +analyze ndvbs_sparse;
    +select ndv_by_segments > 1.5 * ndistinct as spans_segments,
    +       ndv_by_segments <= least(300, 3 * ndistinct) as bounded
    +from (
    +  select ((case 8 when s.stakind1 then s.stavalues1::text when s.stakind2 then s.stavalues2::text
    +                 when s.stakind3 then s.stavalues3::text when s.stakind4 then s.stavalues4::text
    +                 when s.stakind5 then s.stavalues5::text end)::float8[])[1] as ndv_by_segments,
    +         case when s.stadistinct < 0 then -s.stadistinct * c.reltuples
    +              else s.stadistinct end as ndistinct
    +    from pg_statistic s
    +    join pg_class c on c.oid = s.starelid
    +    join pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
    +   where s.starelid = 'ndvbs_sparse'::regclass and a.attname = 'v'
    +) s;
    + spans_segments | bounded 
    +----------------+---------
    + t              | t
    +(1 row)
    +
    +reset default_statistics_target;
    +drop table ndvbs_sparse;
    
    Draft frequency-based estimate patch
    diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
    index 194f49ee164..0fe60d20442 100644
    --- a/src/backend/commands/analyze.c
    +++ b/src/backend/commands/analyze.c
    @@ -5018,12 +5018,10 @@ merge_leaf_stats(VacAttrStatsP stats,
     		old_context = MemoryContextSwitchTo(stats->anl_context);
     		bool valid;
     		double ndinstinct_by_segs = 0;
    -		double leaf_ndistinct_sum = 0;
     		Datum *ndvbs;
     
     		valid = aggregate_leaf_partition_ndvbs(
    -			numPartitions, heaptupleStats, relTuples, &ndinstinct_by_segs,
    -			&leaf_ndistinct_sum);
    +			numPartitions, heaptupleStats, relTuples, &ndinstinct_by_segs);
     
     		if (valid)
     		{
    @@ -5034,17 +5032,12 @@ merge_leaf_stats(VacAttrStatsP stats,
     			 * with the number of partitions and ORCA overestimates the output of
     			 * a local aggregate.
     			 *
    -			 * This statistic counts a distinct value once per segment holding
    -			 * it, so it is the column's ndistinct times the average number of
    -			 * segments a value sits on.  That average does not depend on the
    -			 * partitioning, so take it from the leaves, where the sums are free
    -			 * of the double counting, and apply it to the root's ndistinct.
    -			 * For a partitioning key, whose values belong to one leaf each, the
    -			 * result is the plain sum as before.
    -			 *
    -			 * The average is between one and the number of segments.  Keeping
    -			 * the sum as an upper bound guards against the root's ndistinct and
    -			 * the leaves' one disagreeing, as they are estimated separately.
    +			 * Estimate segment occupancy from root-level frequencies rather
    +			 * than the leaves' segments-per-value ratio.  Under independent
    +			 * placement, k occurrences occupy S * (1 - (1 - 1/S)^k) segments
    +			 * on average.  Use the MCV frequencies and distribute the remaining
    +			 * non-null rows uniformly among the remaining distinct values.
    +			 * Equal values of the sole hash distribution key are colocated.
     			 */
     			double		root_ndistinct = stats->stadistinct < 0 ?
     				-stats->stadistinct * totalTuples : stats->stadistinct;
    @@ -5054,16 +5047,50 @@ merge_leaf_stats(VacAttrStatsP stats,
     				GpPolicy   *policy = GpPolicyFetch(stats->attr->attrelid);
     				int			numsegments = policy->numsegments > 0 ?
     					policy->numsegments : getgpsegmentCount();
    -				double		segs_per_value;
    +				double		nonnull_rows = Max(0.0,
    +					totalTuples * (1.0 - stats->stanullfrac));
    +				double		estimate = 0.0;
    +				double		upper_bound;
    +
    +				if (numsegments == 1 ||
    +					(GpPolicyIsHashPartitioned(policy) && policy->nattrs == 1 &&
    +					 policy->attrs[0] == stats->attr->attnum))
    +					estimate = root_ndistinct;
    +				else
    +				{
    +					double		remaining_rows = nonnull_rows;
    +					double		remaining_distinct = root_ndistinct;
    +					double		log_absent = log1p(-1.0 / numsegments);
     
    -				pfree(policy);
    +					for (int slot = 0; slot < slot_idx; slot++)
    +					{
    +						if (stats->stakind[slot] != STATISTIC_KIND_MCV)
    +							continue;
    +
    +						for (int mcv = 0; mcv < stats->numnumbers[slot]; mcv++)
    +						{
    +							double		count = Max(0.0,
    +								totalTuples * stats->stanumbers[slot][mcv]);
     
    -				segs_per_value = leaf_ndistinct_sum > 0 ?
    -					ndinstinct_by_segs / leaf_ndistinct_sum : numsegments;
    -				segs_per_value = Min(Max(segs_per_value, 1.0), numsegments);
    +							estimate -= numsegments * expm1(count * log_absent);
    +							remaining_rows -= count;
    +							remaining_distinct -= 1.0;
    +						}
    +						break;
    +					}
     
    -				ndinstinct_by_segs = Min(ndinstinct_by_segs,
    -										 root_ndistinct * segs_per_value);
    +					if (remaining_distinct > 0 && remaining_rows > 0)
    +						estimate -= numsegments * remaining_distinct *
    +							expm1(remaining_rows / remaining_distinct * log_absent);
    +				}
    +
    +				upper_bound = Min(ndinstinct_by_segs,
    +								  root_ndistinct * numsegments);
    +				upper_bound = Min(upper_bound, nonnull_rows);
    +				/* Prefer the upper bound if separately estimated bounds cross. */
    +				ndinstinct_by_segs = Min(upper_bound,
    +										 Max(root_ndistinct, estimate));
    +				pfree(policy);
     			}
     
     			ndvbs = (Datum *) palloc(sizeof(Datum));
    diff --git a/src/backend/commands/analyzeutils.c b/src/backend/commands/analyzeutils.c
    index 7d8db5d1d1f..332097b7221 100644
    --- a/src/backend/commands/analyzeutils.c
    +++ b/src/backend/commands/analyzeutils.c
    @@ -1361,13 +1361,11 @@ bool
     aggregate_leaf_partition_ndvbs(int nParts,
     							   HeapTuple *heaptupleStats,
     							   float4 *relTuples,
    -							   float8 *result,
    -							   float8 *ndistinct_sum)
    +							   float8 *result)
     {
     	bool valid;
     	Assert(nParts > 0);
     	Assert(result);
    -	Assert(ndistinct_sum);
     
     	AttStatsSlot **ndvbsSlots = (AttStatsSlot **) palloc0((nParts) * sizeof(AttStatsSlot *));
     	valid = getNdvBySegHeapTuple(ndvbsSlots, heaptupleStats, relTuples, nParts);
    @@ -1375,22 +1373,10 @@ aggregate_leaf_partition_ndvbs(int nParts,
     		for (int i = 0; i < nParts; i++)
     		{
     			if (ndvbsSlots[i]) {
    -				Form_pg_statistic stat;
    -
     				*result += DatumGetFloat8(ndvbsSlots[i]->values[0]);
    -
    -				/*
    -				 * Sum the leaves' own ndistinct as well.  Both sums are over
    -				 * the same leaves and on the same (absolute) scale, so their
    -				 * ratio tells how many segments a distinct value of this
    -				 * column sits on, on average.  See merge_leaf_stats().
    -				 */
    -				stat = (Form_pg_statistic) GETSTRUCT(heaptupleStats[i]);
    -				*ndistinct_sum += stat->stadistinct < 0 ?
    -					-stat->stadistinct * relTuples[i] : stat->stadistinct;
     			}
     		}
     	}
     
     	return valid;
    -}
    \ No newline at end of file
    +}
    diff --git a/src/include/commands/analyzeutils.h b/src/include/commands/analyzeutils.h
    index 8f936b9b6fe..33ca85d458a 100644
    --- a/src/include/commands/analyzeutils.h
    +++ b/src/include/commands/analyzeutils.h
    @@ -64,6 +64,5 @@ extern bool leaf_parts_analyzed(Oid attrelid, Oid relid_exclude, List *va_cols,
     extern bool aggregate_leaf_partition_ndvbs(int nParts,
     								HeapTuple *heaptupleStats,
     								float4 *relTuples,
    -								float8 *result,
    -								float8 *ndistinct_sum);
    +								float8 *result);
     #endif  /* ANALYZEUTILS_H */
    diff --git a/src/test/regress/sql/incremental_analyze.sql b/src/test/regress/sql/incremental_analyze.sql
    index c326ca2d893..1f3adc67209 100644
    --- a/src/test/regress/sql/incremental_analyze.sql
    +++ b/src/test/regress/sql/incremental_analyze.sql
    @@ -931,3 +931,30 @@ select c.relname, a.attname,
      order by 2, 1;
     reset default_statistics_target;
     drop table ndvbs_part_seg;
    +
    +-- A value occurring once in each leaf can land on different segments in
    +-- different leaves.  The leaf segments-per-value ratio is one, but must not
    +-- limit the root to one segment per value.  Being part of a multi-column
    +-- distribution key does not make a column's values colocated either.
    +set default_statistics_target = 100;
    +create table ndvbs_sparse (id int, pk int, v int) distributed by (id, v)
    +  partition by range (pk) (start (0) end (3) every (1));
    +insert into ndvbs_sparse
    +  select p * 100 + v, p, v
    +  from generate_series(0, 2) p, generate_series(1, 100) v;
    +analyze ndvbs_sparse;
    +select ndv_by_segments > 1.5 * ndistinct as spans_segments,
    +       ndv_by_segments <= least(300, 3 * ndistinct) as bounded
    +from (
    +  select ((case 8 when s.stakind1 then s.stavalues1::text when s.stakind2 then s.stavalues2::text
    +                 when s.stakind3 then s.stavalues3::text when s.stakind4 then s.stavalues4::text
    +                 when s.stakind5 then s.stavalues5::text end)::float8[])[1] as ndv_by_segments,
    +         case when s.stadistinct < 0 then -s.stadistinct * c.reltuples
    +              else s.stadistinct end as ndistinct
    +    from pg_statistic s
    +    join pg_class c on c.oid = s.starelid
    +    join pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
    +   where s.starelid = 'ndvbs_sparse'::regclass and a.attname = 'v'
    +) s;
    +reset default_statistics_target;
    +drop table ndvbs_sparse;
    diff --git a/src/test/regress/expected/incremental_analyze.out b/src/test/regress/expected/incremental_analyze.out
    index 5786403d1bb..78604f03dc2 100644
    --- a/src/test/regress/expected/incremental_analyze.out
    +++ b/src/test/regress/expected/incremental_analyze.out
    @@ -2136,3 +2136,34 @@ select c.relname, a.attname,
     
     reset default_statistics_target;
     drop table ndvbs_part_seg;
    +-- A value occurring once in each leaf can land on different segments in
    +-- different leaves.  The leaf segments-per-value ratio is one, but must not
    +-- limit the root to one segment per value.  Being part of a multi-column
    +-- distribution key does not make a column's values colocated either.
    +set default_statistics_target = 100;
    +create table ndvbs_sparse (id int, pk int, v int) distributed by (id, v)
    +  partition by range (pk) (start (0) end (3) every (1));
    +insert into ndvbs_sparse
    +  select p * 100 + v, p, v
    +  from generate_series(0, 2) p, generate_series(1, 100) v;
    +analyze ndvbs_sparse;
    +select ndv_by_segments > 1.5 * ndistinct as spans_segments,
    +       ndv_by_segments <= least(300, 3 * ndistinct) as bounded
    +from (
    +  select ((case 8 when s.stakind1 then s.stavalues1::text when s.stakind2 then s.stavalues2::text
    +                 when s.stakind3 then s.stavalues3::text when s.stakind4 then s.stavalues4::text
    +                 when s.stakind5 then s.stavalues5::text end)::float8[])[1] as ndv_by_segments,
    +         case when s.stadistinct < 0 then -s.stadistinct * c.reltuples
    +              else s.stadistinct end as ndistinct
    +    from pg_statistic s
    +    join pg_class c on c.oid = s.starelid
    +    join pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
    +   where s.starelid = 'ndvbs_sparse'::regclass and a.attname = 'v'
    +) s;
    + spans_segments | bounded 
    +----------------+---------
    + t              | t
    +(1 row)
    +
    +reset default_statistics_target;
    +drop table ndvbs_sparse;
    
  3. added
    type: Bug
    type: Performance
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: Bugtype: Performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions