Skip to content

Half-a-radix-join: PBNP - #115254

Draft
harikrishnan94 wants to merge 26 commits into
pbnp-table-building-blocks-before-l2from
pbnp-join
Draft

harikrishnan94 wants to merge 26 commits into
pbnp-table-building-blocks-before-l2from
pbnp-join

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Part of https://github.com/ClickHouse/ClickHouse/pull/120423. Sits on #120515. #120579 sits on this.

Related: #104585
Related: #111305

parallel_hash probes one shared two-level hash table. Build threads insert into it through slots. Each slot owns a share of the buckets.

right-side block
  split into #slots pieces
  one thread then inserts into every slot it can lock
  a slot still holds 256/#slots buckets, and consecutive rows land in unrelated ones

at max_threads = 96, #slots = 128, a slot is 2 buckets, 2 MiB
at max_threads = 1,  #slots = 1,   one thread juggles all 256 buckets, 256 MiB

probe
  one shared table
  consecutive rows go to unrelated buckets

The bucket count says how the table is divided. It says nothing about the order the writes arrive in. Once the build side outgrows the last-level cache, every probe lookup is a cold miss. The two-level split does not shrink the working set a thread writes.

Both algorithms do random writes. What differs is the range those writes cover. parallel_hash writes across 2 MiB to 256 MiB. A cache-sized partition writes across 1 MiB.

To take partition count and size out of the comparison, both were pinned to 256 partitions of the same size. The shape is 6M distinct UInt64 keys, INNER ALL, 6M build rows against a 64K probe. The machine is one Graviton 4: 96 cores, L1d 64 KiB, L2 2 MiB per core, L3 36 MiB shared. HashJoinPartitions = 256 and HashJoinTableBytes = 268435456, so 256 x 1 MiB. HashJoinPreallocatedElementsInHashTables = 6000000, so 6M / 256 = 23437 keys per bucket. The hash table reserves 65536 cells x 16 B = 1 MiB per bucket, 256 MiB in total. Same geometry, same 6M inserts, equal checksums. Wall time and build thread time are the minimum of 4 runs from system.query_log. The counters are perf stat over the whole query.

wall build (cpu) L2 refills dTLB walks stall_backend_mem
max_threads = 1, parallel_hash 98 ms 93 ms 7.3 M 6.06 M 37.3% of cycles
max_threads = 1, partitioned_hash 91 ms 86 ms 3.0 M 0.74 M 20.8%
max_threads = 96, parallel_hash 36 ms 624 ms 19.3 M 5.90 M 54.7%
max_threads = 96, partitioned_hash 19 ms 143 ms 7.0 M 1.12 M 28.3%

At one thread there is no lock contention and no sharing. parallel_hash still takes 2.4 times the L2 refills and 8.2 times the page-table walks. Time barely moves (98 ms against 91 ms), because one core has enough memory-level parallelism to hide the misses. partitioned_hash spends more instructions for the same cycles (IPC 2.03 against 2.40). At 96 cores the misses show up. Memory stalls are 54.7% of cycles against 28.3%. Build CPU time is 4.4 times higher.

Owning a slot is the smaller half. The build of parallel_hash was patched so slot i has one writer, thread i.

build (cpu) wall L2 refills dTLB walks stall_backend_mem
parallel_hash 624 ms 36 ms 19.3 M 5.90 M 54.7%
parallel_hash, one writer per slot 387 ms 33 ms 19.0 M 3.81 M 43.4%
partitioned_hash 143 ms 19 ms 7.0 M 1.12 M 28.3%

One writer per slot saves 38% of the build CPU and 35% of the page walks. L2 misses stay put (19.3 M to 19.0 M). At one thread it changes nothing (dTLB 6.06 M to 6.13 M), because #slots is 1. Each slot juggling its buckets carries the L2 misses. Any thread touching any slot carries the page walks and the lock traffic.

A radix join shuffles both sides. Its memory floor is |build| + |probe|, and it pays a partitioning cost on the side that is usually the bigger one. Nothing repays that cost.

partitioned_hash scatters only the build side. A worker claims one partition, inserts all of it, then claims the next. The probe is not scattered.

partitioned_hash          SET join_algorithm = 'partitioned_hash'

build
  scatter the right side by key, once
  a worker claims one partition, inserts all of it, then claims the next
  each partition is sized to 0.8 x the private L2, 1 MiB on Graviton 4
  the count stops at one partition per 64 bytes of L1d, 1024 on Graviton 4; deeper fanouts measured no better

probe
  not scattered, not buffered, not copied
  a row hashes its key and walks the one table from its home cell
  rows flow downstream as soon as the build finishes

The table is one buffer, sized from the distinct-key estimate and split into ranges. The histograms and prefix sums size the scatter chunks. The table doubles in place if the estimate was low. RangeCommittedBuffer from the layer below zeroes and charges each range when its owner claims it.

On a large build the partitions are not cache-resident. A 16 GiB build at 1024 partitions gives 16 MiB ranges against a 2 MiB L2. It still wins, for four reasons.

  1. The region a worker writes is contiguous and smaller by the fanout. The page-table entries covering it fit in cache: 32 KiB of entries for a 16 MiB partition, against 32 MiB for the unpartitioned table.
  2. Only the key columns and one row reference per row are scattered. Payload columns stay in the shared row store.
  3. A partition has one owner during the insert wave, and one thread then inserts the rows that wrapped past a range end. No atomics on the insert path. The scatter chunks are freed as soon as it is filled.
  4. The remaining insert misses are overlapped 32 deep by the same ring the probe uses, and only when the tables no longer fit L2.

Build wall time is flat from 64 to 65536 partitions. The insert is already at its bandwidth floor, so what a deeper fanout saves per insert, the extra scatter pass takes back. The probe only pays. Going from 8192 to 32768 partitions adds about 6% to probe thread time at a fixed shape.

This layer is PartitionedHashJoin and HashJoinClause, plus the planner and the settings. It covers INNER, LEFT, RIGHT and FULL, crossed with ALL, ANY, RightAny, SEMI and ANTI. It also covers ASOF, null maps, per-clause ON filters and USING. Anything outside that set is planned onto hash at plan time, and never fails at execution time. Output is emitted by the standard HashJoin machinery over a shared row store. This layer is one clause. Spill, mixed ON, GraceHashJoin, JoinSwitcher and the Join table engine are the next layers. Several OR disjuncts run on a plain HashJoin inside PartitionedHashJoin, built by one thread. Moving them onto the partitioned table is #120595.

The numbers below are from the 2026-08-18 revision of this branch. The code has since been rewritten for readability without changing the algorithm. That rewrite was checked against the previous revision on ten shapes and is within measurement noise. The probe ring now lives in #120515. The typed gather of output columns lives in #117460. Both were in the revision that was measured.

Benchmarks

Two Memory tables joined on one key. Both sides are drawn from a persistent key store. Six properties are swept on their own. Key type: UInt64, composites of 2, 4 and 8 columns, String at 8, 16, 32 and 64 bytes, and Nullable variants of UInt64 and String. Distinct build keys: 65K to 512M. Hit rate: 0.05 to 1.0. Match multiplicity on each side: 1 to 256. Payload width on each side: 0 to 64 bytes of extra UInt64 columns, all projected. max_threads: 2 to 96. That is 335 cells, each one run on both aarch64 and x86_64. Each cell is five timed runs after a warmup. The median is reported.

Every run asserts the execution path through profile events. A cell that fell back to parallel_hash fails the run. It cannot report a speedup of one. Row counts are asserted exactly before timing.

Hardware: two fleets of 96-vCPU servers, one server per shard. aarch64 is Neoverse V2 (Graviton 4), 96 cores on one socket and one NUMA node. L1d is 64 KiB and L2 is 2 MiB per core. Shared L3 is 36 MiB. RAM is 370 GiB. The 2 MiB private L2 is what the partition-count rule sizes each range against. x86_64 is Sapphire Rapids with 96 vCPUs. Settings pinned: join_algorithm to the algorithm under test, enable_analyzer = 1, enable_join_runtime_filters = 0, max_bytes_before_external_join = 0, query_plan_join_swap_table = false.

Speedup means parallel_hash time divided by partitioned_hash time, so above 1 is a win. Aggregates are geometric means.

335 of 335 shapes are wins on aarch64. Geometric mean 1.77x, median 1.66x. The 10th percentile is 1.36x and the 90th is 2.51x. 219 shapes are at or above 1.5x, 85 at or above 2x, 19 at or above 3x. Pooled geometric-mean latency is 207 ms against 368 ms. The best single point is 4.79x (2-column UInt64 key, 64M distinct, 96 threads, 120 ms against 575 ms). The worst is 1.11x (UInt64, 32M distinct, 16 threads, 99 ms against 110 ms).

On x86_64 every cell is a win too, except two. Both are the same shape at two thread counts: a 32M-key build with an extra 128M rows that all carry one hot key. There x86_64 loses 1.17x at 16 threads and ties at 96, while aarch64 wins 1.21x and 1.14x on the same shape.

Scatter of speedup over parallel_hash against distinct build-side keys, log x-axis, 335 points in three thread bands. Every point sits above the parity line at 1.0. The 48-96 thread band reaches a geometric mean of 2.11x and holds the highest points, up to 4.79x above 30M keys; the 2-8 and 16-32 thread bands sit around 1.55x and stay under 2.5x.
max_threads 2 4 8 16 24 32 48 64 96
gmean speedup 1.52x 1.49x 1.57x 1.50x 1.70x 1.68x 2.15x 2.02x 2.12x

At 96 threads partitioned_hash reaches 131 ms pooled where parallel_hash is at 277 ms. At 64 threads it is 91 ms against 185 ms.

distinct build keys ~10^4 ~10^5 ~10^6 ~10^7 ~10^8
gmean speedup 1.50x 1.58x 1.56x 1.79x 2.01x
cells 9 13 58 194 61

Every key type wins. The spread across key types is narrower than the spread across thread counts. It runs from 1.65x for an 8-column UInt64 composite to 2.18x for an 8-byte String.

Two panels. Left: bars of geometric-mean speedup by max_threads from 2 to 96, flat around 1.5x up to 16 threads then stepping to 2.15x at 48 and 2.12x at 96. Right: horizontal bars of geometric-mean speedup by key type, all above parity, from 1.65x for an 8-column UInt64 composite to 2.18x for an 8-byte String.

A 5% hit rate averages 2.01x, against 1.74x at a full hit rate. A miss ends inside the partition and does not emit. Probe-side multiplicity goes the other way: 1:1 averages 1.80x, and 256 probe rows per build key drops to 1.52x. That replication is shared cost, and partitioning does not touch it. Build-side multiplicity helps. 16 build rows per key averages 2.29x, because the duplicates of a key sit in one contiguous span the cell points to.

payload width 0 B 8 B 16 B 32 B 64 B
gmean speedup, build side 1.40x 1.78x 1.90x 1.83x 1.96x
gmean speedup, probe side 1.70x 1.78x 1.70x 1.70x 1.75x

Those payload aggregates are thinly sampled away from 8 B. The next cells hold the key, the cardinality, the hit rate, the multiplicities, the probe payload and the thread count fixed, and change only the build payload.

key distinct probe payload threads 0 B 64 B
UInt64 128M 0 B 96 1.33x 3.24x
UInt64 128M 64 B 96 1.61x 3.16x
UInt64 128M 0 B 16 1.21x 1.55x
UInt64 x4 32M 0 B 96 1.84x 2.25x
UInt64 x4 32M 64 B 96 1.84x 2.15x

