Skip to content

Integrate hash join row store into new column gather framework - #121981

Merged
m-selmi merged 12 commits into
ClickHouse:masterfrom
m-selmi:integrate-row-store-into-column-gather
Oct 6, 2026
Merged

m-selmi merged 12 commits into
ClickHouse:masterfrom
m-selmi:integrate-row-store-into-column-gather

Conversation

@m-selmi

@m-selmi m-selmi commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #104884
Follow-up to #117460

In #117460 an optimized gather framework was added for the columnar part of the hash join output while the row store optimization stayed in the old framework. This PR integrates the row store into the new gather code.

This gives the row store the same optimizations the gather code includes: prefetching and more optimal copying.
Performance results from hash_join_with_row_store.xml show this:

query table size, build match % row store old (s) row store new (s) columnar new (s) row store old / new columnar / row store new
0 100k, 0.9 0.237 0.218 0.207 1.087 0.950
1 100k, 0.6 0.251 0.230 0.237 1.091 1.030
2 10m, 0.9 0.589 0.539 0.598 1.093 1.109
3 10m, 0.6 0.537 0.504 0.564 1.065 1.119
4 100k nullable, 0.9 0.247 0.228 0.224 1.083 0.982
5 100k nullable, 0.6 0.259 0.245 0.256 1.057 1.045
6 10m nullable, 0.9 0.607 0.597 0.829 1.017 1.389
7 10m nullable, 0.6 0.555 0.539 0.742 1.030 1.377
8 FULL 10m, 0.9 0.789 0.710 0.806 1.111 1.135
9 FULL 10m, 0.6 0.757 0.681 0.752 1.112 1.104
10 1m x10, 0.9 1.758 0.814 1.302 2.160 1.600
11 1m x10, 0.6 1.219 0.614 0.926 1.985 1.508
12 1m nullable x10, 0.9 1.948 0.930 1.400 2.095 1.505
13 1m nullable x10, 0.6 1.354 0.683 1.029 1.982 1.507
14 mixed strings, 0.9 0.973 0.966 0.974 1.007 1.008
15 mixed strings, 0.6 0.817 0.829 0.834 0.986 1.006
16 wide 33col, 0.9 1.978 1.721 2.585 1.149 1.502
17 wide 33col, 0.6 1.560 1.419 2.048 1.099 1.443

The PR also includes re-tuning for when the row store is enabled.

With the new optimized gather path, columnar and row store share the exact same gather implementation. The remaining advantage of the row store can be described in terms of improved cache utilization.
The performance analysis below shows this. For small build sides, the row store basically has no effect on performance since build the row store is almost free but everything is cache resident anyway. For large build sides that are narrow (very few columns) the row store can be negative since it does not save enough cache misses to hide the cost of building it.
So a new condition is added to only enable the row store only when the estimated cache misses per row are reduced here. The affected lines are marked in the analysis below.

The minimum output to build size ratio gate is left as is (5x), the numbers show it's still conservative, but given we rely on optimizer estimations when no statistics are cached, that still makes sense.

In terms of absolute runtime:
image
image

In terms of relative speedup:
image
image

Changelog category (leave one):

  • Performance Improvement

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

Speed up hash join output construction in the row-major layout: output reconstruction is up to 2x faster for joins with many rows per key and about 1.5x for wide or Nullable payloads. The row-major layout is now also skipped for payloads too narrow to benefit from it.


Workflow [PR]
Sync PR [sync-upstream/pr/121981]

Version info

  • Merged into: 26.10.1.1638-master (included in 26.10 and later)

@m-selmi m-selmi added the can be tested Allows running workflows for external contributors label Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [59846e7]

Summary: ✅


AI Review

Summary

This PR folds the hash-join row store into the newer gather framework, removes the duplicated row-store emit path, and retunes when the row-major layout is enabled. The core gather refactor looks sound, and the previously reported empty-row-store / per-batch-flattening issues are fixed in the current code. I still do not think the PR fully meets its own “skip narrow payloads” contract on StorageJoin: the row-store decision is still frozen into the shared build and reused by later narrow projections, so a supported surface can keep taking the row-store path even when the current query’s payload is too narrow to benefit.

Findings
  • ⚠️ Majors
    • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/121981#discussion_r4139297433] [src/Interpreters/HashJoin/HashJoin.cpp:272, src/Interpreters/HashJoin/AddedColumns.cpp:246, src/Storages/StorageJoin.cpp:316] The new “skip row-major for narrow payloads” rule is computed once when the persistent StorageJoin build creates shared RightTableData, but later query clones still reuse that shared row_store_state / column_access_indexes. A wide Join-engine table can therefore enable the row store once, and a later query that projects only one or two fixed-width RHS columns will still read through the row store instead of falling back to the columnar path. That violates the PR’s advertised contract on a supported surface and can preserve exactly the narrow-payload slowdown the new gate is meant to avoid. Suggested fix: make the row-store/columnar choice query-local for StorageJoin (for example by recomputing access indexes from positions in planJoinEmit, or by forcing reuseJoinedData to disable the row store until query-local gating exists), and add a focused StorageJoin regression/perf test with row store enabled.
Tests
  • ⚠️ tests/queries/0_stateless/05054_hash_join_gather.sql exercises StorageJoin subset selection only with enable_hash_join_row_store = 0, so the surface where this regression lives is still untested. The smallest proof would be one ENGINE = Join(ALL, LEFT, k) table with a wide stored schema and a later narrow projection that verifies the row store is skipped when the projected payload falls below the cache-miss threshold.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: fix the StorageJoin row-store gating so narrow projections do not inherit a wide build’s row-store decision, and add a focused test that exercises that supported path with enable_hash_join_row_store = 1.

LLVM Coverage Report

⚠️ No coverage measurement for commit 59846e7: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_3.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 24, 2026
@m-selmi m-selmi added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 24, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 59846e789 with master a200f3b9a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

422 object files changed (-1.15 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o 4.03 MiB 3.25 MiB -796.22 KiB (-19.28%)
src/CMakeFiles/dbms.dir/Columns/IColumn.cpp.o 1.98 MiB 1.88 MiB -96.33 KiB (-4.76%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/gatherJoinOutputColumns.cpp.o 100.42 KiB 125.57 KiB +25.14 KiB (+25.04%)
src/CMakeFiles/dbms.dir/Columns/ColumnVector.cpp.o 5.35 MiB 5.33 MiB -18.12 KiB (-0.33%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/AddedColumns.cpp.o 71.62 KiB 54.75 KiB -16.88 KiB (-23.56%)

720 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

2547 translation units recompiled, 14551 s compile time in total, 2547 of them have a recent master baseline.

Job report

@m-selmi
m-selmi marked this pull request as ready for review September 25, 2026 07:37
@harikrishnan94

Copy link
Copy Markdown
Contributor

@m-selmi Can you include benchmark for larger build sides (~ 100M rows distinct)?

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only changes the hash join row store: right-side columns are now emitted through the shared gather path, the store keeps only columns that appear in the join output, the store is skipped unless it saves at least two cache misses per row, and min_rows_ratio_for_hash_join_row_store drops from 5.0 to 3.0. The only flagged query is TPC-H Q1 (tpch_adapted_1_official), which got -16.9% faster (65 ms to 54 ms). Q1 is a single-table scan and aggregation with no join, so it never runs the changed code. Its new 54 ms median sits at the bottom of master's current 54-70 ms range, and the query has a noisy history, so it is downgraded to not sure. No join-heavy query moved enough to be flagged, so this run shows no measurable effect of the PR in either direction.

clickbench

🟢 No significant changes

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 1 not_sure 65 54 -16.9% <0.0001 TPC-H Q1 scans and aggregates lineitem only, with no join, so it never runs the hash join row store code this PR changes. The -16.9% is inside master's current range of 54-70 ms, and this query has a noisy history.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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: 813a88ea-19c1-4dc4-94ad-95d8f256ce8f
  • MIRAI run: fe347682-3324-41bc-8051-5da2e379c46d
  • PR check IDs:
    • clickbench_2883692_1790940491
    • clickbench_2883699_1790940491
    • clickbench_2883709_1790940491
    • tpch_adapted_1_official_2883728_1790940491
    • tpch_adapted_1_official_2883748_1790940491
    • tpch_adapted_1_official_2883763_1790940491

@m-selmi

m-selmi commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

@m-selmi Can you include benchmark for larger build sides (~ 100M rows distinct)?

@harikrishnan94 the diagrams I included above summarizing the benchmarks I did include a 100M rows build side in the last column (all experiments are with distinct row).
Or do you mean have this case pushed in the PR?

Comment thread src/Interpreters/RowDataStore.cpp Outdated
extern const int SIZES_OF_COLUMNS_DOESNT_MATCH;
}

static constexpr UInt64 BYTES_IN_CACHE_LINE = 64;

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.

Could we use DB::CH_CACHE_LINE_SIZE from Common/CacheLine.h here?

/// Add each field's offset, size and nullability to the row store access indexes.
RowDataStore::RowLayoutPtr layout = RowDataStore::computeLayout(row_store_columns, row_store_types);

if (RowDataStore::cacheMissReduction(*layout) < MIN_CACHE_MISSES_SAVED_BY_ROW_STORE)

@harikrishnan94 harikrishnan94 Sep 29, 2026 •

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 fixed 5x reuse gate predates this PR. Since this changes the gather costs, would it be worth revisiting that decision here?

A rough break-even model could be:
gathered_rows * gather_time_saved_per_row > build_rows * construction_time_per_row

Here, gathered_rows counts output rows that read the stored payload. The saving is columnar gather time minus row-store gather time; the right side is the extra construction cost.

Three UInt64 columns and four FixedString(32) columns have the same estimated cache-line saving, but pack 24 vs 128 bytes per build row. This could account for that difference instead of giving both the same reuse cutoff.

Could we run a few experiments measuring construction time and gather savings separately across payload widths, build sizes and reuse ratios, to estimate these costs and check the cutoff?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I ran the suggested experiment with the following parameters:

  • build rows = 100k, 1m, 10m, 50m
  • payload length per row = 16, 32, 64, 128, 256, 512, 1024 B (not every length exists at every size)
  • payload columns = 4, 8, 16, 32 (not every count exists at every width)
  • reuse ratio = 2, 4, 5, 6, 8, 10

The full results are here.

The break-even model somewhat tracks the wall improvement but not perfectly. If we ignore small sizes where the wall diff is basically noise, there are still some cases at 50M build size for example where wall time shows a great improvement but the model doesn't.
image

Regarding the model itself, construction_time_per_row can be predicted well from row length, but it's also affected by number of columns.
image

The gather_time_saved_per_row however varies depending on build size, cache misses saved, row length. So it's hard to predicat with a simple formula. One interesting thing is that a larger payload row also leads to higher gather_time_saved_per_row, probably because the column grows out of cache faster. So this somewhat compensates for the cache line saving estimation being blind to row length.
image

Nevertheless if we still derive the break even gathered_rows / build_rows ratios of the model per case, they at least fall under 5 for the meaningful build sizes.
image

A ratio of 5 seems more on the conservative side, but I doubt we can come up with a more meaningful threshold. We are anyway depending on optimizer estimates and the exact behavior is hardware dependent, so it makes sense to be conservative. wdt?
One thing we could try in the future is to measure if the row store was useful for a specific join during execution and disable it in future executions (but not sure about the other direction).

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.

Can we reduce the threshold to 3x?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah that makes sense, then we don't miss out on some of the speedups seen in the benchmark. Done.
I will also investigate if there are ways to make the choice adaptive in follow-ups.

Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved

@harikrishnan94 harikrishnan94 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.

LGTM

@m-selmi
m-selmi added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 9481c30 Oct 6, 2026
149 checks passed
@m-selmi
m-selmi deleted the integrate-row-store-into-column-gather branch October 6, 2026 09:46
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 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 comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.

4 participants