Repository navigation
Add column scatter kernels and run/chain tags for RowRefList - #120513
harikrishnan94 wants to merge 20 commits into
Conversation
|
Workflow [PR], commit [7829170] Summary: ✅
AI ReviewSummaryAdds column scatter kernels, shared CPU cache probing, and run/chain representations for Missing context / blind spots
Findings❌ Blockers
💡 Nits
Tests
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. |
| { | ||
| UInt64 * header = chunk - 2; | ||
| total = (header[0] & RowRefList::PTR_MASK) + RowRefList::MAX_RANGE_REFS; | ||
| if (total > std::numeric_limits<UInt32>::max()) [[unlikely]] |
There was a problem hiding this comment.
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_) |
There was a problem hiding this comment.
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?
| 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 |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Commit See the job log for details. |
1b52a61 to
68935a2
Compare
8c6b0f9 to
4e05476
Compare
4e05476 to
4dbcbc5
Compare
90dab8a to
402e660
Compare
4dbcbc5 to
3c48983
Compare
…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]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
3c48983 to
043f608
Compare
…-analysis` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…join-worker-id` Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ons` Co-Authored-By: Claude Opus 5.5 <[email protected]>
2f6e11c to
eda991e
Compare
`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()) |
There was a problem hiding this comment.
[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])); |
There was a problem hiding this comment.
[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.
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]>
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.
HashJoinroutes the rows of a block to build slots with selectors. Nothing splits a block into cache-sized pieces. ARowRefListword is either one inline row or aTAG_BATCHnode fromHashJoin's insert path.getL2CacheSizereads the cache size on its own.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.
RowRefListhas no such layout, and that code does not belong inside the join.ColumnsScattersplits columns into N exact-sized pieces by a per-row shard id.getCPUDataCacheSizeis the one reader, andgetL1CacheSizeandgetL2CacheSizeuse it. TheRowRefListword stays 8 bytes, and every layout shares one reader.HashJoinstill publishesTAG_BATCH. The run and the chain are for the partitioned join, which is not in this layer. No query changes behavior.Changelog category (leave one):
Workflow [PR]
Sync PR [sync-upstream/pr/120513]