Skip to content

Fix INNER JOIN cardinality underestimation in join reorder optimizer - #109261

Closed
JingYanchao wants to merge 14 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/fix-inner-join-order
Closed

JingYanchao wants to merge 14 commits into
ClickHouse:masterfrom
JingYanchao:johnjing/fix-inner-join-order

Conversation

@JingYanchao

@JingYanchao JingYanchao commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry

Fixed the join reorder optimizer placing a large fact table on the hash-join build side in star-schema queries when column statistics are unavailable. A narrow guard now suppresses the build/probe swap when a statistics-less composite subtree that contains a base table larger than the other side is joined with a single smaller dimension table.

Analysis

The join reorder optimizer uses 1/max(NDV_left, NDV_right) as join selectivity. Without per-column NDV statistics, estimated_rows of the table is used as a proxy for NDV. For a star schema query like fact JOIN dim_a ON dim_a.key = fact.key_a JOIN dim_b ON dim_b.key = fact.key_b, the selectivity of fact JOIN dim_a becomes 1/max(100000, 100) = 1/100000, producing a cardinality estimate of 100000 * 100 / 100000 = 100 rows — far below the actual ~100000 rows.

This makes the optimizer believe the intermediate result is tiny (100 rows) compared to dim_b (200 rows), so it swaps the join sides and puts the large fact table on the build side — exactly the wrong decision for a star-schema workload.

Fix

A narrow swap guard in chooseJoinOrder (optimizeJoin.cpp): do not swap build/probe sides when all of the following hold:

  • the left side is a composite (multi-table) subtree whose cardinality estimate is proxy-based. The join order optimizer records this in DPJoinEntry::estimate_is_stats_based (markStatsBasedEstimates in joinOrder.cpp), filled for the chosen plan before cleanupJoinPredicates rewrites the predicates. It mirrors every NDV lookup computeSelectivity makes: both sides of every equi-predicate attached to a step (including predicates routed to residual_filter) and every member of every column-equivalence class spanning the two sides — so a proxy-based lookup on the transitive-predicate path is caught even when predicate cleanup removes it from the step's expression. Since the step selectivity is the minimum over contributions of 1/max(ndv...), a proxy fallback only affects the estimate when its value actually wins that competition, so a step is marked proxy-based only when the largest proxy-backed NDV strictly exceeds every stats-backed one — a stats-less small dimension joined on a fact key with a real uniq statistic does not poison the flag. The flag is recursive over the whole subtree because the underestimation of an earlier proxy-based join propagates upward,
  • the right side is a single table (a dimension),
  • the composite contains a base table larger than the right side's estimate.

The guard only gates the physical build/probe-side choice and never changes cardinality estimates, so the enumerated join order is unaffected. When column statistics are available, the standard formula already produces reasonable estimates and the guard does not fire.

Regression tests: 04498_join_reorder_star_schema_cardinality (no statistics at all), 04609_join_reorder_star_schema_mixed_stats (an unrelated dimension statistic must not disable the guard), 04611_join_reorder_star_schema_partial_key_stats (a statistic on a later join key must not mask an earlier proxy-based join inside the composite), 04621_join_reorder_star_schema_transitive_stats (with enable_join_transitive_predicates, a stats-less fact key reachable only through the equivalence class must not be masked by a stats-covered retained predicate), 04622_join_reorder_star_schema_dominant_stats (a proxy lookup that loses the NDV competition to a real fact-key statistic must not fire the guard, so the beneficial swap of the correctly-estimated composite is kept).

(An earlier revision of this PR implemented this as an unconditional INNER JOIN cardinality floor, and an intermediate revision as an NDV cap in estimateJoinCardinality; both changed cardinality estimates globally and were replaced by this narrower guard.)

Per review, the 03960_join_order_dphyp_basic/_cycle/_transitive_predicates tests now pin materialize_statistics_on_insert = 1 — they declared uniq statistics and set use_statistics = 1 but never materialized the statistics, so their pinned plans were driven by the estimated_rows NDV proxy. Their references are regenerated for plans driven by real NDV estimates (the swap guard does not fire on them anymore); result-check hashes and row counts are unchanged.

Example of a star-schema query whose performance was poor because lineorder (the fact table) was moved to the build side:

SELECT l.*, c.C_NAME, s.S_NAME, p.P_NAME, d.D_YEAR
FROM lineorder AS l
INNER JOIN customer AS c ON c.C_CUSTKEY = l.LO_CUSTKEY
INNER JOIN supplier AS s ON s.S_SUPPKEY = l.LO_SUPPKEY
INNER JOIN part AS p ON p.P_PARTKEY = l.LO_PARTKEY
INNER JOIN date AS d ON d.D_DATEKEY = l.LO_ORDERDATE;

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6c015c7]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Stateless tests (amd_tsan, parallel) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Stateless tests (amd_msan, WasmEdge, parallel, 1/2) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, 1/3) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
04622_join_reorder_star_schema_dominant_stats FAIL cidb
04622_join_reorder_star_schema_dominant_stats FAIL cidb

AI Review

Summary

The current head fixes the earlier mixed-statistics and transitive-predicate regressions, but two correctness gaps remain in the new star-schema guard machinery. The guard is still asymmetric in chooseJoinOrder, so supported algorithms such as dphyp can bypass it just by storing the poisoned composite on the right, and joinStepEstimateIsStatsBased no longer reproduces the exact getColumnStats lookups for multi-relation expression keys. Those gaps are enough to keep requesting changes.

PR Metadata

💡 Changelog category should be Performance Improvement, not Bug Fix. This PR changes join-side selection to avoid poor INNER JOIN performance; it does not fix wrong results, a user-visible exception, or another stable-release misbehavior in the Bug Fix sense.

Exact replacement:
Performance Improvement

Improves star-schema join reordering when column statistics are unavailable by keeping large fact-table composites off the hash-join build side, avoiding poor INNER JOIN performance on those queries.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp:1226] The new guard only handles the case where the underestimated composite is entry->left. dphyp stores the final pair as (csg, cmp), not “probe side first”, so the same star query can still reach this code as left = dim_b, right = (fact JOIN dim_a). In that orientation the bad composite remains on the build side without ever hitting the guard.
    Suggested fix: make the guard symmetric around the side that would become the hash-build side, and add a regression that uses query_plan_optimize_join_order_algorithm = 'dphyp' with the larger dimension first in the relation order.
  • [src/Processors/QueryPlan/Optimizations/joinOrder.cpp:1833] joinStepEstimateIsStatsBased stops matching getColumnStats when a join key expression uses a multi-relation subset that is smaller than the final child subtree. The estimator consults dp_table for the exact subset, but this replay substitutes the enclosing child's column_stats / estimated_rows, which can change whether the proxy or the real statistic wins. That makes estimate_is_stats_based unreliable for later star-schema swap decisions on supported multi-relation predicates.
    Suggested fix: record the flag while the DP entry is evaluated, when the exact rels lookup that determined computeSelectivity is still available, instead of reconstructing it from the final plan.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Heads-up on the current state of this PR — the implementation has diverged from what was reviewed, and CI is red.

The approval is stale. The approval here was given on commit 45508adafd4, which implemented a cardinality floor for inner joins in estimateJoinCardinality:

if (join_kind == JoinKind::Inner)
    joined_rows = std::max(joined_rows, std::max(lhs, rhs));

That is exactly the change described in the PR body ("adds a cardinality floor for INNER JOINs: the result cannot be smaller than max(left_rows, right_rows) … mirrors the existing floors for LEFT/RIGHT/FULL joins"). It was then reverted in a4c0239b1c4 and replaced by a different, so-far-unreviewed heuristic in optimizeJoin.cpp (commits a4c0239b1c4 + eee4d2be5fb): instead of flooring the estimate, the new code suppresses the swap_on_sizes decision when the left side is a multi-relation set without per-column NDV stats and its largest base relation is bigger than the right estimate (getMaxBaseRelationRows / allRelationsHaveColumnStats). So the code no longer matches the description, and it is a materially different approach than the one that was approved.

CI is red because of this change. Three deterministic dphyp plan tests now fail — the join order the new heuristic produces differs from the pinned reference plans:

  • 03960_join_order_dphyp_basic
  • 03960_join_order_dphyp_cycle
  • 03960_join_order_dphyp_transitive_predicates

These tests deliberately pin an optimal plan (e.g. 03960_join_order_dphyp_basic documents "the optimal plan is unique across environments. EXPLAIN pins it; the hash must match DPsize"), so I did not want to blindly regenerate their .reference files — doing so would silently redefine the expected plans for that suite, which is actively maintained alongside the join-reorder / NDV-estimation work. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109261&sha=eee4d2be5fbabaff3c0948f61036d2792838329a&name_0=PR&name_1=Fast%20test

@vdimir, since this touches optimizeJoin.cpp and the 03960_join_order_dphyp_* suite you own: could you confirm whether the new join orders these tests now produce are acceptable (in which case the three .reference files should be updated), or whether the swap-guard heuristic needs rethinking? And a decision on cardinality-floor (approved) vs. swap-guard (current) would be helpful, since only one is in the tree.

Also, the PR description should be updated to describe the swap-guard approach if that is the one being kept.

@alexey-milovidov

Copy link
Copy Markdown
Member

Refreshed this branch against current master (merge commit e4d2a996dcd), so it now sits on top of the recent join-reorder work — the DPsub chained-outer-join fix, join_reorder_through_expression, and the greedy-reordering changes. The merge was clean and optimizeJoin.cpp still compiles; the net change vs master is unchanged (the swap_on_sizes guard plus the 04498 test).

Note the CI report link in my previous comment is now stale (it points at eee4d2be5fb). Fresh CI is running on e4d2a996dcd and will show whether the three 03960_join_order_dphyp_* plans still diverge from the pinned references now that the optimizer baseline has changed under this PR.

The design question is still open and I did not touch it: I have not regenerated the three .reference files, since whether the new join orders are acceptable — and whether the swap-guard heuristic is the right approach vs. the originally-approved cardinality floor — is a cost-model call for the join-reorder owner. @vdimir, could you take a look once the fresh CI settles?

@alexey-milovidov

Copy link
Copy Markdown
Member

Fresh CI on e4d2a996dcd has now settled, and it answers the question from my last comment: the three 03960_join_order_dphyp_* plans still diverge from the pinned references on top of the current optimizer baseline —

  • 03960_join_order_dphyp_basic
  • 03960_join_order_dphyp_cycle
  • 03960_join_order_dphyp_transitive_predicates

So the recent join-reorder work (DPsub chained-outer-join fix, join_reorder_through_expression, greedy-reordering changes) does not make the swap_on_sizes guard moot — the guard still changes the join order these tests pin (e.g. 03960_join_order_dphyp_transitive_predicates case 3 flips [(__table3.key) = (__table1.key)] to [(__table1.key) = (__table3.key)] and moves the tp_dim_a/tp_dim_b reads). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109261&sha=e4d2a996dcd3ddbdaee65969aa8265d9844cdf87&name_0=PR&name_1=Fast%20test

I have not regenerated the three .reference files: whether these new join orders are acceptable — and swap-guard vs. the originally-approved cardinality floor — is a cost-model call for the join-reorder owner. @vdimir, this is ready for your decision whenever you have a moment.

(The new_tests_check.py failure in Finish Workflow is downstream of this: the per-arch Bugfix validation jobs were DROPPED in this run, so none validated the added test.)

JingYanchao and others added 4 commits July 16, 2026 19:33
The previous commit regenerated this reference from the intermediate
NDV-cap implementation, which was then reverted back to the swap guard
in `optimizeJoin.cpp`, so the reference no longer matched the plans the
final code produces. Regenerated from the current branch; output is
deterministic across runs. The plan change is the swap guard's intended
effect: the statistics-less composite subtree stays on the probe side
instead of being swapped to the hash-join build side.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109261&sha=6458e59d985da41a64da4c5237711397aa8d300e&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Update after the author's new commits (679cc301bfc, 6458e59d985): the final code is back to the narrow swap guard in optimizeJoin.cpp (the intermediate NDV-cap in estimateJoinCardinality was tried and reverted), and the author now updates the three 03960_join_order_dphyp_* reference files themselves.

I pushed f37f858cf21, which fixes 03960_join_order_dphyp_cycle.reference — it had been regenerated from the intermediate NDV-cap build, so it did not match the plans the final swap-guard code produces (the Fast test failure on 6458e59d985). Verified locally that all three dphyp tests and the new 04498 test now pass deterministically. I also synced the PR description with the final approach (it still described the reverted NDV cap).

@vdimir the remaining question is still yours: the guard changes three pinned dphyp plans (statistics-less composites now stay on the probe side) — please confirm the new pinned plans are acceptable, or whether the guard should be reworked.

`RelationStats::column_stats` is a per-column map, so checking
`entry->left->column_stats.empty()` was too coarse: a composite subtree
`(fact JOIN dim_a)` where only `dim_a` carries statistics has a non-empty
map, yet `getColumnStats` still falls back to the `estimated_rows` NDV
proxy for the fact table's next join key, underestimating the composite
exactly as in the stats-less case — and the guard was wrongly skipped,
swapping the fact subtree to the hash-join build side.

Check the equi-join keys of this join step that belong to the left
subtree instead: the guard now applies iff none of them have column
statistics, mirroring the proxy-fallback condition in `getColumnStats`.
Add `04609_join_reorder_star_schema_mixed_stats` where only one
dimension has statistics (verified to fail without the guard). No
pinned join-order plans change: all `03960_join_order_dphyp_*`,
`03733_join_order_dp`, `03734`/`03738`/`03835`/`04050` join-order tests
and `04498` pass unchanged.

ClickHouse#109261 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
… left subtree

The previous per-step check (`anyLeftJoinKeyHasColumnStats`) was still too
weak: `computeSelectivity` takes the minimum across equality predicates, so
one proxy-based key dominates a multi-key join even when another key has
statistics; and an earlier proxy-based join inside the left composite leaves
`estimated_rows` underestimated on later steps even when the later step's
keys do have statistics.

The star-schema swap guard now precomputes, bottom-up over the post-order
join sequence, whether each subtree's cardinality estimate is stats-based:
true iff every equi-join key at every join step inside the subtree has column
statistics, mirroring the per-key lookup and `estimated_rows` fallback of
`getColumnStats`. The pre-pass runs before the main loop because that loop
moves `join_operator` out of the entries.

Adds `04611_join_reorder_star_schema_partial_key_stats`: statistics only on
`fact.key_b` (the key of the second join), so the composite
`(fact JOIN dim_a ON key_a)` is already underestimated when the second join's
key has statistics; a current-step-only check would still swap the fact
subtree to the hash-join build side. All 20 `03960_join_order_dphyp_*` tests
plus `03733`, `03734`, `03738`, the `03835*` family, `04050`, `04498`, and
`04609` pass unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Expression (Post Join Actions)
Join (JOIN FillRightFirst)
Expression (Left Pre Join Actions)
Expression (Change column names to column identifiers)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I also noted that materialize_statistics_on_insert was not enabled for _dphyp_ tests, so statistics were not used there, enabling it in https://github.com/ClickHouse/ClickHouse/pull/107637/changes

Probably we should do so in this PR and see how it changes referece

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Done in 7b31feb: 03960_join_order_dphyp_basic, _cycle and _transitive_predicates now pin materialize_statistics_on_insert = 1 (they already declared uniq statistics and set use_statistics = 1, so previously every NDV lookup silently fell back to the estimated_rows proxy), and the references are regenerated from the resulting plans.

What changed: with real statistics the pinned plans differ both from the old references and from the swap-guard-under-proxy plans — e.g. in _transitive_predicates the fact table now consistently lands on the probe side of the outermost join, and in _basic/_cycle the build/probe sides of the inner steps shift. Only EXPLAIN plan lines changed; the result-check hashes and row counts are identical, and the output is deterministic across runs. The swap guard itself does not fire on these tests anymore (their estimates are now genuinely stats-based), so the pinned plans reflect the plain cost model on real NDVs, which should also keep them stable against your #107637.

alexey-milovidov and others added 2 commits July 20, 2026 22:35
…der optimizer

The star-schema swap guard needs to know whether a composite subtree's
cardinality estimate was derived from real column statistics. Deriving it
in `chooseJoinOrder` from the final join tree missed one estimator path:
`computeSelectivity` also scans every column-equivalence class spanning
the two sides and uses `getColumnStats` on all of its members, and
`cleanupJoinPredicates` may remove or synthesize predicates before
`chooseJoinOrder` runs, so a proxy-based lookup could disappear from the
step's expression while still dominating the class-wide max NDV.

Record the flag in `DPJoinEntry::estimate_is_stats_based` instead, filled
by `optimizeJoinOrder` right after the solver and before
`cleanupJoinPredicates`, mirroring every NDV lookup `computeSelectivity`
makes: both sides of every equi-predicate attached to a step (including
`residual_filter`) and every member of every spanning equivalence class.
The guard in `chooseJoinOrder` now just reads the flag, and the
`stepJoinKeysHaveColumnStats` helper plus the pre-pass are removed.

Adds `04621_join_reorder_star_schema_transitive_stats`: with
`enable_join_transitive_predicates` and statistics only on the dimension
keys, the stats-less `fact.key` poisons the composite estimate through
the equivalence class, and the fact table must stay on the probe side.

Co-Authored-By: Claude Fable 5 <[email protected]>
Per review: the `03960_join_order_dphyp_basic`, `_cycle` and
`_transitive_predicates` tests declared `uniq` statistics and set
`use_statistics = 1` but pinned `materialize_statistics_on_insert = 0`,
so no statistics were ever built and every NDV estimate fell back to the
`estimated_rows` proxy. Pin the setting to 1 instead, so the declared
statistics are materialized and the pinned plans are driven by real NDV
estimates. References are regenerated for the resulting plans; the
result-check hashes and row counts are unchanged, and the output is
deterministic across runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Pushed two commits addressing today's review feedback:

  • 0d1023c33c4 — the "estimate is stats-based" flag is now recorded by the join order optimizer itself (DPJoinEntry::estimate_is_stats_based, filled before cleanupJoinPredicates), mirroring every NDV lookup computeSelectivity makes, including the spanning column-equivalence classes on the transitive-predicate path. New regression test 04621_join_reorder_star_schema_transitive_stats.
  • 7b31feb92d1 — per @vdimir's suggestion, 03960_join_order_dphyp_basic/_cycle/_transitive_predicates now pin materialize_statistics_on_insert = 1 and their references are regenerated for plans driven by real NDV estimates (details in the thread reply).

All 34 pinned join-order plan tests pass locally and deterministically.

The two CI failures on the previous head are unrelated to this PR:

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated the arm_binary 04365 failure (sha e532419, report linked above). It is a distinct manifestation from the coverage one, so #110716 does not cover it.

Two separate signatures over the last 30 days:

  • amd_llvm_coverage_per_test: 12 hits. The output is correct (500000 / 500000 / 1); the reference diff is only polluted by LLVM Profile Error: lines emitted by coverage-instrumented clients killed mid-insert. That is what Filter LLVM Profile Error noise from cancel-insert-when-client-dies tests #110716 fixes (it extends the thread_insert stderr filter). Coverage-specific.
  • arm_binary, parallel: 8 hits across 7 unrelated PRs. The diff is a value flip on the third line, 1 -> 0: the final assertion select count() > 0 from system.text_log where <cancellation evidence> found no cancellation message within the 40s window, and the harness reruns passed 2/2. This is a genuine timing race in whether thread_cancel catches an insert in flight, not stdout pollution.

So #110716 (in progress) is the coverage fix and does not address this. The arm_binary timing race needs a separate fix that makes the cancellation observation reliable without weakening the assertion (it must still detect a real cancellation). I will open that separate PR and link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Separate PR for the arm_binary flakiness: #111157.

