Skip to content

Build the arrayIntersect hash map from the smallest argument - #113021

Merged
alexey-milovidov merged 11 commits into
masterfrom
arrayintersect-smallest-argument
Aug 13, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
arrayintersect-smallest-argument

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

arrayIntersect filled its hash map from every argument and then rescanned the first one. For arrayIntersect(a, b) with 30 million and 5 million elements that is 35 million insertions into a map sized for the union of both, followed by 30 million lookups.

A value that is missing from any one of the arguments cannot be in the intersection, so it is enough to fill the map from the smallest argument and to only look the other ones up. The map then stays as small as the smallest argument, which is what decides the speed once it no longer fits in cache. Which argument seeds the map does not affect the result, so it is chosen once for the whole column and short arrays pay nothing per row.

Measured with a baseline built from unmodified sources in the same build directory (release, aarch64), best of three:

query baseline this PR
length(arrayIntersect(aa, bb)), 30M vs 5M elements 5.25 s, 1.94 GiB 3.00 s, 1.26 GiB 1.75x
length(arrayIntersect(bb, aa)), 5M vs 30M elements 3.95 s, 1.94 GiB 2.14 s, 1.26 GiB 1.85x
2 x 8M-element arrays 1.59 s, 1.03 GiB 1.26 s, 0.66 GiB 1.26x
3 x 4M-element arrays 0.86 s, 0.62 GiB 0.75 s, 0.62 GiB 1.15x
5M rows x 8-element arrays 1.01 s 1.05 s 0.96x
1M rows x 4-element String arrays 0.26 s 0.26 s 1.00x
arrayUnion, 2 x 8M-element arrays 1.41 s 1.44 s 0.98x
arraySymmetricDifference, 2 x 8M-element arrays 1.39 s 1.42 s 0.98x

The small cases lose 2-4%, reproducibly across best-of-seven runs, even though the new code executes fewer instructions for them (9.97 G against 10.38 G on the 5M x 8 case) - it looks like code layout, the element loop is now instantiated for both the filling and the looking-up argument. I left it as it is: a few percent on arrays that fit in cache in exchange for 1.75x on the arrays where this function actually gets slow. The performance tests run on quieter machines than the one I measured on, so they are the better judge of the small cases.

Reordering the arguments requires the counter to be exact, and that also fixes a wrong result. A value repeated in a later argument used to be counted twice, so it could reach the "present in every argument" count while being absent from an argument in between:

SELECT arrayIntersect([1], [2], [1, 1]);            -- was [1], now []
SELECT arrayIntersect([1, 2], [2], [1, 1, 2]);      -- was [1,2], now [2]
SELECT arraySymmetricDifference([1], [2], [1, 1]);  -- was [2], now [2,1]
SELECT arraySymmetricDifference([1], [2, 2]);       -- was [1], now [2,1]

For arraySymmetricDifference two arguments are enough, because it reads the counter directly instead of rescanning the first argument: the two copies of 2 took the counter to 2, which the old code read as "present in both arguments" and left out of the result.

A value is now counted for an argument only when it was present in every argument before it, so a counter equal to the number of arguments means exactly "present everywhere". arrayUnion is unaffected, it only ever asked whether the counter was non-zero.

The counter used to be exact - if (*value == arg_num) ++(*value);, written together with the comment above it in 5440700. It was relaxed to <= arg_num in d29f0d4, the commit that added arrayUnion in #68989, because that mode takes every key whose counter is non-zero, and with the exact condition a value that first appears in argument k > 0 is inserted as 0, never incremented, and dropped from the union. What the relaxation also allowed - a second increment inside the same array whenever the counter lags behind arg_num - is the wrong result above. This PR does not restore the exact condition in place, it removes the need for the relaxation: arrayUnion no longer looks at the counter at all, because every key of the map is present in at least one of the arguments by construction.

While in the same loop, arrayUnion and arraySymmetricDifference no longer look every key up again through map.find while iterating the map itself, which was one redundant lookup per key.

Related: #2120

Changelog category (leave one):

  • Backward Incompatible Change

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

arrayIntersect and arraySymmetricDifference no longer treat a value repeated inside a single argument as if it appeared in several arguments. Queries relying on the previous behavior can now return different results: arrayIntersect([1], [2], [1, 1]) returns [] instead of [1], arrayIntersect([1, 2], [2], [1, 1, 2]) returns [2] instead of [1, 2], and arraySymmetricDifference([1], [2], [1, 1]) returns [2, 1] instead of [2]. For arraySymmetricDifference two arguments are already enough: arraySymmetricDifference([1], [2, 2]) returns [2, 1] instead of [1]. A value is now counted for an argument only when it was present in every argument before it, so the result contains exactly the values present in all of the arguments. As part of the same change, arrayIntersect builds its hash table from the smallest argument rather than from all of them, which makes it up to 1.85x faster and use a third less memory when the arguments differ a lot in size. arrayUnion is not affected.

Version info

  • Merged into: 26.8.1.1295 (included in 26.8 and later)

`arrayIntersect` filled its hash map from every argument and then rescanned the
first one. For `arrayIntersect(a, b)` with 30 million and 5 million elements that
is 35 million insertions into a map sized for the union of both, followed by 30
million lookups.

A value that is missing from any one of the arguments cannot be in the
intersection, so it is enough to fill the map from the smallest argument and to
only look the other ones up. The map then stays as small as the smallest
argument, which is what decides the speed once it no longer fits in cache.
Which argument seeds the map does not affect the result, so it is chosen once
for the whole column and short arrays pay nothing per row.

Reordering the arguments requires the counter to be exact, and that also fixes a
wrong result: a value repeated in a later argument used to be counted twice, so
`arrayIntersect([1], [2], [1, 1])` returned `[1]` instead of `[]` and
`arraySymmetricDifference([1], [2], [1, 1])` returned `[2]` instead of `[2, 1]`.
A value is now counted for an argument only when it was present in every
argument before it, which means a counter equal to the number of arguments is
exactly "present everywhere".

Related: #2120
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db5b158]

Summary: ✅


AI Review

Summary

This PR makes arrayIntersect seed its hash map from the smallest argument, restores exact per-argument counting so repeated values inside one array no longer produce wrong results in arrayIntersect or arraySymmetricDifference, and fixes the serialized-key arena lifetime on the generic path. I reviewed the current head diff, the full inline-thread history, and the updated tests, and I did not find any remaining correctness, compatibility, or performance issues that warrant a new review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 98/98 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 2, 2026
Comment thread src/Functions/array/arrayIntersect.cpp Resolved
The column pointer, the null map, the overflow mask and the argument index are
the same for every element of an argument, so read them once instead of going
through the lambda's captured references on every element.
@alexey-milovidov
alexey-milovidov marked this pull request as ready for review August 2, 2026 18:32
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is a self-contained optimization of the arrayIntersect/arrayUnion/arraySymmetricDifference array function (smallest-argument map seeding plus arena/lookup cleanup). None of the flagged queries call those functions: ClickBench Q17 and TPC-H Q4 sit entirely off the changed code path, so their flagged deltas (Q17 -16.9%, Q4 +10.9%) are run-to-run variance and have been downgraded to not_sure. ClickBench Q18 was correctly suppressed within master's variance band. No plausible PR-caused regression or improvement was found in this benchmark set; a targeted arrayIntersect microbenchmark would be the right place to confirm the intended speedup.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 556 462 -16.9% <0.0001 This PR only touches the arrayIntersect/arrayUnion/arraySymmetricDifference array function; ClickBench Q17 does not call it, so the -16.9% is run-to-run variance, not a PR effect.

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

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1080 1198 +10.9% <0.0001 The only change is inside the arrayIntersect array function; TPC-H Q4 (an EXISTS/order-priority query) never calls it, so the +10.9% cannot be attributed to this PR and reads as variance.

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.

Debug info
  • StressHouse run: 996b1165-c43d-484d-bd07-1d82f15ca7f5
  • MIRAI run: 32baf8f9-acb1-469f-b4cb-c19386fb41d8
  • PR check IDs:
    • clickbench_944816_1786560698
    • clickbench_944830_1786560698
    • clickbench_944836_1786560698
    • tpch_adapted_1_official_944847_1786560698
    • tpch_adapted_1_official_944873_1786560698
    • tpch_adapted_1_official_944887_1786560699

…n build

Two fixes on top of the previous commits.

On the generic `IColumn` path every element has to be serialized into the
function-scoped `arena` before it can be looked up in the map, and that arena is
never rolled back. So a key that the map does not take - every element of a
looked up argument, and every repeated element of the argument that seeds the
map - stayed resident for the whole call, and the memory kept growing with all
of the arguments instead of with the smallest one. `findOrInsertSerialized` now
rolls the arena back whenever the key was not stored, the same way
`keyHolderDiscardKey` does for `SerializedKeyHolder`. The final scan over the
first argument does the same, it only ever looks keys up.

The lambda that estimates the average array size returned both a
`ColumnArray::Offset` and a `size_t`, which are the same type on Linux but not
on Darwin, where the deduced return type of the first `return` did not match the
second one. Its return type is now spelled out.

The test gets the generic path - `Array(Array(...))` and `Array(Tuple(...))`
elements - for all three functions, including a multi-row case that exercises
the rollback across rows.
@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Aug 3, 2026
Comment thread src/Functions/array/arrayIntersect.cpp Resolved
alexey-milovidov and others added 2 commits August 4, 2026 16:13
Address review: on the generic path (`Array(Array(...))`, `Array(Tuple(...))`)
the `Arena` holding the serialized map keys was function-scoped, and
`map.clear()` only advances the `ClearableHashMap` version without freeing
the arena, so the keys inserted for every previous row stayed resident until
the end of the block. Recreate the arena at each row boundary, so the memory
is bounded by one row of the argument that seeds the map.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stress test (amd_tsan) failure is unrelated to this PR: it is the AST fuzzer's std::abort in the visited-nodes loop check (QueryFuzzer.cpp), where a freed node's address is recycled by a later allocation and mistaken for a loop. A fix is already open: #113114. This branch has been updated with the latest master and the review feedback about per-row arena reclamation is addressed in a073320.

Comment thread src/Functions/array/arrayIntersect.cpp Resolved
alexey-milovidov and others added 2 commits August 5, 2026 13:18
Probe-side keys are rolled back after the lookup, which returns
`usedBytes` to zero while the grown chunks stay resident, so a row with
a large probe-side value and an empty seed could leave an oversized
arena in place for the rest of the block. A freshly constructed `Arena`
allocates its first chunk lazily, so `allocatedBytes` is non-zero
exactly when the previous rows left anything behind.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three red checks on commit 53044b7 are all unrelated to this PR:

I will re-merge master once the stress-test fixes land, so the next CI run is clean.

Comment thread src/Functions/array/arrayIntersect.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both red checks on commit 02bca3e are unrelated to this PR:

The review thread about a compatibility setting is answered on the thread: the old duplicate-counting behavior was a wrong result, not an alternative semantics, so it ships ungated as a Backward Incompatible Change.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db5b158ef with master 809fc9a43 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a63b5b574; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.03 MiB 689.09 MiB -2.94 MiB (-0.43%)

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

Object file sizes

4 object files changed (+171.88 KiB total), 0 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/arrayIntersect.cpp.o 1.22 MiB 1.38 MiB +171.89 KiB (+13.80%)

737 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

7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov

alexey-milovidov commented Aug 12, 2026 •

Copy link
Copy Markdown
Member Author

A value repeated in a later argument used to be counted twice

Why was that? Was that on purpose or by coincidence?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

By coincidence - or rather, it is collateral damage from a deliberate change to a neighbouring line.

The condition used to be exact. It was written in 54407002993 (Nov 2019), together with the comment that is still above it:

/// Here we count the number of element appearances, but no more than once per array.
if (*value == arg)
    ++(*value);

== arg_num is exactly "no more than once per array": the counter only moves when it is in lockstep with the argument index, so a counter equal to args means "present in every argument".

It became <= arg_num in d29f0d4c966 (#68989), the commit that added arrayUnion. That mode iterates the map and takes every key whose counter is non-zero:

if (pair && pair->getMapped() >= 1)

and with the exact condition the counter is not non-zero: a value that first appears in argument k > 0 is inserted as 0, 0 == k is false, so it stays 0 and arrayUnion would drop it. Relaxing to <= lets such a counter catch up to 1, which made the union work. That part was on purpose.

What was not on purpose is that <= also allows a second increment inside the same array whenever the counter lags behind arg_num, which is what breaks the intersection: in arrayIntersect([1], [2], [1, 1]) the value 1 gets 1 from the first argument, is absent from the second, and then the two copies in the third take it 1 -> 2 -> 3 = args. The comment above the line was left unchanged and stopped being true.

arraySymmetricDifference was added later (d15a2a4555e) on top of the already relaxed condition and inherited the same behavior. There it is even a two-argument bug: arraySymmetricDifference([1], [2, 2]) returns [1] on master, because 2 is counted twice, reaches the counter 2 = args and is dropped as "present everywhere". I added that case to the test.

This PR does not tighten <= back into == in place, it removes the need for the relaxation: arrayUnion no longer looks at the counter at all, because every key in the map is present in at least one of the arguments by construction. That is what lets the counter go back to meaning exactly "present in every argument up to this one".

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 12, 2026
For `arraySymmetricDifference` a repeated value did not need three arguments
to be miscounted: with two of them, `arraySymmetricDifference([1], [2, 2])`
returned `[1]`, because the two copies of `2` took the counter to 2, which the
old code read as "present in every argument" and excluded from the result.
The test only had three-argument cases, so add the two-argument ones, for the
numeric and for the serialized path.

Both new results were checked against a binary built from this branch, and the
previous ones against 26.7.1: `arraySymmetricDifference([1], [2, 2])` and
`arraySymmetricDifference([1, 1], [2, 2])` returned `[1]` and now return
`[2, 1]`, and `arraySymmetricDifference([[1]], [[2], [2]])` returned `[[1]]`
and now returns `[[2], [1]]`.
@alexey-milovidov
alexey-milovidov removed this pull request from the merge queue due to a manual request Aug 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 12, 2026
Merged via the queue into master with commit a3f55f0 Aug 13, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the arrayintersect-smallest-argument branch August 13, 2026 00:09
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov, what if the smallest array has more duplicates? Could statistics help on this? What about other functions similar to this? Is there an arrayExcept?

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 30, 2026
Since ClickHouse#113021 (a073320, a7ce761) the arena holding the
serialized keys of the generic path is recreated at a row boundary
whenever it holds anything, to bound its memory by one row. `Arena`
allocates its first chunk lazily, so every row that stores a key
allocated a new 4 KiB chunk and incremented `ArenaAllocChunks` and
`ArenaAllocBytes`. The generic path serves every element type except
numbers, `Decimal`, `Date`, `Date32`, `DateTime`, `String` and
`FixedString` (for example `DateTime64`, `UUID`, `IPv4`, `IPv6`, `Enum`,
`Tuple`, `Array`, `Map`) in `arrayIntersect`, `arrayUnion`,
`arraySymmetricDifference` and `arrayJaccardIndex`. The profile event
counters of a thread group are shared by all threads of the query, so the
function stopped scaling with threads: `arrayIntersect` over `DateTime64`
arrays, 4M rows, took 0.264 s with 1 thread and 0.044 s with 8 on 26.6,
and 0.454 s and 0.649 s on 26.8.

Recreate the arena only once it holds more than 64 KiB. Its memory stays
bounded by 64 KiB plus one growth step, or by one row when a single row
needs more; the keys of earlier rows are dead after `map.clear()`, and an
arena grown by a large row is still recreated at the next row boundary.
With 64 KiB the first chunk is kept on 4 KiB, 16 KiB and 64 KiB pages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants