Repository navigation
Add max_bytes_ratio_before_external_join setting - #103862
Conversation
Mirror `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort` for hash joins. The new `max_bytes_ratio_before_external_join` setting expresses the spill threshold as a fraction of available memory, which is convenient when the absolute byte value is hard to pick. If both the absolute `max_bytes_before_external_join` and the ratio are set, the smaller resulting threshold wins. The ratio defaults to `0` (disabled), so behavior is unchanged unless explicitly enabled. The combination is performed once when constructing `JoinSettings` and `TableJoin`, so the rest of the join code keeps reading a single effective threshold (`maxBytesBeforeExternalJoin`). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [49ec36b] Summary: ✅ AI ReviewSummaryThis PR adds Findings
Tests
ClickHouse Rules
Final VerdictStatus: Minimum required actions:
|
…ore-external-join
| grace_hash_join_max_buckets = query_settings[Setting::grace_hash_join_max_buckets]; | ||
|
|
||
| max_bytes_before_external_join = query_settings[Setting::max_bytes_before_external_join]; | ||
| max_bytes_before_external_join = JoinSettings::getMaxBytesBeforeExternalJoin( |
There was a problem hiding this comment.
Computing the ratio-based threshold here turns max_bytes_ratio_before_external_join into an absolute byte value tied to the coordinator memory snapshot.
That absolute value is then propagated through JoinSettings/plan settings, so remote executors with different memory limits can observe different behavior than the setting semantics imply.
Please keep the ratio setting in serialized join settings (similar to max_bytes_ratio_before_external_sort) and recompute the effective threshold on each executor from local limits.
`max_bytes_ratio_before_external_join` was being collapsed into an absolute byte threshold inside `JoinSettings(const Settings &)`, using the coordinator's memory snapshot. The combined value was then propagated through `JoinSettings`/`QueryPlanSerializationSettings`, so remote executors with different memory limits saw a threshold that no longer matched the setting semantics. Store the raw absolute and ratio settings separately on `JoinSettings`, serialize both via `QueryPlanSerializationSettings`, and combine them through `JoinSettings::getEffectiveMaxBytesBeforeExternalJoin` at the point of consumption (`TableJoin`, `JoinAlgorithmParams`). This mirrors how `max_bytes_ratio_before_external_sort` flows through `SortingStep` and lets each executor recompute the effective threshold from its local memory limits.
…ore-external-join
…ore-external-join
| SELECT * FROM numbers(10) AS t1 INNER JOIN numbers(10) AS t2 ON t1.number = t2.number FORMAT Null SETTINGS max_bytes_ratio_before_external_join = 1; -- { serverError BAD_ARGUMENTS } | ||
|
|
||
| -- Valid ratio: small in-memory join still produces the expected count. | ||
| SELECT count() FROM numbers(100) AS t1 INNER JOIN numbers(100) AS t2 ON t1.number = t2.number SETTINGS max_bytes_ratio_before_external_join = 0.5; |
There was a problem hiding this comment.
The new test covers invalid bounds and a basic valid value, but it does not cover the distributed-path behavior that this change relies on: per-executor recomputation from local memory limits.
Please add a distributed test that fails if the ratio is materialized once on the coordinator and reused on executors with different memory limits.
…ore-external-join
…s_ratio_before_external_join` Reviewer feedback on #103862 was: * the existing `04146_max_bytes_ratio_before_external_join.sql` only exercises invalid-bound rejection and a small in-memory join, and * needs a check that spilling actually happens via profile events, and a check that the ratio survives the distributed query path (rather than being collapsed into an absolute byte value on the coordinator and reused on remote executors with different memory limits). Add `04201_max_bytes_ratio_before_external_join_distributed.sh` covering both: * a non-distributed join under a user with a small `max_memory_usage_for_user` and a tiny `max_bytes_ratio_before_external_join`, asserting `JoinSpillingHashJoinSwitchedToGraceJoin > 0` from `system.query_log`, * a distributed join over `cluster('test_cluster_two_shards', ...)` with `serialize_query_plan = 1`, which forces the join settings (including the ratio) through `QueryPlanSerializationSettings`, asserting the same profile event fires after each shard recomputes the spill threshold from its local memory limits.
…ore-external-join
The style check `various_checks.sh` requires queries against `system.query_log`/`system.query_thread_log` to be filtered by `current_database = currentDatabase()`. The verification queries in `04201_max_bytes_ratio_before_external_join_distributed.sh` already filtered by `log_comment` (which is unique per test), but the regex check is purely textual and looks for the database condition. Add `current_database = currentDatabase()` to both verification queries. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103862&sha=3f46aabe62f09ef1e06406026951136cef0c7320&name_0=PR&name_1=Style%20check
The original `countIf(...) > 0` would pass even if only one executor spilled, which does not exercise the per-shard recomputation path that the test claims to cover. Filter to remote leaf rows (`is_initial_query = 0`) and require at least two of them to record `JoinSpillingHashJoinSwitchedToGraceJoin > 0`. Also force `prefer_localhost_replica = 0`. By default the coordinator absorbs one cluster replica locally and only the initial query is logged, so without this the leaf-row assertion has nothing to count. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103862&sha=0816a74322b3fd9ff150f99663dab743c18b73fe&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 Two distinct problems were producing `local 0` / `distributed 0`: 1. The local query was finishing as `ExceptionWhileProcessing` rather than `QueryFinish`. With `max_memory_usage_for_user = 256 MiB` and the ratio `0.0001`, the spill threshold worked out to ~26 KiB, so the `HashJoin` correctly switched to `GraceHashJoin` after the first 65k-row block (~9 MiB). `JoinSpillingHashJoinSwitchedToGraceJoin` was incremented, but the `GraceHashJoin` probe phase then tripped the user-level `MEMORY_LIMIT_EXCEEDED` while running `DelayedJoinedBlocksTransform` (`would use 256.90 MiB ... maximum: 256.00 MiB`). The verification `SELECT` filtered to `type = 'QueryFinish'`, so it never saw the spill row. Raise the user limit to `1 GiB`. The ratio-derived threshold (~100 KiB) is still well below the right-side hash table, so spilling still triggers, and the post-spill `GraceHashJoin` has enough headroom to actually finish the join. 2. The distributed verification filtered by `current_database = currentDatabase()`. Secondary queries on the executors run as the `default` user with `current_database = 'default'`, so the filter excluded *every* secondary row. The style check `ci/jobs/scripts/check_style/various_checks.sh` requires the filter to appear in any test reading from `system.query_log`, but the check is purely textual. Look up the coordinator's initial query (which legitimately has `current_database = currentDatabase()`) in a CTE that satisfies the style check, then match secondary rows by `initial_query_id`. PR: #103862 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ore-external-join
…ore-external-join
|
@groeneai, investigate and fix the failure of the function_prop_fuzzer)function_prop_fuzzer) |
|
@groeneai, investigate and fix the bug in Kafka2/Keeper: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103862&sha=7c4e0693e310c5a3f4b61d3fc76e89332b90d0d7&name_0=PR&name_1=Stress%20test%20%28arm_release%29&name_1=Stress%20test%20%28arm_release%29 and send a separate PR. |
|
@alexey-milovidov — investigated both: 1. Kafka2/Keeper SIGSEGV in
|
| Metric (last 30 days) | Value |
|---|---|
Total function_prop_fuzzer runs (CIDB) |
16,171 across 424 distinct PRs |
Total function_prop_fuzzer failures |
2 (both PR #97540, 2026-04-30, different STID) |
Hits for prev.thread_id == curr.thread_id (any check, 90d) |
0 |
| Hits for "threads got stuck" in function_prop_fuzzer (60d) | 0 |
So this exact signature is brand new and cannot be reproduced — the assertion fires in RUsageCounters::incrementProfileEvents from ~FunctionsStressTestThread() → detachFromGroup(). The trigger appears to be the harness's "stuck thread" path: one worker hung in a 256-MiB arrayResize over a deeply-nested Array(Nested(...)) for >30s, the test framework then tore it down, and the destructor saw a ThreadStatus whose stored prev_rusage.thread_id no longer matches the calling thread's id.
PR #103862 modifies join memory budgeting (max_bytes_ratio_before_external_join); it does not touch:
src/Common/ThreadProfileEvents.h/RUsageCounterssrc/Interpreters/ThreadStatusExt.cppsrc/Functions/tests/gtest_functions_stress.cppor the stuck-thread teardown patharrayResize
Recommend a CI retry. If the prev.thread_id assertion recurs, it points at a real but pre-existing race in the FunctionsStress harness teardown when a worker thread has hung — worth its own issue separate from this PR.
…ore-external-join
| $CLICKHOUSE_CLIENT -q "CREATE USER ${USER} IDENTIFIED WITH no_password SETTINGS max_memory_usage_for_user = '1Gi'" | ||
| $CLICKHOUSE_CLIENT -q "GRANT ALL ON *.* TO ${USER}" | ||
|
|
||
| LOG_LOCAL="04201_local_${CLICKHOUSE_DATABASE}" |
There was a problem hiding this comment.
This assertion can produce false positives across retries because log_comment is deterministic (04201_*_${CLICKHOUSE_DATABASE}) and the query-log filter only uses event_date >= yesterday(). If the test reruns on the same server/database, stale rows from an earlier run can satisfy countIf(...) >= 2 even when the current distributed query did not spill.
Please make the marker unique per run (for example by appending a random suffix or explicit query_id) and filter by that unique value.
LLVM Coverage Report
Changed lines: 86.60% (84/97) · Uncovered code |
PR ClickHouse#103862 added the new `max_bytes_ratio_before_external_join` setting with a default of `0.` (disabled), with a note that the default would later be flipped to `0.5` to mirror how `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort` were rolled out. This is the follow-up: switch the default to `0.5` so that hash joins automatically spill to grace hash join once the right-side data exceeds half of available system memory (when memory limits are configured). The behavior is unchanged for environments without configured system memory limits — the ratio is logged and ignored in that case, just as for the analogous group-by and sort settings. Original PR: ClickHouse#103862 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
QA notes on recent PRs flagged that the following settings were introduced but not added to the randomization list in `tests/clickhouse-test`: * `max_bytes_ratio_before_external_join` (ClickHouse#103862) — mirrors the existing `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort`, so wire it through the Bytes-vs-Ratio choice in `randomize_external_sort_group_by` alongside its absolute counterpart `max_bytes_before_external_join`. * `max_streams_for_union_step` and `max_streams_for_union_step_to_max_threads_ratio` (ClickHouse#100176) — occasionally clamp to a small number of simultaneously active streams to exercise the `UNION ALL` narrowing path. * `optimize_dictget_tuple_element` (ClickHouse#100186) — default-true; disable with a small probability so both planner paths stay covered. * `use_top_k_dynamic_filtering_for_variable_length_types` (ClickHouse#104216) — cover both the fixed-length-only default and the opt-in path. * `page_cache_max_coalesced_bytes` (ClickHouse#104230) — randomize across small/large values so the coalescing path and the cap that splits long miss runs into multiple reads both get exercised. Also re-enable randomization of `grace_hash_join_initial_buckets`, which had been disabled in `tests/clickhouse-test` after wrong results on some tests. Restore the original conservative range `[1, 2, 4, 8]`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds a
max_bytes_ratio_before_external_joinsetting that mirrors the existingmax_bytes_ratio_before_external_group_byandmax_bytes_ratio_before_external_sortsettings.The new setting expresses the spill threshold as a fraction of available memory, which is convenient when an absolute byte value (
max_bytes_before_external_join) is hard to choose. If both the absolute and the ratio settings are non-zero, the smaller resulting threshold wins.The combination is performed once when constructing
JoinSettingsandTableJoin, so the rest of the join code keeps reading a single effective threshold viaTableJoin::maxBytesBeforeExternalJoin.Default value is
0(disabled), so the behavior is unchanged unless the setting is explicitly set, matchingmax_bytes_before_external_joinitself. The default may be flipped to0.5later, mirroring howmax_bytes_ratio_before_external_group_byandmax_bytes_ratio_before_external_sortwere rolled out.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new setting `max_bytes_ratio_before_external_join`, mirroring `max_bytes_ratio_before_external_group_by` and `max_bytes_ratio_before_external_sort`. It expresses the spill-to-disk threshold for hash joins as a fraction of available memory; combined with the absolute `max_bytes_before_external_join`, the smaller resulting threshold applies.
Documentation entry for user-facing changes
Version info
26.5.1.371