Skip to content

Add max_bytes_ratio_before_external_join setting - #103862

Merged
alexey-milovidov merged 15 commits into
masterfrom
max-bytes-ratio-before-external-join
May 7, 2026
Merged

alexey-milovidov merged 15 commits into
masterfrom
max-bytes-ratio-before-external-join

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 1, 2026 •

Copy link
Copy Markdown
Member

Adds a max_bytes_ratio_before_external_join setting that mirrors the existing max_bytes_ratio_before_external_group_by and max_bytes_ratio_before_external_sort settings.

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 JoinSettings and TableJoin, so the rest of the join code keeps reading a single effective threshold via TableJoin::maxBytesBeforeExternalJoin.

Default value is 0 (disabled), so the behavior is unchanged unless the setting is explicitly set, matching max_bytes_before_external_join itself. The default may be flipped to 0.5 later, mirroring how max_bytes_ratio_before_external_group_by and max_bytes_ratio_before_external_sort were rolled out.

Changelog category (leave one):

  • New Feature

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

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.371

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]>
@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [49ec36b]

Summary: ✅


AI Review

Summary

This PR adds max_bytes_ratio_before_external_join, wires it through join planning/serialization, and adds tests for local and distributed spilling behavior. The implementation looks consistent with existing ratio-based spill settings, but one test still has a correctness gap that can produce false positives.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04201_max_bytes_ratio_before_external_join_distributed.sh:111-137] The system.query_log assertions use deterministic log_comment values plus event_date >= yesterday(), so stale rows from prior runs can satisfy the predicates. This can let the test pass even when the current run did not validate distributed recomputation/spilling.
    Suggested fix: make the marker unique per run (for example append a random suffix or explicit query_id) and filter both local/distributed checks strictly by that unique marker.
Tests
  • ⚠️ Strengthen 04201_max_bytes_ratio_before_external_join_distributed.sh by using a per-run unique marker (query_id/randomized log_comment) and filtering system.query_log by it, so retries and stale logs cannot satisfy assertions.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ✅
Core-area scrutiny ✅
No test removal ✅
Experimental gate ✅
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ✅
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make query-log markers unique per test run in 04201_max_bytes_ratio_before_external_join_distributed.sh and filter assertions by that unique marker to avoid stale-log false positives.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 1, 2026
Comment thread src/Interpreters/JoinOperator.cpp Outdated
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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@antaljanosbenjamin antaljanosbenjamin self-assigned this May 4, 2026
…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.
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
alexey-milovidov and others added 5 commits May 5, 2026 12:52
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate and fix the failure of the function_prop_fuzzer)function_prop_fuzzer)

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated both:

1. Kafka2/Keeper SIGSEGV in Stress test (arm_release) — STID 3555-2986

This is exactly the bug fixed by my open, approved PR #103890 ("Fix use-after-free in KeeperHandlingConsumer::setKeeper (StorageKafka2)"). Same crash signature, same stack trace:

zkutil::EphemeralNodeHolder::~EphemeralNodeHolder()
DB::KeeperHandlingConsumer::setKeeper(...)
DB::StorageKafka2::streamToViews(unsigned long)
... StorageKafka2 ctor lambda → BackgroundSchedulePool::threadFunction

CIDB confirms STID 3555-2986 is chronic and cross-PR — same hit on PR #101113 (url_base_setting, 2026-05-01), now on this PR (2026-05-06). Root cause: setKeeper() was assigning the new keeper shared_ptr before clearing permanent_locks / tmp_locks, so when the consumer was the last shared owner of the previous ZooKeeper, step (1) freed the old session and step (2)'s ~EphemeralNodeHolder then dereferenced the dangling ZooKeeper&. Mirrors the precedent already merged for StorageKafka2::partialShutdown() / replica_is_active_node.

PR #103890 is open and approved (by @antaljanosbenjamin, 2026-05-04). Awaiting merge — no separate PR needed.

2. Unit tests (asan_ubsan, function_prop_fuzzer) — Logical error: 'prev.thread_id == curr.thread_id'

This is a one-off, unrelated to this PR. Data:

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 / RUsageCounters
  • src/Interpreters/ThreadStatusExt.cpp
  • src/Functions/tests/gtest_functions_stress.cpp or the stuck-thread teardown path
  • arrayResize

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.

— @groeneai

$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}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This 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.

@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 86.60% (84/97) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 7, 2026
Merged via the queue into master with commit a48d2ed May 7, 2026
326 of 327 checks passed
@alexey-milovidov
alexey-milovidov deleted the max-bytes-ratio-before-external-join branch May 7, 2026 08:35
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 7, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request May 8, 2026
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]>
itsjoeoui pushed a commit to itsjoeoui/ClickHouse that referenced this pull request Jun 4, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants