Skip to content

Keep the smaller side on the hash join build side when it has no row estimate - #113336

Closed
groeneai wants to merge 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113035-join-build-side-row-upper-bound
Closed

groeneai wants to merge 31 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-113035-join-build-side-row-upper-bound

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #113035
Related: #101398

Changelog category (leave one):

  • Performance Improvement

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_filter q6-10 regressed between 26.6 and 26.7 (q9/q10 by ~1730%). 26.7 enables query_plan_merge_expression_into_join by default, so the reorder reaches a pre-existing gap: the swap gate needs a point estimate on both sides, and estimateReadRowsCount returns none for a relation filtered on a column no index resolves. So the ~100M-row orders stays 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 and ANY by their preserved side, INNER ANY by their larger input), window functions, DISTINCT and IN (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 KEY MergeTree read with no row policy or row-removing mutation, kept by a sort or an OFFSET-free LIMIT, or system.one, and no break-mode read, time or sort limit. Propagation is default-deny at any row-adding step (TotalsHavingStep can 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 an ARRAY JOIN or arrayJoin voids all bounds.

On the fixture, JoinBuildTableRowCount goes 100000 -> 0 and SelectedRows 100004 -> 4. The test asserts plans under greedy, dpsub, dpsize and dphyp, 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]

…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
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
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
separately without reading the implementation notes first. Both findings are recorded below with my
verdict and the evidence for it. Nothing was silently dropped.

⚠️ optimizeJoin.cpp -- the upper bound is not carried through an opaque optimized sub-join

Claim: estimateReadRowsCount's optimized-JoinStepLogical branch returns only the point
estimate, so with query_plan_optimize_join_order_limit = 2 a filtered nested join becomes opaque
to the parent and the parent's fallback sees no left bound.

Verdict: disagree (correct mechanism, out of scope for this change). The mechanism is real and I
do not dispute it. But in that configuration the bound is simply unset, so lhs_for_swap is empty
and the gate cannot fire, which is byte-identical to the current behaviour. The finding's own wording
is "still miss the build-side swap": an unimproved case, not a regression and not new wrongness. It
is also not the reported regression, which is a 3-relation join under the default limit of 10 where
the filtered dimension is a real MergeTree leaf and is bounded. The changelog entry scopes the fix
to a relation "filtered on a column that has neither column statistics nor an index", which an
opaque sub-join is not, so nothing here is over-claimed. Carrying the bound through
JoinStepLogical would touch the serialized step surface (result_rows_estimation is carried
through step serialization and cloning), which is a second change with its own blast radius. Happy
to do it as a follow-up if a reviewer wants the coverage.

⚠️ 04726 -- the DPhyp arm may fall back to greedy, and the negative arm passed before the change

Claim: the DPhyp arm uses dphyp,greedy, so a DPhyp decline can still produce the expected plan;
the unmeasured-right-side arm asserts an orientation that already held; and the oracle should be an
exact plan rather than count() > 0 with ILIKE.

Verdict: disagree, on all three parts. The fallback is mechanically possible, but the arm still
reddens on pristine master, which is what liveness means. The suggested remedy is worse: pure
dphyp raises EXPERIMENTAL_FEATURE_ERROR when it declines -- precedented in-tree as an expected
serverError in 03960_join_order_dphyp_search_budget.sql -- so it would risk converting a passing
assertion into a hard error, and measurement shows pure dphyp is not a carrier of the DPsub-only
plumbing anyway (solveDPhyp builds the shared DP entries, only solveDPsub uses the local one).
Worst case that arm duplicates the greedy arm, which is redundancy rather than a defect.

The unmeasured-right-side arm passing before the change is by design: it is a guard-liveness arm, and
it reddens when the "right estimate must be measured" condition is deleted, while leaving all four
algorithm arms green. Deleting only that condition also fails to compile
(-Wunused-but-set-variable), which independently shows it is the sole consumer of that value.

On the oracle form: the SELECT ... FROM (EXPLAIN ...) WHERE ... ILIKE shape is the form
@nikitamikhaylov asked for, precisely
because a full-output plan diff is brittle under plan-format churn. It is not a presence check --
Join: <left> <symbol> <right> renders the two sides in order, so the predicate is
orientation-sensitive, which is why every arm flips without the fix.

💡 Noted, not blocking

  • optimizeJoinLegacy keeps the both-sides-required swap shape. Deliberate: the regression is in the
    reorder path, and changing the legacy non-reordering path is a separate behaviour change.
  • Non-MergeTree leaves (object storage, memory, system.one, optimized sub-joins) leave the bound
    unset. Unset is always safe -- the gate then simply does not fall back.
  • SortingStep propagates the bound without clamping it to its limit: that loses tightness, never
    soundness.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 1M-row reduction of the join_runtime_filter fixture with use_statistics=0, query_plan_join_swap_table='auto', query_plan_merge_expression_into_join=1 puts the fact table on the build side on 100% of runs. Not a "~1%" repro.
b Root cause explained? estimateReadRowsCount returns no point estimate for a MergeTree relation with has_filter && !is_filtered_by_index; the swap gate needs one on both sides, so it cannot fire; computeJoinCost is orientation-symmetric and costs an unestimated relation as value_or(1), so the emitted orientation is arbitrary and the 100M-row fact table stays on the build side, which also defeats HashJoin::alwaysReturnsEmptySet (it needs the empty side to be the build side).
c Fix matches root cause? Yes: the missing information is supplied at the gate that consumes it. No widened bound, no no-random-* tag, no dataset reduction, no defensive check at the symptom site.
d Test intent preserved / new tests added? New stateless test 04726_join_build_side_row_upper_bound. No existing test weakened, removed or reference-regenerated.
e Both directions demonstrated? Yes. Same data directory, two binaries: JoinBuildTableRowCount 1000000 -> 0 and SelectedRows 1000004 -> 4, matching the reported 100M-row figures. All four algorithm arms of the new test reverse on pristine master.
f Fix is general across code paths? All four join-order algorithms are covered (greedy, dpsize, dpsub, dphyp) and each has its own test arm; a targeted mutation removing the dpsub-specific carriers reddens exactly the dpsub arm. optimizeJoinLegacy has a structurally similar gate and is deliberately out of scope: it is the non-reordering legacy path, and extending the fallback there is a separate behaviour change. Non-MergeTree leaves deliberately leave the bound unset, which is always safe.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers are not applicable: this is a row count, not a type-gated predicate. The relevant matrix is the join-order algorithm and the estimate source, both covered by test arms. Boundaries: an empty filtered relation (bound 0, the reported case) and a saturating bushy join (the bound clamps at UInt64::max, so the gate simply never fires, which is still sound).
h Backward compatible? Yes. No new setting, no changed default, no serialization change, so no SettingsChangesHistory.cpp entry is owed. The only user-visible change is plan choice, and only where there was previously no information; query_plan_join_swap_table = 0/1 still overrides unconditionally.
i Invariants and contracts preserved? The bound's invariant is "if set, it is at least the true row count". Joins derive it through estimateJoinCardinality with selectivity 1.0, sharing the outer-join floors and the UInt64 saturation clamp with the point-estimate path, so there is no second code path to keep in sync. Propagation through pass-through steps is default-deny, and a consistency repair keeps the point estimate at or below the bound after the hash-table-cache override. A missing bound is safe because the gate then does not fall back. Planning-time only: no concurrency and no persisted state.

Session id: cron:clickhouse-impl-slot-43:20260804-071300

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c96f2a8]

Summary: ✅


AI Review

Summary

The 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 c96f2a8674c47b14288ae48dab9cdc1685d12354. No new actionable findings remain. The previously reported overflow-limit issue is addressed, and its review thread is now resolved.

Missing context / blind spots
  • ⚠️ Current-head builds and remaining CI checks are still in progress. No local ClickHouse binary or build directory was available, so I did not rerun the SQL regressions. Completed current-head stateless results would close this runtime validation gap.
Final Verdict

Status: ✅ Approve. No further code changes requested by this review.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 4, 2026
groeneai and others added 4 commits August 4, 2026 17:27
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]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI fix: the new test's build-side arm was order-sensitive, the guard was not

04726_join_build_side_row_upper_bound failed on five checks (four flaky checks plus
arm_binary, parallel), always with the same one-line diff on the
overstated right side keeps orientation row. The arm_binary runner localised it precisely:
127 FAIL / 0 pass with the drawn settings, 0 FAIL / 178 pass with randomization off, culprit
--index_granularity 64717.

The arm was at fault, not the change. It counted the plan lines mentioning residual_04726
without it being the first input and required that count to be exactly one. That count is a
property of the join order, not of the orientation being checked: at index_granularity 64717
the optimizer also places residual_04726 inside the inner join, so it appears on two join
lines, both with the relation still on the build side, and the fixed count of one no longer
matched.

I checked which of the two possible readings applies before touching the test, because pinning
a setting would hide the other one. With build ids asserted before every run, the published
head and a pristine master binary emit byte-identical plans at both index_granularity 8192
and 64717, so nothing in the guard is granularity-sensitive.

The arm now requires that the relation appears 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 for any join order.

Validation, all with asserted build ids:

  • Full test green at index_granularity 1, 300, 8192, 64717 and 65536, and 20/20 at the exact
    CI culprit value through the real runner. 50/50 under ordinary randomization.
  • Positive control: with the old arm restored, the same runner invocation fails at 64717 with
    the identical diff CI reported, and fails 1/10 under plain randomization, so the harness does
    reproduce the CI condition.
  • Liveness kept: pristine master still reddens the four planner arms and the runtime arm
    (100000 100004 against 0 4) at both granularities. Forcing the wrong flip still returns 0
    from the rewritten arm at both granularities, so it is not vacuous.

I did not add no-random-merge-tree-settings or a per-setting clamp: the assertion is now
correct under every value the randomizer draws, so there is nothing to pin.

I also corrected the description. It still described the superseded design, saying the fallback
requires the right-hand estimate to be "measured (Statistics, PrimaryIndex,
HashTableCache)". Since discussion_r3713912702 the gate keys on a proven lower-bound bit
instead, and a source name is explicitly not sufficient, which is the same point that review
raised. The code and its comment already said this; only the description had drifted.

Session id: cron:clickhouse-maint-slot-12:20260804-211600

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2e8f104

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / assertTypeEquality LOGICAL_ERROR, STID 2508-2e0c flaky, pre-existing trunk bug in HashJoin::buildAdditionalFilter (plain column receiving a sparse/const/replicated source) #107957 (ours, open)

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`.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merge with master, plus two soundness guards found in self-review

Rebased onto master (8763 commits behind). The only conflict was joinOrder.h, where master added
avg_row_bytes to RelationStats while this branch adds estimated_rows_upper and
estimated_rows_is_lower_bound - independent additions, all three kept. optimizeJoin.cpp took 26
master commits including the Cascades merge (#86353) and auto-merged; I checked that is semantically
sound and not just textual: the net diff against master is byte-for-byte the original 8-file change,
so nothing of master was reverted, and the gate still keys on the proven-lower-bound bit rather than
on an estimate's source.

Two real defects in my own diff, both found by re-review of the merged tree and both fixed here:

  • A read whose parts carry a lightweight delete or a patch part was treated as a lower bound.
    selected_rows counts physical rows in the selected ranges, but that filter is applied at
    read-pool construction, after estimation. Measured on a right side of 100000 physical / 1 live
    rows against a 3-row left side: pristine master plans l_res on the build side, the pre-fix
    merged head puts the 1-row side on the probe side - the exact inversion this PR exists to
    prevent - and the fix restores master's plan.
  • The composite bound went through the heuristic estimator, which casts to double. For
    94906267 * 94906267 that returned a value one below the exact product, i.e. a declared upper
    bound sitting under the count it bounds. Composite bounds now use saturating integer math; over
    8 operand pairs, representable-product violations go 2 -> 0.

The first one's test arm is new (deleted right side keeps orientation). On the pre-fix binary it is
the only line in the test that changes, and its vacuity margin is granularity-independent, unlike the
residual arm - which I also widened this round after bracketing showed the swap threshold sits at 401
rows while index_granularity = 1 yields an estimate of 100, low enough that a build wrongly
trusting a residual-filtered estimate would have declined the swap and let the arm pass for the wrong
reason.

Liveness re-proved on the merged tree against a pristine merged-master build: all four planner arms
and the runtime arm still reverse without the fix.

Description updated to cover both guards.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c96f2a867 with master 22a323d93 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 85f48a47c; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

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.

Compile time of recompiled translation units

54 translation units recompiled, 438 s compile time in total, 54 of them have a recent master baseline.

Job report

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8ec2de2

CI is fully finished on this head: 178 check-runs, none queued or in progress, Config Workflow and Finish Workflow both green. CIDB agrees independently - 349,847 rows across 165 checks at this commit, 0 with status FAIL or ERROR.

No failures, so there is nothing to own.

The 16 skipped jobs are the expected set for a pr-performance change: the five Bugfix validation legs are skipped by design (no bugfix category), and the rest are the usual not-affected filters.

Session id: cron:our-pr-ci-monitor:20260819-020000

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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
  • StressHouse run: de79b8a7-09a4-4d6c-b756-91041ef4b17d
  • MIRAI run: bb49ddfb-e678-4c66-912e-b4761cf13c14
  • PR check IDs:
    • clickbench_999418_1791783803
    • clickbench_999431_1791783803
    • clickbench_999437_1791783803
    • tpch_adapted_1_official_999448_1791783803
    • tpch_adapted_1_official_999475_1791783803
    • tpch_adapted_1_official_999489_1791783803

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.
@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7405d06

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
Upgrade check (amd_release) / Error message in clickhouse-server.log mutation error the test itself asserts: all 297 of 297 lines in upgrade_error_messages.txt are Code: 16 ... Unexpected const virtual column: _table ... While executing MergeTreeSequentialSource from MutatePlainMergeTreeTask on test_5.t_mut_local, 0 lines anything else, so the whole leaf is 04510_mutation_query_plan_only_virtual_columns and its deliberately-failing DELETE WHERE _table != '' #117218 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Failures: 1/12 on the check; every other job on this head is OK or a label-gated SKIPPED.
Mergeable Check names this row (Failed: Upgrade check (amd_release)), so it is gating.
No master merge is owed here: #117218 is still open, so there is nothing merged to pick up.

Session id: cron:our-pr-ci-monitor:20260902-000000

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 4, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7df483d

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
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) not from this PR: the job ran no test. Its test-selection step (check_coverage_canary in find_tests.py) got HTTP 500 Code: 241 MEMORY_LIMIT_EXCEEDED from the CI database at 05:31 UTC, so Failed to load test selection a fix task is created (investigating at full effort, fixing-PR link to follow here)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above a fix task is created (the owner of the first row)

CIDB has no FAIL or ERROR row on this head; every other job that ran passed.

Session id: cron:our-pr-ci-monitor:20261017-073009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the targeted-job test-selection CIDB HTTP 500: #125613

alexey-milovidov and others added 2 commits October 25, 2026 02:26
…-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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a57ff9c

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
Upgrade check (amd_release) / Changed settings are not reflected in the settings changes history (see changed_settings.txt) not from this PR (it does not touch settings): v26.10.2.103-stable ships use_query_condition_cache_for_time_conditions = false after #127632, while master's settings history still says its default became true in 26.10. Every PR whose Upgrade check started after 2026-10-24 04:17Z reports the same 1 / 0 row #127687 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #127687 (the owner of the first row)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261025-070009

@vdimir vdimir self-assigned this Oct 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

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.

@vdimir

vdimir commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

@groeneai could you resolve conflicts?

groeneai and others added 2 commits November 3, 2026 17:10
…-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]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Done: master is merged in 4ab7075 (the only conflict was the include list of RelationStatisticsEstimator.cpp).

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 ARRAY JOIN, and two shapes got a worse join order than on master. Both are now reset there, with a test arm for each. 04726 passes 50/50 with randomized settings, and 1500 join tests show no regression against master.

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]>
@vdimir

vdimir commented Nov 5, 2026

Copy link
Copy Markdown
Member

@groeneai could you resolve conflicts?

@vdimir vdimir 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.

Overall diff looks to big for such change. Can it be replaced with #129411?

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

Yes. The build-side swap in chooseJoinOrder needs a row estimate on both inputs (optimizeJoin.cpp), and #113336 adds a row bound for the side that has none. With the assumed filter selectivity you asked for on #129411, a filtered table without statistics gets an estimate, and the existing swap covers this case. I checked on master: for (SELECT id FROM dim WHERE nation_id = 5) AS d JOIN fact, the 100,000-row fact is on the build side without statistics, and dim is once it has an estimate. The current keep-order #129411 does not change this query, since a two-table join has no sub-join to keep in order.

The rest of #113336 (keeping an estimate through DISTINCT and IN (subquery) set steps) is a separate gap nobody reported, so I'd drop it. #113336 can be closed in favour of #129411, which is why I haven't resolved its conflicts; if you want it kept until #129411 is merged, I'll resolve them.

@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

Closing as per #113336 (comment)

@rschu1ze rschu1ze closed this Nov 9, 2026
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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements

Projects

None yet

7 participants