Repository navigation
Conversation
…estimate `tests/performance/join_runtime_filter` queries 6-10 regressed between 26.6 and 26.7 (q9/q10 by ~1730%): a ~100M-row fact table was placed on the hash join build side while the filtered dimension side, at most 10101 rows and often 0, became the probe side. Root cause. `estimateReadRowsCount` returns no point estimate at all for a MergeTree relation with `has_filter && !is_filtered_by_index`, i.e. a filter the primary index cannot resolve and no column statistics. The build-side swap gate in `chooseJoinOrder` requires a point estimate on both sides, so a single missing estimate freezes whatever orientation the enumerator emitted, and `computeJoinCost` is orientation-symmetric (it costs an unestimated relation as `value_or(1)`), so that orientation is arbitrary with respect to build side. Keeping the fact table there both builds a hash table over it and defeats `HashJoin::alwaysReturnsEmptySet`, which needs the empty side to be the build side. 26.7 enabling `query_plan_merge_expression_into_join` by default did not introduce the gate, which is byte-identical in 26.6 and 26.7; it made the reorder reach it. Fix. Propagate a sound row-count upper bound alongside the point estimate and use it as the gate's left-side fallback. The bound is `selected_rows`, the row count over post-index ranges; a filter the index cannot resolve only removes rows afterwards, so the bound can only over-state, and a swap therefore fires only if even the left side's worst case is smaller than the right side. Because the right-hand estimate is a heuristic and not a lower bound, the fallback also requires that estimate to have been measured, reusing the existing `RowEstimateSource`. When a left point estimate exists the gate is unchanged, so the new path can only affect decisions that previously had no information at all. The guarantee is a provably bounded build side, not an always-optimal swap. Bound propagation is default-deny: it stops at every step that can add rows, so a keyless aggregation (one row even on empty input), grouping sets, `overflow_row`, `LIMIT WITH TIES`, an `ARRAY JOIN` in a filter's actions, and the generic `preserves_number_of_rows` fallback all leave it unset. That last one matters because the trait is a per-step self-declaration: `TotalsHavingStep` declares it yet emits an extra row for WITH TOTALS. The bound is seeded and propagated in every enumerator, including `solveDPsub`'s local DP entry and the DPsub cost checker, which the shared `DPJoinEntry` path does not cover. Without those the change is a no-op under `query_plan_optimize_join_order_algorithm = 'dpsub'`, and since the default is `greedy` the performance test alone would not catch it. Validation. On a 1M-row reduction of the reported fixture, `JoinBuildTableRowCount` goes 1000000 to 0 and `SelectedRows` 1000004 to 4, matching the reported 100M-row figures. The new test asserts the plan under greedy, dpsub, dpsize and dphyp; all four reverse without the fix. 34 join-planner tests pass with no reference changes, and the new test passes 50 of 50 runs with randomized settings. Closes ClickHouse#113035
Internal second-model review (2 findings, both disagreed with evidence; 3 self-review nits)An independent model reviewed this diff cold against the frozen PR description, and I reviewed it
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-43:20260804-071300 |
|
cc @novikd @davenger, could you review this? The hash join build-side swap gate requires a point estimate on both sides, and a relation filtered on a column the primary index cannot resolve has none, so a 100M-row fact table stayed on the build side; this supplies a sound row-count upper bound as the left-side fallback, gated on the right estimate having been measured. @davenger, #101398 edits the same four lines in the opposite direction, so the two cannot both land as written. |
|
Workflow [PR], commit [c96f2a8] Summary: ✅
AI ReviewSummaryThe change carries row-count upper bounds through join planning so a filtered input without a point estimate can become the hash join build side when its upper bound is below a proven lower bound for the other input. Reviewed the current code, full diff, and prior discussion for head Missing context / blind spots
Final VerdictStatus: ✅ Approve. No further code changes requested by this review. |
The upper-bound fallback added in this PR compared the left side's row-count upper bound against the right side's point estimate, allowing the swap when the right estimate came from Statistics, PrimaryIndex or HashTableCache. That set is not sound: PrimaryIndex reports `selected_rows`, the granule-rounded row count of the ranges the reader will scan, so residual conjuncts applied after the read can leave the true relation far below it. With `lhs_upper = 400` against `rhs_estimation = 8192` for a relation of 1 actual row, the gate flipped a join that master had oriented correctly, putting the larger side on the hash-table build side. That is a fresh regression, not merely a missed optimization. Replace the source allow-list with an explicit `estimated_rows_is_lower_bound` bit on RelationStats and RelationEstimateInfo, default-deny, set only where the point estimate provably cannot exceed the true row count: an unfiltered, unsampled, non-FINAL MergeTree read, a memory-storage total row count, `system.one`, and a measured hash-table cache count. Statistics keeps its heuristic point estimate and is no longer trusted here. Every row-removing or row-adding step on the propagation path clears the bit. The guarantee becomes `left_actual <= lhs_upper < rhs_estimation <= right_actual`, so the fallback can only miss a swap, never invert one. Dropping PrimaryIndex from the trusted set instead was measured and rejected: the reported regression's right side is the fact table read without a filter, which takes the same PrimaryIndex return with `has_filter == false` where `selected_rows` is the exact row count, so that variant would have removed the fix itself. Test 04726 gains an arm covering an overstated right side. It fails on the previous head of this branch and passes here, and a mutation forcing the bit true reddens both guard arms.
…t the build side at runtime `StorageMemory::totalRows` returns a live atomic counter, while `ReadFromMemoryStorageStep` reads the immutable blocks captured in `storage_snapshot->data`. An insert landing between snapshot creation and the optimizer pass raises the counter above the number of rows the step will actually read, so the estimate is not a lower bound and must not enable the upper-bound fallback. Clear the bit there; the primary-index path already covers an unfiltered MergeTree read, which is where the reported regression comes from. Test 04726 also gains a ProfileEvents arm on the issue-shaped query, so a future change cannot keep the asserted plan shape while losing the small build side at runtime. It reports the 100000-row fact table on the build side against pristine master and a small build side after the fix.
…n the runtime arm The hash-table cache override lowers the point estimate to `source_rows` recorded by an earlier execution of the same subplan. That value is precise about what was observed then, but the table can have grown since, so it can sit below the number of rows the current read will produce. Preserving an inherited lower-bound bit across the override therefore breaks the invariant the swap gate relies on. Clear it, so a cached count is precise but never treated as a lower bound. Pin `use_hash_table_stats_for_join_reordering = 0` in 04726: the cache is process-global, the runner randomizes the setting, and a previous run of this very test could otherwise supply the estimate the arms deliberately withhold. The runtime arm now asserts the exact `JoinBuildTableRowCount` and `SelectedRows` rather than an inequality. The filter matches nothing, so both must be minimal; against pristine master they read 100000 and 100004.
The `overstated right side keeps orientation` arm counted the plan lines that mention `residual_04726` without it being the first input, and required that count to be exactly one. The count is a property of the join ORDER, not of the orientation the arm exists to check: under a randomized `index_granularity` of 64717 the optimizer places `residual_04726` inside the inner join as well, so the relation appears on two join lines, both of them correctly with the relation on the build side, and the arm reported a failure. The arm now requires that the relation is mentioned at all, which keeps it non-vacuous if the plan stops reading it, and that it is never the first input of any join, which is the property itself. Both hold regardless of how many joins the chosen order produces. Measured with the published binary and a pristine master binary, build ids asserted before every run: the emitted plans are byte-identical between the two at `index_granularity` 8192 and 64717, so the flip was in the assertion and not in the guard this pull request adds. The rewritten arm still returns 0 when the join is flipped the wrong way, and pristine master still reddens four planner arms plus the runtime arm. Co-Authored-By: Claude Fable 5 <[email protected]>
CI fix: the new test's build-side arm was order-sensitive, the guard was not
The arm was at fault, not the change. It counted the plan lines mentioning I checked which of the two possible readings applies before touching the test, because pinning The arm now requires that the relation appears at all, which keeps it non-vacuous if the plan Validation, all with asserted build ids:
I did not add I also corrected the description. It still described the superseded design, saying the fallback Session id: cron:clickhouse-maint-slot-12:20260804-211600 |
CI finish ledger - 2e8f104Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
Session id: cron:our-pr-ci-monitor:20260805-033000 |
Resolves the sole conflict in `joinOrder.h`: master added `avg_row_bytes` to `RelationStats` while this branch added `estimated_rows_upper` and `estimated_rows_is_lower_bound`. The additions are independent, so all three fields are kept. Master's Cascades merge (ClickHouse#86353) and the row-estimate commits around it auto-merged into `optimizeJoin.cpp`. The swap gate still keys on `estimated_rows_is_lower_bound` rather than a source allow-list, and `relation_infos` still carries the bit to the gate. Verified on the merged tree (build id 9755a533de7390e6): test 04726_join_build_side_row_upper_bound matches its reference, and the build-side arm still discriminates - a forced `query_plan_join_swap_table = true` returns 0 where `'auto'` returns 1.
… bound joins in integer math Two soundness gaps in the build-side fallback, both found while re-reviewing the branch after merging master. A lightweight delete (or a patch part, or an on-fly data mutation) filters rows out while reading, but `selected_rows` counts the physical rows in the selected ranges, so it sits above the true row count. Marking it a lower bound let the gate swap the wrong way: with a right relation of 100000 physical rows of which one is live, and a left side of 3 rows, the plan put the right side on the probe side, which is the regression this branch exists to prevent. `estimateReadRowsCount` now consults the mutations snapshot. The composite upper bound for a join node went through the heuristic cardinality estimator, which converts to `double` and truncates. 94906267 * 94906267 came back as 9007199515875288 instead of 9007199515875289, one below the true cartesian product, so the value declared an upper bound could sit under the row count it bounds. Bounds are now derived with saturating integer arithmetic; the point-estimate path is unchanged. Verified against a build of the same tree, with the binary identity asserted per arm: test 04726 matches its reference, and the new lightweight-delete arm is the only line that changes when the fix is removed. Where the true product exceeds UInt64, saturation is the tightest representable bound.
The arm compares a left composite bound of 400 rows against the right side's primary-index estimate for `id < 100`. That estimate tracks the selected granules, so at a small randomized `index_granularity` it drops to about 100 - below 400 - and a build that wrongly treated it as a lower bound would also decline the swap, leaving the arm green for the wrong reason. The runner randomizes `index_granularity` over 1..65536. Measured at `index_granularity = 1`: `id < 100` yields an estimate of 100, while `id < 10000` yields 10000. Bracketing the left bound shows the swap fires at right_rows >= 401, so the widened range keeps the broken behaviour reachable at every granularity drawn (10000 at ig 1, 2, 400 and 1000; 10048 at 64; 16384 at 8192; 65536 at 65536). The test passes with the fix both at the default granularity and at `index_granularity = 1`.
Merge with master, plus two soundness guards found in self-reviewRebased onto master (8763 commits behind). The only conflict was Two real defects in my own diff, both found by re-review of the merged tree and both fixed here:
The first one's test arm is new ( Liveness re-proved on the merged tree against a pristine merged-master build: all four planner arms Description updated to cover both guards. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units54 translation units recompiled, 438 s compile time in total, 54 of them have a recent master baseline. |
CI finish ledger - 8ec2de2CI is fully finished on this head: 178 check-runs, none queued or in progress, No failures, so there is nothing to own. The 16 skipped jobs are the expected set for a Session id: cron:our-pr-ci-monitor:20260819-020000 |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
Master split joinOrder.cpp into per-algorithm translation units (joinOrderCommon.h, joinOrderGreedy.cpp, joinOrderDPSize.cpp, joinOrderDPHyp.cpp, joinOrderDPSub.cpp, joinOrderDP.cpp), which turned the whole of this branch's joinOrder.cpp change into a conflict. The resolution takes master's file layout and re-applies each of this branch's edits at its new home, with no behaviour change: - boundJoinRows moves to joinOrderCommon.h as an inline free function, beside estimateJoinCardinality, which master had already moved there as the single source of truth for join cardinality. Its only caller outside the DPJoinEntry constructor is the DPsub acceptor, so the JoinOrderOptimizer::boundCardinality method becomes DPSubJoinOrderOptimizer::boundCardinality, mirroring what master did to estimateCardinality. - The forward declaration of estimateJoinCardinality is dropped: master declares it in a header now. - The four leaf-relation construction sites move with their solvers, one each to joinOrderGreedy.cpp, joinOrderDPSize.cpp, joinOrderDPHyp.cpp and joinOrderDPSub.cpp; the DPsub DPEntry row-bound field moves with its struct. - Both DPJoinEntry constructors stay in joinOrder.cpp. Token accounting over src/: every identifier this branch introduced has the same total occurrence count before and after the merge (estimated_rows_upper 23, estimated_rows_is_lower_bound 11, boundJoinRows 3, boundCardinality 3, rows_upper 31, lhs_for_swap 3), with the 11 lines that were in joinOrder.cpp now spread 2/1/1/1/5/1 over joinOrder.cpp, joinOrderCommon.h, joinOrderDPHyp.cpp, joinOrderDPSize.cpp, joinOrderDPSub.cpp and joinOrderGreedy.cpp. optimizeJoin.cpp auto-merged: master's changes there (ActionsDAG lineage extraction, the join-output hash-table cache key, the expression-merge shadowing guard) do not touch the row-estimate producers this branch changes, and the swap gate this branch rewrites is untouched on master.
`boundJoinRows` returns no bound unless both children have one, so a leaf carrying only a point estimate erases the upper bound of every join above it. `system.one` was such a leaf: it declared `estimated_rows = 1` and the lower-bound bit, but no `estimated_rows_upper`. Since it always produces exactly one row, 1 bounds it from above as well. Without this, any join tree containing a constant relation lost the bound this PR relies on, and the fact table went back to the hash-join build side, which is the regression of ClickHouse#113035. Measured on a 100000-row fact table against a filtered dimension with no point estimate, with only the constant join added between the two arms: before Join: dim[no_stats~?] x system.one[1] |><| fact[no_stats~100000] after Join: fact[no_stats~100000] |><| (dim[no_stats~?] x system.one[1]) `(SELECT 1)` and `CROSS JOIN system.one` reach the same path and were affected identically. The proven-empty leaf, the other exact-cardinality source without an upper bound, is unaffected: its exact point estimate of 0 already satisfies the swap gate, measured to keep the correct orientation. The new test arm asserts the one-row leaf is still present in the plan, so it cannot pass by the join being folded away and degenerating into the plain two-relation case that already passes.
CI finish ledger - 7405d06Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260902-000000 |
An INNER ANY join emits at most one row per row of one input, but which input depends on the algorithm and orientation: hash joins pair keys one to one, while partial_merge and hash joins with mixed ON conditions emit one row per probe-side row, so after a swap `l(1000) ANY INNER JOIN r(2000)` returns 2000 rows. `max(left, right)` is the bound that holds for all of them (`min` does not); the product was sound but too loose for the parent's swap. The bound is now computed after an unconnected ANY pair is restored from Cross to Inner, so `ANY INNER JOIN ... ON 1` gets it too. `DelayedCreatingSetsStep` is a placeholder above a subquery that uses `IN (subquery)`; it forwards its input unchanged, but the estimator returned no stats for it, so such a join input had no row bound. The hash join pre-filters each side by the single-relation conjuncts of every OR disjunct in ON, so those conjuncts now drop the lower-bound flag like a top-level single-relation condition does; otherwise `ON (l.id = r.id AND r.pad = 1) OR (...)` swapped a filtered-to-empty right side off the build side. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-join-build-side-row-upper-bound Master moved the index-filtering check in `estimateReadRowsCount` above the statistics path and added the `for_runtime_filter_transport` parameter; the PR's recursive calls now pass it on. Master's `has_filter` ignores a runtime-filter `PREWHERE`, so the lower-bound check now also requires no `PREWHERE` at all. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 7df483dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no Session id: cron:our-pr-ci-monitor:20261017-073009 |
|
Fixing PR for the targeted-job test-selection CIDB HTTP 500: #125613 |
…-join-build-side-row-upper-bound Conflicts: master now hands an optimized sub-join's point estimate to its parent graph (with `composite`); keep it and add the PR's `estimated_rows_upper` (a filter above the join only removes rows, so the bound holds). DPsub seeding now goes through `link_relations`, which also copies `estimated_rows_upper`.
`DISTINCT` only removes rows, so a filtered input that has only an upper bound keeps it, and `(SELECT DISTINCT ... WHERE ...) AS d JOIN fact` still puts the small side on the hash build side. The point estimate is not carried, as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`selected_rows` of an unfiltered `UNIQUE KEY` read also counts the versions the snapshot's delete bitmap hides at read time, and `selectRangesToRead` keeps the totals from before the bitmap. With one key overwritten three times and merges stopped, the right side reported 3 rows for 1 live row, so a 2-row left side with only an upper bound was swapped onto the hash build side, while master leaves the 1-row side there. The new test is a separate file because `UNIQUE KEY` needs tags (RocksDB, local disks, Atomic database) that would drop every other arm of 04726 from those configurations. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - a57ff9cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261025-070009 |
|
Dear @egor-click, 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. |
|
@groeneai could you resolve conflicts? |
…-join-build-side-row-upper-bound # Conflicts: # src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp
Master now estimates an array join as 100 rows per input row instead of returning no estimate, and that branch copies the stats of its input. After the master merge it therefore also copied the input's `estimated_rows_upper` and lower-bound bit through the array join, which can add rows and drops the rows with empty arrays. Measured on the merge commit, both made the join order worse than master: - `(SELECT x AS id FROM t ARRAY JOIN arr AS x WHERE <unindexed>) JOIN r`: the 1-row read bounded the 1000-row array join, so it moved to the build side. - `d JOIN (SELECT x AS id FROM e ARRAY JOIN arr AS x)` with empty arrays: the 100x guess kept the lower-bound bit, so the PR built `d` instead of the empty side. Both bounds are now reset there, as before the merge, and 04726 gains one arm for each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done: master is merged in 4ab7075 (the only conflict was the include list of The merge needed one follow-up, 6f459ca: master's new array join estimate copies the stats of its input, so the input's row-count upper bound and lower-bound flag passed through |
A limit in `break` mode ends its stream early instead of throwing, so the input of a join can emit fewer rows than the estimate the lower-bound bit vouches for, and the swap rule then builds a larger side than master does. Measured against a stats-less 20000-row left input: - `ORDER BY v LIMIT 50000 SETTINGS max_rows_to_sort = 1, sort_overflow_mode = 'break'` emits 8192 rows, but the head swapped and built the 20000-row left side; master keeps the 8192-row side. - `max_rows_to_read` with `read_overflow_mode = 'break'` swapped the same way, and since the read limit is counted per query, the swap also changed which partial result came back (16384 rows instead of master's 20000). The sort step now drops the bit when its own sort limit can break, and the MergeTree read drops it when any level of its storage limits can break on rows, bytes (also the leaf limits) or time. A limit-free sort that the planner removes as redundant still swaps, since nothing truncates its input. 04726 gains one arm for each of the sort, read and time limits, and a pair on a `remote()` shard for the leaf read limits (a swapping control plus the guard). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai could you resolve conflicts? |
|
Yes. The build-side swap in The rest of #113336 (keeping an estimate through |
|
Closing as per #113336 (comment) |
Closes: #113035
Related: #101398
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries that join a large table with a much smaller one filtered on a column that has neither column statistics nor an index no longer put the large table on the hash join build side: join reordering uses a sound row-count upper bound for the filtered side, so the small side is built and the empty-build-side short circuit applies again.
Description
tests/performance/join_runtime_filterq6-10 regressed between 26.6 and 26.7 (q9/q10 by ~1730%). 26.7 enablesquery_plan_merge_expression_into_joinby default, so the reorder reaches a pre-existing gap: the swap gate needs a point estimate on both sides, andestimateReadRowsCountreturns none for a relation filtered on a column no index resolves. So the ~100M-rowordersstays on the build side.The fix propagates a sound row-count upper bound as the gate's left-side fallback:
selected_rows(post-index ranges). An unresolved filter only removes rows, so the bound only over-states; a swap needs the left worst case below the right estimate. One-row relations (system.one), index selections proven empty, relations DPsub links only by a degenerate predicate, separately optimized sub-joins (semi, anti andANYby their preserved side,INNER ANYby their larger input), window functions,DISTINCTandIN (subquery)set steps carry the bound too.Four things keep it sound. Composite bounds use saturating integer math, so a bound never rounds below its count. The right estimate must be a proven lower bound: an unfiltered, unsampled, non-
FINAL, non-UNIQUE KEYMergeTree read with no row policy or row-removing mutation, kept by a sort or anOFFSET-freeLIMIT, orsystem.one, and nobreak-mode read, time or sort limit. Propagation is default-deny at any row-adding step (TotalsHavingStepcan add a row). Estimates precede the ON clause, so a relation filtered by its own ON condition, also inside an OR, is not a lower bound, and anARRAY JOINorarrayJoinvoids all bounds.On the fixture,
JoinBuildTableRowCountgoes 100000 -> 0 andSelectedRows100004 -> 4. The test asserts plans undergreedy,dpsub,dpsizeanddphyp, all reversing without the fix, plus 33 shape and guard arms; no regression over 1500 join tests; 50/50 randomized clean.#101398 edits the same gate the opposite way (trust on both sides); both cannot land.
Workflow [PR]
Sync PR [sync-upstream/pr/113336]