Repository navigation
Build the hash join table on a subset of the equality keys and check the rest during the probe - #106955
Build the hash join table on a subset of the equality keys and check the rest during the probe#106955UnamedRus wants to merge 39 commits into
Conversation
|
Workflow [PR], commit [33f5576] Summary: ❌
|
|
📊 Cloud Performance Report ✅ AI verdict: No query in clickbench or tpch_adapted_1_official shows a verdict attributable to this PR. The one flagged row, clickbench Q30 at -10.0%, stays no_change: it is inside master's current range (199-287 ms), CPU time barely moved, and the query has no JOIN. The new hash-join key demotion, the probe fan-out counters, and the stacked-filter row estimate all sit on JOIN planning and probe paths, which Q30 never enters. No TPC-H join query moved, which fits the demotion's limits (build side of at least 1M rows with known column statistics, and at least 128 MiB of estimated saving), so this run did not measure the new code path either way. Both benchmarks' PR runs shared one machine, which is a small caveat on wall-clock comparisons. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
PR-side fixes for ClickHouse#106955 review comments: * Skip demotion when none of `hash`, `parallel_hash`, or `grace_hash` is enabled in `join_algorithm`. Demotion forces a `mixed_join_expression` and `chooseJoinAlgorithm` only accepts that for hash-family algorithms; silently installing it under e.g. `full_sorting_merge` turned a valid plan into a runtime exception. The existing test now also covers `join_algorithm = 'full_sorting_merge'`. * Drop the unbounded `MULTI` candidate (product of per-column NDVs) and let the cardinality enumeration probe `HashTablesStatistics` for joint NDV of any subset that a previous query on the same right subtree happened to build a hash table on. The cache value is observed joint NDV, so it captures correlation between keys directly rather than assuming independence. `SINGLE`-key candidates still come from storage `STATISTICS(uniq)`; the smaller NDV per indices set wins. * Replace the depth-first walk to the underlying `ReadFromMergeTree` with the relation-stat propagation from `Optimizations::estimateReadRowsCount`, so the right-side row count and per-column stats account for intervening `FilterStep`, `LimitStep`, `AggregatingStep` and nested joins instead of returning the raw-table values. `estimateReadRowsCount` itself now falls through any single-input `ITransformingStep` with `preserves_number_of_rows = true` (covers `BuildRuntimeFilterStep`, `ExtractColumnsStep`, etc.) so default-on `enable_join_runtime_filters` does not hide the underlying source. * `HashTablesStatistics` cache key now reflects the post-demote kept equi-key set. The parent join's `JoinStepLogical` stores the right subtree's parent-independent raw hash; `buildPhysicalJoinImpl` applies the per-side contribution computed from the surviving clause keys after `demoteLowNdvKeysToResidual` finishes, so demote-on and demote-off shapes of the same logical join no longer share a cache slot. * Fix style check: unify the type of `query_plan_join_subset_keys_min_kept_selectivity` between `src/Core/Settings.cpp` and `src/Processors/QueryPlan/QueryPlanSerializationSettings.cpp` (both `Double`). Related: ClickHouse#106955 Closes: ClickHouse#102595 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Flip `query_plan_join_subset_keys_auto` default to `true` so the same plain join SQL runs on master (no demotion) and on this branch (demotion applies). Record the change in `SettingsChangesHistory`. Add `tests/performance/join_subset_keys_auto.xml`: a 10M-row joined with 10M-row workload with a 10x cardinality ratio between the two equality keys (`high_card` = number, `low_card` = number / 10), to mirror the issue reproducer in <ClickHouse#102595 (comment)>. The PR build keeps `low_card` as the hash key and pushes `high_card` to the residual probe-time filter; peak memory drops roughly 2x and elapsed time is at least neutral and typically faster. Related: ClickHouse#106955 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ions `HashJoin::validateAdditionalFilterExpression` only accepts mixed- condition predicates for a fixed (kind, strictness) matrix. The previous demote guard only excluded `Asof`, so other rejected combinations - `RightAny`, `Semi`/`Anti` over Inner/Full, and `Any` over Full - turned a valid query into a "Non equi condition '...' from JOIN ON section is supported only for ALL INNER/LEFT/FULL/RIGHT JOINs" exception at runtime. The user-facing case is `any_join_distinct_right_table_keys = 1`, which the analyzer applies to `ANY ... JOIN` to promote strictness to `RightAny` (see `Analyzer/QueryTreeBuilder.cpp`). A multi-key `ANY LEFT JOIN` with that setting on, plus storage `STATISTICS(uniq)`, was getting silently rewritten into a `mixed_join_expression` and then rejected by `HashJoin`. Mirror `validateAdditionalFilterExpression`'s matrix inside `demoteLowNdvKeysToResidual` so the rewrite only fires for the combinations the executor can actually run: `All` over any kind, `Semi`/`Anti` over Left/Right, `Any` over Left/Right/Inner. Regression test exercises `any_join_distinct_right_table_keys = 1` with a multi-key `ANY LEFT JOIN` and asserts no exception plus both keys remain in the hash table. Related: ClickHouse#106955 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`chooseJoinAlgorithm` (`Planner/PlannerJoins.cpp:1372`) gates `mixed_join_expression` on `isEnabledAlgorithm(HASH | PARALLEL_HASH | GRACE_HASH)`. `JoinAlgorithm::AUTO` does not satisfy any of those (see `TableJoin::isEnabledAlgorithm`, which only expands `DEFAULT` into `HASH`/`DIRECT`), so demoting under `auto` would silently install a `mixed_join_expression` and then trip the "JOIN with mixed conditions supports only hash join or grace hash join" exception, even though the `JoinSwitcher` `auto` would create wraps a `HashJoin` that can actually run the mixed condition. Drop `JoinAlgorithm::AUTO` from the mixed-capable predicate inside `demoteLowNdvKeysToResidual`. `DEFAULT` stays because `isEnabledAlgorithm(DEFAULT, HASH)` returns true. Regression test sets `join_algorithm = 'auto'` on the same multi-key shape and asserts no exception plus both keys retained. Related: ClickHouse#106955 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`estimateRelationProfileImpl`'s final NDV loop clamped every column to `min(filtered_rows, full_column_NDV)`, ignoring whether the filter actually constrained the value space of that column. For `WHERE r.region = 1` joined on `region` plus another key, that meant the column_stats reported `NDV(region) = min(rows, 10_000)` instead of 1; the JOIN key-subset demote rewrite (PR ClickHouse#106955) then treated `region` as a valid bucket bound even though the filtered stream had exactly one distinct value, demoting the real discriminator and making every probe scan the whole filtered bucket. Compute per-column conditional NDV inline alongside selectivity: * `RPNElement` carries `column_ndv`; `RPNElement::finalize` walks the atom's `column_ranges` / `column_not_ranges` together with the per-column selectivity it already derives and produces an NDV bound: - equality (single-point range) -> 1 - IN list of `k` singletons -> `k` (clamped to `full_ndv`) - generic bounded / open range -> `ceil(full_ndv * sel)` - `column != const` / `NOT IN` -> `full_ndv - k` * The AND/OR/NOT branches of `estimateRelationProfileImpl` combine `column_ndv` alongside selectivity (`min` for AND, saturating sum for OR, `full_ndv - n` for NOT) using two file-static helpers. * Replace the row-clamp with: use the conditional NDV from `final_element->column_ndv` when present, otherwise apply `sampleDistinctNDV(full_ndv, result.rows)` for columns the predicate does not touch. The Yao "distinct values in a sample" formula converges to `full_ndv` when the sample covers the population and to the row count when it is sparse, so the no-filter case is unchanged and the previous over-estimate in the intermediate range is fixed. Direct consumer of the affected `RelationProfile::column_stats` is the JOIN key-subset demote in `JoinStepLogical::demoteLowNdvKeysToResidual`; no code change is needed there - the existing `single_ndv >= target_ndv` gate now rejects filter-constrained keys as expected. Regression test in `04326_join_subset_keys_auto.sql` (`filtered_picks_real_discriminator`) exercises the reviewer's case: equality on a high-NDV column joined on that column plus another key; the plan keeps both keys (demote bails) instead of demoting the wrong key. Direct unit coverage for the new NDV path in `gtest_stats.cpp::Statistics::ConditionalNDV` asserts NDV under equality, IN, OR-of-equalities, NOT, and conjunction shapes. Related: ClickHouse#106955 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…idy) The clang-tidy `arm_tidy` build flagged the new `UInt64 cardinality;` declaration in `ConditionSelectivityEstimator::estimateRelationProfileImpl` under `cppcoreguidelines-init-variables`: error: variable 'cardinality' is not initialized Both branches that follow assign to `cardinality` before any read, so the variable is never actually used uninitialized — but ClickHouse treats this lint as a warning-as-error. Default-initialize to `0` to satisfy the check. Related: ClickHouse#106955 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Add cardinality-based JOIN equality-key demotion: when one equality key already discriminates well, keep that key in the hash table and push the remaining higher-NDV keys to a residual probe-time equality filter. Hash table shrinks to ~target bucket size; the residual filter runs over a bounded number of rows per probe. Gated by `query_plan_join_subset_keys_auto` (off by default), with `query_plan_join_subset_keys_min_rows` and `query_plan_join_subset_keys_min_kept_selectivity` tuning the firing threshold and the target kept-key selectivity. Without companion per-column conditional NDV statistics, the rewrite relies on master's `ConditionSelectivityEstimator`, which reports `min(filtered_rows, full_ndv)` for filtered columns. This can pick a sub-optimal discriminator under equality filters on the right side, so the setting is off by default. Originally part of ClickHouse#106955; this is the demote optimization split out without the per-column conditional NDV statistics changes. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Restore the `make_distributed_plan` field in `Optimization::ExtraSettings`, accidentally dropped while reshaping the struct for the demote pass; it is read by `tryOptimizeTopK` and `optimizeTree` to suppress top-K rewrites on plans that will be distributed. - Pass `JoinStrictness` as the new 3rd argument to `allowParallelHashJoin` from `calculateHashTableCacheKeys` (signature gained `strictness` upstream). - Drop the duplicate default argument from the forward declaration of `estimateReadRowsCount` in `makeDistributed.cpp`; the canonical declaration with the default now lives in `Optimizations.h`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
d1de5fa to
765cb22
Compare
Resolve conflicts from upstream master rename and feature work: - `enable_join_runtime_filter_shared_fixed_hash_table` was renamed to `join_runtime_filter_from_fixed_hash_table` in master (PR ClickHouse#107668). All references on this branch are updated to the new name; the obsolete `SettingsChangesHistory.cpp` entry for the old name is dropped. - `Settings.cpp` and `QueryPlanSerializationSettings.cpp` keep both the master additions (`query_plan_max_limit_for_join_lazy_indexing`, `query_plan_min_columns_for_join_lazy_indexing`) and this branch's demote settings. - `makeDistributed.cpp` keeps master's `validateBucketCount` / `MAX_DISTRIBUTED_PLAN_BUCKET_COUNT` and drops the duplicate default argument from the local `estimateReadRowsCount` declaration; the canonical declaration with the default now lives in `Optimizations.h`. - `optimizeJoin.cpp` keeps the demote-side comment block explaining the generic row-preserving pass-through. Also rename the demote settings for clarity that they only apply to the hash join algorithm: - `query_plan_join_subset_keys_auto` -> `query_plan_hash_join_subset_keys_auto` - `query_plan_join_subset_keys_min_rows` -> `query_plan_hash_join_subset_keys_min_rows` - `query_plan_join_subset_keys_min_kept_selectivity` -> `query_plan_hash_join_subset_keys_min_kept_selectivity` Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous merge of `origin/master` concatenated overlapping `26.6` section entries from both sides, leaving duplicate keys (`optimize_limit_by_in_order`, `analyzer_compatibility_prefer_alias_over_subcolumn`, `query_plan_max_set_size_for_projection_match`, `use_reader_executor`, `allow_tuple_element_aggregation`). Keep the master copy of each. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Restore upstream lines that were accidentally removed when the demote optimization was first split out from PR ClickHouse#106955: - `Settings.cpp`: revert `NonZeroUInt64` -> `UInt64` flip for `distributed_plan_default_reader_bucket_count`. - `JoinStepLogical.h`: restore `bool isSerializable() const override`. - `optimizeJoin.cpp`: restore `#include` of `ReadFromObjectStorageStep`, `LogicalExchangeStep`, `ShuffleExchangeStep`, `GatherExchangeStep`, the `ReadFromObjectStorageStep` short-circuit in `estimateReadRowsCount`, and the `keep_logical |= make_distributed_plan` line in `convertLogicalJoinToPhysical`. - `SettingsChangesHistory.cpp`: restore master's ordering of the 26.6 entries that the dedup re-ordered. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address PR review: `tryEstimateRelationProfile` re-keyed every matched statistic by `stripTableQualifier(name)`, so two qualified right-side outputs sharing a storage column name (e.g. `__table2.id` and `__table3.id`) collapsed into one `column_stats` entry and inherited whichever NDV was written last. Demotion could then keep or drop the wrong key and violate the bounded-bucket contract. Key the output profile by the exact join-key name (the map is the optimization's own, so exact names are unambiguous), and look candidates up by the exact name too. The stripped name is still used only as a fallback to find the underlying direct-storage statistic. Mirrors the existing convention in `remapColumnStats` (optimizeJoin.cpp) and `DPJoinEntry` (joinOrder.cpp), which key column stats by the exact qualified name. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e demoted `demoteHighNdvKeysToProbe` moves ON equalities out of `JoinOperator::expression` into `JoinOperator::probe_conditions`, and `tryAddJoinRuntimeFilter` runs after it (`optimizeTree` calls the join-order pass on enter and the runtime-filter pass on leave). The filter pass reads only `expression`, so a demoted equality is invisible to it. For `LEFT ANTI` that produces wrong results. The pass builds an exact `NOT IN` set and already refuses to do so when it finds any condition beyond a plain cross-side equality, because an over-broad set turns into false exclusions. A demoted equality is exactly such a condition, but it no longer appears in `expression`, so the guard did not fire: the set was built on the kept keys alone and excluded left rows whose kept keys occur on the build side even when the full key tuple has no match. With a build side of near-unique `a` and 10-valued `b`, a left row `(2, 1)` against right rows `(number, number % 10)` was dropped instead of returned: `b = 1` occurs on the right, `(2, 1)` does not. The plan showed `Clauses: [(b) = (b)]` with `Residual filter: equals(a, a)` and `BuildRuntimeFilter ... on __table2.b` applied in prewhere. Skip the filter for `LEFT ANTI` when `probe_conditions` is non-empty. Other join kinds are unaffected: there a set built on a key subset only lets extra rows through and the join rejects them, so demotion keeps its filter. Both existing tests set `enable_join_runtime_filters = 0`, so the combination was uncovered; `04612` also covers only LEFT and FULL, no SEMI/ANTI. The new test pins the result across all four combinations of the two settings and asserts that demotion still happens while the filter is skipped. ClickHouse#106955 (comment) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The optimization is gated by more than the flag: the build side must have at
least `query_plan_hash_join_subset_keys_min_rows` rows (1 million by default)
and known column statistics, and demotion is skipped when the build-side row
count had to be guessed. Say so in the doc string, which the autogenerated
settings documentation is built from.
`SettingsChangesHistory` records the change as `false -> true` for 26.9, so
`compatibility` below that version keeps the hash table keyed on every
equality:
compatibility = '26.8' -> false
compatibility = '26.9' -> true
unset -> true
`tests/performance/join_subset_keys_auto.xml` keeps naming the setting
explicitly so it still measures the optimization against a reference build
where the default is the old one; only its now-stale "off by default" comment
is corrected.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`query_plan_hash_join_subset_keys_auto` is on by default now, so the query does
not have to opt in - and opting in inline was actively hiding the measurement.
The perf comparison runs the same query text against the reference build, whose
connection is opened with `settings_is_important = True`, so an inline
`SETTINGS query_plan_hash_join_subset_keys_auto = 1` fails there with
`UNKNOWN_SETTING`. The harness then keeps the query on the new server only and
excludes it from the comparison, reporting it under "Backward-incompatible
Queries" with a single PR-side median and no baseline:
https://performance.ci.clickhouse.com/runs/pr-106955-fc873716689ba5717d444b511537455090e21212
listed `join_subset_keys_auto` query 0 there at 0.280s (amd) and 0.190s (arm),
and the test is absent from the comparison entirely.
Without the inline setting the query text runs on both builds: the reference
build has neither the setting nor the optimization and keys the hash table on
both equalities, while this build demotes `high_card`, so the report compares
them directly. The test's other prerequisites already hold on the reference
build - `use_statistics` and `allow_statistics` default to `true` and
`query_plan_optimize_join_order_limit` is `10`, so join reordering is active.
Signed-off-by: UnamedRus <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…test The test creates its two tables with `ORDER BY ()`, so there is no primary key and the pushed-down `uid < 100` predicate is resolved by the automatic column statistics. Those prune at part level, not at granule level, so the query reads in full the single part that holds `uid < 100`, and how many rows that is depends only on how the `INSERT` cut its parts and on how far the background merge has folded them together. The reported read amount therefore swung between 2223906 rows (the predicate still inside an unmerged 1.1M-row part on both sides) and 13343436 rows (a merged 6.7M-row part), with a merge landing between two runs making one server report both, so `SelectedRows`, `SelectedMarks`, `ReadCompressedBytes` and the times derived from them were reported as changed for two identical query plans - in https://performance.ci.clickhouse.com/runs/pr-106955-fc873716689ba5717d444b511537455090e21212/tests/join_convert_full_to_left_or_right the amd shard read 2223906 rows against the arm shard's 13343436, purely because their merges had progressed differently. `SYSTEM STOP MERGES` before the `INSERT` keeps the inserted parts as they were written, and pinning `max_block_size` and `min_insert_block_size_rows` makes the way they are cut a property of the settings rather than of the number of insert streams the machine chose: 10 parts of 1048576 rows, the last one 562816, on every server. The predicate then sits in the first part, `EXPLAIN indexes = 1` prunes to `Parts: 1/10`, and the query reads 2097152 rows over 256 marks, run after run - measured over 8 consecutive local runs, 11-24ms each. `OPTIMIZE TABLE ... FINAL` on both tables fixes the layout just as well, but it rewrites 10M rows per table during the fill (1.98s against 1.01s) and leaves the query reading the whole table on every run (20000000 rows, 2442 marks, 50-67ms). A single-block `INSERT` reaches one part without the rewrite, but holds the whole block in memory - 343 MiB against 67 MiB - and reads the full table too. Related: ClickHouse#106955 Signed-off-by: UnamedRus <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`05077_join_runtime_filter_skip_saturated_bloom_filter` asserts that a join on
two keys builds one runtime filter per key column - the point of its second
pair of queries is that the hash table statistics count distinct *pairs*, which
bounds the per-column filters but never makes them be skipped.
With `query_plan_hash_join_subset_keys_auto` on by default, that join is exactly
a demotion candidate: the build side is 2000000 rows, `a` has 100000 distinct
values and `b` has 20, so the table is keyed on `a` alone and `b` moves to
`JoinOperator::probe_conditions`. `tryAddJoinRuntimeFilter` reads only
`JoinOperator::expression`, so it sees one key and builds one filter:
-2 0 1 -1 0 0
-2 0 1 +1 0 1
Results are unaffected - the counts above the filter columns match - but the
test is about the filters, so it pins the setting off instead of following the
new plan. Reported by the Fast test on
https://github.com/ClickHouse/ClickHouse/actions/runs/34455761648/job/102802163359
Signed-off-by: UnamedRus <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| kept_expression.push_back(join_operator.expression[i]); | ||
| else | ||
| { | ||
| join_operator.probe_conditions.push_back(join_operator.expression[i]); |
There was a problem hiding this comment.
probe_conditions becomes part of the real JOIN ON semantics here, but the distributed Cascades stats path still ignores it. optimizeTree runs CascadesOptimizer after optimizeJoinLogical, and StatisticsDerivation::deriveJoinStatistics still iterates join_step.getJoinOperator().expression only.
That means a demoted two-key join is priced as if only the kept hash key existed. For example, with make_distributed_plan = 1, enable_cascades_optimizer = 1, a 1M-row build side, query_plan_hash_join_subset_keys_min_kept_selectivity = 0.01, and right-side NDVs like user_id = 20000, request_id = 1000000, this rewrite can keep user_id and move request_id here, but Cascades still estimates selectivity as 1 / 20000 instead of applying both equalities. The resulting estimated_row_count can be inflated by orders of magnitude and distort later broadcast/shuffle and pushdown choices.
Please make deriveJoinStatistics fold probe_conditions into the equality-selectivity and inner-join equivalence walks as well.
|
Q4 degradation debug, TLDR:
Investigation report |
| <fill_query>OPTIMIZE TABLE jks_perf_right FINAL</fill_query> | ||
|
|
||
| <query> | ||
| SELECT count() FROM jks_perf_left l JOIN jks_perf_right r |
There was a problem hiding this comment.
Performance Improvement needs coverage for the default-on outer-join path too. This file only benchmarks a plain inner join, but demoteHighNdvKeysToProbe still applies the same heuristic to LEFT/RIGHT/FULL joins, and the 2026-09-10 PR discussion already reports regressions there. As written, the benchmark validates only the easiest case while the shipped behavior is broader. Please either gate demotion away from the outer kinds in this PR or add a focused outer-join perf case or before-after numbers that show the default thresholds are safe there too.
`demoteHighNdvKeysToProbe` had a floor on the benefit and no ceiling on the
cost. `query_plan_hash_join_subset_keys_min_kept_selectivity` bounds the mean
bucket the kept keys leave at 1/selectivity, i.e. 100 by default, and the
`chosen->ndv * 2.0 > rows` check requires the table to shrink at least 2x. What
the probe then spends walking that bucket was never priced, and the smallest-NDV
candidate was selected, which demotes the most discriminating key and so inflates
the bucket as much as the other guards allow.
On `right_full_parallel_join` query 4 that demoted `t1.URL = t2.Referer` out of a
`FULL ALL` join and left `UserID` as the only hash key. The table shrank from
4,925,640 entries to 1,865,152 and peak memory fell 8.7%, while the query went
from 1.152s to 2.532s in CI on both architectures. The probe was checking a
String equality per candidate row over a bucket of ~5 rows on average, and 55 on
this data once the skew of `UserID` is accounted for.
Price both sides instead:
- Cost, capped by `query_plan_hash_join_subset_keys_max_probe_cost_ns`: the
mean bucket times what one candidate check costs for the demoted key types
and the join kind. Demoting cannot make the probe cheaper - it only shrinks
the table - so this is what is being paid for the memory, and it is a cap
rather than one half of a ratio. A variable-length key costs about 290ns per
candidate against 8ns for a fixed-width one, dominated by gathering values
out of the stored blocks rather than by the comparison; RIGHT/FULL carry the
`add_missing` and `need_flags` bookkeeping an inner join does not, and
ANY/SEMI/ANTI stop at the first surviving candidate.
- Benefit, floored by `query_plan_hash_join_subset_keys_min_saving_bytes`: the
cell array the full key set allocates minus the one the kept subset would.
`HashJoin::chooseMethodForTypes` answers which map variant a hypothetical key
set uses from the key types alone, since `chooseMethod` reads only
class-level properties of the key columns, so empty columns answer it
exactly. That also catches the case where dropping a key moves the key set
into a narrower method, which counting entries alone misses. The estimate is
an upper bound: it counts cells only, and the arena holding the rows that
chain past the first per key grows as keys are removed.
Then take the cheapest surviving candidate rather than the smallest-NDV one.
With the defaults, query 4 is refused - a String key over a bucket of 5 comes to
~2100ns per probe row against a 200ns ceiling - while a two-fixed-width-key join
whose kept key already discriminates, the shape the feature is for, still
applies at ~80ns.
Two test fixes come with it. `join_subset_keys_auto.xml` never measured the
feature at all: the demote requires every algorithm in `join_algorithm` to
evaluate a mixed ON condition, and the default value includes `direct` and
`ie_join`, which do not, so both sides of the comparison ran the unoptimized
plan - 10,000,000 hash entries either way and 2,048 bytes of memory difference
against a comment claiming a 2x drop. It now pins `join_algorithm`.
`04612_join_subset_keys_auto_correctness` compares a demoted plan against a
non-demoted one, so it passed whether or not anything fired; it now asserts that
the plan does carry a residual filter on this fixture, and that the default gate
refuses the same fixture.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The two checks added with the cost gate assert the shape of the plan rather than comparing two results, so unlike the six cases above them they are not invariant to how the join is planned. The stateless harness randomizes join order outright via `query_plan_optimize_join_order_randomize`, which moves the build side, and `jks2_left` carries no column statistics - so on a randomized run the demotion had nothing to score and `demote_fired` reported 0. Pin `query_plan_optimize_join_order_randomize`, `query_plan_join_swap_table` and the statistics settings on those two queries. Pinning the queries keeps this out of the other six cases, which compare a demoted plan against a non-demoted one and are correct however the join is planned, and avoids putting `no-random-settings` on the whole file for the sake of two statements. Verified against a server built from this branch: 8 consecutive randomized runs of `clickhouse-test` pass, where the unpinned version failed on the first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The cell array is not the whole table. A string-keyed map copies every key into the join's own pool, while `hashed` keeps only a 128-bit digest in the cell, so comparing the two on cell size alone says a `key_string` table is the cheaper of the two when it is in fact much larger. Measured on `right_full_parallel_join` query 4, the gate accepted a demotion that kept `URL` as the only hash key: the query went from 2.74s to 13.55s and from 1.88GB to 3.62GB against the same query with the optimization disabled. Add the key payload to `HashJoin::estimateTableBytes` for the variants that store keys out of line, and refuse to answer at all when the key width is unknown rather than undercount by exactly the term that decides the comparison. Widths come from the build side's measured `avg_bytes` where it has them, and from `estimateColumnWidthFromType` otherwise. That alone was not enough, because the size of the table being replaced was also wrong. With no measured joint NDV for the full key set, the estimate multiplied the per-key NDVs and clamped to the row count, giving 10000000 where the table really holds 4925640 entries - so every candidate was credited with removing a table twice the size of the one that gets built. The joint NDV lies between the largest single-key NDV and that product; take the former. It is the conservative end, and on a key set whose largest key already determines the joint NDV, which is the shape this optimization targets, it is exact. Query 4 is now refused and plans exactly as it does with the optimization off - 4925640 entries either way, 2.87s against 2.70s, 1.894GB against 1.888GB - while the two shapes where demoting pays are unchanged at ~1.3x faster and ~25% less memory. Lifting the gate still reaches the demoted plan at 27.2s, so it is the gate declining rather than the plan having become unreachable. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`demoteHighNdvKeysToProbe` demanded that *every* algorithm in `join_algorithm`
evaluate a mixed JOIN ON condition. The default value is
`direct,parallel_hash,hash,ie_join`, so the optimization was unreachable unless
the setting was narrowed by hand - which is why its own performance test measured
two identical plans.
One such algorithm being enabled is enough, which is the condition
`chooseJoinAlgorithm` itself asserts. The others do not silently drop a mixed
condition, they decline it and fall through to the hash family: `tryDirectJoin`
returns nothing, `MergeJoin::isSupported` and `FullSortingMergeJoin::isSupported`
return false, and `AUTO` builds a `JoinSwitcher` only when
`MergeJoin::isSupported`, so it degrades to `HashJoin` too.
Two cases genuinely cannot fall back, and both are now guarded directly:
- IEJoin is chosen by its position in `join_algorithm` rather than by being
applicable, and evaluates a mixed condition nowhere, so `isIEJoinPreferred`
rejects the demotion outright.
- A `Join` engine right side is read through `StorageJoin::getJoinLocked`,
which rejects a mixed expression and is reached before the algorithm loop.
Demoting there would turn a working query into an error, so the call site
skips a right child that is a lookup over one.
Measured on the default `join_algorithm` after the change: `hits_10m_single`
FULL JOIN plans identically to the optimization being disabled - 4925640 entries,
2.656s against 2.660s - while lifting the cost and saving thresholds reaches the
demoted plan at 25.6s, which before this change was unreachable at any setting.
The shape the feature targets now applies without pinning anything, at 1.26x
faster and 26% less memory.
`04612` needed two fixture fixes to survive settings randomization once the
optimization became reachable: both tables carry statistics, because which side
the DP builds is not fixed by `query_plan_join_swap_table` alone and a build side
without statistics has no NDVs to score; and the plan-shape assertions pin
`query_plan_optimize_join_order_limit`, since the demotion lives inside
`chooseJoinOrder` and the harness sets that limit to 0 or 1 - either too low to
reorder a two-table join - often enough to matter. 16 consecutive randomized runs
pass, against 2 failures in 16 before.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The demotion depends on join reordering - it needs the build side the DP settled
on, together with that side's row count and column statistics, and it has to run
before the hash table cache keys are derived - but depending on the reorder is
not a reason to live inside it. `optimizeJoin.cpp` had grown 386 lines of an
unrelated pass.
Move it to `Optimizations/demoteJoinKeys.{h,cpp}`. The only thing tying it to the
reorder file was `RuntimeHashStatisticsContext`, which is local to that
translation unit; the new unit takes a `CachedSubsetNdvLookup` callback instead,
so it does not have to know how the reorder tracks runtime hash-table statistics.
Everything else it uses is already public. The reorder file keeps the call and a
lambda, and the header states the ordering contract, which is the part of the
dependency that is not obvious from a call site.
`optimizeJoin.cpp` goes from 2243 to 1864 lines. The scoring helpers become
internal to the new unit rather than file-scope functions in a shared one.
No behaviour change, which the measurements confirm: on the default
`join_algorithm`, `hits_10m_single` FULL JOIN still plans identically to the
optimization being disabled (2.712s against 2.739s, 4925640 entries either way),
lifting the thresholds still reaches the demoted plan at 26.0s, and the two
shapes the feature targets still come out ~1.3x faster on ~25% less memory. Every
figure is within run-to-run spread of the same measurement taken before the move.
16 randomized runs of `04612` pass.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The gate estimated probe-time fan-out as `rows / NDV(kept keys)`, which assumes every distinct key is equally likely. On `right_full_parallel_join` query 4 that gives 4.9 candidate rows per probe row where the real figure is 55 - the join emits 551698958 pairs against the 49307306 the optimizer predicts - so a demotion was scored at a fraction of what it would cost. The error is one-sided: skew only ever makes the real fan-out larger, so the estimate always flatters demotion. Record what the probe measured instead. `joinRightColumnsWithAdditionalFilter` already counts the candidate rows it examines before the filter runs, and the probe rows they came from; sum both across probe streams and store the ratio as `HashJoinFanoutEntry`, keyed like the build statistics, because the fan-out belongs to this build side keyed on this key set - exactly what a demotion chooses between. `ConcurrentHashJoin` sums its sub-joins and writes once, since they partition one logical table. The gate then takes `max(estimate, measured)`: a measurement can make a candidate look more expensive, never cheaper, so a stale or unrepresentative reading cannot license a demotion the estimate would have refused. This needs no new setting, no new cache key and no change to `IJoin`: the counts never leave the join, because the probe holds it by const reference where it already consumes `lazy_output`. Demonstrated on query 4 within one server: with the cost ceiling raised to 5000ns - above the 2144ns the uniform estimate scores it at, below the 23925ns the real fan-out scores it at - the first execution demotes and takes 26.5s, and every execution after it declines and takes ~2.7s. At the default ceiling it never demotes at all. The rest of the measurements are unchanged, which is expected: each starts a fresh server, so nothing is ever read back. Two limits worth stating. The reading only exists for a key subset some earlier query demoted down to, so a first execution is still scored from the estimate - this un-learns a bad demotion but cannot discover a good one. And the key covers the build side and its keys but not the probe side's distribution, so it is exact for a repeating query shape and approximate when the same build side is probed by something else. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`5626bdb6205` added `query_plan_hash_join_subset_keys_min_saving_bytes` and `query_plan_hash_join_subset_keys_max_probe_cost_ns` and changed which candidate wins - the cheapest surviving one rather than the one with the smallest NDV. It updated `04612_join_subset_keys_auto_correctness` but not the two other tests that assert a demoted plan, so both failed in the fast test. Both fixtures build a 5000-row hash table, which can never save the 128 MiB `query_plan_hash_join_subset_keys_min_saving_bytes` defaults to, so no demotion happened at all. Drop that floor to 0 in each test - it is a byte figure sized for real tables and has nothing to assert here - and leave the probe cost ceiling at its default, so the cost gate stays real in these tests and the plans they pin are the ones it admits. That makes the cheapest candidate the one with the largest kept NDV, which is the opposite of what the references held: `04326_join_subset_keys_auto` now keeps `user_id` (NDV 500, a 10-row bucket) and demotes `request_id`, and `05153_join_subset_keys_anti_runtime_filter` keeps `a` and demotes `b`. The comments explaining each choice are updated with the references. The `LEFT ANTI` test keeps its point: its one left row still has a kept key that appears on the right and a full key tuple that does not, so a runtime filter built on the kept keys alone would still wrongly exclude it. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106955&sha=d8c27f478f109d43cef15cc14b0314ff6df27e3a&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| settings[QueryPlanSerializationSetting::query_plan_hash_join_subset_keys_auto] = query_plan_hash_join_subset_keys_auto; | ||
| settings[QueryPlanSerializationSetting::query_plan_hash_join_subset_keys_min_rows] = query_plan_hash_join_subset_keys_min_rows; | ||
| settings[QueryPlanSerializationSetting::query_plan_hash_join_subset_keys_min_kept_selectivity] = query_plan_hash_join_subset_keys_min_kept_selectivity; | ||
| settings[QueryPlanSerializationSetting::query_plan_hash_join_subset_keys_max_probe_cost_ns] = query_plan_hash_join_subset_keys_max_probe_cost_ns; | ||
| settings[QueryPlanSerializationSetting::query_plan_hash_join_subset_keys_min_saving_bytes] = query_plan_hash_join_subset_keys_min_saving_bytes; |
There was a problem hiding this comment.
QueryPlanSerializationSettings is a strict named schema: writeChangedBinary emits every touched entry by name, and an older peer throws on a name it does not know. JoinStepLogical::serializeSettings still ignores version, so under serialize_query_plan = 1 / make_distributed_plan = 1 a mixed-version cluster will now ship these five new names to older workers and fail to deserialize the whole JoinStepLogical.
This is already reachable on a default query because Settings.cpp now defaults query_plan_hash_join_subset_keys_auto to true, while QueryPlanSerializationSettings still defaults it to false; even if you align those defaults, any explicit threshold override would still hit the same incompatibility. Please gate writing these names on a new DBMS_MIN_QUERY_PLAN_SERIALIZATION_VERSION_WITH_* constant (like the adaptive-aggregator / packed-string-keys settings do) and add a focused mixed-version gtest for JoinStepLogical.
rschu1ze
left a comment
There was a problem hiding this comment.
This PR is supposed to reduce memory consumption for the hash tables during joins, right?
The alternative to that is grace hash joins which doesn't rely on cardinality estimates. Tbh, what this PR is doing seems kind of ad hoc.
Not really, #102595 |
|
I have a concern about the design. Building the table on This PR replaces that with a plan-time guess. The probe becomes O(1) + O(C) per row, where The O(C) is also not C cheap compares. So we give up a guaranteed O(1) probe for a memory saving the query may not need. The decision rests on statistics that cannot see skew or the real memory budget. What I would prefer: keep building on all keys. If the build side hits the memory bound, decide at that moment between spilling ( If the plan-time version stays, it should not be on by default. The description and changelog still say "disabled by default", but |
|
I would also like to see a detailed performance comparison on the eligible join queries from the ClickBench workloads (benchmark.clickhouse.com): the gains, and the regressions, documented with numbers. What exists today does not show the effect of the shipped behavior. |
I've considered that, but didn't wanted to pay cost of rebuilding hashtable, if we decide to remove some keys from it.
I don't think of it as alternative to/same bucket as grace hash, but more like optimization from opposite edge. Another aspect, which i did not perf validated, that data often imply some sorting/locality, at it likely to align with this opt.
Previous point, it's also hashtable resize we didn't need to execute, ie saved CPU time. IE it's implied to be both time/memory improvement, or at least ~neutral on time.
100 is mere artifact of statistics quirks, ideal target is buckets around dozen of rows, may be few at max.
I think, having it runtime level also might be useful/more accurate to fire, but having it as plan is also worth, it matter of having either more/better statistics on stored objects (columns/tables), better estimators, or statistics on runtime entities (hashtable sizes). And this will be improved anyway in future. Plus, it indeed can/should affect join reorder opt, because it change NDV rows in source tables.
I don't mind gating it under INNER only. But, in general, may be worth to think if additional filters perf can be improved somehow.
You mean TPC-DS and TPC-C?
It's true, so it can be tested across all queries in perf tests. So, it will be changed to opt in when ready, (unless it can be done that it always neutral/beneficial) Extra notes:
|
|
Yeah, I like the general idea of shrinking the hash table and with it the join memory. Join memory is two parts: the table and the payload. In some joins the payload is much larger than the table, so the table is noise. In others, semi joins for example, there is almost no payload. Even in inner joins the payload can be small or about the same size as the table, and those are exactly the cases where this pays off. It is not all cases, and I don't think it is even the majority, and separating them needs a lot of estimation. The bar we're increasingly leaning towards is a feature that is on by default, with a clear threshold where the gain is meaningful and nothing regresses. Gated under The other part I keep coming back to is the direction of the trade. Optimising for memory at the cost of probe time, when we don't know we needed the memory, still doesn't feel justified to me. Today there is no simple runtime guarantee that the workload the planner singled out actually comes out faster, so I don't see what turning this on buys us. Where I think it would clearly pay is as a fallback before On the default: if we knew at plan time which queries clearly benefit, we wouldn't need a setting at all. We would just turn it on, and disable it for specific cases if something goes wrong. That part is easy. Off by default is the worse outcome, because then nobody runs it, and we never learn when it is safe to enable without another full round of performance testing. So my real problem with deciding this at plan time is that we don't know the feature always pays off once it is on. I don't currently see that guarantee. |
…residual Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - retargeted PR record [email protected] to 26.10 (settings-history check rule) - semantic merge fixes in non-conflicting files: src/Processors/QueryPlan/Optimizations/RelationStatisticsEstimator.cpp Also resolved conflicts in: - `src/Interpreters/HashJoin/HashJoin.cpp` - `src/Interpreters/HashJoin/HashJoin.h` - `src/Interpreters/HashJoin/HashJoinMethodsImpl.h` - `src/Processors/QueryPlan/JoinStepLogical.cpp` - `src/Processors/QueryPlan/Optimizations/calculateHashTableCacheKeys.cpp` - `src/Processors/QueryPlan/Optimizations/optimizeJoin.cpp` Master moved `estimateReadRowsCount` into `RelationStatisticsEstimator.cpp`; the stacked `FilterStep` conjunction change is ported there. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Dear @harikrishnan94, 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. |
A multi-key equi-join keys its hash table on the product of the key spaces even when one key already discriminates well enough. For
ON t1.user_id = t2.user_id AND t1.request_id = t2.request_id, with few requests per user, the table is keyed onuser_idxrequest_idwhereuser_idalone gives buckets of a few rows.query_plan_hash_join_subset_keys_auto(off by default) lets the join-order optimizer build the table on a subset of the equality keys and check the rest per row during the probe. The kept subset is the one with the smallest NDV still reachingbuild_side_rows * query_plan_hash_join_subset_keys_min_kept_selectivity, so the probe-time check stays inside a bounded bucket. Candidate NDVs come fromSTATISTICS(uniq)on the build side and fromHashTablesStatistics, which contributes a measured joint NDV for subsets earlier queries actually built — that accounts for correlated keys, which multiplying per-column NDVs does not.The decision runs in
chooseJoinOrder, where the DP already holds the build side's rows and column stats, so nothing has to be re-estimated. The demoted equalities also leaveJoinOperator::expressionbeforederiveCacheKeysForNewJoin, so theHashTablesStatisticskey describes exactly the keys the table is built on. It therefore requires join reordering (query_plan_optimize_join_order_limit), which is anyway the only case where that cache key is populated.They move to
JoinOperator::probe_conditionsand are routed intomixed_join_expression— as ON conditions, not post-join predicates, which would drop an outer join's NULL-extended rows.serializewrites them back into the ON expression, so a deserialized plan keys on every equality: no format change, and the optimization simply does not cross a serialization boundary.Skipped when any enabled
join_algorithmdoes not evaluate a mixed condition (allowlist ofhash,parallel_hash,grace_hash,default— a merge algorithm would be picked first and silently ignore the equality), for(kind, strictness)outsideHashJoin::isAdditionalFilterSupported(now shared withvalidateAdditionalFilterExpressioninstead of duplicated), belowquery_plan_hash_join_subset_keys_min_rows, when the build-side row count came from a primary-index guess rather than statistics, and for null-safe equalities.Separately:
estimateReadRowsCountdropped the outer predicate when twoFilterSteps stack, over-estimating the build side that sizes this decision. It now passes the conjunction down.If #101398 lands, the statistics-source gate here should become its propagated
rows_estimate_trusted, which also catches an untrusted NDV inside a composite build side.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a query planner optimization, controlled by the new setting
query_plan_hash_join_subset_keys_auto(disabled by default), that builds the hash join table on a subset of the JOIN equality keys and evaluates the remaining equalities during the probe. On a multi-key join whose trailing keys are near-unique, such asON t1.user_id = t2.user_id AND t1.request_id = t2.request_idwith few requests per user, the table is keyed on theuser_idspace instead of theuser_idxrequest_idspace, reducing its memory. The kept subset is chosen from column statistics and from hash table sizes measured by earlier queries, targetingquery_plan_hash_join_subset_keys_min_kept_selectivity;query_plan_hash_join_subset_keys_min_rowssets the build side size below which it is skipped. Requires join reordering to be enabled.Workflow [PR]
Sync PR [sync-upstream/pr/106955]