Skip to content

Unified cardinality estimation across join order, distributed and Cascades planners - #124320

Open
davenger wants to merge 158 commits into
masterfrom
estimation-minimal-plan
Open

davenger wants to merge 158 commits into
masterfrom
estimation-minimal-plan

Conversation

@davenger

@davenger davenger commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

ClickHouse chooses join orders, broadcast-or-shuffle and aggregation strategies from row count estimates. Three components make these estimates (the join order optimizer, the rule-based distributed planner and the Cascades optimizer), and until now each did it its own way. Worse, when no estimate was available, each silently invented one: one row here, zero rows or a million there. A guessed "one row" makes a join look free, so the optimizer joins it first and broadcasts it, and nothing in the system showed that the number was a guess.

This PR makes estimation one shared thing and makes it honest:

  • Same numbers everywhere. All three components call the same functions for joins, aggregations and filters, so a join is estimated once and every planner sees the same value. Several operations that had no estimate at all (semi and anti joins, subqueries, unions, distinct) now have one.
  • Unknown is unknown. When statistics cannot give an estimate, the planners work with the maximum number of rows the step can possibly produce instead of a made-up value, and the estimate is reported as unknown. Guesses no longer drive plan choices.
  • Estimates are visible. EXPLAIN estimates = 1 shows the estimate and where it came from for every planner. system.processors_profile_log records, for every processor, the estimate of the step that created it next to the rows the step actually produced. Estimation errors can finally be measured on real queries.
  • A safety cap for broadcasts. A distributed plan copies a join side or a small table to every node. The new setting distributed_plan_max_bytes_to_broadcast (default 1 GB) caps the size of such a copy. An estimate that rests on guessed selectivities does not authorize a broadcast on its own; the plan has to prove with the row bound that the copy fits.

The result is more predictable plans (no more decisions that hinge on an invented number), consistency between the local and the distributed planners, a way to measure how good the estimates are, and protection against the costliest mistake a wrong estimate can cause.

Several plans in the TPC-H reference test change; each change traces to an estimate that is now computed rather than assumed.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Query planners share one set of row estimation formulas, and a missing estimate is treated as unknown instead of being replaced by a guessed row count. EXPLAIN estimates = 1 shows the estimates of every planner, and system.processors_profile_log records the estimate of each plan step next to its actual row count (plan_step_estimated_rows, plan_step_estimate_source). New setting distributed_plan_max_bytes_to_broadcast caps the amount of data a distributed query plan copies to every node.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/124320]

davenger and others added 11 commits October 6, 2026 23:27
…ptimizer's join estimate

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…a, count each predicate once

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…off and damped product, shared by all planners

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…s, reduce key NDVs through filters

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e, shared by both planners

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…es, default provenance, saturating conversions

Semi over an empty side, paste, any and asof joins follow one formula and bound in every planner;
the Cascades clamps are gone. Each Cascades operator decides what an unknown or empty input means.
A limit is a bound, not an estimate, and bounds nothing with ties; statistical NDVs do not bound a
group count; grouping sets count the groups of every set, array joins have no bound. The statistics estimator reports every
default it takes and the flag reaches the replication budget in both planners; the scan cap applies
to replicated scans only; the cloud object storage read takes the budget. Float row counts convert
with saturation. The rule-based rewrites keep their node estimates.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…or, one key estimate, no optional multi-key models

The Cascades join, aggregation and distinct derivations call the shared `estimateJoin` and
`estimateGroupStats` over the inputs as relations instead of mirroring them. The two optional
models (`query_plan_join_selectivity_exponential_backoff`, `query_plan_group_count_damped_product`)
and the predicate deduplication they needed are removed; the most selective key decides, as before.
One saturating conversion, one saturating arithmetic, one stand-in and domain lookup, an origin enum
on the join step instead of two flags, no write-only annotation flag.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…icate sections and cost noise

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52a9aa4]

Summary: ❌

job_name test_name status info comment
Unit tests (amd_debug) FAIL
CascadesTaskLimit.OverrideOnlyLowersTheBudget FAIL cidb
AllTests FAIL cidb
Unit tests (asan_ubsan) FAIL
CascadesTaskLimit.OverrideOnlyLowersTheBudget FAIL cidb
AllTests FAIL cidb
Unit tests (tsan) FAIL
CascadesTaskLimit.OverrideOnlyLowersTheBudget FAIL cidb
AllTests FAIL cidb
Unit tests (msan) FAIL
CascadesTaskLimit.OverrideOnlyLowersTheBudget FAIL cidb
AllTests FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (amd_illumos) DROPPED

AI Review

Summary

This PR shares cardinality estimation across join ordering, distributed planning, and Cascades; exposes estimates in EXPLAIN and processor logs; and adds a replication byte budget. ❌ Block: moving runtime-filter key expressions across exchanges can lose valid matches, and several bounds, widths, and provenance transitions still defeat the replication guard or mislead planning. The 24 existing open findings below remain applicable to the current code. No new inline findings or thread replies were posted.

Missing context / blind spots
  • ⚠️ Findings are verified by current-source traces, without compiled local reproductions: this checkout has no build directory. Cross-host runtime-filter execution and Cloud-only object-storage planning still need focused runtime validation. The fetched Praktika reports show 14,479 passed tests, 4,503 skipped, and no failures; those results do not exercise the specific outstanding traces below.
Findings

❌ Blockers

  • filterPushDown.cpp:1266 — server-local keys: query determinism does not guarantee the same value on different hosts. FQDN passes this guard, so moving a probe key below a gather changes its hostname suffix while the build key remains on the join host. Valid join matches can be filtered out. Reject server-constant functions throughout the expression, including lambda bodies.

  • filterPushDown.cpp:1266 — stateful keys: the guard also accepts stateful functions such as timeSeriesTagsToGroup. A read task can retain tag B under group ID 2, then the join task's fresh collector recomputes B as ID 1 and loses its match. Reject stateful functions using the existing traversal that includes hidden function bodies.

⚠️ Majors

  • RelationStatisticsEstimator.cpp:254 — aggregation output NDVs: grouping-key NDVs are capped by the input bound rather than the aggregation output. An input estimated at 10 rows, bounded by 1000, with key NDV 100 produces a 10-group estimate but retains NDV 100. Downstream joins consume the contradictory value. Cap each output NDV by the estimated output rows, otherwise the output bound.

  • StatisticsDerivation.cpp:736 — union search provenance: UNION ALL inherits search_value_is_join_product only from its first input. A later unknown join branch therefore misses exchange costing that should consult the bound, making plan choice depend on branch order. Combine this provenance across every input.

  • joinOrder.cpp:168 — manufactured NDVs: a bound-only 10-row input can inherit NDV 1000 from the opposite join side. With no output estimate, the final NDV clamp does not run, and downstream joins treat the synthetic value as measured statistics. Cap it by available row bounds and preserve its assumed provenance.

  • StatisticsDerivation.cpp:731 — unknown union widths: widths are weighted by search values even for unknown inputs, then used with the union's hard row bound. A wide branch with search value 1 and bound one billion is nearly ignored, admitting an oversized broadcast. Use conservative widths when cardinalities are unknown.

  • RelationStatistics.cpp:311 — composite equality bounds: the floating-point exclusion checks only the outer type. Four stored signed-zero combinations in Tuple(Float64, Float64) can satisfy one equality while remaining four grouping representations, yet receive a distinct-value bound of 1. Exclude nested floating-point carriers or prove equality implies one grouping representation.

  • StatisticsDerivation.cpp:252 — row-expanding steps: generic propagation preserves input cardinality and bounds for RollupStep, CubeStep, and FillingStep. One aggregated row over ten cube keys can become 1024 rows while retaining a bound of 1. Derive expansion bounds or mark the output unknown and unbounded at the common propagation point.

  • RuleUtils.cpp:57 / StatisticsDerivation.cpp:625 — expression output widths: expressions preserve the input row width after changing the output type. An 8-byte key expanded to FixedString(1024) below a sort/limit is priced at 800 bytes for 100 rows rather than 102400. Recompute output widths from the output header and preserved column measurements before any replication decision.

  • Serialization.cpp:256 — wire specification: serialized plans now contain per-node CostEstimationInfo bytes under version 21, but the matching protocol specification is unchanged. Document the record layout and version gate in the same change.

  • joinOrderCommon.h:202 — legacy ANY RIGHT JOIN: legacy RightAny emits a match for every matching left row, whereas this helper bounds it by the right side. One right zero joined to 1000 left zeros produces 1000 rows with a reported bound of 1. Model this strictness separately, including unmatched right rows.

  • Statistics.cpp:279 — fractional estimates: knownRows rounds a positive estimate such as 99 / 99 / 99 to zero. The shared join estimator then takes its empty-input shortcut, and subsequent sizing can trust a zero estimate. Preserve positive estimates or distinguish estimated zero from proven emptiness.

  • StatisticsDerivation.cpp:333 — unknown single-match joins: unknown ANY/SEMI/ANTI results fall back to an unrestricted join product instead of the shared strictness-aware search calculation. A LEFT ANY JOIN bounded by 1000 rows can be costed as one million. Use the shared calculation and respect the output bound.

  • ConditionSelectivityEstimator.cpp:1238 — default NULL selectivity: an existing column estimator without a measured NULL count takes a default without setting used_default. For 100000 rows containing 50000 NULLs, IS NULL can estimate 1000 rows and authorize replication as measured statistics. Propagate defaults from both NULL estimators when their counts are unavailable.

  • RuleUtils.cpp:59 / Statistics.cpp:257 — repeated-scan width: scan bytes use the read's output width, excluding columns consumed only by PREWHERE or row policies. Reading 100 wide predicate values while returning an 8-byte key can count 800 bytes instead of over 102400. Derive scan volume from all columns actually read, separately from network output width, in both planners.

  • RelationStatisticsEstimator.cpp:657 — delayed Memory reads: materialized CTEs and GLOBAL subqueries populate their temporary tables during execution. Reading their current zero count during planning publishes a false zero estimate and bound. Leave delayed inputs unknown or use their producing subplans; obtain ordinary read bounds from the pinned snapshot.

  • RelationStatisticsEstimator.cpp:319 — empty grouping sets: multiplying an empty input bound by the number of grouping sets returns zero even when () emits one aggregate row. A downstream cross join can consequently receive a false zero bound and pass replication sizing. Bound each grouping set according to its own keys and empty-input semantics.

  • StatisticsTDigest.cpp:69 — mixed centroids: distinct centroid means do not establish one original value per centroid. With repeated endpoint values and an interior value, mixed centroids can outnumber the original distinct values while omitting the interior value itself. getCountEqual then reports zero for matching rows. Require a condition that proves unmixed centroids or decline exact equality counting.

  • StatisticsDerivation.cpp:603 — arrayJoin in filter DAGs: the expression guard does not cover FilterStep. With lowering disabled, a filter expanding each of 100 input rows 1000 times retains the 100-row bound, allowing replication based on 800 bytes instead of 800000. Invalidate cardinality guarantees for this carrier in both estimators.

  • joinOrder.cpp:99 — comparison-compatible uniqueness: grouping uniqueness does not guarantee uniqueness under the join's comparison. Hash grouping distinguishes signed-zero representations, while full_sorting_merge matches them numerically; two grouped zeros can match each of 100 probe rows despite a bound of 100. Require uniqueness compatible with the comparison and key coercions before narrowing bounds.

  • StatisticsDerivation.cpp:270 — unknown source width: an unknown source keeps the one-byte width default even for FixedString(1024). A following LIMIT 100 can authorize replication under a 4096-byte budget although its values require 102400 bytes. Initialize source widths from the output header and available column measurements.

  • RelationStatisticsEstimator.cpp:784 — repeated grouping keys: the shared estimator preserves grouping-key uniqueness and input max_rows across explicit and expression-form array expansion. Repeating each grouped key 1000 times can leave a downstream join bounded by 100 rows although it emits 100000. Invalidate uniqueness and row bounds across every row-expanding carrier.

  • RelationStatisticsEstimator.cpp:280 — multi-key grouping assumptions: fully measured individual NDVs do not measure their combinations. A complete 1000-by-1000 grid is estimated as 1000 groups without an imprecision flag, so a 16000000-byte result is admitted as 16000 bytes. Mark modeled multi-key correlation assumptions as imprecise unless joint statistics or a proven bound justify them, including Cascades DISTINCT.

  • Statistics.cpp:333 — unknown data-lake cardinality: the object-storage adapter substitutes the row bound for an absent estimate but leaves rows_unknown = false. A filtered Iceberg read without usable statistics is then exposed and consumed as a known full-table estimate. Initialize cardinality and provenance through applyRelationStats before filling widths and scan size.

Tests
  • ⚠️ Add focused runtime-filter comparisons with filtering enabled and disabled across different hosts and fresh task contexts, covering server-local and stateful keys, including lambda carriers.
  • ⚠️ Check actual rows against reported bounds for array-expanding expressions/filters, CUBE/ROLLUP/WITH FILL, empty grouping sets, legacy RightAny, delayed materialized CTEs, and signed-zero keys. Include a downstream replication decision so the false-bound consequences are observable.
  • ⚠️ Add budget regressions for expanded fixed-width projections, unknown sources, unions with unknown wide branches, and narrow outputs with wide PREWHERE inputs. Assert that results exceeding the modeled budget are declined.
  • ⚠️ Cover fully measured independent grouping keys, missing NULL-count statistics, skewed mixed centroids, positive sub-row estimates feeding joins, and filtered Iceberg reads without usable statistics. Existing formula snapshots do not establish these provenance and boundary invariants.
Final Verdict

❌ Block. Reject stateful and server-local key expressions before exchange pushdown; repair cardinality, width, and provenance propagation at the shared boundaries above; update the serialized-plan specification; and add focused regressions for the failing traces. Existing threads already cover every finding, so no duplicate inline comments are needed.

@davenger
davenger marked this pull request as draft October 6, 2026 21:48
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Oct 6, 2026
davenger and others added 2 commits October 7, 2026 12:24
…th from the estimator

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ERE move and the join algorithm

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 52a9aa4c6 with master 2c0b9d725 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

779 object files changed (+1.87 MiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeJoin.cpp.o 746.59 KiB 1.24 MiB +518.76 KiB (+69.48%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Rules/JoinEnumeration.cpp.o new 132.27 KiB +132.27 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/Optimizer.cpp.o 322.36 KiB 441.89 KiB +119.53 KiB (+37.08%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp.o 146.72 KiB 256.89 KiB +110.17 KiB (+75.09%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDPSub.cpp.o 328.14 KiB 434.10 KiB +105.95 KiB (+32.29%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/RelationStatistics.cpp.o 56.70 KiB 143.57 KiB +86.88 KiB (+153.22%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/JoinGraphStep.cpp.o new 73.76 KiB +73.76 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrder.cpp.o 250.45 KiB 289.68 KiB +39.23 KiB (+15.66%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexReadResultPool.cpp.o 291.68 KiB 323.54 KiB +31.86 KiB (+10.92%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDP.cpp.o 100.13 KiB 131.71 KiB +31.58 KiB (+31.54%)
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.28 MiB 2.30 MiB +23.57 KiB (+1.01%)
src/CMakeFiles/dbms.dir/Core/Settings.cpp.o 3.57 MiB 3.59 MiB +22.97 KiB (+0.63%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderDPSize.cpp.o 124.77 KiB 105.22 KiB -19.55 KiB (-15.67%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/joinOrderBitSet.cpp.o 59.65 KiB 77.92 KiB +18.27 KiB (+30.64%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/ReplicationEligibility.cpp.o new 17.52 KiB +17.52 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/Cascades/RuleUtils.cpp.o 178.05 KiB 195.52 KiB +17.47 KiB (+9.81%)
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp.o 256.83 KiB 273.37 KiB +16.54 KiB (+6.44%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

2289 translation units recompiled, 14777 s compile time in total, 2286 of them have a recent master baseline.

Translation unit Master PR Δ vs median
src/Processors/QueryPlan/Optimizations/joinOrderDPSub.cpp 5.2 s 14.8 s +9.3 s (+170%)
src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp 17.0 s 25.2 s +7.5 s (+42%)
src/Processors/QueryPlan/Optimizations/Cascades/GroupExpression.cpp 3.0 s 10.0 s +6.9 s (+222%)
src/Processors/QueryPlan/Optimizations/Cascades/Group.cpp 3.3 s 10.3 s +6.9 s (+201%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/TopNImplementation.cpp 3.9 s 10.8 s +6.6 s (+162%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/ReplicatedSubplanImplementation.cpp 4.2 s 10.9 s +6.6 s (+151%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/TwoStageTopN.cpp 4.1 s 10.8 s +6.6 s (+154%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/DistributionEnforcer.cpp 4.3 s 10.9 s +6.5 s (+144%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/SortingEnforcer.cpp 4.0 s 10.6 s +6.5 s (+154%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/JoinCommutativity.cpp 4.3 s 10.9 s +6.4 s (+144%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/DistributionPassthrough.cpp 4.2 s 10.7 s +6.4 s (+146%)
src/Processors/QueryPlan/Optimizations/Cascades/Task.cpp 4.4 s 11.0 s +6.3 s (+138%)
src/Processors/QueryPlan/Optimizations/Cascades/Rule.cpp 4.1 s 10.5 s +6.3 s (+148%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/WindowImplementation.cpp 4.3 s 10.7 s +6.3 s (+140%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/DistinctImplementation.cpp 4.1 s 10.5 s +6.2 s (+145%)
src/Processors/QueryPlan/Optimizations/Cascades/Memo.cpp 3.9 s 10.3 s +6.2 s (+150%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/HashJoinImplementation.cpp 5.2 s 11.4 s +6.0 s (+110%)
src/Processors/QueryPlan/Optimizations/Cascades/Rules/AggregationImplementations.cpp 6.5 s 12.1 s +5.4 s (+80%)
src/Processors/QueryPlan/Optimizations/RuntimeFilterExchangeWiring.cpp 6.4 s 11.8 s +5.1 s (+76%)

Translation units without a recent master baseline:

  • src/Processors/QueryPlan/Optimizations/Cascades/Rules/JoinEnumeration.cpp: 11.4 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 14.31 MiB 14.38 MiB +64.00 KiB (+0.44%)
programs/clickhouse ProfileEvents::global_counters_storage 14.31 MiB 14.38 MiB +64.00 KiB (+0.44%)

Job report

…plan

The join order optimizer keeps master's rule for an equality without a key NDV from statistics:
the join keeps its larger side, as a foreign key meeting a primary key. A relation with neither
an estimate nor a row bound counts as one row again, a join without an estimate counts the rows
its cost counted, and the greedy algorithm prefers a pair joined on a key.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Processors/QueryPlan/QueryPlan.cpp Resolved
davenger and others added 2 commits October 8, 2026 10:25
… cloned subplan keeps its estimates

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ion, take min(name) instead of any(name)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
davenger and others added 15 commits November 8, 2026 23:01
…0 tables in the prototype

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the join enumeration prototype

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the `DPsub` cost over all splits

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…`: the `DPsub` winner of every set

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…of every set by the `DPsub` cost

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oin budget to `best_splits`

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… join keys

Adds `query_plan_join_order_distribution` and `cascades_join_enumeration = 'frontier'`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…reads by storage widths

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `hash_join_layout` tests take their inputs without an estimate from a filter, since the join order optimizer is no
longer the only source of estimates. 05406 matches the label of an input without an estimate that shows its bound,
05350 the `HashJoin` name of both layouts, 05260 the join order with the new estimates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
UInt64 rows_without_statistics = 0;
/// Every value of the column is on at most one row: the column is the only key of an aggregation. A join on it
/// matches each row of the other side at most once. Whatever can repeat a row (a join, a union) drops the flag.
bool unique = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] Clear grouping-key uniqueness when an ARRAY JOIN repeats rows.

The shared estimator now sets this flag for a single grouping key, but its existing ArrayJoinStep / ExpressionStep expansion branch (RelationStatisticsEstimator.cpp:784–806) copies the input statistics and never clears unique on the columns it repeats. For example, SELECT k FROM (SELECT k, count() FROM t GROUP BY k) ARRAY JOIN range(1000) AS a emits 1000 copies of each k, yet still advertises k.unique = true. The same branch also retains the new input max_rows despite expanding the result.

DPJoinEntry consumes that flag to cap an ALL join by the opposite input's row count (joinOrder.cpp:99–102). With 100 grouped keys and 100 matching probe keys, the result contains 100000 rows but can receive a hard bound of 100. For an imprecise estimate, the new replication guard deliberately uses that false bound: an 8-byte projected key is priced at 800 bytes under a 4096-byte budget instead of 800000 value bytes.

Please invalidate uniqueness and row bounds at every row-expanding carrier in the shared estimator, including the explicit clause and expression forms, and cover an expanded grouped key feeding another join. Cascades already clears these properties for those two forms; fixing only the separate filter-DAG carrier leaves this path open. This is a concrete source trace; I could not run a compiled reproduction in this checkout.

davenger and others added 2 commits November 9, 2026 20:33
if (keys.size() == 1)
aggregation_stats.column_stats[keys.front()].unique = true;

auto groups = estimateGroupCount(group_keys, input_stats.estimated_rows, input_stats.max_rows);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] Mark the multi-key grouping model as an assumption before using it to authorize replication.

When every grouping key has statistics, estimateGroupStats leaves both reliability flags false, although the default estimateGroupCount model uses only the largest individual NDV. Individual NDVs do not measure the number of key combinations.

For a stored complete 1000 × 1000 grid of two UInt64 columns, with uniq statistics covering both columns and all parts, SELECT DISTINCT a, b has 1,000,000 rows. This path estimates 1000, retains a 1,000,000-row bound, and reports a precise estimate. Both replication guards therefore count 16,000 bytes and accept a 32,000-byte budget instead of consulting the 16,000,000-byte bound. GROUP BY a, b has the same issue. This differs from the missing-key case: all per-column statistics are present, and the unmarked assumption is their correlation. The analogous multi-key join assumption is explicitly tracked by joinRowsRestOnAssumption.

Please propagate an imprecision/default flag for modeled multi-key group counts unless joint statistics or a proven bound justify the smaller result, including the Cascades DISTINCT path. Add a focused byte-budget regression with independent keys whose individual NDVs are fully measured. This is a source trace; I could not run a compiled reproduction in this checkout.

Comment on lines +331 to +333
stats.imprecise_estimate = relation_stats.imprecise_estimate;
stats.estimate_from_defaults = relation_stats.estimate_from_defaults;
stats.source = relation_stats.source;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[Major] Preserve unknown cardinality in the data-lake adapter.

estimateReadRowsCount deliberately returns estimated_rows = nullopt with a row bound when an Iceberg predicate has neither column statistics nor file pruning. This adapter puts that bound in estimated_row_count but leaves rows_unknown at its default false.

For example, an unpartitioned Iceberg table with 1000 rows in Avro files, without column statistics, filtered by WHERE k = 7 reaches the shared estimator with only max_rows = 1000. Cascades instead publishes a known 1000-row estimate through buildBestPlan, and downstream joins consume it through knownRows. Thus the planners disagree, and EXPLAIN estimates = 1 / the processor log report a bound as an estimate, violating the new “unknown is unknown” contract.

Please initialize the adapter through applyRelationStats before filling widths and scan size, so all cardinality/provenance fields travel together. Add a focused estimate regression for a filtered Iceberg read without column statistics, with make_distributed_plan = 1 and enable_cascades_optimizer = 1. This is source-traced, not an executed reproduction.

This branch has not been deployed

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

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants