Skip to content

Fix parallel_hash global JOIN limit not enforced on ARM - #109404

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-concurrent-hash-join-limit-memory-ordering
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-concurrent-hash-join-limit-memory-ordering

Conversation

@groeneai

@groeneai groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator

Closes: #109400
Related: #108938

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed the global max_rows_in_join / max_bytes_in_join limit not being enforced for the parallel_hash join algorithm on ARM, where a query with join_overflow_mode = 'throw' could silently succeed instead of raising SET_SIZE_LIMIT_EXCEEDED.

Description

ConcurrentHashJoin enforces the global max_rows_in_join / max_bytes_in_join limit at the end of addBlockToJoin by summing per-instance snapshots via getTotalRowCount / getTotalByteCount. For parallel_hash the right side is split across buckets, so no single instance reaches the limit; only the sum does, so enforcement depends entirely on that summation reading the committed totals.

#108938 made those snapshots lock-free atomics written and read with memory_order_relaxed. The previous code took each instance's mutex in the getters, and it was that lock/unlock which provided the acquire/release synchronization between a build thread's snapshot store and another thread's summation in the limit check. With relaxed ordering there is no happens-before, so on weak memory models (ARM) the check can observe stale-low totals, compute a sum below the limit, and skip the throw. On x86 (TSO) the stores are effectively ordered, so the failure is arm-only.

Fix: publish the snapshots with memory_order_release and sum them with memory_order_acquire, restoring the exact happens-before the removed mutex provided. This is stlr / ldar on ARM and negligible on x86, far cheaper than the lock contention #108938 removed. The performance win of #108938 is preserved (still lock-free).

Regression coverage already exists: 04061_spilling_hash_join_overflow_limits test 3 (parallel_hash + max_rows_in_join + join_overflow_mode='throw'), which fails on arm_binary on master and passes with this change.

CI failure (master, arm_binary): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=e2368f7c094207fee27d342463ae98a6977d79bf&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

ConcurrentHashJoin enforces the global max_rows_in_join / max_bytes_in_join
limit at the end of addBlockToJoin by summing per-instance snapshots via
getTotalRowCount / getTotalByteCount. PR ClickHouse#108938 made those snapshots
lock-free atomics written and read with memory_order_relaxed, removing the
per-instance mutex whose lock/unlock previously provided the acquire/release
synchronization between a build thread's snapshot store and another thread's
summation in the limit check.

With relaxed ordering there is no happens-before, so on weak memory models
(ARM) the check can observe stale-low totals, compute a sum below the limit,
and skip the SET_SIZE_LIMIT_EXCEEDED throw. On x86 (TSO) the stores are
effectively ordered, so the failure is arm-only.

Publish the snapshots with memory_order_release and sum them with
memory_order_acquire, restoring the exact happens-before the removed mutex
provided. This is stlr/ldar on ARM and negligible on x86, far cheaper than
the lock contention ClickHouse#108938 removed.

Closes: ClickHouse#109400

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

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes on ARM (issue reports 361/361 with randomization off, 225/225 in one run). Not reproducible on my x86_64 build host: x86 TSO effectively orders the relaxed stores, which is why the failure is arm-only. Reasoned from the memory model + code path per the read of ConcurrentHashJoin.cpp.
b Root cause explained? The global JOIN limit check sums per-instance snapshots (getTotalRowCount/getTotalByteCount). #108938 made those atomics memory_order_relaxed for both store and load, removing the per-instance mutex whose lock/unlock had provided acquire/release synchronization. With no happens-before, on ARM the summation reads stale-low totals, stays below max_rows_in_join, and skips the SET_SIZE_LIMIT_EXCEEDED throw.
c Fix matches root cause? Yes. Snapshot stores use memory_order_release, aggregate loads use memory_order_acquire, restoring exactly the happens-before the removed mutex provided. No band-aid (no limit widening, no tag).
d Test intent preserved / new tests? Preserved. 04061_spilling_hash_join_overflow_limits test 3/4 (the failing cases) are unchanged and remain the regression coverage; they fail on arm_binary on master and pass with this fix.
e Demonstrated both directions? On ARM: fails without fix (per issue), expected to pass with fix. On x86: 30/30 passes with randomization (no regression). x86 cannot show the failing direction because TSO masks the race.
f Fix general, not a narrow patch? All 6 snapshot sites fixed (2 aggregate loads, post-insert stores, constructor store, releaseSlotBlocks reset stores). Sibling GraceHashJoin uses hash_join->getTotalRowCount() directly under its own locks, not the relaxed-atomic sum, so it is not affected and benefits transitively when its inner join is a ConcurrentHashJoin.
g Generalizes across inputs? The ordering fix covers both total_rows and total_bytes (rows and bytes limits), all overflow modes, and all bucket counts (max_threads). Not input-shape specific.
h Backward compatible? Yes. No setting, format, or default change. Pure intra-process memory-ordering correctness fix; recovers behavior that was reliably green before #108938.
i Invariants/contracts preserved? Yes. The invariant is that the limit check observes a total reflecting all committed bucket inserts; release/acquire re-establishes it. Lock-free property of #108938 preserved (no mutex reintroduced), so its performance win stands.

Session id: cron:clickhouse-worker-slot-1:20260704-182600

@groeneai

groeneai commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai @m-selmi for review. Restores the acquire/release synchronization on the ConcurrentHashJoin total-count snapshots that #108938's relaxed atomics dropped, fixing the arm-only global JOIN limit miss (#109400).

@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [28d4507]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, s3 storage, parallel, 2/2) FAIL
03532_window_function_and_null_source_max_threads FAIL cidb
Stress test (arm_release) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 2228-453d) FAIL cidb

AI Review

Summary

This PR tries to fix the parallel_hash ARM regression from #109400 by changing the per-slot total snapshots in ConcurrentHashJoin from relaxed atomics to release/acquire. The intended contract is that the final global max_rows_in_join / max_bytes_in_join check sees every slot's committed total again, but the current patch still leaves the summation lock-free and opportunistic, so it can undercount concurrent slots and let the query succeed instead of throwing.

Findings
❌ Blockers
  • src/Interpreters/ConcurrentHashJoin.cpp:473 memory_order_acquire does not restore the old "read the current total for every slot" guarantee. Before #108938, getTotalRowCount / getTotalByteCount locked each slot and therefore waited for that slot's active writer to finish before reading HashJoin state. The new load can still observe the previous snapshot value, so two concurrent addBlockToJoin calls can both miss each other's final slot update and return success while the combined total already exceeds the configured limit. This means the original parallel_hash overflow regression can still survive this patch.
    Suggested fix: use a final-check path that waits for or validates the latest publication from every slot before accepting the sum. The simplest safe version is to restore the mutex-based summation for the global limit check; if the lock-free fast path must stay, it needs an explicit stable-snapshot protocol (for example with per-slot sequence/version counters and retry).
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    1. Make the final global JOIN-limit check observe the current per-slot totals again, not just release/acquire snapshots.
    2. Re-verify the existing ARM regression case from 04061_spilling_hash_join_overflow_limits against that stronger fix.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 6, 2026
@m-selmi m-selmi self-assigned this Jul 6, 2026
size_t res = 0;
for (const auto & hash_join : hash_joins)
res += hash_join->total_rows.load(std::memory_order_relaxed);
res += hash_join->total_rows.load(std::memory_order_acquire);

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.

memory_order_acquire here still does not restore the pre-#108938 correctness guarantee for the global limit check. Before that PR, getTotalRowCount / getTotalByteCount took hash_join->mutex, so the summation blocked until each slot's active writer finished and then read the current HashJoin totals. With the snapshot atomics, the load can still observe the previous snapshot value even after another thread has already published a newer one, so two concurrent builders can still both miss each other's final slot update and return success while the combined total is already over the limit.

A concrete interleaving is:

  • slot 0's last writer stores 1000, slot 1's last writer stores 1000
  • thread A's final check sees {slot0 = 500, slot1 = 1000}
  • thread B's final check sees {slot0 = 1000, slot1 = 500}

Both calls pass even though the true total is 2000, so #109400 can still reproduce. To actually close the regression, the final global check needs a read path that waits for or verifies the latest publication from every slot before accepting the sum (for example by keeping the mutex-based summation for the limit check, or by adding a versioned stable-snapshot protocol), not just acquire/release ordering.

@m-selmi m-selmi left a comment

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.

@groeneai let's keep the memory_order_relaxed and add a limit check in onBuildPhaseFinish() to avoid the last blocks escaping the check.

@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.80% +0.00%

Changed lines: Changed C/C++ lines covered: 25/26 (96.15%) · Uncovered code

Full report · Diff report

@m-selmi

m-selmi commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

closed in favor of #109488

@m-selmi m-selmi closed this Jul 6, 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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky/regression: 04061_spilling_hash_join_overflow_limits fails on arm_binary — parallel_hash global JOIN limit not enforced

3 participants