Repository navigation
Build the arrayIntersect hash map from the smallest argument - #113021
Conversation
`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
|
Workflow [PR], commit [db5b158] Summary: ✅
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 98/98 (100.00%) · Uncovered code |
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (1 of 22)
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
|
…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.
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]>
|
🕵 The |
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]>
|
🕵 The three red checks on commit 53044b7 are all unrelated to this PR:
I will re-merge |
|
🕵 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. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes4 object files changed (+171.88 KiB total), 0 added.
737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 14 s compile time in total, 7 of them have a recent master baseline. |
Why was that? Was that on purpose or by coincidence? |
|
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 /// Here we count the number of element appearances, but no more than once per array.
if (*value == arg)
++(*value);
It became if (pair && pair->getMapped() >= 1)and with the exact condition the counter is not non-zero: a value that first appears in argument What was not on purpose is that
This PR does not tighten |
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 — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
@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? |
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]>
arrayIntersectfilled its hash map from every argument and then rescanned the first one. ForarrayIntersect(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:
length(arrayIntersect(aa, bb)), 30M vs 5M elementslength(arrayIntersect(bb, aa)), 5M vs 30M elementsStringarraysarrayUnion, 2 x 8M-element arraysarraySymmetricDifference, 2 x 8M-element arraysThe 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:
For
arraySymmetricDifferencetwo arguments are enough, because it reads the counter directly instead of rescanning the first argument: the two copies of2took 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".
arrayUnionis 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_numin d29f0d4, the commit that addedarrayUnionin #68989, because that mode takes every key whose counter is non-zero, and with the exact condition a value that first appears in argumentk > 0is inserted as0, never incremented, and dropped from the union. What the relaxation also allowed - a second increment inside the same array whenever the counter lags behindarg_num- is the wrong result above. This PR does not restore the exact condition in place, it removes the need for the relaxation:arrayUnionno 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,
arrayUnionandarraySymmetricDifferenceno longer look every key up again throughmap.findwhile iterating the map itself, which was one redundant lookup per key.Related: #2120
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
arrayIntersectandarraySymmetricDifferenceno 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], andarraySymmetricDifference([1], [2], [1, 1])returns[2, 1]instead of[2]. ForarraySymmetricDifferencetwo 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,arrayIntersectbuilds 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.arrayUnionis not affected.Version info
26.8.1.1295(included in26.8and later)