Root cause is a timing gap in the test's own thread_cancel: it took one /proc/*/cmdline snapshot per loop then slept 3x sleep 0.$RANDOM (~1s), so it sampled for an in-flight insert only about once a second. On fast release/binary builds an insert finishes well under a second, so the sampler lands between inserts, nothing is cancelled in the 40s window, and the guard count() > 0 returns 0 (the line-3 1 -> 0 flip). The fix polls at 10ms until an insert is in flight, then kills it at once; the assertion, the SIGINT/SIGKILL mix, the row counts, and the tags are unchanged. The same thread_cancel is shared by 02434 / 04365 / 04366 and all three flake on arm_binary, so the fix is applied to all three.

Reproduced both directions locally (extracting the actual thread_cancel from the file, fast inserts): current version flips ~38%, fixed version 30/30. This is separate from the coverage stdout-pollution fix (#110716 / #108864).

…wins the competition

`joinStepEstimateIsStatsBased` treated any NDV lookup that fell back to the
`estimated_rows` proxy as poisoning the subtree estimate, but
`computeSelectivity` uses `1 / max(lhs_ndv, rhs_ndv)` per equality and then
takes the minimum across predicates and the class-wide maximum inside each
equivalence class — so a proxy fallback only affects the estimate when its
value actually wins that competition. The helper now tracks the largest
stats-backed and largest proxy-backed NDV over every mirrored lookup of the
step and marks the step proxy-based only when the proxy value strictly
exceeds every stats-backed one. A stats-less small dimension joined on a
fact key with a real `uniq` statistic no longer disables the beneficial
build/probe swap for the composite.

Regression test `04622_join_reorder_star_schema_dominant_stats`: statistics
only on the unique `fact.key_a`; the composite `(fact JOIN dim_a)` estimate
(~50 rows) is driven by the real fact NDV, so the swap must still move the
composite to the build side against the larger `dim_b`. Verified the previous
code keeps `fact` on the probe side (test fails) while all 33 pinned
join-order plan tests pass unchanged with the new code.
/// estimate is proxy-based is joined against a single smaller table. It
/// only gates the physical build/probe-side choice and never changes
/// cardinality estimates, so the enumerated join order is unaffected.
if (swap_on_sizes && !optimization_settings.join_swap_table.has_value()

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.

swap_on_sizes is only suppressed when the poisoned composite happens to be entry->left, but the optimizer's left/right orientation is not semantic. In dphyp, the final pair is stored as (csg, cmp), so the same star join can reach this code as left = dim_b, right = (fact JOIN dim_a) when the larger dimension has the smallest relation id.

In that shape lhs_estimation < rhs_estimation is false (100 < 50), so flip_join stays false and the underestimated fact subtree remains on the build side without ever hitting this guard. A focused regression with query_plan_optimize_join_order_algorithm = 'dphyp' and the relations ordered dim_b, fact, dim_a should still reproduce the original bad plan. The check needs to be symmetric around the side that would end up on the build side, not only entry->left.

return true;
}

const DPJoinEntry * child = nullptr;

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.

This no longer mirrors getColumnStats for multi-relation expression keys. getColumnStats looks up dp_table[rels] for the exact source-relation set of the key, but here any multi-relation key is charged to whichever immediate child merely contains that set.

That diverges as soon as a predicate side uses a proper subset of a larger child, e.g. A.x = B.y + C.z after (B JOIN C) has already been joined with D: the cost model still uses dp_table[{B,C}] for B.y + C.z, while this helper falls back to {B,C,D}'s column_stats / estimated_rows instead. The proxy-vs-stats winner can change in both directions, so estimate_is_stats_based can still suppress or allow later swaps for the wrong reason. This probably needs to be recorded while the DP entry is evaluated, when the exact rels lookup that drove computeSelectivity is still available, rather than reconstructed from the final tree.

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Jul 21, 2026

@rschu1ze rschu1ze left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If I understand the PR message correctly, the problem occurs only in the absence of statistics. Statistics will soon be available on all parts: #109454

Please check if this PR will be of use then.

@clickhouse-gh

clickhouse-gh Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 104/111 (93.69%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Dear @alexey-milovidov, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze

Copy link
Copy Markdown
Member

Resolved by #109454

If the problem persists for you, please reopen (and also provide a minimal reproducible example then please).

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 hold Skip for auto-updating. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants