Skip to content

Do not cost a relation without a row estimate as a single row when reordering joins - #120762

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-join-order-unknown-cardinality-not-cheap
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-join-order-unknown-cardinality-not-cheap

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120176

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not needed: the regression is master-only and unreleased.

Description

Performance Comparison (arm_release, master_head, 5/6) has been red on master and ~48% of PR runs since #120176 merged: iceberg_suite_tpch aborts when TPC-H Q5 crosses max_execution_time = 15. It is user-visible on default settings too: a second execution was 11x slower at 6.8x the memory.

Root cause: computeJoinCost charged a relation with no row estimate one row (estimated_rows.value_or(1)). Since #120176 an equi join without reliable NDV keeps the larger side, so a pair of unestimated relations costs max(1, 1) = 1 while any pair touching a measured relation costs that estimate. The solver therefore joins the relations it knows nothing about first, although estimates are usually available for the small, filtered relations.

Change: cost an absent cardinality as the largest estimated relation of the same query graph. With nothing estimated the surrogate is 1 and behaviour is unchanged; with everything estimated it is never consulted.

Review follow-up: DPsub's cost path ignored the join's resolved strictness, so the surrogate priced a SEMI/ANTI join over an unestimated relation as expanding to it and deferred a selective filter behind the larger join (peak RSS 425-566 MB -> 717-757 MB, same results). It is now capped at its preserved side's rows when a row count was substituted; fully estimated graphs keep today's plans.

Validation, TPC-H Q5 over the CI Iceberg SF10 dataset, second execution: 37173 ms / 24.42 GiB peak (aborted on the memory limit) -> 3122 ms / 4.00 GiB, identical results. On MergeTree the shipped tests/benchmarks/tpc-ds query_59 goes 437 ms -> 76 ms, 5.65M -> 412K rows into the aggregation, identical answers. The test pins the join order for greedy, dpsub, dphyp and for semi/anti under a conflict detector, and fails without the change; it is the only outcome change across 1131 stateless *join* tests.

CI provenance (true master, 07f2c4013ce9): report.


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

groeneai and others added 2 commits September 18, 2026 08:24
…ordering joins

optimizeJoin has no row estimate for a relation read from object storage
(RelationStatisticsEstimator.cpp returns an empty RelationStats for
ReadFromObjectStorageStep) or for a MergeTree relation filtered on a non-index
column. computeJoinCost charged such a relation one row, via
estimated_rows.value_or(1), in joinOrderCommon.h for greedy/dpsize/dphyp and in
EnumeratorCheckerWithCosts::computeJoinCost for dpsub.

Since a42ceae (PR ClickHouse#120176) an equi join without reliable NDV keeps the
larger side, so a join of two unestimated relations costs max(1, 1) = 1 while
any join touching a relation with a real estimate costs that estimate. The
solver therefore joins every relation it knows nothing about first and defers
the ones it measured. That is inverted: an estimate is most often available
exactly for the small, filtered relations, so the plan builds the big unfiltered
relation into a huge intermediate and applies the selective filter last.

Before ClickHouse#120176 the fabricated 1 was latent. The old model derived NDV from the
relation row count, so known(N) x unknown(1) also cost (1/N) * 1 * N = 1, every
candidate tied, the greedy solver fell back to enumeration order, and the plan
was the good one.

Cost an absent cardinality as the largest estimated relation of the same query
graph instead. With no relation estimated the surrogate is 1 and the model is
byte-identical to before; with every relation estimated it is never consulted;
only the mixed case changes, which is the defective one. The alternative of
gating the cached hash-table row counts on a fully estimated graph was rejected:
it guards the symptom, and the same inversion is reachable with no cache at all,
e.g. a MergeTree table filtered on a non-index column joined to an Iceberg one.

effectiveSelectivity keeps value_or(1) deliberately. It exists to be comparable
with the cartesian selectivity EXPLAIN ANALYZE reports, so with unknown sides
the honest value is the neutral 1.0; the surrogate would print a fabricated
1/surrogate there.

This reddened Performance Comparison (arm_release, master_head, 5/6) on master
and on ~48% of PR runs: iceberg_suite_tpch aborts when TPC-H Q5 crosses
max_execution_time = 15, discarding the shard's whole perf verdict. Measured on
the CI Iceberg SF10 dataset, two executions of Q5 in one server process (the
harness's prewarm then measure), debug build, both servers capped at 32G:

  before: 3448 ms / 3.61 GiB, then 37173 ms / 24.42 GiB (hit the memory limit)
  after:  3618 ms / 3.62 GiB, then  3122 ms /  4.00 GiB, identical results

The optimizer's logged plan cost for the second execution goes from 2275923
(= 2275919 + 4x1) to 11379595 (= 5 x 2275919), i.e. every candidate now ties at
the surrogate and the second execution reproduces the first one's plan. The
first execution's cost is unchanged at 5.

The new test asserts the join order for greedy, dpsub and dphyp on a graph with
three estimated relations and one unestimated one; it fails without this change
on all three. No .reference in the join-order family changes, and across all
1131 stateless *join* tests the new test is the only outcome difference.

Co-Authored-By: Claude Opus 5 <[email protected]>
Removed the rowsForJoinCost block (restated value_or below it; rationale is in the commit message) and reduced the unknown_relation_rows field comment to a one-line invariant.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own cold
review of the resulting tree (3 nits). No fix round was needed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The unknown-row surrogate ignores SEMI/ANTI strictness and can defer a selective semi join behind a larger join (enumeratorChecker.h:97-118) DISAGREE Reordering a SEMI/ANTI join needs conflictDetectorReordersSemiAnti (optimizeJoin.cpp:411-418): a conflict detector ON and dpsub as the sole algorithm. Both detector settings default to false and are EXPERIMENTAL (Settings.cpp:9424-9431), the default algorithm is greedy, and the CI randomizer never enables a detector. Otherwise such a join is swap-only (optimizeJoin.cpp:1504-1510) and the swap path never calls computeJoinCost. computeJoinCost was also strictness-blind before this PR; the strictness-blind primitive is estimateJoinedRows from #120176. No plan change was observed, and a solver offered 100010 and 200000 takes 100010.
2 ⚠️ The new test does not prove t_unknown is unestimated or that the fallback is exercised DISAGREE The test fails on pristine HEAD and passes with the change, measured with two Build-IDs from one commit, and all three solver blocks move, so both cost sites are exercised. I re-derived it by hand: surrogate 100000 gives t_big,t_unknown,t_small_a,t_small_b at cost 200020, value_or(1) gives t_small_a,t_unknown,t_small_b,t_big at 100030; both match the servers' logged plan costs. The gate's own probe injected cardinality:100000, which is exactly the surrogate this graph derives, so identical output is the predicted result. Asserting an internal no_stats label and an exact cost instead would pin strings and a scalar that any cost-model change rewrites.
3 💡 The surrogate is derived at the call site (optimizeJoin.cpp:955-971) while the sibling graph-carried optimizer inputs are set in optimizeJoinOrder (joinOrder.cpp:368-370); the field defaults to 1, the old value AGREE, not blocking Only one caller exists today, so there is no live defect. Left as is to keep the diff minimal; happy to move the derivation if you prefer it next to the detector flags.
4 💡 dpsize is the fourth costing solver and is not in the test's solver matrix AGREE, not blocking It costs through the same evaluateJoin line as dphyp, which is asserted, so the changed statement is covered; only the per-solver outcome is not.
5 💡 The local base-vs-fix outcome diff covered the 1131 *join* tests; plan-pinning tests without join in the name were not diffed locally AGREE, not blocking Only mixed-estimate graphs can change, and this PR's own CI runs the whole suite.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Two notes from the investigation that are not changes here, in case they are useful:

  • The report for this failure showed six perf.py frames and no error message. perf.py re-raises a
    driver error from a measured run and aborts the whole test file, and compare.sh's head -10 of
    the per-test err.log cuts the traceback immediately before the Code: 159 Timeout exceeded
    line, so the actual cause is not visible in the report at all. That is why this was first
    mis-triaged as a path-permission problem.
  • The report stage restarts the perf servers with relative --path / --user_files_path, which
    yields a doubled left/db/left/db/user_files root and a Code: 481 PATH_ACCESS_DENIED on every
    IcebergLocal ATTACH. It happens ~50 minutes after the tests finish and does not affect the
    check's verdict.
  • ReadFromObjectStorageStep returns no row estimate at all, although Iceberg manifests carry
    record_count; supplying it would remove the need for a surrogate in this shape entirely.
  • My open Keep the smaller side on the hash join build side when it has no row estimate #113336 touches these same files with a per-relation sound upper bound for build-side
    selection. Different consumer, no overlap in the substituted value, but it will conflict textually
    and its bound would be a better surrogate source than this graph-wide maximum.

Session id: cron:clickhouse-review-slot-8:20260918-082800

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05227_join_order_unknown_cardinality_not_cheap fails on pristine HEAD (Build-ID c82559ebc20d) and passes with the change (b1bc55ffa497), 100/100 runs with and without CI settings randomization. The real workload reproduces on demand too: TPC-H Q5 over the CI Iceberg SF10 dataset, second execution in the same server process, 37173 ms / 24.42 GiB.
b Root cause explained? computeJoinCost charged a relation with no row estimate one row (estimated_rows.value_or(1)). Since #120176 an equi join without reliable NDV keeps the larger side, so unknown x unknown costs max(1,1)=1 while any join touching an estimated relation costs that estimate; the solver joins the relations it cannot estimate first. Confirmed against the optimizer's own logged plan costs: 100030 vs 200020 synthetic, 2275923 vs 5 x 2275919 on Q5.
c Fix matches root cause? Yes, the fabricated 1 is replaced at both of its sites. Not a band-aid: the rejected alternative (apply cached hash-table hints only when every relation is estimated) guards the symptom - the same inversion is reachable with no cache at all, which is exactly the shape of the new test.
d Test intent preserved / new tests added? New regression test added. Nothing weakened: no bound widened, no dataset shrunk, no no-random-* tag, and no .reference in the 49-test join-order family changed.
e Both directions demonstrated? Yes, twice: the new test (FAIL pristine / OK patched, two servers from the same commit) and the real query (37173 ms / 24.42 GiB, aborting on the memory limit, -> 3122 ms / 4.00 GiB with identical results).
f Fix is general across code paths? Both cost functions fixed - joinOrderCommon.h (greedy, dpsize, dphyp) and enumeratorChecker.h (dpsub) - so all four solvers are covered, and three are asserted in the test. Fixed in the cost model, not guarded at the Iceberg reader or at the statistics cache. effectiveSelectivity, estimateJoinCardinality, computeSelectivity and the Cascades cost model were each checked and are deliberately unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? No column types or values are involved; the substituted quantity is a row count. The input matrix is the estimate state of the graph, all three cases covered: all estimated (surrogate never read), none estimated (surrogate 1, byte-identical - proven by the unchanged cost: 5 on Q5's first execution and 0 reference changes), mixed (the defective case). Boundaries: < 2 relations throws before the solver; estimated_rows = 0 yields 1 via the std::max floor; UInt64::max is carried as before.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no changed default, no SettingsChangesHistory.cpp entry, no format or serialization change. Plan shapes for partially-estimated graphs do change - that is the fix - and no in-tree plan assertion is affected.
i Invariants and contracts preserved? estimated_rows stays nullopt for an unestimated relation, so imprecise_estimate, RowEstimateSource, EXPLAIN's "unknown rows" label and every other RelationStats consumer are untouched; only the cost scalar changes. The surrogate is computed once before the solver runs and is read-only afterwards (const member in the DPsub checker), so no solver can see two values in one optimization; it defaults to 1, so no early-return path can leave it unset. No locks, no concurrency, no persisted state.

Session id: cron:clickhouse-impl-slot-41:20260918-071100

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5fab300]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR changes join-order costing so relations without estimated_rows are charged a query-graph surrogate instead of 1, and it adds regression coverage for the DP, greedy, and conflict-detector SEMI/ANTI paths. The current tree also fixes the earlier DPsub SEMI/ANTI costing gap, and I did not find new correctness, compatibility, or coverage issues in the touched code.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 5fab300.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 45/46 (97.83%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 5fab300b6cb44f16e0ba2d817241163dfb22a21e with master failed: RuntimeError: CI logs cluster query failed: SELECT file, symbol, sumIf(size, side = 'pr….

See the job log for details.

`EnumeratorCheckerWithCosts::accept` resolves the join's kind and strictness before costing the
pair, but `computeJoinCost` ignored both and always used `estimateJoinedRows`, which returns
`max(lhs, rhs)` for a non-reliable equi join. Charging an unestimated relation
`unknown_relation_rows` therefore priced a semi/anti join over it as expanding to that surrogate,
although such a join only filters its preserved side and its recorded cardinality is clamped
accordingly.

With `query_plan_optimize_join_order_algorithm = 'dpsub'` and a conflict detector (the only
configuration that reorders semi/anti joins instead of swapping them), a selective `SEMI`/`ANTI`
filter over an unestimated relation was deferred behind the larger join. Measured on `k_a` (10
rows) semi-joined to an unestimated relation and inner-joined to `k_big` (1e6 rows, 100k per key):
the plan changed from filter-first to filter-last and peak RSS rose from 425-566 MB to 717-757 MB
over three runs each, because the 1e6-row intermediate is materialised before the filter. Results
are unchanged.

The cost increment is now capped at the preserved side's row count when a side's row count was
substituted, which is an unconditional upper bound on what a semi/anti join emits. Two narrower
variants were measured and rejected: taking the increment from `estimateJoinCardinality` prices
every anti join at 1 row without column statistics (1 instead of 1000 on a disjoint-key fixture),
and capping unconditionally also reorders fully estimated graphs, where it moves a non-selective
anti join ahead of a selective inner join. Costing a relation the optimizer cannot estimate is
what this change is about, so graphs whose relations are all estimated keep the plans and costs
they have today.

Only DPsub under CD-A/CD-C is affected: `evaluateJoin` always passes `JoinStrictness::All`, and
the greedy solver never receives a semi/anti graph because `conflictDetectorReordersSemiAnti`
requires DPsub as the sole algorithm. `rowsForJoinCost` returns `UInt64` so a row count never
round-trips through `double` (`estimated_rows` can be `UInt64::max()`, whose round-trip is
undefined).

Reported by the automated reviewer on the pull request.
@snelheidai

Copy link
Copy Markdown

Independent confirmation on a different workload: this also recovers a shipped TPC-DS query on MergeTree, not only TPC-H Q5 on the CI Iceberg fixture.

Setup: TPC-DS adapted SF10 on MergeTree (store_sales 28,800,991), shipped tests/benchmarks/tpc-ds queries and settings, 4 vCPU / 30 GiB x86, one server at a time on one datadir, serving binary verified per block by hashing /proc/PID/exe. Base master 83a6d57ed224 (26.10.1.1), with the PR head 5fab300 applied unmodified (9 files, +194/-14).

Shipped query_59, warm: 3.336 s (mean of 12 timed runs on clean master) -> ~1.69 s with the PR. The mechanism is the join order, not a change in filter count:

clean master with PR
rows into AggregatingTransform 54,993,272 11,219,459
user CPU 3773 ms 1751 ms
read_rows 57,894,382 57,894,382
runtime-filter steps in plan 4 4

Answers byte-identical in every run. A 26.9.1.1 binary on the same datadir feeds about 11.0M rows into the aggregation, so the PR restores the pre-regression pruning level here. That binary still runs query_59 in ~1.29 s; since it is a release build rather than this checkout, I would not read the remaining ~0.4 s as a plan defect.

One thing worth knowing given the link to #120176: on this query the regression has a second, independent trigger. Because an equi join with one unknown side now reports the known side, query_59 reports a 102-row probe, and join_runtime_filter_min_probe_rows (1000) declines a runtime filter that would prune below the aggregation. Making that gate ignore a guessed estimate is worth -30.7% on master as it stands, but with this PR applied it no longer helps (1.693/1.690 s default vs 1.707/1.719 s at join_runtime_filter_min_probe_rows=0) because the better join order already restores the pruning. The two are not additive here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Reproduced both halves locally on MergeTree, with the shipped tests/benchmarks/tpc-ds query_59 and settings.json.

Fixture: store_sales 2,880,404 rows (SF1 volume, 4.48% NULL ss_sold_date_sk, synthetic calendar), date_dim 73,049, store 102. Sales span 5,000 days, so each 12-month window keeps ~7% of them against ~20% at SF10, which is why my ratios come out larger than yours. Binaries: master 83a6d57ed224 (Build-ID c82559eb) and this PR's head 5fab300 (ced69239, confirmed by reproducing 05227's reference). clickhouse local, 5 timed runs per arm, median:

arm wall rows into Aggregating* peak runtime filters built
master 437 ms 5,648,742 287 MiB d_date_sk x2, s_store_sk x2
master, join_runtime_filter_min_probe_rows=0 311 ms 3,029,748 267 MiB + d_week_seq x2, s_store_id
this PR 76 ms 411,870 30 MiB d_date_sk x2, d_week_seq x2
this PR, gate off 82 ms 407,893 32 MiB same

read_rows is 6,053,208 and the 100 result rows are byte-identical in all four arms.

The solver log names your second trigger outright: on master the first pair taken is wss JOIN store at cost 1 with cardinality 102, and that 102 is what join_runtime_filter_min_probe_rows = 1000 reads as the probe size, so it declines the d_week_seq filter that would prune below the aggregation. Before #120176 that composite had no estimate at all, so the gate could not decline anything. With the surrogate the same pair costs 330, store JOIN store goes first, and the week filter is built again.

So -28.8% from relaxing the gate on master alone, next to your -30.7%, and no further win once the join order is fixed (76 -> 82 ms): not additive, agreed. I am not extending this PR to that gate. Whether a guessed estimate should feed min_probe_rows is a separate question, and I have no measurement of a consequence that survives this fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5fab300

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff CI-infrastructure: the job aborts with RuntimeError: CI logs cluster query failed in compare_symbols (ci/jobs/build_profile_diff_job.py:1375); 180 distinct PRs carry it today #118708 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260918-220128

@rschu1ze

Copy link
Copy Markdown
Member

Resolved by #120923

@rschu1ze rschu1ze closed this Sep 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified and agreed, nothing here to re-target, so I am leaving this closed.

What I checked on current master: computeJoinCost is back to selectivity * lhs * rhs with getColumnStats falling back to a relation's row count as its NDV, so a relation with a cached row count is no longer the expensive thing to join, and estimateJoinCardinality returns no estimate at all when either side is unknown. The nine source files the revert touches match the merge parent 8701bfd byte for byte, except for the later conflict-detector enum change in joinOrder.h and joinOrderDPSub.cpp. CI agrees: 378 master Performance Comparison shard runs today across 33 commits with no failure, and 1768 iceberg_suite_tpch rows since the revert landed, none failed (8 slower).

One note for whenever the heuristic re-lands, since it is a second consumer of that estimate rather than the cost model: the runtime-filter effect I measured earlier in this thread (#120762 (comment)) fires only when getInputRowsEstimation(Left) is present and at most join_runtime_filter_min_probe_rows, and the 102-row value that triggered it on TPC-DS query_59 (437 ms against 311 ms with the gate off) was the propagated guess, so it is moot with the revert in place.

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

Labels

can be tested Allows running workflows for external contributors comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants