Skip to content

Transform JOIN hash table payload to row major - #104884

Merged
m-selmi merged 97 commits into
ClickHouse:masterfrom
m-selmi:transform-hash-table-payload-to-row-major
Aug 26, 2026
Merged

m-selmi merged 97 commits into
ClickHouse:masterfrom
m-selmi:transform-hash-table-payload-to-row-major

Conversation

@m-selmi

@m-selmi m-selmi commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #97883

Introduce an alternative layout for hash table payload in hash joins, where fixed and contiguous columns under a certain size are transformed into one row-major block of data.
Before the change:

    col1 Int32     col2 String    col3 UInt8     col4 Float64
   ┌──────────┐   ┌──────────┐   ┌──────────┐   ┌────────────┐
   │   ....   │   │   ....   │   │   ....   │   │    ....    │
   │   ....   │   │   ....   │   │   ....   │   │    ....    │
   └──────────┘   └──────────┘   └──────────┘   └────────────┘
         └──────────────┴──────────────┴───────────────┘
                row N → col1[N], col2[N], col3[N], col4[N]

After the change:

   ROW STORE (col1 + col3 + col4, contiguous per row)     col2 String (columnar)
   ┌──────────┬──────────┬────────────┐                   ┌──────────┐
   │   col1   │   col3   │    col4    │ ← row N (record)  │   ....   │ ← col2[N]
   ├──────────┼──────────┼────────────┤                   ├──────────┤
   │   col1   │   col3   │    col4    │                   │   ....   │
   └──────────┴──────────┴────────────┘                   └──────────┘

Rational:

The row-major format allows the output construction to be a tight loop over each column, basically one pointer load and data copy:

for (size_t i = 0; i < n; ++i)
{
    const char * row_store_ptr = row_store_ptrs[i];
    col->insertData(row_store_ptr + value_offset, value_size);
}

In comparison the columnar version has to do more work: load columns[j], row_numbers[j], replicated_columns access, insertFrom ...
For the following query SELECT * FROM rs_probe_200m l JOIN rs_right_10m r ON (l.k % toUInt64(10000000 / 0.9)) = r.k FORMAT Null from 04054_hash_join_with_row_store.sql the perf counters for LazyOutput::buildOutput in AddedColumns look as follows:

┌─variant────────────────────────────┬─query_id─────────────────────────────┬─runtime_ms─┬───────instr─┬──────cycles─┬──────cmiss─┬──brmiss─┬───ipc─┬─cmiss_per_kinstr─┬─brmiss_per_kinstr─┐
│ row-major-enabled-multi-threaded   │ 9d2d6886-2ad7-430f-af2c-6c7cd32f3808 │       1621 │ 11393048228 │ 31974507197 │ 1470246364 │ 5892574 │ 0.356 │           129.05 │             0.517 │
│ row-major-enabled-multi-threaded   │ 56b33013-8bec-4d7a-a415-2a06beb14bf6 │       1633 │ 11547943445 │ 31874206968 │ 1484117664 │ 6265932 │ 0.362 │           128.52 │             0.543 │
│ row-major-enabled-multi-threaded   │ 65583fa7-9ce0-4426-95eb-977251d38f75 │       1708 │ 11338601601 │ 31825721703 │ 1468670383 │ 5921051 │ 0.356 │           129.53 │             0.522 │
│ row-major-disabled-multi-threaded  │ 5ff1b154-3c3f-40c6-bae9-f6cf0feafe81 │       2548 │ 15453833738 │ 58322156979 │ 2636461094 │ 9533242 │ 0.265 │            170.6 │             0.617 │
│ row-major-disabled-multi-threaded  │ 6e92c1d4-8432-4a79-a6cc-85e38232116d │       2580 │ 15400954730 │ 58683032344 │ 2623136775 │ 9455570 │ 0.262 │           170.32 │             0.614 │
│ row-major-disabled-multi-threaded  │ 133f384f-c09a-4e12-9e69-85b61272a360 │       2686 │ 15419169622 │ 59548322941 │ 2647601264 │ 9746405 │ 0.259 │           171.71 │             0.632 │
│ row-major-enabled-single-threaded  │ 20039e91-b5dc-4b4a-8e22-f4451f6067be │      30610 │  9046504977 │ 16964398066 │  995568814 │ 3235355 │ 0.533 │           110.05 │             0.358 │
│ row-major-disabled-single-threaded │ a3f9a822-dae6-45c1-9a4e-63e87a3592e8 │      56821 │ 15279361788 │ 27940919919 │ 1167368997 │ 4694553 │ 0.547 │             76.4 │             0.307 │
└────────────────────────────────────┴──────────────────────────────────────┴────────────┴─────────────┴─────────────┴────────────┴─────────┴───────┴──────────────────┴───────────────────┘

Changes:

  • A RowDataStore that takes a set of columns and lays them in row major format. It exposes access to individual rows and the layout of each row (offset and size of fields in a row).
  • New IColumn interfaces that handle building the output columns from the row store, used manly by AddedColumns.cpp.
  • Two new settings to control the row-major transformation:
    • enable_hash_join_row_store.
    • min_rows_ratio_for_hash_join_row_store: Minimum estimated ratio of join output rows to build-side rows to enable transforming hash join payload to row-major. Used in the planner to decide when to enable the optimization.
  • A runtime feedback loop that tracks the number of hash table matches from a join and feeds it to the next execution of the join instead of relying on the estimated join output:
    • The match count is only published when the probe phase fully completes.
    • Only joins that went through the join reorder optimizer get a cache key.
    • Plans serialized to distributed workers don't collect or use the feedback.

Limitations:

  1. Only supports fixed and contiguous types and nullable version of them.
    Supporting non fixed rows would make the row-major layout non-uniform between rows and output column construction loop would not be as tight anymore. Also transforming unbounded unfixed types to row major could be very heavy.
  2. ColumnReplicated might get materialized. The decision is made based on the column state the join sees in the first block. If it's ColumnReplicated the column is excluded from the row store, if it's not the column is included and if it's replicated in a future block it get's materialized.
  3. If spilling occurs, the row stored data is split back into columns for now. In a follow up we can make the row store a column and spill it as is.

Build overhead:

Type Rows Columns avg per worker thread (ms)
Int64 2M 8 28.2
Int64 1M 16 31.9
FixedString(16) 1M 8 24.6
FixedString(16) 2M 4 21.5

Benchmarks:

Experiments used for parameter tunning:

Absolute runtime diff:
image image
Relative speedup:
image image
TPC-H and TPC-DS:

At sf100, they were unaffected by the row store. There are multiple factors: build sides quite small, runtime filters pruning probe sides and another important factor: sort order. The tables are usually sorted/clustered on the join keys so cache locality is already good.

Effect of sort order and no runtime filters (left join):
image image

from 04054_hash_join_with_row_store.sql:

image image image

Changelog category (leave one):

  • Performance Improvement

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

Introduce an alternative layout for hash table payload in hash joins, where qualifying columns are transformed into one row-major block of data in order to speed up join output reconstruction. Controlled by two new settings: enable_hash_join_row_store (default true) and min_rows_ratio_for_hash_join_row_store (default 5, the minimum estimated ratio of join output rows to build-side rows to enable the transformation).


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

@clickhouse-gh

clickhouse-gh Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acaf36f]

Summary: ✅


AI Review

Summary

This PR adds a row-major payload layout for hash joins together with a match-feedback heuristic that tries to reuse previous executions when deciding whether the layout is worth building. The HashJoin and parallel_hash plumbing is much closer now, but I do not think the PR is ready yet: the distributed and grace_hash / spill paths still break the new heuristic's contract, and the committed performance test no longer guarantees that it is measuring the new row-store path at all.

Findings

⚠️ Majors

  • [src/Processors/QueryPlan/JoinStepLogical.h:218-228; src/Processors/QueryPlan/JoinStepLogical.cpp:2135-2205; src/Planner/PlannerJoins.cpp:1199-1209] [dismissed by author -- https://github.com/Transform JOIN hash table payload to row major #104884#discussion_r3537600146] Distributed plan serialization still drops the planner state that the physical join uses to enable the row store (result_rows_estimation and the cache keys). On serialized worker fragments the heuristic therefore re-runs with no estimate or feedback and falls back to enable_row_store = false under the default ratio, which is broader than the PR body's stated limitation of "no feedback reuse on workers". Suggested fix: either serialize enough state to preserve the first-run decision on workers, or explicitly disable and document row-store enablement for serialized distributed plans.
  • [src/Interpreters/GraceHashJoin.cpp:833-835; src/Interpreters/SpillingHashJoin.cpp:278-280; src/Interpreters/IJoin.h:197-200; src/Planner/PlannerJoins.cpp:1201-1208] [dismissed by author -- https://github.com/Transform JOIN hash table payload to row major #104884#discussion_r3752522118] The new match-feedback loop still disappears once execution goes through GraceHashJoin, both for direct grace_hash and after SpillingHashJoin switches over. GraceHashJoin does not override onProbePhaseFinish, and its per-bucket in-memory HashJoin objects are built without HashJoinStatsCollectingParams, so large/spilled joins never publish HashJoinMatchEntry and the next execution falls back to stale estimates on exactly the workloads most likely to need the heuristic. Suggested fix: either propagate match-stat collection into the bucket-local joins, or make the unsupported scope explicit and keep these plans from advertising the feedback-based behavior.
Tests
  • ⚠️ [tests/performance/hash_join_with_row_store.xml:45-64] The committed perf suite no longer pins enable_hash_join_row_store / min_rows_ratio_for_hash_join_row_store = 0, even though PlannerJoins.cpp:1199-1208 only enables the optimization when the planner has a usable estimate or cached match hint. That means a future planner/statistics change can silently benchmark the old columnar path while this PR still claims a Performance Improvement. The smallest proof would be to force the row-store path in the benchmark queries or assert that the row store was initialized before measuring.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  • Restore a committed benchmark/test that guarantees the row-store path is what gets measured for the Performance Improvement claim.
  • Decide whether distributed worker and grace_hash / spill executions are supported for the new heuristic; either preserve the required planner/match state there or scope the feature down consistently in code and PR text.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 92.00% +0.10%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 1050/1132 (92.76%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 13, 2026
Comment thread src/Core/Settings.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@harikrishnan94

Copy link
Copy Markdown
Contributor

@m-selmi
Can we combine null flags together (as bit masks) at the start of each row?
This will reduce the padding requirement drastically.
ie.
From this
[null_flag(1B) | uint32_val(4B) | float64_val(8B) | null_flag(1B) | uint64_val(8B)]
to
[nulls_bitmap(1B) | uint32_val(4B) | float64_val(8B) | uint64_val(8B)]
ofcourse aligned.

@m-selmi

m-selmi commented May 19, 2026

Copy link
Copy Markdown
Contributor Author

@m-selmi Can we combine null flags together (as bit masks) at the start of each row? This will reduce the padding requirement drastically. ie. From this [null_flag(1B) | uint32_val(4B) | float64_val(8B) | null_flag(1B) | uint64_val(8B)] to [nulls_bitmap(1B) | uint32_val(4B) | float64_val(8B) | uint64_val(8B)] ofcourse aligned.

@harikrishnan94 Thanks for taking a look. Right now it at least keeps the same memory footprint as separate columns, but that's a very good point, I can try it out.

@nickitat nickitat self-assigned this May 26, 2026
Comment thread src/Interpreters/RowDataStore.cpp Resolved
Comment thread src/Interpreters/RowDataStore.cpp Resolved
Comment thread src/Interpreters/RowDataStore.cpp Resolved
Comment thread src/Interpreters/RowDataStore.cpp Resolved
Comment thread src/Interpreters/RowDataStore.cpp Resolved
Comment thread src/Columns/IColumn.cpp Resolved
Comment on lines +45 to +64
<!-- Unique keys + non-nullable payload -->
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_100k r ON (l.k % toUInt64(100000 / {match_rate})) = r.k FORMAT Null</query>
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_10m r ON (l.k % toUInt64(10000000 / {match_rate})) = r.k FORMAT Null</query>

<!-- Unique keys + nullable payload -->
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_100k_nullable r ON (l.k % toUInt64(100000 / {match_rate})) = r.k FORMAT Null</query>
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_10m_nullable r ON (l.k % toUInt64(10000000 / {match_rate})) = r.k FORMAT Null</query>
<query>SELECT * FROM rs_probe_100m l FULL JOIN rs_right_10m r ON (l.k % toUInt64(10000000 / {match_rate})) = r.k FORMAT Null</query>

<!-- 10 matches per key + non-nullable payload -->
<query>SELECT * FROM (SELECT * FROM rs_probe_100m LIMIT 20000000) l JOIN rs_right_1m_x10 r ON (l.k % toUInt64(1000000 / {match_rate})) = r.k FORMAT Null</query>

<!-- 10 matches per key + nullable payload -->
<query>SELECT * FROM (SELECT * FROM rs_probe_100m LIMIT 20000000) l JOIN rs_right_1m_nullable_x10 r ON (l.k % toUInt64(1000000 / {match_rate})) = r.k FORMAT Null</query>

<!-- Mix of fixed sized and String columns -->
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_mixed_10m r ON (l.k % toUInt64(10000000 / {match_rate})) = r.k FORMAT Null</query>

<!-- Wide build columns results in large blocks -->
<query>SELECT * FROM rs_probe_100m l JOIN rs_right_wide_10m r ON (l.k % toUInt64(10000000 / {match_rate})) = r.k FORMAT Null SETTINGS max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0</query>

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.

These benchmark queries no longer force the row-store path on, but this PR is still claiming a Performance Improvement and PlannerJoins.cpp only enables the optimization when it has either min_rows_ratio_for_hash_join_row_store = 0 or a usable result_rows_estimation / cached match hint. As written, a future planner or statistics change can silently make this suite benchmark the preexisting columnar path instead of the new layout. Please pin the feature on here (for example with enable_hash_join_row_store = 1, min_rows_ratio_for_hash_join_row_store = 0) or otherwise assert that the measured queries actually initialized the row store.

@m-selmi
m-selmi added this pull request to the merge queue Aug 26, 2026
Merged via the queue into ClickHouse:master with commit 6eabef9 Aug 26, 2026
179 checks passed
@m-selmi
m-selmi deleted the transform-hash-table-payload-to-row-major branch August 26, 2026 17:51
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 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 hold Skip for auto-updating. 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.

Evaluate using Row-Major Storage instead of RowRef/RowRefList in Hash Table

6 participants