Repository navigation
Description
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_plansandsubselect_gppass withoptimizer=onandoptimizer=off.incremental_analyzepasses 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
github-actions commentedon Nov 24, 2026
Hi, @yjhjstz welcome!🎊 Thanks for taking the time to point this out.🙌
Alena0704 commentedon Nov 25, 2026
I compared your frequency-based occupancy formula with the simpler conservative cap:
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_partregression 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_partcase has eight partitions and 24,000 rows, with grouping columnsg % 53andg % 3. The old uncapped leaf sums are 1272 and 72; in the earlier statistics-level check these selected:Both compiled fixes store 159 and 9 and preserve:
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:
Current main selects:
Both fixes select:
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:
independent_4joined todim): 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.spread_4joined todim): 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.colocated_2joined todim_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=1000and 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:
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.
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 asspread_4, and case C ascolocated_2joined todim_dup16. It rolls back all test objects at the end.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:
The cap chooses one-stage aggregation; occupancy chooses partial aggregation before the join.
Conservative cap, EXPLAIN:
Occupancy + MCV, EXPLAIN:
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:
Here the partial aggregate selected by occupancy reduces the rows entering the multiplying join; the cap chooses one-stage aggregation.
Conservative cap, EXPLAIN:
Occupancy + MCV, EXPLAIN:
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)withv = dk + 1000. Both alternatives estimate 159 instead of the actual 53. The testedGROUP BY vquery 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
Actual output from the SQL calculation, identical on all three binaries (this calculation uses exact value counts):
The stored statistic produced by ANALYZE differs:
Current main, EXPLAIN ANALYZE excerpt:
Both patched binaries produced the following EXPLAIN ANALYZE excerpt (memory diagnostics and timing summaries omitted):
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_skincreased 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
8bfa4cd2b83eab464221bc57c37c6aa01c0b0350on 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, andjit=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:
The
incremental_analyze,bfv_aggregate,olap_plans, andsubselect_gpregression tests pass for all three binaries with bothoptimizer=onandoptimizer=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
Draft frequency-based estimate patch