Skip to content

Enable grace hash join by default globally - #107814

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:grace-hash-default-global
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:grace-hash-default-global

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

The default join_algorithm is now direct,grace_hash,hash instead of direct,parallel_hash,hash. Large joins now spill to disk automatically (via max_bytes_before_external_join / max_bytes_ratio_before_external_join) instead of running out of memory, because grace_hash is the hash-based algorithm that supports spilling. parallel_hash keeps the whole right side in RAM and was the reason large joins still ran out of memory; it was removed from the default. direct is still used for dictionary and key-value lookups, and hash remains as the fallback for joins grace_hash cannot perform (ASOF, CROSS, multi-disjunct ON). To restore the previous behavior, set join_algorithm = 'direct,parallel_hash,hash'.

Description

Implements the global default requested in #107461: grace hash join enabled by default so that automatic disk spilling for JOINs works out of the box.

What changed

  • src/Core/Settings.cpp: join_algorithm default direct,parallel_hash,hash -> direct,grace_hash,hash.
  • src/Core/SettingsChangesHistory.cpp: 26.6 entry restoring the previous default for older compatibility levels.

Why this chain

  • direct: fast path for dictionary / EmbeddedRocksDB / MergeTree key lookups, no memory cost. Kept.
  • grace_hash: the only hash-based algorithm that honors max_bytes_before_external_join and max_bytes_ratio_before_external_join for automatic disk spilling. Made the main default.
  • parallel_hash: does NOT spill (keeps the full right side in RAM), which is exactly why large joins still OOM with the old default. Dropped from the default.
  • hash: kept as the fallback for shapes grace_hash cannot perform (ASOF, CROSS, multi-disjunct ON, constant ON).

Fallback to hash for unsupported shapes was verified locally with the new default: JOIN ON <constant>, CROSS JOIN, ASOF JOIN, and multi-disjunct OR joins all execute correctly; FULL JOIN uses grace_hash directly.

Test updates

join_algorithm is not part of the CI randomization pool, so functional tests rely on the default value. A design note from the read-in-order optimizer (optimizeReadInOrder.cpp) is relevant: "Grace hash join scatters rows into buckets by hash, destroying the input order", so the optimizer rejects grace hash for read-in-order-through-join. The same applies to top-k-through-join and to PK-range sharding (a ConcurrentHashJoin/parallel_hash feature). These optimizations do not apply under the new default by design.

Tests were updated to preserve their original intent rather than weakened:

  • 03274_join_algorithm_default, 03711_read_in_order_through_join: these document the default's behavior. 03274 is updated to the grace hash default; 03711 drops the DEFAULT iteration of its [hash, parallel_hash, DEFAULT] loop because grace hash cannot stream read-in-order through a join.
  • Tests validating a parallel_hash / ConcurrentHashJoin plan or pipeline pin join_algorithm = 'parallel_hash' (or 'parallel_hash,hash' where a constant/scalar join needs the hash fallback): 02236, 02835, 03036, 03357 (PK sharding), 03405, 03545_*, 03595, 03701, 03773, 04011, 04012, 04060, 04234_explain_pipeline_compact_repeated_processor_chains.
  • Tests validating the read-in-order / top-k deferral pin join_algorithm = 'hash' (an order-preserving join): 04209, 04230, 04234_top_k_through_join_final_desc_gate.
  • 03786_storage_join_type_conversion pins 'hash' (StorageJoin RIGHT JOIN uses a plain HashJoin).
  • 02815_join_algorithm_setting: default value-string assertion updated.

02995_new_settings_history passes with the new history entry. All touched tests pass locally on a debug build.

Change the default join_algorithm from 'direct,parallel_hash,hash' to
'direct,grace_hash,hash' so that large joins spill to disk automatically
instead of running out of memory.

grace_hash is the only hash-based algorithm that honors
max_bytes_before_external_join / max_bytes_ratio_before_external_join for
automatic disk spilling. parallel_hash keeps the whole right side in RAM and
was the reason large joins still OOM with the previous default, so it is
dropped from the default chain. direct is kept as the fast path for
dictionary / key-value lookups, and hash remains as the fallback for joins
that grace_hash cannot perform (asof, cross, multi-disjunct ON, constant ON).

A SettingsChangesHistory entry restores the previous default for older
compatibility levels.

Test updates: tests that assert the default value or validate plans/pipelines
specific to ConcurrentHashJoin (parallel_hash) pin the algorithm they were
written for. grace_hash reorders rows, so optimizeReadInOrder rejects it by
design; the read-in-order-through-join and top-k-through-join tests therefore
pin a non-reordering algorithm, and 03711 drops its DEFAULT loop iteration.
03274_join_algorithm_default documents the default pipeline and is updated to
grace_hash.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. This is a default-setting change, not a flaky fix. The effect is deterministic: a fresh server reports SELECT value FROM system.settings WHERE name='join_algorithm' = direct,grace_hash,hash, and the affected functional tests fail/pass deterministically with the old/new default.
b Root cause explained? The JOIN roadmap goal is automatic disk spilling. Only grace_hash honors max_bytes_before_external_join / max_bytes_ratio_before_external_join; parallel_hash keeps the full right side in RAM, so large joins still OOM under the old default direct,parallel_hash,hash. Making grace_hash the default (keeping direct fast-path and hash fallback) enables spilling out of the box.
c Fix matches root cause? Yes. The one-line default change in Settings.cpp directly addresses the mechanism; the SettingsChangesHistory.cpp entry preserves the old behavior for older compatibility levels (mandatory for a default change).
d Test intent preserved / new tests added? Yes. No assertion was weakened. Tests that validate a parallel_hash/ConcurrentHashJoin plan pin that algorithm; tests that validate read-in-order/top-k deferral pin an order-preserving algorithm (hash); 03274/03711 document the default and were updated/trimmed accordingly. 02995_new_settings_history validates the history entry. Fallback to hash for ASOF/CROSS/multi-disjunct/constant-ON joins was verified to still return correct results.
e Both directions demonstrated? Yes. Each affected test FAILS on the new default without its pin/reference update and PASSES with it; all 24 touched tests (plus variants) pass on a Build-ID-verified debug binary (Build ID 538736323211, version 26.6.1.1).
f Fix is general, not a narrow patch? Yes. The default chain direct,grace_hash,hash is general: direct for key-value lookups, grace_hash for spilling, hash as the fallback for join shapes grace_hash cannot perform. No symptom-guarding; verified the engine falls back to hash correctly for all unsupported shapes rather than erroring.

Session id: cron:clickhouse-worker-slot-0:20260618-003800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin — this is the separate PR @alexey-milovidov asked for in #107461, making grace hash the default for automatic disk spilling. Proposed chain is direct,grace_hash,hash (direct fast-path, grace_hash spilling default, hash fallback for asof/cross/multi-disjunct that grace_hash cannot do; parallel_hash dropped because it does not spill). If you prefer a different ordering (e.g. grace_hash,hash without direct), let me know and I will adjust.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b21c663]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04105_limit_by_into_sort_explain FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR changes the global default join_algorithm from direct,parallel_hash,hash to direct,grace_hash,hash and updates tests to pin algorithms where they were validating the old default. The high-level goal is reasonable, but the current default path bypasses the existing SpillingHashJoin threshold mechanism, so the PR does not actually preserve automatic spilling for large default joins.

Findings

❌ Blockers

  • [src/Core/Settings.cpp:3410] The new default selects standalone GraceHashJoin, which does not enforce max_bytes_before_external_join / max_bytes_ratio_before_external_join. The existing automatic-spill path is entered from the HASH / PARALLEL_HASH branch, where tryCreateJoin builds SpillingHashJoin and passes the computed threshold into GraceHashJoin. The explicit GRACE_HASH branch constructs standalone GraceHashJoin without that threshold; standalone grace_hash relies only on max_rows_in_join / max_bytes_in_join, and max_bytes_in_join defaults to 0. As a result, large joins using the new default can still grow the first bucket in memory until a memory-limit exception instead of re-partitioning at the configured external-join threshold.
    Suggested fix: keep the default on a hash path that creates SpillingHashJoin, or pass and enforce params.max_bytes_before_external_join from the GRACE_HASH branch when grace_hash is part of the default.
Tests

⚠️ The tests that validate max_bytes_before_external_join / max_bytes_ratio_before_external_join currently pin hash or parallel_hash, so they do not prove the new default spills at the configured threshold. Add a focused default-path regression test that would fail if join_algorithm = DEFAULT constructs standalone GraceHashJoin without the external-join threshold.

Final Verdict

Status: ❌ Block

Minimum required action: fix the default path so it still enforces the external-join spill threshold, then add a focused regression test for the default join_algorithm.

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Jun 18, 2026
Comment thread src/Core/Settings.cpp
- [join_default_strictness](#join_default_strictness)
)", IMPORTANT) \
DECLARE(JoinAlgorithm, join_algorithm, "direct,parallel_hash,hash", R"(
DECLARE(JoinAlgorithm, join_algorithm, "direct,grace_hash,hash", R"(

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 default bypasses the automatic-spill threshold that the PR is meant to enable. With direct,parallel_hash,hash or explicit hash/parallel_hash, tryCreateJoin enters the hash branch and, when max_bytes_before_external_join or max_bytes_ratio_before_external_join is effective, builds a SpillingHashJoin that passes the computed threshold into GraceHashJoin. With the new default, the planner reaches the explicit GRACE_HASH branch instead and constructs standalone GraceHashJoin; that path passes no external_join_threshold, and GraceHashJoin documents that standalone grace_hash deliberately ignores max_bytes_before_external_join and relies only on max_rows_in_join / max_bytes_in_join. Since max_bytes_in_join defaults to 0, a large default join can keep growing the first bucket in memory instead of re-partitioning at the external-join threshold.

Please either keep the default on a hash path that creates SpillingHashJoin, or teach the GRACE_HASH branch to pass and enforce params.max_bytes_before_external_join when grace_hash is part of the default. The tests that exercise max_bytes_before_external_join currently pin hash or parallel_hash, so they would not catch this default-path regression.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed correct, reproduced on this branch (2M ⋈ 2M, max_bytes_ratio_before_external_join=0):

  • direct,grace_hash,hash + max_bytes_before_external_join=20MB: ExternalJoinWritePart=2, SwitchedToGrace=0 — invariant at threshold 0/20MB/200MB (the GRACE_HASH branch builds standalone GraceHashJoin with external_join_threshold=0, and hasMemoryOverflow applies the byte threshold only when external_join_threshold > 0).
  • direct,parallel_hash,hash + same threshold: ExternalJoinWritePart=64, SwitchedToGrace=1 (honors the threshold via SpillingHashJoin).

So direct,grace_hash,hash routes large joins to the one path that does not respond to max_bytes_before_external_join. This changes the PR's direction; escalated to the maintainers in a top-level comment, holding the code until they decide.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The automated review surfaced a correctness problem with the proposed direct,grace_hash,hash default, which I reproduced locally. It changes which direction this PR should take, so I am holding the code for a decision.

Finding. With direct,grace_hash,hash, a plain INNER JOIN reaches the explicit GRACE_HASH branch (PlannerJoins.cpp:1264), which builds a standalone GraceHashJoin with external_join_threshold=0. GraceHashJoin::hasMemoryOverflow applies the byte threshold only when external_join_threshold > 0, so standalone grace ignores max_bytes_before_external_join and spills only on max_rows_in_join/max_bytes_in_join (both default 0). The current direct,parallel_hash,hash default instead builds SpillingHashJoin (merged in #61e641d, "support spilling join and join switcher"), which does auto-spill at the threshold and switches to grace under the cap.

Repro (2M ⋈ 2M, max_bytes_ratio_before_external_join=0):

default max_bytes_before_external_join ExternalJoinWritePart SwitchedToGrace 600 MB mem cap
direct,grace_hash,hash 20 MB 2 (same at 0/20MB/200MB) 0 completes
direct,parallel_hash,hash 20 MB 64 1 completes (spills)

Under a tight max_memory_usage the picture reverses for the threshold case: parallel_hash spills and survives, while the relevant knob for grace would be max_bytes_in_join (explicit grace_hash+max_bytes_in_join=20MB → 64→ 32 spill parts). So today, automatic byte-threshold spilling already works via the parallel_hash/hash path, and direct,grace_hash,hash would route large joins to the one algorithm that does not honor that threshold.

This is a design decision I do not want to make unilaterally. Two coherent directions:

  1. Keep the default on the hash path, drop the algorithm-chain change. SpillingHashJoin already gives automatic disk spilling at max_bytes_before_external_join (effective by default via max_bytes_ratio_before_external_join=0.5). If the roadmap goal is "joins spill to disk automatically by default," that may already be satisfied on master without changing join_algorithm at all — the PR would then be unnecessary.

  2. Make grace_hash the default AND teach the GRACE_HASH branch to pass params.max_bytes_before_external_join into GraceHashJoin so standalone grace honors the byte threshold like the wrapper does. This is a real engine change to grace's contract (today standalone grace deliberately ignores it), so it needs @antaljanosbenjamin's sign-off on whether standalone grace should respond to max_bytes_before_external_join.

@alexey-milovidov @antaljanosbenjamin — which direction do you want? If (1), I will close this PR (and the override in #107461 becomes unnecessary as you noted). If (2), I will implement the threshold plumbing in the GRACE_HASH branch plus a test exercising max_bytes_before_external_join under the new default. Holding the code until you decide.

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this. After re-verifying against current master (1322ce4):

The roadmap goal (automatic disk spilling by default) is already met on master without this change. max_bytes_ratio_before_external_join defaults to 0.5, so the current default direct,parallel_hash,hash builds a SpillingHashJoin (PlannerJoins.cpp:1210/1222), which converts the hash join to grace and spills the right side once it exceeds half of the available memory.

The literal direct,grace_hash,hash change in this PR would regress that. A plain INNER JOIN takes the explicit GRACE_HASH branch (PlannerJoins.cpp:1253), which builds a standalone GraceHashJoin with external_join_threshold = 0. GraceHashJoin::hasMemoryOverflow (GraceHashJoin.cpp:339) applies the byte threshold only when it is greater than 0, so a standalone grace join relies on max_rows_in_join / max_bytes_in_join (both default 0) and would not spill at the max_bytes_before_external_join threshold at all. It also disables read-in-order-through-join, top-k-through-join, and hash-table-size-stats prealloc.

The grace-hash owner is already making grace hash the default properly (PRs 108936, 108289) and asked not to enable it naively yet. Deferring to that work rather than shipping a default that regresses spilling. Happy to reopen with the alternative (teach the GRACE_HASH branch to pass max_bytes_before_external_join into GraceHashJoin) if that direction is preferred.

@groeneai groeneai closed this Jul 1, 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 pr-backward-incompatible Pull request with backwards incompatible changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants