Skip to content

Gather hash join output columns directly from the stored blocks - #117207

Closed
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:port-direct-typed-gather-116833
Closed

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:port-direct-typed-gather-116833

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116833
Related: #115254

Changelog category (leave one):

  • Performance Improvement

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

Speed up JOIN result emission for right-side columns in the hash and parallel_hash
algorithms. Values of numeric, Date/DateTime/Time, UUID, Decimal, FixedString,
Interval, IPv4/IPv6, String, Nullable, Array, Tuple and Variant columns, and of
columns 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 HashJoinDirectGatheredValues ProfileEvent 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
StoredBlock pointer, the ColumnPtr in its column vector, then the column object. Since all
stored blocks share the saved-block structure, the source column is a function of block_no alone.

StoredColumnsIndex::resolveEmitColumns builds a per-column descriptor mirroring the column's
nesting - the raw plane base pointers per block at every level - and both buildOutputFromBlocks
builders gather through it, reading the encoded ref words as they are:

  • fixed-width leaves use a stride-specialized copy;
  • String and Array append slices through their offsets; an Array child is gathered by
    contiguous ranges with adjacent runs merged, so a row-list batch of neighboring build rows
    becomes a single nested copy;
  • Nullable gathers the null map plane and the nested column;
  • Tuple recurses per element over the same ref words;
  • Variant remaps each stored block's local discriminators onto the destination's and gathers
    per-variant sublists;
  • a column stored as ColumnReplicated reads 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. Enum is not admitted because its default is not a zeroed value, and
JSON/Dynamic, LowCardinality, Map and QBit are not either; they all still go through the
old 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_hash defaults,
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 engagement
of each mechanism is asserted per run through system.query_log ProfileEvents). "Generic" is
this branch with the gather admission disabled, i.e. the old emit path.

build side emit CPU vs generic wall vs generic
8 x String, 10M 2.2x 1.7x
4 x Tuple(Int64, Float64), 10M 2.3-2.5x 1.4-1.6x
4 x Variant(String, UInt64), 10M 2.4-2.5x 1.6-1.8x
4 x Array(UInt64), 10M 2.1-2.2x 1.5-1.6x
replicated build side (arrayJoin), 10M 2.2-2.3x 1.2-1.3x
8 x Nullable numerics, 10M 2.0-2.2x 1.4-1.6x
8 x Nullable numerics, 100k 2.7-2.8x 1.2-1.3x
8 x plain numerics, 10M 2.2-2.4x 1.4-1.5x
33 columns (Int64/Float64/FixedString(32)), 10M 3.2-3.5x 2.0-2.4x

Against 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 Nullable is 1.5-1.8x in its favor, 100k Nullable at
parity. For String/Array/Tuple/Variant build sides the row store cannot initialize, and
the gather is the only emit optimization that reaches them.


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

@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Every change in this PR was reviewed cold by a second model against the ClickHouse review skill, in
several rounds, and each finding was adjudicated against the source before anything was changed.
Rounds so far: 5 review rounds, 3 approach-review rounds.

Round 1 (head 724515b)

❌ The arming oracle could not see one admitted type falling back. The test asserted only that the
gather ProfileEvent was above zero per arm, and the values of the two paths are
identical by construction, so a type quietly leaving the gather was undetectable. Fixed: a new
arm pins the exact gathered-value count with the row store off, and a mutant deleting one
TypeIndex from the admission list reddens it while all value lines stay byte identical.

⚠️ The reviewer's own suggestion to assert exact counts on the existing arms was refuted by
measurement
and not applied: a 52-run system.query_log census shows four of those arms take two
distinct counter values, because the in-memory row store's initialization follows a planner estimate
that drifts with accumulated statistics. Pinning the row store off in one new arm removes the
estimate from the path instead.

💡 Three comment and dead-collection nits, fixed in the same round.

Round 2 (head c08246b)

❌ A guard added in round 1 suppressed the generic column collection for ASOF joins. Both
admission counters stay zero for ASOF (which skips emit-table resolution yet is still lazy), so the
"everything was gathered" test held vacuously and right-side columns came back empty. Fixed: the
guard now requires at least one gathered column, and a LEFT ASOF JOIN arm covers it, verified to
redden with the old guard restored.

❌ The gather's exact allocation was fed by a 32-bit-truncated row count. Batch::total_rows is
56 bits but RowRefList::rows() narrowed it, which was harmless for its previous consumers (reserve
hints) and is not harmless for an exact insertRawUninitialized size. Fixed at the source: the
count keeps its full width, with a unit test pinning the boundary.

❌ Interval was admitted by the gather but excluded from the per-type oracle, on the incorrect
grounds that it cannot be a table column. Fixed: its own exact-count arm, plus a mutant proving
it reddens.

Round 3 (head 08f09ad)

❌ The arm covering the row store and the gather coexisting could not tell that shape apart from
the ordinary all-gathered one.
With the row store active only the FixedString(40) column is
gathered; without it all three payload columns are, and the arm asserted just "something was
gathered", which both satisfy with identical result values. A 52-run counter census showed the row
store actually initialized in 7 of those 52 runs, so the arm was green in 45 runs where it was not
covering its own subject. Fixed: the arm now pins row store eligibility, which takes the planner
estimate out of the decision, and asserts the exact gathered count. A configuration mutant moves that
count from 1000 to 3000 while every result line stays byte identical, which is precisely the
distinction the previous assertion could not make.

💡 Three nits, fixed in the same round: a method named as f() where the repository rules ask for
f; a comment overstating why the row store initializes for that arm, since a USING join does not
save the right key; and the reserve of a collection that an earlier round had already made dead.

Round 4 (head ba76c86)

Two independent cold reviews of this head converged on the same three findings and found nothing
else. No emit-path behaviour was changed in response.

❌ The new ProfileEvent counted values but was named for rows. It is incremented once per gathered
destination column, so 1000 result rows over 30 gathered columns reported 30000, while all 17
pre-existing *Rows events count rows and this one sits three lines below JoinResultRowCount in the
same list, so dividing the two gave a ratio above 1. The per-value arithmetic is deliberate, because
it is what lets the per-type oracle notice a single type leaving the admission list, so the name was
the defect. Fixed: renamed to HashJoinDirectGatheredValues, counting unchanged.

💡 Two comment and coverage nits, fixed in the same round: a comment claiming that the explicit
ColumnReplicated test has to run first, which is not so because isFixedAndContiguous already
refuses that column on its own; and the replicated-column arm having disjoint key ranges, so all of
its rows came from the non-joined emit path and its counter line could not distinguish the refusal
from having nothing to gather. Both were corrected, and what the arm can and cannot prove is now
stated where it is asserted.

Round 5 (head bb6c9bf)

Two independent cold reviews of this head converged on a single nit and found nothing else. No source
change was made in response, and no blocker or major survived from any earlier round.

💡 The new ProfileEvent's description says every value it counts was copied from the stored blocks'
raw data, but unmatched rows are zero-filled and counted too.
Accurate: the gather writes
memset(out, 0, stride) for a zero ref word, and the counter is then incremented by the whole output
count, so the event measures values that took the direct gather rather than values that were copied.
The number and its magnitude are unaffected, and in a mostly-matching join the difference is nil. Left
as is rather than spending a sixth push, a rebuild and a 50-run re-validation on one clause of a
string; if it should read "handled by the direct gather, including zero-filled defaults", say so and
it is a one-line change. Two further cosmetic nits were recorded and likewise not actioned.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A as a failure: a performance request, no defect and no failing test. The equivalent is deterministic and single-command: the new stateless test produces byte-identical value lines on pristine master and on this branch, and differs only in the HashJoinDirectGatheredValues lines.
b Root cause explained? Emitting one right-side column cost, per output row, a load of the materialized StoredBlock pointer, a dependent load of the ColumnPtr inside the block's column vector, and a dependent load of the column object, before the random value load. The first three are pure indirection: all stored blocks share the saved-block structure, so an output position's source column is a function of block_no.
c Fix matches root cause? It removes exactly those three loads, by caching the raw fixed-width base per block per position in the same place where master already caches the resolved const IColumn *. No new setting, no widened bound, no guard at a symptom site.
d Test intent preserved / new tests added? New 05054_hash_join_direct_gather with 18 cases: 8 assert the new path ran, 6 assert it did not, and 4 assert the exact number of values gathered, so that a single admitted type falling back to the generic path fails the test rather than passing silently. New tests/performance/hash_join_direct_gather.xml, and a new RowRefList gtest for the row count, whose width is not observable from SQL at any size a test can reach. No existing test weakened or removed. Ten mutants (zero-word write, row off-by-one, list head duplication, admitting Enum8, hoisting getRawData above its guard, dropping UInt128 from the admitted list, dropping Interval from it, dropping the zero-admission term from the columnar-collect guard, re-narrowing the saturated row count, and declining the row store in the coexistence case) were each built where they touch source and each reddened the tests on a distinguishable subset of cases; the restored tree is green with matching source checksums. Three further mutants pin which case carries which refusal: admitting ColumnReplicated reddens the replicated case with NOT_IMPLEMENTED, dropping isFixedAndContiguous reddens the Nullable case, and dropping the replicated test alone is green, that last one being why the replicated case now asserts an exact gathered count instead of a boolean.
e Both directions demonstrated? Yes, on the same fixture and server config, with each server's buildId() asserted against the binary it was launched from. Pristine base binary: all 18 value lines identical and every arming line 0. This branch: the same 18 value lines, with 8 arming lines 1, the four exact counts at 30000, 1000, 45 and 1000, and 6 still 0. So the test fails on master and passes here, and only in the lines that say the new code ran.
f Fix is general across code paths? Both buildOutputFromBlocks variants take it, for hash and parallel_hash alike (ConcurrentHashJoin probes through per-slot HashJoin::joinBlock). buildOutputFromRowRefLists and buildJoinGetOutput are deliberately untouched. NotJoinedHash, the other pair of fillJoinOutputColumns call sites, is untouched and structurally out of reach: it collects (StoredBlock *, row) pairs off the hash map with no ref words at all. ASOF and joinGet share the emit builder without resolving the admission table, and the test carries an arm for that shape. Carrier table in the PR description.
g Fix generalizes across inputs (params/datatypes/wrappers)? One payload column per admitted type, all 30 of them (every integer width to 256 bits, BFloat16, both floats, Date, Date32, DateTime, DateTime64, Time, Time64, IPv4, IPv6, UUID, all four decimals, two FixedString widths, and Interval on its own fixture), compared across hash, parallel_hash and full_sorting_merge. Wrappers: Nullable and ColumnReplicated have their own refusal cases; LowCardinality, Sparse and Const are refused by the same conditions; Enum8 is refused by type in a mixed query. Boundaries: unmatched rows, duplicate keys, chunk-splitting limits, mixed admitted and non-admitted output in both builders, the row-store coexistence shape with its eligibility pinned so its gathered count is exact, and a saturated per-key row count above 2^32.
h Backward compatible? Yes. No new or changed setting, so no SettingsChangesHistory.cpp row; no serialization or format change; results are bit identical. The only user-visible addition is one ProfileEvent.
i Invariants and contracts preserved? The invariant relied on is that an output position's raw source base is a function of block_no and stays valid for the lifetime of the resolved emit table. Generation bumps on add, clearEntry and invalidateEmitTable drop the table; shrinkStoredBlocksToFit is already covered by an unconditional SCOPE_EXIT invalidateEmitTable. The one site that mutates a stored column's buffer in place, tryRerangeRightTableDataImpl, was verified unobservable (a reranged join sets data->sorted and routes to buildOutputFromRowRefLists, which is not a gather path), so no extra invalidation call was added. Two contracts of the shared emit builder are asserted rather than assumed: every columnar destination is filled on paths that admit nothing for the gather, and the exact allocation the gather makes is fed by a count wide enough for the 56-bit field behind it. Concurrency contract unchanged: resolution happens once per probe under the existing index mutex and the per-row loop stays lock free. Verified clean under an address,undefined build, 50 randomized runs of the new test, and a 1069-test join sweep against a base-binary control with zero tests failing on this branch that pass on master.

Session id: cron:clickhouse-impl-slot-4:20260830-224100

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b0b5c06]


AI Review

Summary

This PR extends the direct-gather fast path for right-side hash/parallel_hash JOIN output columns to complex and replicated column shapes, and the new coverage closes the earlier Variant local-order blind spot. I still see one silent correctness regression in the replicated gather path and one large-input regression in Array(Variant(...)), so I do not think this is merge-ready yet.

Findings

❌ Blockers

  • [src/Interpreters/HashJoin/gatherJoinOutputColumns.cpp:143-144] The direct gather now admits replicated sources whose index column is UInt64, but remapFlatWord still squeezes the remapped nested row back into RowRef::row_no. In release builds the chassert disappears, so a mapped row above 2^32 - 1 truncates and the gather reads the wrong nested value silently. The old generic path addressed the nested column with a size_t, so this is a new correctness regression, not just a missed optimization.
    Suggested fix: reject index_width == 8 in StoredColumnsIndex::resolveEmitColumns, or keep the remapped coordinate in a 64-bit representation until the nested fetch instead of packing it into RowRef.
  • [src/Interpreters/HashJoin/gatherJoinOutputColumns.cpp:425,510] Variant children under Array reuse RowRef for in-variant element positions, but those positions come from ColumnVariant::Offset / array offsets and are not bounded by addBlockToJoin's 32-bit outer-row limit. Large Array(Variant(...)) build rows that the generic path could emit will now fail with RowRef out of range as soon as the direct gather path is taken.
    Suggested fix: keep nested element positions in a 64-bit carrier here too, or conservatively refuse Array(Variant(...)) direct gather until that representation exists.

💡 Nits

  • [PR body] The description says an unadmitted column falls back to the generic path "per column", but buildOutputFromBlocksLimitAndOffset is all-or-nothing: once one columnar destination is not gatherable, that builder routes every columnar output through the generic path.
    Suggested fix: qualify the description for the limit-and-offset builder.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @nickitat, could you review this? StoredColumnsIndex::resolveEmitColumns already caches the resolved const IColumn * per stored block, so it now also caches that column's raw fixed-width base, and both buildOutputFromBlocks builders copy values straight off the encoded ref words instead of expanding them into (StoredBlock *, row_number) pairs. A zero ref word writes bitwise zero, which is what insertDefaultInto writes for every admitted type, so the values are bit identical and only a new ProfileEvent moves.

@harikrishnan94 harikrishnan94 self-assigned this Aug 31, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Run the following performance test:
Three arms: a) Direct gather with stride 32, b) Rowstore ON c) Rowstore OFF without direct gather.
All 3 in the regime where rowstore is beneficial (>> min_rows_ratio_for_hash_join_row_store) and sweep across thread count T = {8, 16, 32} and build side row count = {10k, 100k, 1M, 10M, 100M}.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 239 284 +18.6% <0.0001 aggregation: ClickBench Q30 is a join-free aggregation, so it never runs the hash-join emit path this PR changes; +18.6% sits inside master's variance band with CPU flat — run-to-run noise.
⚠️ 31 not_sure 317 361 +13.9% <0.0001 aggregation: ClickBench Q31 is a join-free aggregation and cannot exercise the changed hash-join emit path; +13.9% is inside master's variance band with CPU flat — run-to-run noise.

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
  • StressHouse run: 0b4bc343-8fd8-4175-9ef0-b6e784ff8330
  • MIRAI run: f697209f-5c26-4f70-8c26-46c3975fc95f
  • PR check IDs:
    • clickbench_707932_1788248673
    • clickbench_707938_1788248673
    • clickbench_707944_1788248673
    • tpch_adapted_1_official_707956_1788248673
    • tpch_adapted_1_official_707968_1788248673
    • tpch_adapted_1_official_708003_1788248673

@groeneai

Copy link
Copy Markdown
Collaborator Author

Numbers below. 27 cells, and each arm's mechanism is asserted per cell rather than assumed.

Setup. c8id.metal-96xl (384 vCPU, 755 GiB), server pinned to the same fixed 64-core cpuset for every arm so T=32 has headroom. RelWithDebInfo, clang-21, -O3 -march=x86-64-v3. Fix binary built from this PR's head bb6c9bfd42e2f24 (buildId b56f384b...), base from its merge base 88f51c8dbe08130 (buildId 8eaac9d6...), each asserted with buildId() on the running server. One port, one data directory, one fixture: the arms swap by restarting the server, so nothing but the binary and the two settings differs between them. Two passes with the binary alternating per pass; 6 measurements per cell, 4 at 100M.

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:

arm binary settings
a PR head enable_hash_join_row_store = 0
b PR head defaults (enable_hash_join_row_store = 1, min_rows_ratio_for_hash_join_row_store left at 5)
c base enable_hash_join_row_store = 0

Query. Build side is (k UInt64, a UInt256, c UInt256) MergeTree with unique k; probe is numbers_mt(fanout * build_rows), so output rows are fanout * build_rows and the planner evaluates its row-store gate on real estimates:

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. wall is the query_log median. emit-only CPU is median UserTime + SystemTime minus the same figure for a SELECT count() control over the identical join and fixture, which reads the same rows and builds the same hash table but emits no right-side column. That subtraction is what isolates the emit: at 100M the control is about 60% of the query's CPU, so unsubtracted totals understate every ratio.

Build-side sweep, fanout fixed at 10x

build rows T wall ms, median (a/b/c) emit-only CPU ms (a/b/c) b/a c/a
10k 8 4 / 5 / 5 1 / 1 / 2 1.67x 3.83x
10k 16 4 / 5 / 4 2 / 2 / 1 0.89x 0.67x
10k 32 4 / 4 / 5 2 / 2 / 2 1.00x 0.95x
100k 8 13 / 16 / 17 11 / 16 / 19 1.47x 1.72x
100k 16 13 / 15 / 14 13 / 19 / 18 1.39x 1.33x
100k 32 14 / 13 / 15 13 / 19 / 22 1.43x 1.62x
1M 8 63 / 85 / 70 134 / 177 / 185 1.32x 1.39x
1M 16 70 / 81 / 73 199 / 253 / 255 1.27x 1.28x
1M 32 70 / 81 / 70 259 / 340 / 347 1.31x 1.34x
10M 8 875 / 1042 / 848 1577 / 2054 / 2186 1.30x 1.39x
10M 16 753 / 804 / 814 1693 / 2205 / 2383 1.30x 1.41x
10M 32 692 / 804 / 678 2180 / 2920 / 3463 1.34x 1.59x
100M 8 9547 / 11325 / 9062 15313 / 20714 / 19496 1.35x 1.27x
100M 16 8502 / 11194 / 9107 17339 / 23931 / 20598 1.38x 1.19x
100M 32 8330 / 10769 / 6954 16112 / 26451 / 26317 1.64x 1.63x

Fanout sweep, build side fixed at 1M rows

Added because "much greater than the ratio" is the load-bearing part of your question and 10x alone does not answer it.

fanout T wall ms, median (a/b/c) emit-only CPU ms (a/b/c) b/a c/a
5x 8 49 / 61 / 54 104 / 129 / 121 1.24x 1.16x
5x 16 60 / 72 / 68 135 / 176 / 150 1.30x 1.11x
5x 32 51 / 76 / 48 151 / 189 / 183 1.25x 1.21x
10x 8 70 / 84 / 76 122 / 167 / 197 1.37x 1.62x
10x 16 51 / 79 / 61 154 / 246 / 253 1.60x 1.64x
10x 32 64 / 79 / 56 266 / 347 / 350 1.30x 1.31x
50x 8 156 / 193 / 175 554 / 805 / 784 1.45x 1.42x
50x 16 144 / 156 / 150 951 / 1244 / 1230 1.31x 1.29x
50x 32 102 / 159 / 126 1149 / 1361 / 1822 1.18x 1.58x
200x 8 461 / 627 / 571 2037 / 2903 / 3028 1.43x 1.49x
200x 16 461 / 447 / 417 3681 / 4709 / 4527 1.28x 1.23x
200x 32 233 / 399 / 352 3921 / 4575 / 6243 1.17x 1.59x

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, b/a is min 1.17x, median 1.32x, max 1.64x and c/a is min 1.11x, median 1.39x, max 1.72x.

Controls.

  • Armed in all 27 cells. Arm (a): HashJoinDirectGatheredValues is exactly 2 * output_rows (two payload columns) in every cell. Arm (b): JoinBuildRowStoreMicroseconds > 0 in every cell including fanout 5x, so the planner enabled the row store itself at the default ratio, and HashJoinDirectGatheredValues is 0 there, so the row store did claim both stride-32 columns. Zero cells where a mechanism silently failed to run.
  • Cross-binary bias, no-emit control (SELECT count(), same query on both binaries): fix/base CPU 0.88 to 1.13, median 0.96.
  • Cross-binary bias, row store path exercised on both binaries (identical code there): 0.76 to 1.22, median 1.03.

So b/a is one binary on one server and carries no cross-binary confound; c/a carries roughly +-12% of it at T=8 and T=16, and more at T=32.

What I read from this.

  1. The gather is cheaper than the row store inside the row store's own favourable regime, at every size from 100k to 100M and at every T, and the margin does not decay with fanout: 1.24-1.30x at 5x, 1.17-1.43x at 200x. It is not a low-fanout-only win.
  2. The row store additionally pays a build-side transform the gather does not: 0.1 ms at 10k build rows, 10.1 at 1M, 145 at 10M, 2019 at 100M. It scales with build rows and is flat in fanout (8.8 to 9.7 ms at 1M across 5x to 200x), so it does not amortize away.
  3. Emit CPU per emitted value at T=16: gather 6.8-9.9 ns, row store 9.4-12.6 ns, generic 9.0-12.8 ns.
  4. The regression side, stated plainly: the win is on CPU, not reliably on wall clock. At T >= 8 on a 64-core cpuset the query is not CPU-saturated, wall medians carry 10-25% spread, and several individual wall cells favour arm (c), most visibly 100M at T=32 (8330 vs 6954) where arm (a)'s wall minimum, 6547, is nonetheless below arm (c)'s 6641. I would not quote any single wall cell from this table. At these thread counts the gather buys CPU per output value, which shows up under concurrency rather than in single-query latency.
  5. This measures one stride class, so it says nothing about the row store and the gather coexisting on the same join; with a single stride they never do.

I can add parallel_hash, a mixed-stride shape, or a concurrency axis (N clients at fixed T) if any of those is more useful to you than more cells here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The Stateless tests (amd_debug, parallel) red at bb6c9bfd was mine, and it was the test rather
than the gather: one line, arm7_replicated 45 -> 0, with every value line byte identical.

Cause. Every gathering arm keeps its gathered-value count stable by carrying a FixedString(40)
column, which is above the row store's inclusive 32-byte limit and so stays on the columnar path
whichever way the row store's planner estimate lands. Arm 7 cannot do that: 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 property the arm exists to check.
When the row store initializes it claims that column too, and the arm counts nothing.

The job's own query_log settles 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 own output estimate.
Neither input is under the test's control, which is why the 81 same-settings reruns all passed.

4f42c38 pins enable_hash_join_row_store = 0 in six arms, which is what arms 1d and 1e already
did. No expected value changes, and no source file is touched.

Sweeping the rest of the file rather than only the red arm found five more instances of the same
gap, in two shapes. Arms 5b and 5c move 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 pass 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. Arm 2 gathers 1800 values with the row store off
against 600 with it on.

Verified: the shipped tree reproduces 45 -> 0 under a forced row store while the fixed tree
holds 45; three test-side mutants each redden exactly one line and restore green; 1000 randomized
runs green; and the file matches its reference at defaults and under three hostile row-store
configurations.

Comment thread src/Common/ProfileEvents.cpp Resolved
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
`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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 31, 2026
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]>
groeneai and others added 10 commits August 31, 2026 17:03
…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]>
@harikrishnan94
harikrishnan94 force-pushed the port-direct-typed-gather-116833 branch from fa249bc to cad9f4b Compare August 31, 2026 11:35
@harikrishnan94 harikrishnan94 changed the title Gather fixed-width hash join output columns directly from the stored blocks Gather hash join output columns directly from the stored blocks Aug 31, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

@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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Taken over from cad9f4b. I'll carry CI fallout, bot threads and review comments from here.

On this head Config Workflow, Fast test and Style check are green and the build and test matrix is still starting; the one bot thread (the HashJoinDirectGatheredValues description) is resolved. I'll post a finish ledger here when the workflow completes, with an owner against every failure. I won't touch the description you just wrote - if a review asks for a change there I'll propose it here first.

groeneai and others added 2 commits August 31, 2026 14:00
`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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Build (arm_tidy) fixed in 920bacdc

Two -warnings-as-errors diagnostics in gatherJoinOutputColumns.cpp: mapped in remapFlatWord had no initializer (cppcoreguidelines-init-variables), and gatherVariantRows' dst_local_by_global was left uninitialized (cppcoreguidelines-pro-type-member-init, hicpp-member-init). Of the cppcoreguidelines-* family, .clang-tidy enables exactly those two.

I applied clang-tidy's own fixes (= 0 and {}). 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 two lines down, 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. I also corrected two comments of mine that named a data_by_block member DirectGatherColumn does not have.

Two things I measured while in there and deliberately did not change, since both are your call:

  1. Arm 11 does not exercise the per-block Variant discriminator remap. Replacing local_to_global[block_no * num_variants + local] with plain local leaves 05054 green. The arm is not inert: emitting a deliberately wrong local discriminator in the same function does turn it red, so it checks Variant values but not the remap. That fits the fixture, a MergeTree column written in global order, since SerializationVariant restores global order on read and every block's mapping is then identity. A fixture with blocks whose local orders actually differ would close the gap.

  2. gatherVariantRanges narrows nested positions to 32 bits. The ranges coming out of gatherArrayRanges carry 64-bit begin/length, but they are flattened through RowRef(block_no, row), whose constructor throws above UInt32 max. For Array(Variant(...)) the bound that matters is a block's array element count, which addBlockToJoin's 4G row limit does not constrain. I could not construct a block that large to demonstrate it (the offsets plane alone would be about 34 GB), so I left the code alone rather than push a change I cannot test.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b0b5c0660 with master 9f35a2b2a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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

39 object files changed (+144.93 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/gatherJoinOutputColumns.cpp.o new 50.23 KiB +50.23 KiB

716 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

59 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.
The matched translation units cost -38.4 s (-5%) in total before that adjustment.

Job report

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 920bacdcc747f77307100145c5de366871d0812c

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link I will post here when it opens.

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]>
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

05054 arm 5b on the old-analyzer lane: fixed in ebe4dd1f

Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) was the
only PR-caused row in the finish ledger for 920bacdc. One line differed,
arm5b_mixed_limit_offset printing 1 where the reference has 0, every value line byte-identical,
and the runner's own 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 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 get the by-blocks builder instead. Arm 5b is
where that shows: the by-blocks builder decides per column, so it gathers a beside the
LowCardinality(String) the gather cannot take.

Arms 5, 5b and 14c now pin enable_analyzer = 1. Arms 5 and 14c admit every column, so both
builders agree on their numbers and they stayed green while covering the builder arms 3 and 14
already cover. Same remedy as #117364.

Validation, against a server whose default profile sets enable_analyzer = 0: the CI line reproduces
in 0.59 s; after the pins 30/30 green there with randomized settings and 50/50 on the analyzer, with
no reference value changes. Removing only arm 5b's pin brings the same line back. I also forced both
settings the runner randomizes for this file, joined_block_split_single_row and
join_output_by_rowlist_perkey_rows_threshold, over 18 combinations bracketing each fixture's
per-key row count: all green.

03707_autopr_unsupported_cases needs nothing here. Its fixing PR merged at 22:05Z and this
workflow checks out refs/pull/117207/merge, so the run on ebe4dd1f already carries it; I have
not merged master into the branch.

One clause of the description I would like to change rather than change myself, @harikrishnan94: "A
column whose shape is not admitted falls back to the generic path, per column" holds for the
by-blocks and single-ref builders, but buildOutputFromBlocksLimitAndOffset requires every columnar
destination to be admitted, so one unadmitted column moves all of them. That is exactly what arm 5b
pins. Say the word and I will add the qualification.

Also noticed, not raised: the old-analyzer path never carries joined_block_split_single_row at all,
so the setting is inert there; nothing user-visible follows, since it only declines a memory
optimization.

Session id: cron:clickhouse-maint-slot-18:20260901-004800

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();

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Two 32-bit narrowings on coordinates that are not block rows

@harikrishnan94 one design call for you. RowRef packs a 31-bit block number and a 32-bit row number, and its comment justifies that width by addBlockToJoin's per-block row limit (HashJoin.cpp:853). Two sites reuse the same word for a coordinate that is not a block row, so that justification does not reach them.

  1. gatherVariantRanges (gatherJoinOutputColumns.cpp:501-513) and gatherVariantRows (:427), under an Array: the coordinate is a nested element index. Outcome is a loud LOGICAL_ERROR from throwRowRefOutOfRange. Bar is 2^32 elements in one stored block, so at least 38.7 GiB of ColumnVariant bookkeeping alone (a UInt8 discriminator plus a UInt64 offset per element). The path is live: Array(Variant(Int64, UInt64)) gathers 2000 values where the full_sorting_merge control gathers 0. The review bot raised this one; details are in that thread.

  2. remapFlatWord (:127-146), the case 8 branch: the coordinate is a replicated nested row. convertOffsetsToIndexes (ColumnReplicated.cpp:767-776) picks the UInt64 width from offsets.size(), the source row count, while ColumnReplicated::size() is the expanded count that addBlockToJoin bounds. The only guard is chassert, and base/base/defines.h:99-103 compiles it to (void)sizeof(!(x)) outside debug and sanitizer builds, so in release the index truncates and still lands inside the nested column: wrong values, no error. This one is silent, which is why I am flagging it although no bot has.

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:

  • resolveGatherNode (RowRefs.cpp:325) returns false to move the whole output column off the gather.
  • RowRefs.cpp:496 already refuses index widths outside 1, 2, 4 and 8. Dropping 8 refuses exactly case 2 and can never refuse a representable index, because width 8 is chosen only above 2^32 source rows.

Your call, and I will implement whichever you pick.

b0b5c066 also lands arm11c variant local order, closing the blind spot the bot found in arm 11: a cast-widened Variant keeps a non-identity local order, so the per-block remap becomes load-bearing there. With the remap bypassed, arm 11 stays byte-identical and arm 11c segfaults. The description qualification I proposed earlier is still open whenever you get to it.

/// 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);

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.

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.

@harikrishnan94

Copy link
Copy Markdown
Contributor

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,
and it has no fallback to the per-row path.

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Direct typed gather for hash/parallel_hash emit, and remaining column types

2 participants