Repository navigation
Conversation
Internal second-model reviewEvery change in this PR was reviewed cold by a second model against the ClickHouse review skill, in Round 1 (head
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260830-224100 |
|
Workflow [PR], commit [b0b5c06] AI ReviewSummaryThis PR extends the direct-gather fast path for right-side Findings❌ Blockers
💡 Nits
Final VerdictChanges requested. |
|
cc @vdimir @nickitat, could you review this? |
|
@groeneai Run the following performance test: |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a direct-gather fast path for hash-join right-side output columns; nothing outside the hash-join emit path is touched. The two flagged ClickBench queries, Q30 (+18.6%) and Q31 (+13.9%), are join-free aggregations that never execute the modified code, and both medians stay inside master's current variance band with CPU essentially flat. Read these as run-to-run variance, not a PR-caused regression. This benchmark set contained no join workload that would actually exercise the new gather path. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Numbers below. 27 cells, and each arm's mechanism is asserted per cell rather than assumed. Setup. Arms. This PR adds no setting, so the gather cannot be switched off on the fix binary and arm (c) has to be the base binary. And since the row store claims every fixed-and-contiguous column of stride <= 32 inclusive, a stride-32 payload only reaches the gather when the row store is off:
Query. Build side is SELECT b.a, b.c FROM numbers_mt(<fanout*N>) AS p JOIN b_<N> AS b ON (p.number % <N>) = b.k
FORMAT Null
SETTINGS join_algorithm = 'hash', query_plan_join_swap_table = 0, max_threads = <T>,
max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0, <arm setting>Metric. Build-side sweep, fanout fixed at 10x
Fanout sweep, build side fixed at 1M rowsAdded because "much greater than the ratio" is the load-bearing part of your question and 10x alone does not answer it.
10k is below this harness's resolution: the whole query is 4-5 ms and the emit delta is 1-2 ms, so the 3.83x in that row is noise, not a result. Over the 24 cells from 100k up, Controls.
So What I read from this.
I can add |
|
The Cause. Every gathering arm keeps its gathered-value count stable by carrying a The job's own
Sweeping the rest of the file rather than only the red arm found five more instances of the same Verified: the shipped tree reproduces |
`HashJoinDirectGatheredValues` was described as counting values copied straight from the stored blocks' raw data. The gather also emits the unmatched rows of an outer JOIN: a zero ref word takes the `memset` branch in `gatherFixedStride`, and the counter is then incremented by the whole output count, so those zero-filled values are counted as well. Measured on arm 2's fixture in 05054 (600 output rows, 500 of them matched, one gathered column): the event reports 600, while an INNER JOIN control over the same column and fixture reports 500. Description only; the counting is unchanged, the event keeps its name, and no test reads the description. Reported by the automated review at ClickHouse#117207 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
Three claims in those comments were false: - "Every arm that must gather carries a `FixedString(40)` column": arms 1e and 7 gather without one, because their gathered column has to stay narrow. - "Arms that must NOT gather carry no such column": the row-list, reranged and ASOF negative arms all read fixtures that carry one. - "dropping one type from `directGatherAdmits` moves it by 1000": there is a single `FixedString` case there and `dg_build` carries both a 7-byte and a 40-byte payload, so dropping that one type moves the count by 2000. The invariant the arms do hold is that each one takes the row store's unstable planner estimate out of its own outcome, either by reading a fixture whose payload is above the inclusive 32-byte limit (9 arms) or by pinning `enable_hash_join_row_store` (9 arms). Comments only; no query, setting or expected value changes. Reported by the automated review of PR ClickHouse#117207. Co-Authored-By: Claude Opus 5 <[email protected]>
…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]>
…istic The stateless test asserts per case whether the gather actually ran, which is the only thing that distinguishes it from the generic path. Arranging that by keeping the estimated fanout below min_rows_ratio_for_hash_join_row_store is not enough: that gate compares against a planner estimate, which moves with accumulated statistics, so under clickhouse-test --test-runs 50 the row store sometimes claimed the narrow columns and the assertion flipped. Every value line stayed correct in all 50 runs; only the arming lines were unstable. Every case that must gather therefore carries one FixedString(40) column. That width is above the row store's inclusive 32-byte limit, so the column stays on the columnar path whichever way the estimate goes, while the narrow typed columns still get value coverage in both configurations. In the two cases that compare the per-column fallback against the all-or-nothing rule of the limit and offset builder, the non-admitted column is a String, which the row store cannot claim either, so the output stays mixed in every configuration. Also trims four source comments to the per-block length the repository asks for. Related: ClickHouse#116833 Co-Authored-By: Claude Opus 5 <[email protected]>
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]>
…ther The `need_columnar_collect` guard added in the previous commit read `num_direct_gather < num_columnar_dst`, which is false when both counters are zero. Zero out of zero is not "every columnar destination was gathered", it is "the admission test never ran": both counters are written only in the `AddedColumns` constructor under `if (!is_join_get && !is_asof_join)`, while an ASOF join is lazy and still selects the `from_columns` emit path from `!has_row_store` alone. The collection then stayed empty and `fillJoinOutputColumns` filled every right-side column from nothing, so an ASOF join returned zero-row right columns against N left rows and tripped `Chunk::checkNumRowsIsConsistent`. Restores the pre-existing behaviour for that path; the two other uses of the same condition in this file already carry the `num_direct_gather > 0` term. Also widen `RowRefList::rows()` and `refWordRows()` to `size_t`. `Batch::total_rows` is a 56-bit field, and both functions narrowed it to `UInt32` on the saturated path. That was harmless while every consumer only accumulated a reserve hint, but the direct gather turns this number into an exact `insertRawUninitialized` allocation and then writes one stride per ref word from the full chain walk, so a key with at least 2^32 rows under-allocated and the copy ran past the destination buffer. No debug assertion fires first: `rows_to_add <= size_to_reserve` still holds because the count only shrinks, and the trailing bounds `chassert` runs after the overrun. All four call sites already receive the value into a `size_t`. Tests. 05054 gains two arms. `arm_asof` covers the guard above, with ten build rows per key at distinct `ts` so the chosen row is unique and the values are deterministic, and 30 unmatched probe keys so both the matched and the default branch of the collection run; its arming line is 0, which also pins the scope contract that ASOF does not gather. `arm1e_per_type_interval` closes the one gap in the exact per-type count: `Interval` is admitted by `directGatherAdmits` and is storable in a table, `cannotBeStoredInTables` not being overridden for it, so the comment claiming otherwise was wrong. It sits on its own fixture rather than in `dg_build` so that no existing reference value moves. Both additions are reference-additive: 4 inserted lines, 0 deleted. A gtest covers the widened count, since the property is not observable from SQL at any size a test can reach and inserting 2^32 refs is not feasible.
Arm 8 is the only test arm covering the in-memory row store and the direct
gather on one chunk. Its oracle was the boolean
`max(ProfileEvents['HashJoinDirectGatheredRows']) > 0`, and two different
configurations satisfy it: with the row store active only `w FixedString(40)`
is gathered (1000 values), with it declined `n1`, `n2` and `w` are (3000). The
value line cannot separate them either, because identical values on both emit
paths is the property this change asserts. So the arm stayed green whether or
not the shape it exists for occurred.
A 52-run census of the previous head measured exactly that: `dg_arm8_row_store`
took 3000 in 45 runs and 1000 in 7. Eligibility depends on an estimate:
`PlannerJoins.cpp` gates the row store on `getHashJoinMatchHint` or
`result_rows_estimation`, and the test runner randomizes
`use_hash_table_stats_for_join_reordering`, so the hint comes and goes.
`min_rows_ratio_for_hash_join_row_store = 0` is the first disjunct of that
gate, so pinning it short-circuits the stats hint, `result_rows_estimation`
and `rhs_size_estimation` at once, leaving `enable_hash_join_row_store`, which
is pinned to 1 and is not randomized. `USING` saves no right key, so the saved
block is `(n1, n2, w)`: `isRowStorageUseful` admits the two `UInt64` columns at
stride 8 and refuses `FixedString(40)` at stride 40, which is exactly the two
columns `initRowStore` needs to not disable itself. The row store therefore
claims `n1` and `n2` and leaves `w` gathered, so 1000 is an identity. Measured
over 50 runs with randomization on, `dg_arm8_row_store` takes one distinct
value, while the unpinned `arm1_hash`, `arm2_defaults`, `arm3_by_blocks` and
`arm4_semi` each still take two.
Arm 8's comment stated a false mechanism: `USING` does not save the right key,
so there were two qualifying columns and not three, and the fanout stops
mattering once the ratio is pinned.
Also here:
- The columnar collection's reserve now sits behind the same
`need_columnar_collect` flag as the collection itself. With every columnar
destination gathered and a row store on the same chunk, both vectors were
sized and never written. `buildOutputFromBlocksLimitAndOffset` already
conditions its own reserve.
- One comment writes `rows` rather than `rows()`, per the rulebook in
`.claude/CLAUDE.md`, which asks for a function's name without the call
parentheses when the text refers to the function itself.
…l gather `gatherColumnDirect` increments once per gathered destination column, so an emit of R rows over C columns adds R * C. `HashJoinDirectGatheredRows` therefore counted values, not rows, while all 17 other `*Rows` events count rows and the three events immediately above it in `ProfileEvents.cpp` are true row counts, so dividing it by `JoinResultRowCount` yields a ratio above 1. The name is public once released: `system.events`, `ProfileEvent_*` in `system.metric_log` and the generated events reference. Renamed to `HashJoinDirectGatheredValues`; what is counted is unchanged, because per-value counting is what makes dropping one type from `directGatherAdmits` move the per-type arm by exactly one payload's worth. The rename is mechanical: a full run of `05054` differs from the committed reference in exactly one line, which is arm 7's, below. Arm 7 was asserting nothing. Its left side was `numbers(10, 10)`, keys 10..19, against a right side of keys 1..9, so the two ranges were disjoint and all 45 output rows came from `NotJoinedHash`, which this change deliberately leaves on the generic fill. `arm7_replicated 0` held for that reason, and would have held just as well if a replicated column had been admitted. It now overlaps the ranges with `numbers(1, 9)`, so every row reaches the probe emit path, and pins the builder the way arm 3 does, because 45 rows over 9 keys leave `output_by_row_list` true and the choice of builder then depends on two settings the runner randomizes. Measured on the arm rather than predicted: `u` (`UUID`), `w` (`FixedString(32)`) and `d` (`Decimal128`) arrive as `ColumnReplicated` and are refused, `i` (`UInt64`) is gathered, so the count is 1 column times 45 rows. The 8-byte boundary the comment states was measured too, by adding a `FixedString(8)` or `Decimal64` payload, which raises the count to 90, against `FixedString(9)` or `Int128`, which leave it at 45. The arm's value line does not move: on `RIGHT JOIN ... USING (k)` the left side contributes no output column, so the same 45 right rows are emitted on either path. Liveness is now two-sided and measured. Admitting replicated columns while still refusing `Nullable` reddens this arm with `Column Replicated(UUID) is not a contiguous block of memory`. Dropping `isFixedAndContiguous` from the refusal chain reddens the `Nullable` arm instead, and dropping the replicated test alone leaves the suite green. That last result is why the comment on the chain changed. It claimed the order of the three tests is what keeps `getRawData` from throwing, which is false in both directions: `replicated_columns[i]` is set by a `typeid_cast`, so it is non-null exactly for a `ColumnReplicated`, and `ColumnReplicated::isFixedAndContiguous` is hard-coded false, so that one test refuses every replicated column by itself. The comment now names the test that does the work and keeps the part that is not obvious, which is that `ColumnConst` forwards both `isFixedAndContiguous` and `getRawData` to a one-element data column and so needs its own test. The redundant disjunct stays: it is one comparison, and the sibling rerange path reads the same field.
Gather Nullable, String, Array, Tuple and Variant right-side columns, and columns stored as ColumnReplicated, straight from the stored blocks. The emit table now resolves a recursive per-column descriptor - the raw plane base pointers per block at every nesting level - and the emit builders gather through it: fixed-width leaves keep the stride-specialized copy, String and Array append slices through their offsets (an Array child is gathered by contiguous ranges, adjacent runs merged), Variant remaps each block's local discriminators onto the destination's, and a replicated column reads its rows through the per-block indexes. A column whose shape is not admitted falls back to the generic path exactly as before, and an unmatched row writes the type default; Enum leaves stay generic because their default is not a zeroed value. Implements the remaining checklist of ClickHouse#116833 Co-Authored-By: Claude Fable 5 <[email protected]>
05054_hash_join_direct_gather failed in CI with a one-line diff, arm7_replicated 45 -> 0, with every value line byte identical. The arming block asserts which arms took the direct gather and, for a few, how many values it copied. The file keeps those numbers stable by giving every gathering arm a FixedString(40) column: the in-memory row store claims fixed-width columns of stride 32 and below, so a 40-byte column stays on the columnar path however the row store's planner estimate lands. Arm 7 cannot follow that rule. Its one gatherable column is the 8-byte arrayJoin output, because lazy replication wraps anything wider in ColumnReplicated and the gather then refuses it, which is the very property the arm exists to check. So when the row store initializes it claims that column too and the arm counts nothing. The failing job's own query_log confirms it: the failing row carries JoinBuildRowStoreMicroseconds = 2 and no HashJoinDirectGatheredValues, while all 85 passing runs of the same query in the same job have the row store counter absent and the gather counter at 45. enable_hash_join_row_store was at its default there, so the row store was admitted by the estimate comparison in PlannerJoins.cpp, which prefers a match count observed on an earlier run over the optimizer's output estimate. Neither input is under the test's control, which is why re-running with the same randomized settings does not reproduce it. Five more arms share the gap, in two shapes. Arms 5b and 5c break the reference when the row store is active, and their comment claimed it could not initialize there at all; measured, it can. Arms 2 and 6 keep passing either way, which is worse: an active row store claims c_enum, so arm 2 can no longer show a wrong Enum8 default, and it claims both nullable payloads, so arm 6 reports zero without the isFixedAndContiguous refusal ever running. Measured, arm 2 gathers 1800 values with the row store off and 600 with it on. All six now pin enable_hash_join_row_store = 0, as arms 1d and 1e already do. The runner randomizes neither row store setting, and no expected value changes. Co-Authored-By: Claude Opus 5 <[email protected]>
`HashJoinDirectGatheredValues` was described as counting values copied straight from the stored blocks' raw data. The gather also emits the unmatched rows of an outer JOIN: a zero ref word takes the `memset` branch in `gatherFixedStride`, and the counter is then incremented by the whole output count, so those zero-filled values are counted as well. Measured on arm 2's fixture in 05054 (600 output rows, 500 of them matched, one gathered column): the event reports 600, while an INNER JOIN control over the same column and fixture reports 500. Description only; the counting is unchanged, the event keeps its name, and no test reads the description. Reported by the automated review at ClickHouse#117207 (comment) Co-Authored-By: Claude Opus 5 <[email protected]>
The gather is no longer limited to fixed-width columns, and an unmatched row's default is no longer always a zero fill (a Nullable is NULL, a Variant a NULL discriminator). Co-Authored-By: Claude Fable 5 <[email protected]>
fa249bc to
cad9f4b
Compare
|
@groeneai the PR now covers the full #116833 checklist: Nullable, String, Array, Tuple, Variant and ColumnReplicated gather too, and the runtime flag experiment is pruned. Rebased on master and force-pushed, tip is cad9f4b. 05054 is green locally across 10+ randomized runs, letting CI do the rest. Emit CPU vs the generic path on a 96-core Neoverse-V2 with a 100M random probe: 2.1-2.5x on the new types, 3.2-3.5x on the 33-col wide table. Numbers and updated description are in the PR body. Continue maintaining the PR from here: CI fallout, bot threads, review comments. |
|
Taken over from On this head |
`Build (arm_tidy)` failed on cad9f4b with two `-warnings-as-errors` diagnostics in `gatherJoinOutputColumns.cpp`: `mapped` in `remapFlatWord` had no initializer (`cppcoreguidelines-init-variables`), and `gatherVariantRows`' `dst_local_by_global` array was left uninitialized (`cppcoreguidelines-pro-type-member-init`, `hicpp-member-init`). Of the `cppcoreguidelines-*` family, `.clang-tidy` enables exactly these two. Applied clang-tidy's own fixes. Neither changes behaviour: every arm of the `switch` assigns `mapped` before it is read, and the `[0, num_variants)` prefix of `dst_local_by_global` is overwritten on the next two lines, so only its never-read tail moves from indeterminate to zero. Checked with clang-tidy-22 under the repo's own `.clang-tidy`, including its `HeaderFilterRegex`, over all six translation units this PR touches: 2 errors before, 0 after. 05054 is 50/50 on the rebuilt binary, and its arm 11 covers `gatherVariantRows` against a `full_sorting_merge` control. Co-Authored-By: Claude Opus 5 <[email protected]>
`DirectGatherColumn` carries `node` and `remap_by_block`; there is no `data_by_block` member, and the source it reads is no longer only fixed width. Two comments still described both. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes39 object files changed (+144.93 KiB total), 1 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units59 translation units recompiled, 708 s compile time in total, 58 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) and (amd_debug, parallel) / 05054_hash_join_direct_gather |
PR-caused: my own new test is not robust. arm5b_mixed_limit_offset gave 1 instead of 0 on the coverage/old-analyzer/s3/DBReplicated config (3 of 3 reruns), and arm7_replicated gave 0 instead of 45 on amd_debug (not reproducible there, 81 reruns) |
PR-caused, I am fixing it in this PR |
AST fuzzer (amd_debug, targeted) / Logical error Equal values are not contiguous within the range assumed to be sorted (STID 2508-36d8) |
pre-existing: 5 unrelated PRs on this check plus 15 on Stress test (arm_debug) in 21d. #113242 is already on this branch and it still fires, so that fix does not cover this instance |
a fix task owns it at P1 (fixing PR link to follow here) |
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases |
trunk: the autopr positive canaries report 0 0 in the old-analyzer lane (84 unrelated PRs, 109 runs, 12 true-master hits in 14d) |
#117364 (external, merged 2026-08-31 22:05Z), not yet on this branch |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
host memory over-commit: the /docker cgroup leaf OOM-kills the nested containers and the whole shard loses its signal (244 PRs, 305 runs, 25 true-master hits in 7d) |
a fix task owns it at P1 (fixing PR link to follow here) |
Only the 05054_hash_join_direct_gather row is mine; I am fixing that test here. #117202 is already on this branch and the container-memory signature still fires. #117364 gets picked up by the master merge that rides with the test fix.
Session id: cron:our-pr-ci-monitor:20260901-003000
…builder `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3)` failed on 920bacd with a one-line diff: `arm5b_mixed_limit_offset` printed 1 where the reference has 0. Every value line was byte-identical, so only the arming assertion moved. The runner's own reproducibility check reported 3 failures out of 3 reruns. `TableJoin::TableJoin(const Settings &, JoinAnalyzeMode, ...)`, the constructor `JoinedTables::makeTableJoin` uses, never assigns `joined_block_split_single_row`, so it keeps its in-class `false`; only the `JoinSettings` constructor the analyzer's join step uses reads the setting. `HashJoinResult::next` selects `buildOutputFromBlocksLimitAndOffset` from that property, so with `enable_analyzer = 0` the three arms that ask for the limit and offset builder silently get the by-blocks builder instead. Arm 5b is the arm where that shows: it exists to pin that the limit and offset builder is all or nothing, and the by-blocks builder decides per column, so it gathers `a` beside the `LowCardinality(String)` the gather cannot take. Arms 5 and 14c admit every column, so both builders agree on their numbers and they were passing while covering the same builder arms 3 and 14 already cover. All three now pin `enable_analyzer = 1`. Measured against a server whose default profile sets `enable_analyzer = 0`, which is how the failing job configures it. The CI diff line reproduces in 0.59 s, and `HashJoinDirectGatheredValues` for arm 5b's shape is 0 with the analyzer and 1000 with the old analyzer while both return the same 1000 rows and the same `cityHash64` sum. The switch is the builder, not the column type: with every payload admitted the count is 2000 either way, and a `Map(String, UInt64)` payload behaves exactly like the `LowCardinality(String)` one. `output_by_row_list` is true on both planners, which `arm3_by_ref_lists` confirms by staying at 0. With the pins the test is 30/30 green on the old-analyzer server with randomized settings and 50/50 on the analyzer one, and no reference value changes. Removing only arm 5b's pin from this tree brings back the same single diff line, so the arm still fails if the property it asserts breaks. Same remedy as ClickHouse#117364, which pinned `enable_analyzer` in `03707_autopr_unsupported_cases` for an optimization only the analyzer's query plan reaches. Co-Authored-By: Claude Opus 5 <[email protected]>
05054 arm 5b on the old-analyzer lane: fixed in
|
| UInt64 * out = words.data(); | ||
| for (const GatherRange & range : ranges) | ||
| for (UInt64 row = range.begin; row < range.begin + range.length; ++row) | ||
| *out++ = RowRef(range.block_no, row).encode(); |
There was a problem hiding this comment.
gatherVariantRanges re-encodes nested Variant element positions through RowRef, but RowRef::row_no is still capped at UInt32 while range.begin / range.length come from Array offsets and can exceed 2^32 within a single build row. HashJoin::addBlockToJoin only bounds outer block rows, so a right-side Array(Variant(...)) that used to work through the generic insertRangeFrom path will now throw RowRef out of range as soon as this optimized gather is admitted. Please either keep these nested positions in a 64-bit representation instead of RowRef, or conservatively refuse the Array(Variant(...)) gather until that encoding can address large nested offsets too.
There was a problem hiding this comment.
Agreed on the mechanism, and I confirmed the premise instead of assuming it: Array(Variant(Int64, UInt64)) on the right of a hash join really does take this path (HashJoinDirectGatheredValues = 2000, against 0 for the full_sorting_merge control), so gatherVariantRanges is live for that shape.
Two corrections to the localisation. GatherRange is already 64-bit in begin and length, and every other ranges gather consumes it as such, so this is the only narrowing on the ranges path. But gatherVariantRows narrows the same way one level down, packing value_row (a ColumnVariant::Offset) into RowRef. Both are sound for a top-level Variant, where an in-variant row cannot exceed the block's rows, and unsound only under an Array, where the coordinate is an element index. The shared reasoning error is that the in-code justification cites addBlockToJoin's per-block row bound (HashJoin.cpp:853), which governs rows, not elements.
The bar is a single stored block holding 2^32 nested elements. ColumnVariant spends 9 bytes per element on bookkeeping alone (a UInt8 discriminator plus a UInt64 offset), so at least 38.7 GiB before any payload. The outcome is also a loud LOGICAL_ERROR naming both numbers, not a truncation.
I have applied neither remedy: both change the coordinate space of this design, and I cannot back such a change with a test at that size. I put the mechanism and one cheap lever to @ harikrishnan94 in a PR comment instead.
Arm 11 reads its Variant straight from MergeTree, and SerializationVariant only ever writes the global variant order (deserializeBinaryBulkWithMultipleStreams throws otherwise), so every stored block of that fixture has an identity local order. The local_to_global_by_block lookup in gatherVariantRows is therefore never exercised: replacing it with the local discriminator leaves arm 11 byte-identical. Arm 11c reaches a non-identity order through a cast instead. Widening a Variant renumbers the global discriminators while the locals keep the source order, so Variant(String, UInt64) casts to locals 1, 2, 0 and Variant(Array(UInt64), UInt64) to 0, 2, 1, and a union of the two puts blocks with two different orders into one join. Measured on this tree: with the remap replaced by the local discriminator, reference lines 1 to 24 (arm 11 and its full_sorting_merge control included) stay byte-identical while arm 11c takes the server down with SIGSEGV in gatherStringRows, reached from gatherVariantRows - the wrong global discriminator routes a row to another variant's child. On the unmodified tree the arm is green on both planners, 50/50 with randomized settings and 30/30 with enable_analyzer = 0 as the profile default. Co-Authored-By: Claude Opus 5 <[email protected]>
Two 32-bit narrowings on coordinates that are not block rows@harikrishnan94 one design call for you.
Both bars are tens of GB inside one block, so I can reproduce neither, and I have therefore changed nothing: widening the coordinate or refusing the shape is a decision about your design, not a defect I can back with a test. If you want the conservative option, both refusals already exist in your own code and already fall back to the generic path:
Your call, and I will implement whichever you pick.
|
| /// The nested column of a replicated column is never larger than the block it deduplicates, | ||
| /// which addBlockToJoin limits to 4G rows. | ||
| chassert(mapped <= std::numeric_limits<UInt32>::max()); | ||
| return (word & 0xFFFFFFFF00000000ull) | static_cast<UInt32>(mapped); |
There was a problem hiding this comment.
remapFlatWord still admits UInt64 replication indexes and then packs the remapped nested row back into RowRef::row_no. convertOffsetsToIndexes already chooses UInt64 once the replicated source column has more than 2^32 rows, while addBlockToJoin only bounds the expanded ColumnReplicated::size(), not that nested source row count. In release builds the chassert disappears here, so the low 32 bits are silently truncated and the direct gather reads the wrong nested value. Please either reject index_width == 8 in resolveEmitColumns, or keep this remapped coordinate in a 64-bit carrier until the final nested fetch instead of storing it back in RowRef.
|
Closing this one. I do not like this change, so I am not taking it forward. @groeneai please stop work on this PR. No more CI fixes and no more review replies here, thank you. A replacement PR will follow. It gathers every column type, not only the ones listed in the issue, |
Closes: #116833
Related: #115254
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up
JOINresult emission for right-side columns in thehashandparallel_hashalgorithms. Values of numeric,
Date/DateTime/Time,UUID,Decimal,FixedString,Interval,IPv4/IPv6,String,Nullable,Array,TupleandVariantcolumns, and ofcolumns stored under lazy replication, are now copied straight from the stored right-side blocks
instead of being resolved one row at a time through the block and its column vector. Results are
unchanged. The
HashJoinDirectGatheredValuesProfileEvent counts the values emitted this way.Description
The lazy emit of a right-side column walked three levels of pure indirection per output row: the
StoredBlockpointer, theColumnPtrin its column vector, then the column object. Since allstored blocks share the saved-block structure, the source column is a function of
block_noalone.StoredColumnsIndex::resolveEmitColumnsbuilds a per-column descriptor mirroring the column'snesting - the raw plane base pointers per block at every level - and both
buildOutputFromBlocksbuilders gather through it, reading the encoded ref words as they are:
StringandArrayappend slices through their offsets; anArraychild is gathered bycontiguous ranges with adjacent runs merged, so a row-list batch of neighboring build rows
becomes a single nested copy;
Nullablegathers the null map plane and the nested column;Tuplerecurses per element over the same ref words;Variantremaps each stored block's local discriminators onto the destination's and gathersper-variant sublists;
ColumnReplicatedreads its rows through the per-block indexes(
row' = indexes[row]).A column whose shape is not admitted falls back to the generic path, per column. An unmatched row
writes the type default.
Enumis not admitted because its default is not a zeroed value, andJSON/Dynamic,LowCardinality,MapandQBitare not either; they all still go through theold un-optimized path.
The in-memory row store claims fixed columns of at most 32 bytes first whenever it initializes;
the gather also covers the types the row store cannot hold at all.
Performance
Measured with a 3-arm protocol on one binary (96-core Neoverse-V2,
parallel_hashdefaults,100M
rand64()probe rows against 100k/10M builds,SELECT *emit, medians of 5 runs;emit-only CPU is the query CPU minus a
count()control over the identical join; the engagementof each mechanism is asserted per run through
system.query_logProfileEvents). "Generic" isthis branch with the gather admission disabled, i.e. the old emit path.
String, 10MTuple(Int64, Float64), 10MVariant(String, UInt64), 10MArray(UInt64), 10MarrayJoin), 10MNullablenumerics, 10MNullablenumerics, 100kInt64/Float64/FixedString(32)), 10MAgainst the row store on the same grid: where it can initialize (two or more fixed columns of at
most 32 bytes) the row store keeps the better emit CPU on 10M narrow payloads (0.5-0.8x of the
gather's) and on the row-list path; 10M
Nullableis 1.5-1.8x in its favor, 100kNullableatparity. For
String/Array/Tuple/Variantbuild sides the row store cannot initialize, andthe gather is the only emit optimization that reaches them.
Workflow [PR]
Sync PR [sync-upstream/pr/117207]