At 48 threads and above, a key-only build side averages 1.57x and a 64-byte payload 2.48x. The build-side widening is the typed gather of output columns. That code is #117460, and it was in the revision these cells were measured on.

A single hot key is the shape that pulls the advantage down. Across the 13 skewed cells the geometric mean is 1.48x, against 1.78x on the uniform ones, with a floor of 1.14x. One partition ends up far larger than the budget, and because a partition has a single writer, that worker sits on the critical path. Largest-first claiming spreads uneven partitions but cannot split one. Both x86_64 exceptions live here.

Memory: 293 of 335 cells peak below parallel_hash, geometric mean 0.85x, median 0.87x. Nothing on the probe side is held, and the scatter chunks of a partition are released as its table is filled. 12 cells are above 1.2x and the worst is 2.27x. All of them are duplicate-heavy build sides with wide keys, at 96 threads. The scattered key columns and row references are large next to the tables they feed.

Histogram of peak memory as a multiple of parallel_hash across 335 shapes, clustered between 0.7x and 1.0x with a mode just under 0.9x. 293 shapes fall below the parity line at 1.0; a thin tail runs to 2.27x.

TPC-H SF100

SF100 on MergeTree (lineitem has 600,037,902 rows), one server, aarch64 m8g.24xlarge: 96 vCPU, 370 GiB, the same Graviton 4.

SET join_use_nulls = 1, max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0;
SET join_algorithm = 'parallel_hash';

The same script with join_algorithm = 'partitioned_hash'. Five runs per query. Time is the hot minimum of query_duration_ms and memory the hot peak of memory_usage, both over runs 2 to 5 from system.query_log. Q01 and Q06 are left out because they have no join.

18 of 20 queries are wins, 2 are at parity, none is slower. Geometric mean 1.21x, median 1.15x, best 1.87x. Total hot time 11,966 to 10,374 ms, 13.3% less.

query build rows parallel_hash partitioned_hash speedup
Q02 16.7M 306 ms 204 ms 1.50x
Q03 17.6M 409 ms 371 ms 1.10x
Q04 5.7M 262 ms 221 ms 1.19x
Q05 7.8M 360 ms 322 ms 1.12x
Q07 15.9M 463 ms 346 ms 1.34x
Q08 27.9M 480 ms 361 ms 1.33x
Q09 156.4M 969 ms 613 ms 1.58x
Q10 20.7M 845 ms 452 ms 1.87x
Q11 80K 124 ms 106 ms 1.17x
Q12 3.1M 260 ms 248 ms 1.05x
Q13 15.0M 590 ms 521 ms 1.13x
Q14 7.5M 215 ms 177 ms 1.21x
Q15 1.0M 358 ms 351 ms 1.02x
Q16 3.0M 157 ms 119 ms 1.32x
Q17 40K 236 ms 221 ms 1.07x
Q18 51K 724 ms 699 ms 1.04x
Q19 48K 400 ms 385 ms 1.04x
Q20 869K 2862 ms 2859 ms 1.00x
Q21 43.9M 1816 ms 1702 ms 1.07x
Q22 1.9M 130 ms 96 ms 1.35x
total 11966 ms 10374 ms 1.15x
total build rows < 1M 1M to 10M 10M to 50M > 50M
gmean speedup 1.06x 1.17x 1.31x 1.58x
queries 5 7 7 1

The five queries below 1M build rows are where partitioning has nothing to buy. Four of them have a build side below parallel_hash_join_threshold and build one partition on one fill thread.

Q20 is at parity, 2862 against 2859 ms, and it is about a quarter of the total. Without Q20 the other 19 queries take 17.5% less time, at a geometric mean of 1.22x. Its join is faster (build 409 ms less, probe 12 ms less thread time), but the query is not, because the JOIN runtime filter is harmful on this shape and both algorithms pay for it. parallel_hash runs Q20 in 2907 ms with filters and 2107 ms without.

Peak memory: 15 of 20 queries peak below parallel_hash, median 0.88x, and none of the other five is more than 12% above it. Summed peak goes from 67.1 to 62.6 GiB. The largest single peak barely moves: Q18, 23.07 to 22.90 GiB.

Changelog category (leave one):

  • Experimental Feature

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

New experimental join algorithm partitioned_hash, enabled with SET join_algorithm = 'partitioned_hash'. It builds the hash table of a hash join in cache-sized partitions and probes it without partitioning the probe side. Compared with parallel_hash it was faster on all 335 measured shapes on aarch64 (geometric mean 1.77x) and on all but two of them on x86_64, and used less peak memory on most of them.


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

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a32920e]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
join_nullable_keys_small_table #1 FAIL dashboard
join_nullable_keys_small_table #0 unstable query history
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

This PR adds the experimental partitioned_hash join, building one shared table in partitions while probing the original left blocks. ❌ Block: refinement can write beyond allocated buffers, distributed-plan serialization breaks older receivers, and join limits and several memory-sizing paths remain incorrect. Ten findings remain: nine from existing threads and one new serial-reserve finding. Reviewed head: a32920ef17c90243d26baeaca7642479b946cfdc.

Missing context / blind spots
  • ⚠️ Validation was by code tracing and existing CI reports; no local build or executable was available to execute additional reproductions. The focused regressions below would close the remaining runtime-evidence gaps.
Findings

❌ Blockers

  1. HashJoinClause.cpp:2283: Refinement uses UInt32 histogram counts for buckets aggregated across input blocks. A child containing 2^32 hot-key rows wraps its count; allocation uses the wrapped value, then scatter writes all rows, causing out-of-bounds writes. Use wide counts throughout allocation and scatter, or reject oversized buckets before writing. Existing thread.

  2. JoinOperator.cpp:485: Both new plan-setting names are assigned unconditionally. Even default assignments mark them changed, so ordinary serialized joins send names unknown to older receivers and fail with UNKNOWN_SETTING during rolling upgrades. Gate the names by a negotiated serialization version and handle the new algorithm value when sending to older peers. Existing thread.

  3. PartitionedHashJoin.cpp:540: max_bytes_in_join checks cover stored input and routes but omit the table, key arenas, duplicate spans and null maps allocated afterward. Both serial and deferred builds can exceed the configured join limit without applying join_overflow_mode. Enforce the limit against actual accounted join memory during construction and before publication. Existing thread.

  4. PartitionedHashJoin.cpp:369: Both row-limit checks count raw input rows instead of built keys. Duplicate or entirely filtered rows can incorrectly exceed max_rows_in_join; with join_overflow_mode = 'break', later build blocks are discarded although the table remains within its cap. Check actual built-key counts in both build modes. Existing thread.

  5. HashJoinClause.cpp:1875: Overflow row count is treated as additional distinct keys before draining. Repeated keys whose walks cross an owner boundary can expand a table thousands of times unnecessarily, including LEFT ANY builds. Drain under the last-free-cell guard, then base load-factor growth on actual claimed keys. Existing thread.

⚠️ Majors

  1. New — PartitionedHashJoin.cpp:339: Serial fill reserves using estimated source rows as distinct keys. With parallel_hash_join_threshold = 100000000, an estimated 64,000,000 duplicate UInt64 rows commit a 2 GiB table before the first insert, even when only one key is needed. Planner overestimates similarly inflate small builds. Bound the initial reserve and grow from actual distinct claims, or use a genuine distinct estimate. New thread.

  2. HashJoinClause.cpp:1689: Persistent string-key arenas reserve every input key byte, including duplicates. A deferred, one-thread LEFT ANY build with one million copies of a 1 KiB string allocates approximately 1 GiB of persistent arena storage for one retained key. Estimate retained key bytes or grow the arena incrementally. Existing thread.

  3. PartitionedHashJoin.cpp:667: The literal-empty-right and LEFT SEMI cases have been improved, but effective emptiness still uses raw input rows. An INNER build whose rows are all excluded by null keys or ON filters keeps scanning the left input, potentially indefinitely. Track rows that can contribute to output while preserving right-side non-joined rows where required. Existing thread.

  4. PartitionedHashJoin.cpp:124: With no row estimate, the maximum parallel_hash_join_threshold does not force serial fill as documented. A sufficiently large table still partitions and builds in parallel. Recognize the maximum-value sentinel independently of estimate availability and initialize capacity safely without a hint. Existing thread.

  5. PartitionedHashJoin.h:111: The probe preserves left-row order, but the class inherits preservesLeftBlockOrder = false. Consequently, ordered-read and top-K optimizations through the join are disabled. Override the capability for the supported paths and cover it with a focused plan test. Existing thread.

Tests
  • ⚠️ Add downgrade serialization coverage showing ordinary joins omit new setting names for older peers.
  • ⚠️ Cover both build modes with join byte/row limits, duplicate keys and fully filtered input; include early termination for an effectively empty INNER build.
  • ⚠️ Exercise refinement counters at the 2^32 boundary and duplicate overflow across an owner boundary; assert safe allocation and bounded table growth.
  • ⚠️ Add memory bounds for high row estimates with few distinct keys and for repeated long string keys.
  • ⚠️ Test the maximum serial-threshold sentinel without estimates, and ordered-read/top-K plans through partitioned_hash.
Final Verdict

Status: ❌ Block. Correct the refinement buffer sizing and serialization compatibility first; enforce join limits, bound the three excessive-allocation paths, and address the remaining early-stop, threshold and ordering contracts with focused regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 18, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

cc: @rschu1ze @ayakovlev-clickhouse

@harikrishnan94 harikrishnan94 changed the title [Experiment] Partitioned-build, non-partitioned-probe hash join: partitioned_hash [Experiment] Half-a-radix-join: Partitioned-build, non-partitioned-probe hash join Aug 18, 2026
@harikrishnan94 harikrishnan94 changed the title [Experiment] Half-a-radix-join: Partitioned-build, non-partitioned-probe hash join [Experiment] Half-a-radix-join: partitioned_hash Aug 18, 2026
@harikrishnan94 harikrishnan94 changed the title [Experiment] Half-a-radix-join: partitioned_hash [Experiment] Half-a-radix-join: PBNP Aug 18, 2026
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-experimental Experimental Feature labels Aug 19, 2026
harikrishnan94 pushed a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
…blocks

The lazy emit of a right-side column walks, per output row, the materialized
StoredBlock pointer, then the ColumnPtr inside the block's column vector, then
the column object, before the value itself. The first three loads are pure
indirection: every stored block shares the saved-block structure, so the source
of a given output position is a function of block_no alone.

StoredColumnsIndex::resolveEmitColumns already caches the resolved
const IColumn * per block for the fillFromRowRefs path. It now also caches that
column's raw fixed-width base per block, and the two buildOutputFromBlocks
builders copy the values from it directly off the encoded ref words, without
expanding them into (StoredBlock *, row_number) pairs first. A zero ref word
writes bitwise zero, which is what insertDefaultInto writes for every admitted
type, so the values are bit identical.

The mechanism is ported from harikrishnan94's draft ClickHouse#115254, where it lives on
the PartitionedHashJoin probe path behind a flag. On master the flag's four
guards (lazy emit, not joinGet, not ASOF, not ANY) are already the exact
condition under which the emit table is resolved, so the gather needs no flag
and no call-site special case, and HashJoinMethodsImpl.h is untouched.

Admission is resolved once per probe rather than per output chunk, and requires
a single-plane contiguous source of a uniform stride across blocks whose raw
buffer holds exactly its own rows. That refuses a ColumnReplicated source
(which needs an index indirection and has no raw data), a ColumnConst (which
forwards its raw data to a one-element buffer), and Enum8/Enum16 destinations
(whose default is the first enum value, not zero). Anything refused keeps the
generic path, per column.

The limit and offset builder is all or nothing, because its gather input is the
subset of ref words the walk selects after applying the offset and the limits,
and that sequence only exists if the walk records it.

New ProfileEvent HashJoinDirectGatheredRows counts the values emitted this way,
which is what lets a test tell the two paths apart.

Related: ClickHouse#116833
Related: ClickHouse#115254

Co-Authored-By: Claude Opus 5 <[email protected]>
harikrishnan94 pushed a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
The arming assertions counted a boolean per arm: some column of that arm took
the direct gather. That cannot see one admitted type quietly falling back to the
generic path, because the two paths produce identical values by construction, so
the result lines cannot move either, and some other column keeps the boolean at
one. The optimization is the deliverable here, so a silent loss of it for one
type has to fail the test.

New arm 1d asserts the exact count of gathered values over the existing 30
payload column fixture. It pins enable_hash_join_row_store = 0 so that the count
is an identity rather than a measurement of the planner: whenever the in-memory
row store initializes it claims every fixed and contiguous column of stride 32
or less, and its initialization compares against an estimate that drifts with
accumulated statistics, so four of the boolean arms were measured taking two
different counts across 52 runs. With the row store out of the path all 30
columns stay columnar for all 1000 probe rows. Every other arm keeps its
boolean, and no existing arm, setting, fixture or reference line changed.

Also skip collecting block pointers and row numbers when every columnar
destination was gathered. fillJoinOutputColumns skips exactly those destinations,
so on the shape where a row store coexists with a fully gathered columnar set the
two appends per output row were dead.

The size invariant in resolveEmitColumns is a positive test rather than a list of
column classes to refuse, so that a column class added later which delegates
getRawData to a buffer that does not hold its own rows is refused without needing
an entry here.

Related: ClickHouse#116833
Related: ClickHouse#115254

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... submodule changed At least one submodule changed in this PR. labels Sep 4, 2026
@harikrishnan94 harikrishnan94 linked an issue Sep 11, 2026 that may be closed by this pull request
@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 16, 2026
/// a build estimated small keeps the narrow pipeline on purpose.
bool supportParallelJoin() const override { return !delegate_mode && !single_fill_thread; }
/// Probe blocks are joined whole, never scattered across slots, and the result caps its own blocks.
bool emitsSizedOutputBlocks() const override { return true; }

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 probe path keeps the left block in order (probeImpl wraps the original block in ScatteredBlock{std::move(block)} and never scatters it), but PartitionedHashJoin never opts into preservesLeftBlockOrder(). Since IJoin defaults this to false, optimizeReadInOrder and topKThroughJoin will treat an explicit join_algorithm = 'partitioned_hash' as order-destroying and skip the through-join optimizations that plain HashJoin gets. If there is no hidden reordering path here, this class should override preservesLeftBlockOrder() and add a focused plan test.

@harikrishnan94
harikrishnan94 changed the base branch from master to pbnp-table-building-blocks September 17, 2026 09:05
build_blocks.clear();
build_blocks.shrink_to_fit();
/// From here the byte count tracks only the stored blocks.
accumulated_bytes.store(hash_join->data->allocated_size, std::memory_order_relaxed);

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.

max_bytes_in_join stops being enforced once the actual table allocation happens. Up to this point the only checks are at lines 319 and 344, and they look only at accumulated_bytes (stored blocks plus route bytes). After finishSinglePartitionInsert / postBuild, the shared table, duplicate arenas, and nullmaps can add a lot more memory, but here we only reset accumulated_bytes and never run sizeLimits().check() against the real total (getTotalByteCount()). A build that fits the buffered input but blows up while building the table will therefore ignore join_overflow_mode, unlike HashJoin, which checks the accounted table size after every insert.

Please re-check the limit after the post-build phase using the actual join size, and cover the single-fill-thread path as well.

{
if (delegate_mode)
return hash_join->alwaysReturnsEmptySet();
return isInnerOrRight(table_join->kind()) && accumulated_rows.load(std::memory_order_relaxed) == 0;

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 regresses the "empty effective right side" fast path that the other hash-family joins expose through alwaysReturnsEmptySet(). HashJoin returns true not only for INNER / RIGHT, but also for LEFT SEMI on an empty right side, and it bases the answer on the rows that actually survived into the build. Here the check only looks at isInnerOrRight(kind) and raw accumulated_rows, so the pipeline will keep scanning the entire left input for cases like LEFT SEMI JOIN (SELECT ... WHERE 0) or when every build row was filtered out by null keys or ON conditions before insertion.

That is a large regression from the existing hash-join behavior. This should either delegate to the wrapped HashJoin's notion of effective emptiness, or reproduce the same condition against the rows that really made it into the build.

/// The fill-phase analogue of `HashJoin`'s per-block limit check. Rows are the accumulated
/// input rows, an upper bound on the keys the map-based algorithms check; bytes cover the stored
/// blocks and the route transients.
return table_join->sizeLimits().check(

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.

❌ max_rows_in_join is defined on the built right-side join structure, but both checks here and at line 314 use accumulated_rows, i.e. raw build rows before duplicate collapse and before null-key / ON filtering. That changes behavior relative to HashJoin: a duplicate-heavy build can stay at one hash-table key and still trip the limit here, and with join_overflow_mode = 'break' this stops reading later right blocks even though the actual table is still within the configured row cap. Please base the row-limit check on the built table size (clause.tableRowCount() / getTotalRowCount()) and add a regression that covers duplicates plus a fully filtered build.

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a32920ef1 with master 2a4ae1408 (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: binary sizes, object file sizes.

Binary sizes ⚠️
Binary Master PR Δ
programs/clickhouse-stripped 787.74 MiB 778.93 MiB -8.81 MiB (-1.12%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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 ⚠️

139 object files changed (-4.18 MiB total), 13 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp.o new 4.14 MiB +4.14 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp.o new 3.14 MiB +3.14 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp.o new 2.89 MiB +2.89 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/HashJoinClause.cpp.o new 1.63 MiB +1.63 MiB
src/CMakeFiles/dbms.dir/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp.o new 1.36 MiB +1.36 MiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o 3.36 MiB 4.23 MiB +886.31 KiB (+25.72%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 3.57 MiB 2.85 MiB -737.27 KiB (-20.18%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 3.38 MiB 2.70 MiB -699.49 KiB (-20.21%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnti.cpp.o 2.63 MiB 1.96 MiB -677.23 KiB (-25.19%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAny.cpp.o 2.68 MiB 2.02 MiB -673.27 KiB (-24.56%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 3.08 MiB 2.43 MiB -664.28 KiB (-21.07%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o 3.31 MiB 2.67 MiB -662.55 KiB (-19.52%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 3.47 MiB 2.82 MiB -661.44 KiB (-18.64%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAnti.cpp.o 2.59 MiB 1.95 MiB -653.20 KiB (-24.61%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsSet.cpp.o 2.41 MiB 1.78 MiB -648.39 KiB (-26.29%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 2.64 MiB 2.01 MiB -646.48 KiB (-23.92%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAny.cpp.o 2.64 MiB 2.01 MiB -646.47 KiB (-23.92%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 3.05 MiB 2.43 MiB -639.04 KiB (-20.44%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAnyMapsAll.cpp.o 3.16 MiB 2.54 MiB -636.89 KiB (-19.66%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 3.31 MiB 2.69 MiB -636.64 KiB (-18.79%)

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

2142 translation units recompiled, 13427 s compile time in total, 2128 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeLeft.cpp: 20.0 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeInner.cpp: 16.5 s
  • src/Interpreters/PartitionedHashJoin/HashJoinClause.cpp: 16.0 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeRight.cpp: 15.8 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinProbeFull.cpp: 10.9 s
  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.6 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoin.cpp: 6.9 s
  • src/Interpreters/PartitionedHashJoin/PartitionedHashJoinNotJoined.cpp: 5.9 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 13.38 MiB 13.50 MiB +128.00 KiB (+0.93%)
programs/clickhouse ProfileEvents::global_counters_storage 13.38 MiB 13.50 MiB +128.00 KiB (+0.93%)
programs/clickhouse-keeper auto DB::HashJoinClause::insertPartitionSection(DB::HashJoinClause::PostBuildContext&, unsigned lon… new 65.00 KiB +65.00 KiB
programs/clickhouse auto DB::HashJoinClause::insertPartitionSection(DB::HashJoinClause::PostBuildContext&, unsigned lon… new 65.00 KiB +65.00 KiB

Job report

@harikrishnan94
harikrishnan94 removed this pull request from stack #124166 October 7, 2026 12:21
@harikrishnan94
harikrishnan94 removed this pull request from stack #124421 October 8, 2026 09:43
@harikrishnan94
harikrishnan94 removed this pull request from stack #124582 October 9, 2026 04:32
harikrishnan94 and others added 12 commits October 14, 2026 10:04
The parent now carries the rewritten `uhj`. This branch's own changes conflicted with it in the metrics, the settings, `TableJoin` and the planner, and are applied again on top of the new text:

- `parallel_hash` is an alias of `hash` now and `JoinAlgorithm::PARALLEL_HASH` is gone, so the `partitioned_hash` additions no longer list it. `TableJoin::isHashFamilyEnabled` is back and covers `hash` and `partitioned_hash`.
- `TableJoin` keeps the `parallel_hash_join_threshold` member and its `parallelHashJoinThreshold` accessor, which the partitioned join reads. `preferParallelHashLayout` still takes the threshold as an argument.
- The old per-phase `HashJoin` timers that `uhj` removed are not brought back, only the `HashJoinPartitioned*` events of this branch.
- The history of the two new `partitioned_hash_join_*` settings and of the `partitioned_hash` value of `join_algorithm` moves into their declarations in `Settings.cpp`, which is where the history lives now.

Code that this branch adds and the new `uhj` has not seen is not adapted here. The partitioned join still builds its `HashJoin` with the old constructor arguments.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`PartitionedHashJoin::addBlockToJoin` takes a `JoinBuildContext` and reads the fill lane and the limit check from it. The delegate `HashJoin` and the clone made by `cloneNoParallel` are built with `HashJoinBuildLayout::oneBucket(1)`. `getAlgorithm` reports `PARTITIONED_HASH`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…the new `uhj`

`KeyGetterForType` and `LowCardinalityKeyGetterForJoin` take no offset flag any more, so the routing, probe and fill code no longer passes one. The row store is a gather source, so the non-joined scan emits the row store columns through `gatherJoinOutputColumns` together with the columnar ones instead of resolving row pointers itself. `JoinCommon::canBeExecutedByEnabledAlgorithm` treats `partitioned_hash` like `hash`, and the threshold argument of `preferParallelHashLayout` no longer shadows the member of the same name.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…t the new `uhj` rewrote

The new `uhj` tests `isEnabledAlgorithm(HASH)` where this branch's earlier base asked `isHashFamilyEnabled`, so seven places stopped treating a `join_algorithm` list with `partitioned_hash` as a hash join: the mixed `ON` guard and the hash-enabled flag of the planner, general join planning in the logical planner, `JoinStepLogical`, the rewrite of a join to `IN`, the join on a constant of the legacy rewriter, and the cache keys check of `TableJoin`. They ask `isHashFamilyEnabled` again.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…join planning test

The new `uhj` pushes the one-sided `ON` conditions into `PREWHERE` for both `hash` and `partitioned_hash`, so `EXPLAIN` prints `Prewhere filter column` for them instead of `Filter column`. The first query of the test matches both spellings.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the last two commits of `uhj`: the key and byte count of a slot insert that throws, and the rename of the `StorageJoin` count test.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the fix of the join key getter template arguments.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The base now runs an `INNER ANY` join whose `ON` expression has no equality key as a block nested loop join, so `05220` expects the counts instead of an `INVALID_JOIN_ON_EXPRESSION` exception. The base also pushes the one-sided condition of the second `05219` query into `PREWHERE`, so its `EXPLAIN` line reads `Prewhere filter column`. The loop variable of the routing test is `size_t`, like `skip.size()`, and the argument comment in `ExpressionAnalyzer` names the parameter `threshold`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj`. Four files conflicted. `preferParallelHashLayout` takes the new rule of `uhj` under this layer's parameter name `threshold`: without an estimate, only the largest threshold keeps the serial layout. The old analyzer call passes the `parallel_hash_join_threshold` setting. The settings history keeps this layer's `26.9` row below the moved `26.11` row. The runtime filter check allows `partitioned_hash` and keeps the new `ASOF` exclusion for `grace_hash`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A probe that reaches `max_joined_block_size_rows` stops and leaves the rest of the left block in `next_block`. The join transform of the base no longer looks at it and asserts that it is empty, because `HashJoin` continues inside its own result. The partitioned join result did not, so the unprocessed rows were dropped without an error. It now probes the rest and adds up the matched right rows of the parts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the merge of `uhj` that repairs the `gtest_functions_stress` build.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…6.11`

The `settings_changes_history` style check requires a record for the current version, `26.11`, on every setting that a pull request adds. `partitioned_hash_join_max_fanout_per_pass` and `partitioned_hash_join_cap_partitions_by_l1_descriptors` only had records for `26.10`, so the check failed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
settings[QueryPlanSerializationSetting::grace_hash_join_max_buckets] = grace_hash_join_max_buckets;

settings[QueryPlanSerializationSetting::partitioned_hash_join_max_fanout_per_pass] = partitioned_hash_join_max_fanout_per_pass;
settings[QueryPlanSerializationSetting::partitioned_hash_join_cap_partitions_by_l1_descriptors] = partitioned_hash_join_cap_partitions_by_l1_descriptors;

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.

❌ Gate the new plan-setting names by the negotiated serialization version.

These assignments mark both settings as changed even when their values equal the defaults (SettingFieldNumber::operator= always sets changed = true). Consequently, writeChangedBinary writes both names for every serialized join, including an ordinary hash join that never enables partitioned_hash. A peer predating this PR has neither name in its strict QueryPlanSerializationSettings schema, so BaseSettings::readBinary throws UNKNOWN_SETTING. This breaks distributed-plan joins during a rolling upgrade without opting into the new algorithm.

Add a release-appropriate plan serialization version and guard these assignments, as the surrounding code does for other newly introduced plan settings. Also handle sending the new join_algorithm value to an older peer explicitly. A downgrade serialization test should prove that a default hash join omits both new names for older versions.

UInt64 group_overflow = 0;
for (const auto & overflow : ctx.overflow)
group_overflow += overflow.rows();
maybeGrowForLoadFactor(claimedTotal() + group_overflow);

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.

❌ Do not size the table from the number of overflow rows.

group_overflow includes duplicate rows, but this projection treats each row as a new distinct key. For a concrete CRC32C UInt64 case, keys 343 and 2317 both have home cell 1023 in a degree-11 table. With two partitions, insert 343 first and then one million rows of 2317: every later row reaches the partition boundary at 1024 and enters overflow. This line projects 1,000,001 distinct keys and grows to degree 21 before the drain discovers only one new key. The table expands 1024-fold for two distinct keys, including for LEFT ANY, which needs no duplicate spans. Larger hot-key builds can exhaust memory unnecessarily.

Drain with the existing last-free-cell growth guard, then base load-factor growth on the actual claimed-key count. Cover a duplicate-heavy key whose first insertion crosses its partition boundary; the existing duplicate-growth test keeps its hot key inside the owner range.

/*allow_set_maps_=*/false))
, delegate_mode(!table_join->oneDisjunct())
, build_rows_hint(build_rows_hint_)
, single_fill_thread(!delegate_mode && build_rows_hint_ && *build_rows_hint_ < table_join->parallelHashJoinThreshold())

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.

⚠️ Honor the force-serial threshold when no row estimate is available.

parallel_hash_join_threshold = 18446744073709551615 is documented to build one part on one thread even without an estimate, and TableJoin::preferParallelHashLayout implements that rule for hash. Here the missing build_rows_hint_ forces single_fill_thread to false. With estimation disabled (query_plan_optimize_join_order_limit = 0, and no collected statistics), a build whose distinct-key table exceeds L2 still gets multiple partitions in decidePartitionPlan and parallel fill, ignoring the user's explicit serial setting.

Handle the maximum-threshold sentinel independently of estimate availability, including capacity initialization when there is no hint. Add a focused pipeline/partition-count test with estimation disabled.

harikrishnan94 and others added 3 commits October 17, 2026 06:43
`insertSingleLaneBlock` added every row of a block to `inserted_rows` and to `HashJoinInsertedRows`. Rows with a NULL key, and rows that the `ON` condition filters out, never reach the table. In debug and sanitizer builds `verifyPublishedTable` compares the rows of the table with `inserted_rows`, so a single-lane build with such rows failed with a logical error. The multi-partition path already counts only the rows it inserts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
CI randomizes settings, and these tests assume the defaults. `04927`, `04928`, `05111` and `05137` need several build threads, so they set `max_threads`. `05138` needs build blocks of 100000 rows, so it sets `max_block_size`. `05141` needs the planner's row estimate, which a randomized join order drops, so it sets `query_plan_optimize_join_order_randomize`. `05219` expects a `Prewhere filter column`, so it sets `optimize_move_to_prewhere`.

`05140` sets `collect_hash_table_stats_during_joins`, because a repeated run reads the hint that the first run left. `05139` orders the first rows by `b.a` as well. It also reads its `ANY` join with one thread, because the right row that a key keeps depends on the block order.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`05141` also sets `query_plan_optimize_join_order_limit`, because a limit of 0 leaves out the row estimate that the test needs. `04931` sets `parallel_non_joined_rows_processing`, because it asserts that the non-joined rows come from parallel sources. `05218` sets `optimize_move_to_prewhere`, because its reference shows the one-sided conditions as `Prewhere filter column`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
ColumnsScatter::ScatterScratch scratch;
scratch.init(sub_fanout, swwc_fanout);
PaddedPODArray<UInt16> pids;
PaddedPODArray<UInt32> hist(sub_fanout);

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.

❌ Keep refinement bucket counts wide enough for the full build.

ctx.bucket_rows[g] aggregates multiple input blocks, but this histogram uses UInt32. For example, four distinct UInt64 keys with 2^32 rows of one hot key, max_threads = 4, parallel_hash_join_threshold = 0, and partitioned_hash_join_max_fanout_per_pass = 2 select four partitions and two scatter passes. All hot-key rows stay in the same child, so ++hist[p] wraps and undercounts that child by 2^32. The following resize_exact(hist[p]) allocates from the wrapped count, yet scatterPidChunk writes all n rows through its raw destination cursor. This produces out-of-bounds writes. The per-input-block UInt32 row limit does not bound a refinement bucket.

Use wide counts throughout refinement, including allocation and the generic scatter interface, or reject an oversized bucket before scattering. Add focused coverage of the counter boundary.

/// every block still holds its keys.
void HashJoinClause::measureGenericKeyBytes()
{
generic_key_bytes = keyLayout().generic ? keyColumnBytes() : 0;

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.

⚠️ Size persistent string-key storage from retained keys rather than all input bytes.

On the deferred build path, keyColumnBytes includes every duplicate key. With max_threads = 1 and parallel_hash_join_threshold = 0, a LEFT ANY build containing one million copies of one 1 KiB String sets generic_key_bytes to approximately 1 GiB. predictedArenaBytes passes that to emplaceSizedBuildArena, so persisting the first distinct key allocates an approximately 1 GiB arena chunk, although only 1 KiB of key data is needed. That chunk remains through probing after the prepared input keys are released. Equivalent hash key storage grows only with distinct keys; this can make the new algorithm exceed max_memory_usage unnecessarily.

Estimate the retained distinct-key bytes, or let key storage grow incrementally instead of giving it the full input-byte reserve. Please cover repeated long strings with a memory bound, independently of duplicate-row span storage.

harikrishnan94 and others added 4 commits October 17, 2026 11:31
Brings in the latest merge of `uhj` and the fix of the structure check in the scatter.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
`SinglePartitionAsofGrowthFailureReleasesLookups` measures what a small `std::vector` costs the memory tracker and sets the limit from that. In the asan, tsan and msan builds the measured cost was 0, so the assertion failed. The test now skips in a build that does not charge small allocations.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…er settings

A flaky check runs copies of the same test at once, which makes a test that takes a few seconds in a debug build exceed its limit. `04927`, `04928`, `04929`, `05111`, `05139` and `05140` now carry the `long` tag, which exempts a test from that limit.

The planner's row estimate decides the build layout, and a randomized join order or a reordering limit of 0 loses it. The tests that assert on the layout now pin `query_plan_optimize_join_order_randomize` and `query_plan_optimize_join_order_limit`. `04929` also pins `max_threads`, because a single thread gives one partition.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The flaky check randomizes `query_plan_optimize_join_order_randomize`. With a random join order the planner plants no runtime filter for the join, so the first check of `04931_partitioned_hash_join_plan_integration` returned 0 instead of 1. The test now sets the setting to 0.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
/// only costs doublings during the inserts.
if (!clause.hasTable())
clause.beginSinglePartitionInsert(
clause.reserveFor(*build_rows_hint, static_cast<double>(*build_rows_hint)),

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.

⚠️ Bound the initial serial reserve instead of treating source rows as distinct keys.

build_rows_hint estimates input rows, but passing it as the distinct estimate makes the first block allocate for every estimated row. For example, with parallel_hash_join_threshold = 100000000, an accurate estimate of 64,000,000 repeated UInt64 keys reserves 2^27 cells (2 GiB for the RowRef table), even for LEFT ANY with just one distinct key. beginSinglePartitionInsert commits the entire buffer before inserting anything, and it never shrinks. A high planner overestimate has the same effect on a small actual build. The serial HashJoin deliberately avoids reserving from a row estimate.

Use a bounded initial reserve and grow from actual distinct claims, or use a genuine distinct-key estimate. Please add a memory-bounded regression with a high row hint and few distinct keys; the existing below-threshold tests only assert results and partition count.

@harikrishnan94
harikrishnan94 removed this pull request from stack #124822 October 21, 2026 12:32
@harikrishnan94
harikrishnan94 changed the base branch from pbnp-table-building-blocks to pbnp-table-building-blocks-before-l2 November 6, 2026 10:37

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Partitioned-build, streamed-probe for HashJoin

1 participant