Skip to content

Allow parallel_hash for ASOF JOIN - #105375

Merged
alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
gregakinman:gm/asof-parallel-hash
Jun 11, 2026
Merged

alexey-milovidov merged 14 commits into
ClickHouse:masterfrom
gregakinman:gm/asof-parallel-hash

Conversation

@gregakinman

@gregakinman gregakinman commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Performance Improvement

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

Allow ASOF JOIN to use the parallel_hash join algorithm, parallelizing the build across distinct equality-key values. Previously ASOF was unconditionally opted out of parallel_hash.

Detailed description / Documentation / Tests / Additional context

Partially addresses #105371 (see the scope note below — the constant / very-low-cardinality equality-key case is a follow-up).

allowParallelHashJoin in src/Interpreters/TableJoin.cpp previously returned false for JoinStrictness::Asof. The exclusion appears to be defensive carryover from the original ConcurrentHashJoin PR (#37648, April 2022) — it shipped with the gate in place from day one with no rationale in the source or PR text.

Correctness: scatter by the equality-key prefix only. ConcurrentHashJoin scatters right-side blocks by hashing the join keys. For ASOF, the trailing key is the inequality (ASOF) key, and HashJoin deliberately excludes it from hash-map keying (createKeyGetter pops the trailing key). If ConcurrentHashJoin hashed the full key list, rows sharing the same equality keys but differing in the ASOF key could scatter to different partitions and never meet on the probe side — breaking ASOF matching for the multi-key keys128 / keys256 / hashed methods. This PR makes selectDispatchBlock hash only the equality-key prefix (dropping the trailing ASOF key), matching the per-partition HashJoin bucket key. Thanks @vdimir and the review bot for catching this — the initial revision only exercised a single equality key and missed it.

With that fix, rows with the same equality-key value always land in the same internal HashJoin partition, and the per-key SortedLookupVector that backs ASOF lives entirely within that partition, so the parallel build behaves the same way as for non-ASOF strictness.

Tests. 04300_asof_join_parallel_hash.sql runs the same ASOF INNER and ASOF LEFT queries under join_algorithm = 'hash' and 'parallel_hash' and checks per-row equivalence via mutual EXCEPT, for both single-equality-key and multi-equality-key ((a, b, t)) shapes. The multi-key cases are the ones that fail without the prefix-only dispatch fix. 02835_join_step_explain reference updated to reflect that ASOF now reports ConcurrentHashJoin in EXPLAIN.

Scope — what this does and does not do. This parallelizes ASOF builds across distinct equality-key values: each scatter partition builds its own SortedLookupVectors in parallel. It does not parallelize the build within a single equality-key value — when the equality key is constant or very low-cardinality (the motivating workload in #105371, e.g. generated SQL using a constant 'a' AS k predicate to satisfy ASOF's syntactic requirement), all rows for that key still route to one HashJoin slot and the build on that slot remains serial. Parallelizing within a single equality key (e.g. range-partitioning the ASOF key, or a parallel SortedLookupVector build) is a separate, larger change that we'll pursue in a follow-up PR; #105371 stays open to track it.

Note on a related but separate gate. optimizeJoinByShards in src/Processors/QueryPlan/Optimizations/optimizeJoinByShards.cpp also has an ASOF exclusion. I haven't removed that one — it has different requirements (PK-prefix sharding) and may have a real correctness reason that needs separate investigation. Filing as a follow-up if this PR lands cleanly.

Comment thread src/Interpreters/TableJoin.cpp Resolved
@gregakinman
gregakinman force-pushed the gm/asof-parallel-hash branch from 52deb56 to cc28346 Compare May 19, 2026 20:39
@gregakinman
gregakinman marked this pull request as ready for review May 19, 2026 20:39
@gregakinman

Copy link
Copy Markdown
Contributor Author

For posterity / future reviewers — the rationale for why removing the JoinStrictness::Asof gate is safe:

ConcurrentHashJoin scatters right-side blocks by hashing the equality-key columns (dispatchBlock(key_names_right, ...)), so rows with the same equality-key value always land in the same internal HashJoin partition. The per-key data structure that backs ASOF (SortedLookupVector in src/Interpreters/RowRefs.cpp) is built and queried entirely within one partition's HashJoin, so the parallel build behaves the same way as for non-ASOF strictness — each partition's HashJoin handles its slice independently. ASOF semantics are preserved because the closest-at-or-before match for any left row is, by construction, within the same equality-key partition.

Two pieces of corroboration:

  1. grep -i asof src/Interpreters/ConcurrentHashJoin.{cpp,h} returns zero results. ConcurrentHashJoin has no ASOF-specific code paths or assertions.
  2. The original ConcurrentHashJoin PR (Bugfixes and performance improvements for parallel_hash #37648, April 2022) shipped with the gate already in place, with no rationale in the source, commit message, or PR body. Reads as defensive carryover from when the algorithm was introduced rather than a known correctness issue.

The regression test (tests/queries/0_stateless/04300_asof_join_parallel_hash.sql) covers ASOF INNER and ASOF LEFT under both join_algorithm = 'hash' and 'parallel_hash' with multi-key data, and asserts per-row equivalence via mutual EXCEPT.

@gregakinman
gregakinman force-pushed the gm/asof-parallel-hash branch 4 times, most recently from bac85fb to 3d101d1 Compare May 20, 2026 01:47
ConcurrentHashJoin scatters right-side blocks by hashing the equality key,
so rows with the same equality key always land in the same internal HashJoin
partition. The per-key SortedLookupVector that backs ASOF lives entirely
within that partition, so the parallel build behaves the same way as for
non-ASOF strictness.

The exclusion in allowParallelHashJoin appears to be defensive carryover from
the original ConcurrentHashJoin PR (ClickHouse#37648, April 2022) — it shipped with the
gate in place from day one with no rationale in the source or PR text, and
ConcurrentHashJoin itself contains zero ASOF-specific code paths or
assertions.

For workloads where the ASOF equality key has low cardinality (e.g. SQL
generated by visualization tools that compute multi-channel derived
metrics like vector magnitude sqrt(x^2 + y^2 + z^2) and use a constant
equality predicate to satisfy ASOF's syntactic requirement), this
unblocks parallelism on the build phase: e.g. one of our workloads goes
from ~93s wall (single-core build of a 250M-row hash table x 2 stacked
ASOF joins) toward what the existing manual UNION-ALL time-shard
workaround achieves (~25s with 4x CPU utilisation), per
ClickHouse#73086.

Adds a regression test that runs the same ASOF INNER and ASOF LEFT
queries under both join_algorithm = 'hash' and 'parallel_hash' and
checks per-row identity via mutual EXCEPT.
@gregakinman
gregakinman force-pushed the gm/asof-parallel-hash branch from 3d101d1 to de5b21e Compare May 20, 2026 04:01
@gregakinman

Copy link
Copy Markdown
Contributor Author

@vdimir based on your activity it looks like you're the best reviewer for this change? Let me know what you think of it.

I verified the added test passes locally on macOS/aarch64 with a RelWithDebInfo build of this branch. I also verified a set of 27 other selected existing tests based on relevance to make sure this didn't cause a regression. Also verified we see in EXPLAIN PIPELINE that the parallel path is used with ASOF JOIN + SETTINGS join_algorithm = 'parallel_hash'.

This would be a highly, highly impactful performance improvement for us! A very common query pattern for us is aligning time series where the timestamps don't match exactly using ASOF JOIN at scale where you really need join parallelization to have acceptable performance (100s of millions of rows+). Would really appreciate a look at this! Thanks.

@alexey-milovidov alexey-milovidov self-assigned this May 20, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 20, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This sounds good, and the change is reasonable. Thank you!

@clickhouse-gh

clickhouse-gh Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa697cd]

Summary: ✅


AI Review

Summary

This PR enables ASOF JOIN to use parallel_hash by removing the JoinStrictness::Asof gate and making ConcurrentHashJoin scatter on the equality-key prefix. The earlier correctness issue around hashing the ASOF inequality key is fixed in the current code, and the new stateless test covers the multi-key dispatch path with multiple shards. I am not approving yet because the PR is still categorized as Performance Improvement without focused before/after evidence for the narrowed high-cardinality equality-key case.

Missing context / blind spots
  • ⚠️ Current PR workflow still had Fast test and Build (arm_tidy) queued when checked; completed Style check was green, and the direct Praktika report for the current SHA had no failed test rows. Passing CI would close this validation gap.
Tests
  • ⚠️ [src/Interpreters/ConcurrentHashJoin.cpp:641] The PR promises a Performance Improvement for ASOF JOIN with distinct equality-key values, but the available Cloud Performance Report does not exercise ASOF JOIN or any join-bearing query, and no focused benchmark numbers are included. Please add before/after timings for a representative high-cardinality equality-key ASOF JOIN workload, or change the changelog category to Improvement and avoid claiming measured performance.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: provide focused performance evidence for the newly enabled ASOF JOIN parallel_hash path, or downgrade the PR metadata to a non-performance category.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 20, 2026
Comment thread src/Interpreters/TableJoin.cpp Resolved
@vdimir vdimir self-assigned this May 20, 2026

@vdimir vdimir left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for your PR and the detailed description!

I don't really understand whether we handle the asof key component correctly with parallel hash joins. Consider rows like {a: 1, b: 1} and {a: 1, b: 3}. If we use (a, b) for scattering, these rows may end up in different buckets. Then a probe-side row like {a: 1, b: 2} will pick only one bucket depending on where it lands, while we should inspect both.
I suppose the same issue mentioned in the bot's comment above

Probably ASOF JOIN would work correctly only if we used just the prefix keys that participate in the equality match for hashing (usually all keys except last one). But I assume we currently use all keys. Correct me if I'm wrong.

ConcurrentHashJoin::selectDispatchBlock was hashing all key columns to
compute the scatter selector, including the trailing ASOF inequality
column. The per-partition HashJoin's bucket key is the equality-only
prefix (HashJoin::HashJoin pops the asof column from key_columns before
chooseMethod()), so dispatching by the full key list sent rows with the
same equality keys but different asof values to different partitions and
they never met during probe.

Slice off the trailing asof key from both key_columns_names and key_sizes
when computing the scatter hash, encapsulated in a small getDispatchKeyShape
helper so the asof-specific logic has a named home with a doc comment.

The single-equality-key case happened to work even without the slice
because the chosen key getter is HashMethodOneNumber, which only reads
column[0] and ignored the extra column. The slice is load-bearing for
multi-equality-key joins where HashMethodKeysFixed / HashMethodHashed
hashes N columns based on key_sizes.size().

Extends the regression test to cover both single- and multi-equality-key
shapes with per-row mutual EXCEPT against the hash algorithm.
Removing the parallel_hash gate for ASOF in allowParallelHashJoin causes
EXPLAIN to print Algorithm: ConcurrentHashJoin (instead of HashJoin) for
the ASOF block in this test. This is the intended new behavior — update
the reference accordingly.

The non-ASOF block in the same test already expected ConcurrentHashJoin,
so only the single line under "Strictness: ASOF" changes.
@gregakinman

Copy link
Copy Markdown
Contributor Author

@vdimir thank you for the review! Yep, looks like you were right. The test case pushed initially only tested the case with a single equality key, but looks like it didn't work with multiple equality keys. Updated the code to only consider the equality keys, not the ASOF key, for hashing, and also updated the test to test against multiple equality keys. Looks like everything passes now - the failures that I see look like flakes to me. Could you retrigger them for me?

@gregakinman

Copy link
Copy Markdown
Contributor Author

Thank you for the approval @vdimir! Do you know what's going on with the failing checks? They don't seem to be related to the code...

Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
@gregakinman

Copy link
Copy Markdown
Contributor Author

@vdimir the bot is asking to provide numbers showing a performance improvement here, but do we need that in order to merge? I think it's pretty clear that parallelizing when there is high equality key cardinality will improve performance and we don't need to individually benchmark that, but let me know if you disagree.

alexey-milovidov and others added 3 commits June 1, 2026 14:57
…i-shard dispatch

With max_threads = 1, ConcurrentHashJoin uses a single shard and
dispatchBlock returns the whole block without ever calling
selectDispatchBlock, so the ASOF prefix-slicing fix would not be
covered. Setting max_threads = 4 forces more than one shard so the
multi-equality-key cases actually exercise selectDispatchBlock.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After merging master, 04300_asof_join_parallel_hash collided with
04300_deltalake_ffi_panic_guard and 04300_final_sequential_partitions_null
added on master. Renumbered to the free slot 04312.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master (was 350 commits behind, CI red on a chronic flake) and renumbered the test to avoid a collision introduced by the merge.

  • Merge: clean, zero conflicts (dbdb628432b).
  • Test renumber: after the merge, 04300_asof_join_parallel_hash collided with 04300_deltalake_ffi_panic_guard and 04300_final_sequential_partitions_null (both added on master). Renamed to the free slot 04312_asof_join_parallel_hash (645c177ba79). Picked 04312 to also steer clear of 04306/04309–04311, which are in use by other in-flight PRs.

Empirical verification on a freshly built binary (this branch, merged):

  1. EXPLAIN actions=1 with parallel_hash_join_threshold = 0 now reports Algorithm: ConcurrentHashJoin for an ASOF join — the allowParallelHashJoin gate is lifted.
  2. Multi-equality-key ASOF INNER JOIN (ON l.k=r.k AND l.b=r.b AND l.t>=r.t) with max_threads=4 and parallel_hash_join_threshold=0 (forcing multi-shard dispatch) gives identical results under hash and parallel_hash — both mutual EXCEPT directions return 0, confirming the prefix-only selectDispatchBlock fix.
  3. 02835_join_step_explain reference matches exactly on the fresh binary.

CI: the only failures are Tests/Server died in the arm_asan_ubsan, targeted stateless run — a chronic, unrelated infrastructure flake on master, not caused by this change.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This PR enables the parallel-hash join algorithm for ASOF joins and only changes the ASOF-specific scatter logic; non-ASOF joins and join-free queries are functionally unchanged. The flagged TPC-H Q4 regression (+42.75%) is on a non-ASOF semi-join the PR cannot affect, and its measurements were noisy, so it is downgraded to not-sure. ClickBench Q32 runs over a single flat table with no joins, so it sits entirely off the changed path. No join-related performance impact is attributable to this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 32 not_sure 1387 1561 +12.6% <0.0001 join_operator: ClickBench has no joins; PR only touches the ASOF parallel-hash path. Off the path this query exercises.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 2159 3082 +42.8% 0.0251 join_operator: Q4 is a non-ASOF semi-join; PR alters only the ASOF parallel-hash path, leaving non-ASOF joins unchanged. Noisy too.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 2c847a1f-9de3-413e-8d3e-c169e397905e
  • MIRAI run: e5160804-12b0-455d-b325-b439ec8e877a
  • PR check IDs:
    • clickbench_551790_1780718231
    • clickbench_551792_1780718231
    • tpch_adapted_1_official_551802_1780718231
    • tpch_adapted_1_official_551804_1780718231
    • tpch_adapted_1_official_552227_1780718349

alexey-milovidov and others added 2 commits June 6, 2026 01:08
After merging master, 04312 collided with 04312_iceberg_file_filter_progress,
04312_in_order_aggregation_inconsistency, and
04312_text_index_lazy_segment_cache_reuse. 04319 is the next free number.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up to keep it current (it was 711 commits behind master and red).

What I did:

  • Merged master (clean, no conflicts) and rebuilt — the diff is unchanged (7 files, +233/-11).
  • Renumbered the test 04312_asof_join_parallel_hash → 04319_asof_join_parallel_hash: after the merge, 04312 collided with three tests that landed on master (04312_iceberg_file_filter_progress, 04312_in_order_aggregation_inconsistency, 04312_text_index_lazy_segment_cache_reuse). 04319 is the next free number.
  • Built clean (arm) and re-verified locally:
    • 04319_asof_join_parallel_hash — all 8 mutual-EXCEPT counts are 0 (hash and parallel_hash give identical results for both single- and multi-equality-key ASOF INNER/LEFT).
    • 02835_join_step_explain — reference matches (ASOF now reports ConcurrentHashJoin).

On the two CI failures — both unrelated, pre-existing flakies:

  • Scraping system tables (arm_asan_ubsan, azure) — a heap-use-after-free at clickhouse-local shutdown: the DateLUT atexit destructor (DateLUT::~DateLUT → ~unordered_map of DateLUTImpl) frees the timezone map while the AsyncLogger thread T3 is still formatting a log message via OwnPatternFormatter::formatExtended → LocalDateTime::init → findIndex (src/Common/DateLUTImpl.h:245). A shutdown-ordering race in the logger/DateLUT teardown, nothing to do with joins. It fails on dozens of unrelated PRs daily over the last 30 days.
  • OOM in dmesg — infra-level OOM, also unrelated to this change.

@groeneai, could you take a look at the Scraping system tables shutdown heap-use-after-free (DateLUT atexit teardown vs AsyncLogger in clickhouse-local)? It's a pervasive flaky and worth a separate fix. CI report: #105375

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov, picked this up — investigating the Scraping system tables heap-use-after-free as a separate fix.

Confirmed signature (CIDB, 30d, 9 hits, 6 PRs, all PR runs, last 2026-06-05 13:42Z):

  • Free side (T0): DateLUT::~DateLUT → ~unordered_map → ~unique_ptr<DateLUTImpl>.
  • Read side (T3 AsyncLogger): OwnAsyncSplitChannel::runChannel → OwnPatternFormatter::formatExtended → LocalDateTime::init → DateLUTImpl::findIndex (src/Common/DateLUTImpl.h:245).
  • Build matrix: arm_asan_ubsan (azure / targeted), amd_asan_ubsan (flaky check / distributed plan).

Root cause: Cross-translation-unit static-destructor-order race. DateLUT::getInstance returns a function-local static DateLUT ret; (src/Common/DateLUT.cpp:209); Poco's auto_logger_shutdown is a namespace-scope static in base/poco/Foundation/src/Logger.cpp:460 that ultimately calls ~OwnAsyncSplitChannel (which joins the async log threads in close). The order of these two static destructors is unspecified, so a clickhouse-local exit can free the timezone map while T3 is still formatting a queued log message.

Fix shape: Deliberately leak DateLUT so it outlives every other static (and thus every async thread). This is the standard C++ idiom for static-init-order destruction races; the OS reclaims the memory at process exit. The leak is reachable via a static pointer, so LSan does not flag it. PR coming shortly.

Session: cron:clickhouse-ci-task-worker:20260606-013800

…rg::alter

PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to
declare last_version and compression_method outside an if/else that
assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables
flags the bare declarations and Build (arm_tidy) is built with
-warnings-as-errors, so the build fails for every PR whose CI ran on
master after this commit.

CIDB shows 30+ unrelated PRs hitting this in the last 2 days
(e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102,
ClickHouse#106590).

Initialize both variables to safe defaults at declaration. They are
unconditionally overwritten in both if and else branches before use,
so behavior is unchanged. The new defaults are only relevant if a
future code path skips both assignments, in which case last_version=0
and compression_method=CompressionMethod::None are sane no-op values
(the same defaults the old structured-binding form would produce
through default-construction of the destructured aggregate).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
(cherry picked from commit d72cac5)
@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

Fix PR: #106620 — DateLUT is now intentionally leaked so it outlives the asynchronous logger threads. Reproduced the UAF locally on build-asan (4/400 with master, 0/400 with fix; captured stack matches CIDB exactly).

@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.40% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 40/41 (97.56%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit 9da49d8 Jun 11, 2026
166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 11, 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-performance Pull request with some performance improvements 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.

5 participants