Repository navigation
Make arrayCount return UInt64 and rewrite length(arrayFilter(...)) - #113023
Conversation
`arrayFilter` builds an array of the elements that pass the predicate, and `length` then throws that array away and keeps only its size. `arrayCount` computes the same number without materializing anything. The rewrite is done by a new query tree pass, controlled by the `optimize_rewrite_array_filter_length_to_array_count` setting, in the spirit of the existing `RewriteArrayExistsToHasPass`. The result is cast back to `UInt64` because `length` returns `UInt64` while `arrayCount` returns `UInt32`, so the type of the column does not change. A new node is built instead of rewriting the `arrayFilter` node in place, because the filtered array can be referenced elsewhere in the query tree, where it is still an array. Related: #2120
|
Workflow [PR], commit [b345f12] Summary: ✅
AI ReviewSummaryThis PR makes Findings
Final VerdictStatus: LLVM Coverage ReportMeasured on commit b345f12.
Changed lines: Changed C/C++ lines covered: 96/101 (95.05%) · Uncovered code |
…r-length-to-array-count
`ArrayCountImpl` returned `UInt32`, so `arrayCount` silently wrapped for a row whose array has more than `4294967295` matching elements, while `length(arrayFilter(...))` - which counts through `ColumnArray::Offset`, a `UInt64` - stayed correct. The rewrite added in this pull request therefore restored only the *type* of the result and not its value, and, being enabled by default, turned such a query into a wrong answer. `arrayCount` now counts into `UInt64` and returns `UInt64`, which fixes the overflow of `arrayCount` itself and makes the rewrite value-preserving for arrays of any size. As both `length` and `arrayCount` now return `UInt64`, the `CAST` around the rewritten node is gone as well - the pass only rewrites when the two result types match. Addresses the review finding on #113023 Also add `SET enable_analyzer = 1` to the test: `EXPLAIN QUERY TREE` is analyzer-only, and the test failed in the old analyzer run of "Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 1/3)".
|
🕵 Pushed:
The remaining failure, "Hung check failed, possible deadlock found" in @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113023&sha=0a1652b91d1caf7891b704d1415d2ab4f90ffac6&name_0=PR&name_1=Stress%20test%20%28arm_release%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
The pass replaces the `length` node with a new `arrayCount` node, so the alias of the old node has to be carried over to the new one.
|
Investigated. This is a real, self-inflicted deadlock in
The bug is that I am working on the fix in a separate PR and will link it here. Direction I am validating: drop the One note on breadth, since it affects how the check reads: |
|
Fix is up: #113228. It does both halves I described.
|
…r-length-to-array-count
The return type of `arrayCount` changes from `UInt32` to `UInt64` in this pull request, so that the result is exact for arrays with more than 4294967295 matching elements. Per review, such a change of a stable public signature needs a compatibility path: the new setting `array_count_legacy_uint32_result` (default `false`) restores the `UInt32` result type, and is wired into the settings changes history, so `compatibility = '26.7'` (or older) restores it automatically - including for mixed-version distributed queries. In legacy mode the `length(arrayFilter(...))` rewrite does not fire, because the pass requires the result types to match. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Pushed:
The remaining failures are unrelated:
|
…r-length-to-array-count
|
🕵 The only red on the last run, |
…r-length-to-array-count
…hange The AI review asked to prove that a new coordinator can query a mix of old and new servers with `array_count_legacy_uint32_result = 1` (or `compatibility` set to an older version) without a type mismatch: the coordinator builds a `UInt32` header, new servers compute `UInt32` because the setting is forwarded to them, and old servers compute `UInt32` natively while ignoring the unknown setting (it is not marked `IMPORTANT`).
|
🕵 Pushed:
The remaining red, |
Build profile diff (arm_release)Commit See the job log for details. |
An old (pre-26.8) coordinator resolves `arrayCount` as `UInt32` and sends no settings to the shards, so an upgraded shard computes `UInt64` and the initiator converts the remote block to its `UInt32` header. That conversion is a modular cast — the same truncation the old implementation performed itself (it counted in `size_t` and narrowed with `static_cast<UInt32>`), so the old coordinator observes exactly the pre-upgrade semantics. Requested by the AI review. Co-Authored-By: Claude Fable 5 <[email protected]>
…r-length-to-array-count
|
🕵 Pushed:
The previous CI run aborted mid-flight (dozens of jobs |
…Count` test The AI review asked to make the remaining mixed-version gap visible: a type-sensitive expression executed on an upgraded shard observes the new `UInt64` type of `arrayCount` before an old coordinator can convert anything. The test now asserts `byteSize(arrayCount(...))` returns 4 and 8 across mixed shards from the old coordinator, and 4 uniformly from a new coordinator with `array_count_legacy_uint32_result = 1` (forwarded to new shards, ignored by old ones). `byteSize` is used instead of the suggested `length(reinterpretAsString(...))` probe because `reinterpretAsString` discards trailing zero bytes, so it returns 1 for both types and cannot distinguish them. #113023 Co-Authored-By: Claude Fable 5 <[email protected]>
…r-length-to-array-count
…t_legacy_uint32_result` The AI review pointed out that the mixed-version claim was overstated: a not-yet-upgraded initiator cannot forward the setting, so type-sensitive expressions evaluated locally on upgraded shards observe `UInt64` unless the setting is pinned in the upgraded servers' default profile. Narrow the claim in the PR description and add the explicit rolling-upgrade guidance to the `arrayCount` documentation note and the setting's description. Co-Authored-By: Claude Fable 5 <[email protected]>
…r-length-to-array-count
…rite `ArrayCountImpl` returned a `ColumnConst` when the predicate folded to a constant false, while `length(arrayFilter(...))` over a non-constant array stays a full column, so `isConstant(length(arrayFilter(x -> 0, materialize([1, 2, 3]))))` flipped from 0 to 1 once the rewrite fired. `arrayCount` now returns a full column of zeros in that branch, in the same way as its constant-true branch already returns a full column; constant folding for a constant array argument is done by the function wrapper anyway. The test asserts that the constness matches with the rewrite on and off.
…constness of `arrayCount` In legacy mode (`array_count_legacy_uint32_result = 1`), a predicate folding to a constant false again produces a constant result column, as before version 26.9, so that the compatibility setting restores the old contract of `arrayCount` completely. The full-column behavior stays for the default `UInt64` mode, where the rewrite of `length(arrayFilter(...))` needs constness parity.
…r-length-to-array-count
|
🕵 CI on 5e8fb16 — all four reds are unrelated to this PR (none of the failing paths involves
|
…r-length-to-array-count
…rapper The mixed-version test pinned shard-local `arrayCount` behavior (via `byteSize`) only for the explicit `array_count_legacy_uint32_result = 1` path. The documented `compatibility = '26.8'` path was checked with the coordinator-side header assertion alone, which would still pass if an upgraded shard stopped deriving `array_count_legacy_uint32_result` from the forwarded `compatibility`, because `ReadFromRemote` narrows the shard's `UInt64` block back to the initiator's `UInt32` header. Add the same `byteSize(arrayCount(...))` assertion under `compatibility = '26.8'`, so the settings-changes-history path is covered end to end. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Status on
Pushed in this pass:
|
…r-length-to-array-count Conflict in `SettingsChangesHistory.cpp`: master opened the `26.10` block, so the entries for `optimize_rewrite_array_filter_length_to_array_count` and `array_count_legacy_uint32_result` move from the `26.9` block to `26.10`. The version boundary mentioned in the `arrayCount` documentation, the setting description, the integration test and the stateless test (`compatibility = '26.9'` now restores the `UInt32` result) is updated accordingly. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
🕵 Merged |
|
|
||
| :::note Use setting `array_count_legacy_uint32_result` to return `UInt32` | ||
| Version 26.10 introduced a backward-incompatible change: `arrayCount` returns `UInt64` instead of `UInt32`, so that the result is exact for arrays with more than `4294967295` matching elements. | ||
| To retain the previous behavior, set setting `array_count_legacy_uint32_result` (default: `false`) to `true`. |
There was a problem hiding this comment.
The arrayCount function note still describes only the UInt32 -> UInt64 result-type change, but the default contract changed in one more observable way here: for a non-constant array and a predicate that folds to false/NULL, isConstant(arrayCount(...)) flips from 1 before 26.10 to 0 now.
Settings.cpp and 04759_array_count_legacy_uint32_result already treat that constness as part of the legacy contract restored by array_count_legacy_uint32_result / compatibility = '26.9', so the source-level docs for arrayCount should mention it explicitly too; otherwise users reading the function docs learn only half of the backward-incompatible change.
There was a problem hiding this comment.
🕵 Done (head 466a2847b153): the arrayCount docs note now also states that for a non-constant array and a predicate folding to a constant false, isConstant(arrayCount(...)) was 1 before 26.10 and is 0 now (matching length(arrayFilter(...))), and that array_count_legacy_uint32_result restores both the UInt32 type and the constness. I left NULL out on purpose: arrayCount(x -> NULL, materialize([1, 2])) stays constant under both behaviors (checked locally), so it is not part of the change.
There was a problem hiding this comment.
NULL still belongs in the compatibility note. The current code routes it through the same changed path as x -> 0:
FunctionArrayMappedturns aNothing/Nullable(Nothing)lambda result into a constantUInt8(0)filter (src/Functions/array/FunctionArrayMapped.h:406-410).- In default mode,
ArrayCountImplnow materializes any constant-false filter as a full zero column instead of aColumnConst(src/Functions/array/arrayCount.cpp:69-77).
So for a non-constant array, isConstant(arrayCount(x -> NULL, materialize([1, 2]))) flips from 1 in legacy mode to 0 now for the same reason as x -> 0. The function note here and the matching setting description in src/Core/Settings.cpp:4729-4730 still describe only the constant-false case, so the backward-incompatible surface is under-documented.
There was a problem hiding this comment.
This still is not fully documented for NULL.
FunctionArrayMapped routes a Nothing / Nullable(Nothing) predicate through the same constant-false path (src/Functions/array/FunctionArrayMapped.h:406-410), and in the default mode arrayCount now materializes that path into a full zero column (src/Functions/array/arrayCount.cpp:69-77). So for a non-constant array, isConstant(arrayCount(x -> NULL, materialize([1, 2]))) flips for the same reason as x -> 0.
The new stateless coverage already encodes that behavior on the rewritten path: tests/queries/0_stateless/04692_rewrite_array_filter_length_to_array_count.sql:64-67 expects the x -> NULL case to be non-constant too. The function note here and the matching setting description in src/Core/Settings.cpp:5030-5032 still mention only the constant-false case, so users reading the compatibility docs still miss part of the 26.10 surface change.
…r-length-to-array-count # Conflicts: # src/Core/SettingsChangesHistory.cpp
Besides the `UInt32` -> `UInt64` result type, 26.10 also changed the constness of the `arrayCount` result for a non-constant array and a predicate folding to a constant false, and `array_count_legacy_uint32_result` restores both. Mention it in the function docs. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A `NULL` predicate yields a constant result under both behaviors, so it is not part of the change. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
🕵 Merged
|
…r-length-to-array-count Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@alexey-milovidov — title/description suggestions: Description (currently
Ignore if intentional. |
|
The fix is #114053 (merged 2026-08-13). CIDB has no STID |
arrayFilterbuilds an array of the elements that pass the predicate, andlengththen throws that array away and keeps only its size.arrayCountcomputes the same number without materializing anything.The rewrite is a new query tree pass in the spirit of the existing
RewriteArrayExistsToHasPass, controlled by the newoptimize_rewrite_array_filter_length_to_array_countsetting (on by default). A new node is built rather than rewriting thearrayFilternode in place, because the filtered array can be referenced elsewhere in the query tree, where it is still an array.arrayCountcounted intoUInt32, which silently wrapped for a row whose array has more than4294967295matching elements, whilelength(arrayFilter(...))counts throughColumnArray::Offsetand is exact. It now counts intoUInt64and returnsUInt64: this fixes the overflow ofarrayCountitself, and makes the rewrite value-preserving for arrays of any size. The result type ofarrayCounttherefore changes fromUInt32toUInt64; the values are unchanged. BecauselengthandarrayCountnow have the same result type, the rewritten node needs noCAST, and the pass only rewrites when the two result types match.Since this changes the stable public signature of an existing function, the previous behavior is kept behind the new compatibility setting
array_count_legacy_uint32_result(defaultfalse): setting it totruerestores theUInt32result type, and it is wired into the settings changes history, socompatibility = '26.9'(or older) restores it automatically on the servers where it is set. For distributed queries, the setting (like any setting) is forwarded from the initiator to the shards, so a query initiated by a server that has it set behaves exactly as before on every shard. The one case it does not cover is a rolling upgrade with a not-yet-upgraded initiator: an old server does not know the setting and cannot forward it, so type-sensitive expressions evaluated locally on already-upgraded shards (for example,byteSize(arrayCount(...))) observeUInt64there, while the initiator still converts the top-level result to its ownUInt32header. To keep such queries fully unchanged during the upgrade, setarray_count_legacy_uint32_result = 1on the upgraded servers for the users under which shard-side queries execute (with an interserversecretconfigured that is the initiator's current user; otherwise it is the user from the cluster definition or theremotetable function - the simplest robust approach is to enable it for all users of the upgraded servers), and remove it once the whole cluster is upgraded. This is documented in thearrayCountdocumentation and in the setting's description, and both directions of the mixed-version scenario are pinned by the integration testtest_backward_compatibility/test_array_count_return_type.py. In legacy mode the rewrite does not fire, because the pass requires the result types to match. The setting also restores the pre-26.10 constness of the result: before this change, a predicate folding to a constant false produced a constant result column even for a non-constant array (unlike every other predicate), which is inconsistent and would have made the rewrite change the constness oflength(arrayFilter(...)); in the defaultUInt64modearrayCountnow returns a full column there, and in legacy mode the old constant column is kept, soarray_count_legacy_uint32_result = 1restores the old contract ofarrayCountcompletely.Measured with the setting toggled on the same binary (release, aarch64), best of five, before the
CASTwas removed:StringarrayStringarraysThe gain grows with the array length, which is where the copy that
arrayFilterdoes starts to cost something. The last row loses 5%: for short arrays the copy is cheap,ArrayCountImplcounts the filter with a scalar loop whilearrayFiltercopies with vectorized code, and the cast toUInt64added a column of its own - that cast is no longer generated. I did try replacing that scalar loop withcountBytesInFilter, but its vectorized path is__SSE2__only, so on the aarch64 machine I measured on it made no difference and I dropped it rather than commit something I could not verify. It may be worth doing separately, measured on x86.Found while profiling #2120, where
length(arrayFilter(x -> (x >= 2), arrayEnumerateUniq(...)))is applied to a single array of 60 million elements.Related: #2120
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
arrayCountnow returnsUInt64instead ofUInt32, so that it is exact for arrays with more than 4294967295 matching elements; set the new settingarray_count_legacy_uint32_resulttotrue(or usecompatibility = '26.9') to restore the previous result type. During a rolling upgrade, setarray_count_legacy_uint32_result = 1on the upgraded servers for the users under which shard-side queries execute (the simplest robust approach is to enable it for all users of the upgraded servers), so that distributed queries initiated by not-yet-upgraded servers (which cannot forward the setting) keep the previous behavior on upgraded shards; remove it after the upgrade is complete. In addition,length(arrayFilter(func, arr))is now rewritten toarrayCount(func, arr), which counts the matching elements instead of building an array of them only to take its size - up to 1.29x faster on long arrays, controlled by theoptimize_rewrite_array_filter_length_to_array_countsetting.Workflow [PR]
Sync PR [sync-upstream/pr/113023]
Version info
26.10.1.1190-master(included in26.10and later)