Skip to content

Add column scatter kernels and run/chain tags for RowRefList - #120513

Draft
harikrishnan94 wants to merge 20 commits into
masterfrom
pbnp-scatter-foundations
Draft

harikrishnan94 wants to merge 20 commits into
masterfrom
pbnp-scatter-foundations

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

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

A hash join finishes one lookup in one table before it starts the next, and prefetches a few rows ahead. HashJoin routes the rows of a block to build slots with selectors. Nothing splits a block into cache-sized pieces. A RowRefList word is either one inline row or a TAG_BATCH node from HashJoin's insert path. getL2CacheSize reads the cache size on its own.

RowRefList
+-- inline ref, or one Batch node

The partitioned join scatters the build side into cache-sized pieces before it inserts, and it writes duplicate keys as a headerless run of refs or as a chain of ranges. RowRefList has no such layout, and that code does not belong inside the join.

ColumnsScatter splits columns into N exact-sized pieces by a per-row shard id. getCPUDataCacheSize is the one reader, and getL1CacheSize and getL2CacheSize use it. The RowRefList word stays 8 bytes, and every layout shares one reader. HashJoin still publishes TAG_BATCH. The run and the chain are for the partitioned join, which is not in this layer. No query changes behavior.

ColumnsScatter          split columns into N exact-sized pieces, by shard id
getCPUDataCacheSize     one reader for the cache sizes

RowRefList
  inline          one row, the word is the RowRef
  TAG_BATCH       HashJoin's insert path, a Batch node
  TAG_RUN         a headerless block of contiguous refs
  TAG_CHAIN       a newest-first chain of ranges

DuplicateSpans.h
  PassScratch     one pass of duplicate rows during the build
  SpanWriter      writes one exact arena span per key
                  the first span of a key is a TAG_RUN

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@harikrishnan94 harikrishnan94 added pr-not-for-changelog This PR should not be mentioned in the changelog pr-performance Pull request with some performance improvements labels Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7829170]

Summary: ✅


AI Review

Summary

Adds column scatter kernels, shared CPU cache probing, and run/chain representations for RowRefList, without enabling the partitioned join. Reviewed PR head 78291701979c088a67a69b4ee652ffb57afc4ed0; all changed checkout files match that head. Eight existing findings remain, including unsafe SWWC configurations and rejected valid column representations. No new inline findings or duplicate replies were posted.

Missing context / blind spots
  • ⚠️ No configured local build was available, so the C++ tests were not run locally. The Praktika report reports success, but does not establish coverage of the boundaries below.
Findings

❌ Blockers

  • src/Columns/ColumnsScatter.cpp:177: SWWC can remain enabled while unsupported widths bypass staging. With a cursor initially at offset 48 in a cache line, one width-32 write advances it to offset 16 while fill remains 48; drain then writes 32 uninitialized staging bytes beyond the destination. Reject unsupported SWWC widths and enforce agreement between the kernel argument and scratch mode.
  • src/Columns/ColumnsScatter.h:85: init with SWWC disabled leaves staging and fill storage unallocated. Enabling it through setUseSwwc is protected only by chassert; release builds subsequently write outside fill and access null staging storage. Allocate the required state when enabling SWWC, or reject the transition in every build.

⚠️ Majors

  • src/Columns/ColumnsScatter.cpp:866: Valid nested LowCardinality columns still fail the debug/sanitizer structure check when dictionaries have different index widths. The head commit exempts top-level LowCardinality, but ColumnTuple, ColumnArray, and ColumnMap recurse into the same width comparison. Validate semantic nested types independently of dictionary-index widths.
  • src/Columns/ColumnsScatter.cpp:785: A top-level detached ColumnBLOB throws LOGICAL_ERROR during getDataType, before wrapper normalization can reconstruct it. Normalize detached sources before inspecting their types or considering compact constants, then validate the resulting columns.
  • src/Interpreters/PartitionedHashJoin/DuplicateSpans.h:211: Both this guard and the guard at line 241 reject duplicate totals above 2^32 - 1, although RangeHeader::total has 48 bits and the existing Batch representation supports larger totals. Preserve the wider total instead of introducing a lower per-key limit.
  • src/Interpreters/RowRefs.h:354: firstWord walks every older range for a chain, replacing constant-time first-row access with work proportional to chain depth. This becomes a probe-time cost when the new layout reaches existing firstRefWord consumers. Keep the first reference directly accessible, or explicitly exclude chain words from those consumers until that guarantee exists.
  • src/Columns/tests/gtest_columns_scatter.cpp:163: Trace restoration is not exception-safe here or at the repeated capture sites. An exception destroys the stack trace while leaving its address installed in thread-local storage; a later scatter can write through a dangling pointer. Use a scoped install/restore guard.

💡 Nits

  • base/base/getCPUCacheSize.cpp:65: Darwin maps every level other than 1 or 2 to L3, violating the helper's failure contract for unsupported levels. Use explicit cases for supported levels and return zero otherwise. Existing callers request only levels 1 and 2.
Tests
  • ⚠️ Add focused SWWC tests for enabling unallocated staging, inconsistent modes, and unsupported widths at a misaligned destination boundary.
  • ⚠️ Cover nested LowCardinality dictionaries with small and greater-than-255 cardinalities in both source orders, and detached sources alone and mixed with regular sources.
  • ⚠️ Exercise a synthetic chain total just above 2^32; the current saturation tests stop well below this boundary.
  • ⚠️ Verify scoped trace restoration after an injected exception. For chain first-row access, provide a depth-scaling measurement or an enforced restriction on its consumers.
Final Verdict

❌ Block. Fix the unsafe SWWC states, complete representation handling, preserve wide duplicate totals, address chain first-row lookup cost, and make test tracing exception-safe. Add the focused boundary coverage above. Existing threads remain open; none contained an author reply or dismissal requiring a response.

@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 17, 2026
{
UInt64 * header = chunk - 2;
total = (header[0] & RowRefList::PTR_MASK) + RowRefList::MAX_RANGE_REFS;
if (total > std::numeric_limits<UInt32>::max()) [[unlikely]]

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 new run/chain path is supposed to preserve the existing RowRefList reader contract, but these UInt32::max() guards here and in closeKey reintroduce a lower duplicate-key limit than the existing Batch path. RowRefList::rows and the existing Batch tests already handle totals above 2^32, and RangeHeader::total still has 48 bits available, so a key with more than 4,294,967,295 duplicates would now start throwing during SpanWriter::finish even though the old representation could still encode and emit it.

Could we keep accumulating the span total in the header's low 48 bits instead of rejecting it at UInt32::max(), and add a focused chain test just above 2^32 to lock that in?

}
}

void setUseSwwc(bool use_swwc_)

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.

ScatterScratch now exposes a mode toggle, but init(fanout, false) does not allocate either staging_mem or fill. A caller that reuses one scratch across columns can naturally do init(..., false) for a non-SWWC width and later flip this to true; in release builds the next seed writes fill[p] past an empty array, and scatterSwwc / drain then dereference a null staging pointer.

Could we either allocate the SWWC state unconditionally in init, or make setUseSwwc(true) a hard runtime error unless the scratch was initialized with staging?

Comment thread src/Columns/ColumnsScatter.cpp Outdated
case 4: scatterOne<4>(route, data, n, use_swwc, scratch); break;
case 8: scatterOne<8>(route, data, n, use_swwc, scratch); break;
case 16: scatterOne<16>(route, data, n, use_swwc, scratch); break;
/// Width 32 fails `widthSupportsSwwc` - a 16-byte alignment guarantee cannot keep a

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 chunk-kernel contract currently lets seed/drain believe SWWC is active even when the row loop bypasses staging for unsupported widths. A concrete trace is a shard seeded at misalignment 48, then scatterPidChunk(32, ..., /*use_swwc=*/true, scratch): this path writes directly, leaves fill[p] == 48, and advances the cursor to misalignment 16; drain then sees f > m and copies 32 garbage bytes from the never-written staging line past the shard's exact allocation.

Please reject use_swwc && !widthSupportsSwwc(width) before these direct paths (and ideally make scatterPidChunk and ScatterScratch use one authoritative SWWC mode), otherwise a caller can hit heap corruption without tripping any debug check.

/// Apple Silicon does not expose CPUID.
size_t readFromSysctl(unsigned level)
{
const char * name = level == 1 ? "hw.l1dcachesize" : (level == 2 ? "hw.l2cachesize" : "hw.l3cachesize");

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 helper contract in getCPUCacheSize.h says getCPUDataCacheSize(level) returns 0 when the requested level cannot be probed, but this Darwin mapping falls through to hw.l3cachesize for every level other than 1 or 2. That makes getCPUDataCacheSize(0) and getCPUDataCacheSize(4) report the L3 size instead of failure, so callers cannot distinguish an unsupported level from a real probe. Please switch this to an explicit switch and return 0 in the default case.

ColumnsScatter::ScatterKernelId expected_kernel)
{
ColumnsScatter::DispatchTrace trace;
auto * previous = ColumnsScatter::exchangeDispatchTrace(&trace);

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.

exchangeDispatchTrace stores a thread-local raw pointer, but this helper restores it manually. If checkEquivalence unwinds through an unexpected exception from ColumnsScatter::scatter, referenceScatter, or one of the nested column operations, the stack trace is destroyed before line 165 runs and the thread-local still points at freed memory; the next traced scatter can then push_back through a dangling pointer. Please wrap the install/restore in a scoped RAII helper and use it for the repeated trace-capture sites in this file.

Comment on lines +352 to +356
case TAG_CHAIN: {
UInt64 pending = chainHeader()->prev;
while (RangeHeader::prevHasHeader(pending))
pending = reinterpret_cast<const RangeHeader *>(RangeHeader::prevPtr(pending))->prev;
return RangeHeader::prevPtr(pending)[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.

TAG_CHAIN makes firstWord linear in the number of ranges: this loop walks prev through every header until it reaches the oldest span. That keeps the old semantics, but it no longer keeps the old cost. The existing probe-time users still call firstRefWord(mapped) on their hot paths (src/Interpreters/HashJoin/HashJoinMethodsImpl.h:626 / :642, and src/Interpreters/HashJoin/JoinUsedFlags.h:190), so once a partitioned build publishes a deeply chained key, an ANY/SEMI match will pay a full chain walk just to fetch one stable row.

The representation can get deep quickly: OneRowAfterRange in the new gtest already shows that even a single later-pass row adds a header, so a key spread across many build passes degenerates into O(number_of_ranges) work per probe hit. Could we keep the first ref accessible in O(1) for chain words, or explicitly keep TAG_RUN / TAG_CHAIN out of the firstWord users until that invariant exists?

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 78291701979c088a67a69b4ee652ffb57afc4ed0 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

harikrishnan94 and others added 8 commits September 22, 2026 18:34
…r pushdown off the read step

`estimateReadRowsCount` runs index analysis on a `ReadFromMergeTree` step and
memoizes it in the step's `indexes`. `ReadFromMergeTree::applyFilters` builds
the indexes only when they do not exist yet, so an estimate taken before the
filters reach the step leaves a `KeyCondition` built from an empty filter on
it, and the executed read prunes nothing.

Every caller on master estimates after `optimizePrimaryKeyConditionAndLimit`,
so none of them hits this. A caller that estimates before the plan is
optimized passes `keep_index_analysis = false`, and the analysis then goes
into a local `Indexes` object. `selectRangesToReadForEstimation` takes the
same flag. An analysis that already exists is reused either way, and the
default path does exactly what it did before.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…d `worker_id`

`IJoin` had two overloads, `(block, check_limits = true)` and
`(block, num_rows, check_limits = true)`, the second forwarding to the first
everywhere except `ConstantJoin`. There is one pure virtual now:
`addBlockToJoin(const Block & block, size_t num_rows, size_t worker_id, bool check_limits)`.

Every entry point passes `worker_id = 0`, the wrapper joins forward
`num_rows`, `worker_id` and `check_limits` to the join they wrap, and
`check_limits` is spelled out where the old default applied, so behavior does
not change. No implementation reads `worker_id` yet: concurrent fillers will
pass distinct ids, and `IJoin::getMaxBuildThreads` (default 0, the pipeline
decides) is where a join will cap them.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ches

The blocks are replayed into the new `MergeJoin` under the switch lock by the
one thread that triggered the switch, so the id it was called with carries no
information there; pass 0, like every other single-threaded caller.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment-only change from the retro `reduce-complexity`, `humanize` and `plain-prose` pass over this pull request. The `reduce-complexity` pass found nothing to apply.

Every sentence in the edited comments now stays within 25 words. The `selectRangesToReadForEstimation` doc keeps the link between `analyzed_result_ptr` not being set and the re-analysis at execution. The body comment in `selectRangesToReadForEstimation` names `keep_index_analysis` instead of "either way". The blocks wrap at the width of the neighbouring comments.

No statement, signature or default argument changes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Follow-up of the retro three-skill pass (`reduce-complexity`, `humanize`, `plain-prose`) over PR #120002.
Only comment lines in `IJoin.h` change; behaviour and every signature stay the same.

The parameter paragraphs of `addBlockToJoin` now use one idea per sentence.
`PREWHERE` and `CROSS JOIN` are written as SQL names. The four blank `///` separator lines
are gone, because the file does not use them elsewhere. The `getMaxBuildThreads` comment
is split at its semicolon. Every fact of the old text is kept.

`reduce-complexity` found no structural change to make: the layer above (PR #115605) reads
`worker_id` and `getMaxBuildThreads`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the pbnp-scatter-foundations branch from 3c48983 to 043f608 Compare September 22, 2026 13:29
harikrishnan94 and others added 4 commits September 23, 2026 15:20
`TwoLevelHashTable` no longer has `isFixedRangeStorage`, `getRoutedBucket`
or the min/max methods. The trait `is_partitioned_fixed_table` tells the two
table shapes apart, the iterator's `getBucket` is the routed bucket on both,
and only the fixed table restores its min/max optimization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the hash-join-parallel-destroy branch from 2f6e11c to eda991e Compare October 6, 2026 07:20
@harikrishnan94
harikrishnan94 removed this pull request from stack #120423 October 6, 2026 07:36
@harikrishnan94
harikrishnan94 removed this pull request from stack #124166 October 7, 2026 12:21
@harikrishnan94
harikrishnan94 changed the base branch from hash-join-parallel-destroy to uhj 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 2 commits October 14, 2026 09:56
`uhj` was rewritten after this branch was cut, so a plain merge conflicts in about a hundred files that this branch never changed. The merge result is the new `uhj` plus only what this branch adds on top of the old `uhj` and the parallel destroy change: the column scatter kernels, the run and chain tags for `RowRefList`, `DuplicateSpans.h` and the CPU cache size helpers.

The one conflicting hunk, in `HashJoin.cpp`, annotated `CollectorNonJoined` with `ALWAYS_INLINE`. The new `uhj` no longer has that struct, so the hunk is dropped and the file is the one from `uhj`.

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]>
pids_per_source[b].size());
/// One virtual call per chunk buys the same-concrete-type contract the raw-byte kernels
/// would otherwise violate silently.
if (sources[b]->getDataType() != sources[0]->getDataType())

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.

[P2] Normalize detached columns before inspecting their type

The wrapper-removal contract is bypassed for a top-level ColumnBLOB. Even with one source, matching pid and row counts, and one shard, this loop calls getDataType on source 0. ColumnBLOB::getDataType always throws LOGICAL_ERROR (src/Columns/ColumnBLOB.h:167), so execution never reaches convertToFullIfWrapped at line 851, whose detached conversion would reconstruct the regular column. Nested detached columns can reach normalization through their enclosing composite, making the behavior depend on where the wrapper occurs.

Please remove detached wrappers before inspecting types or taking the compact-constant path, and validate the resulting columns. Add a focused test for a detached source by itself and mixed with an equivalent regular source in both orders.

Brings in the latest merge of master into `uhj`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
/// type with a dedicated kernel implements `structureEquals`; the fallback types need not.
if (kernel_id != ScatterKernelId::Fallback)
for (size_t b = 1; b < sources.size(); ++b)
chassert(sources[b]->structureEquals(*sources[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.

[P2] Accept independently widened LowCardinality indexes

A valid multi-source batch can contain two LowCardinality(String) columns whose dictionaries require different index widths: one with a few distinct values uses ColumnUInt8, while one with 300 distinct values uses ColumnUInt16. ColumnLowCardinality::structureEquals compares those index-column types, so this assertion aborts in debug and sanitizer builds before scatterLowCardinality can reach its multi-source merge path. The existing tests use small dictionaries on both sides and miss this boundary. ColumnTuple::structureEquals and ColumnArray::structureEquals recurse into their elements, so the same problem affects nested LowCardinality columns.

Please validate the semantic nested type without requiring identical dictionary-index widths, including inside composites. Add a focused equivalence test with small and >255-entry dictionaries in both source orders.

harikrishnan94 and others added 3 commits October 16, 2026 22:54
Brings in the latest merge of master into `uhj`. It repairs the use of `ResolvedAddress` in `gtest_functions_stress.cpp`, which no longer compiled and stopped the `arm_tidy` build.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Brings in the latest merge of master into `uhj`. It changes the `test_custom_s3_disk_remote_url_allow_hosts` upgrade test, which failed on this branch.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The debug check in `ColumnsScatter::scatter` asserted that all sources have the same structure for every type with a dedicated kernel. The `LowCardinality` kernel hands several sources to the fallback, and the blocks of one such column differ in the width of their indexes, for example `UInt16` and `UInt32`. A join with a `LowCardinality` key therefore failed the assertion in debug and sanitizer builds.

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

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-not-for-changelog This PR should not be mentioned in the changelog pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant