Skip to content

Make arrayCount return UInt64 and rewrite length(arrayFilter(...)) - #113023

Merged
alexey-milovidov merged 56 commits into
masterfrom
rewrite-array-filter-length-to-array-count
Oct 1, 2026
Merged

alexey-milovidov merged 56 commits into
masterfrom
rewrite-array-filter-length-to-array-count

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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.

SELECT length(arrayFilter(x -> (x >= 2), arr));
-- becomes
SELECT arrayCount(x -> (x >= 2), arr);

The rewrite is a new query tree pass in the spirit of the existing RewriteArrayExistsToHasPass, controlled by the new optimize_rewrite_array_filter_length_to_array_count setting (on by default). A new node is built rather than rewriting the arrayFilter node in place, because the filtered array can be referenced elsewhere in the query tree, where it is still an array.

arrayCount counted into UInt32, which silently wrapped for a row whose array has more than 4294967295 matching elements, while length(arrayFilter(...)) counts through ColumnArray::Offset and is exact. It now counts into UInt64 and returns UInt64: this fixes the overflow of arrayCount itself, and makes the rewrite value-preserving for arrays of any size. The result type of arrayCount therefore changes from UInt32 to UInt64; the values are unchanged. Because length and arrayCount now have the same result type, the rewritten node needs no CAST, 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 (default false): setting it to true restores the UInt32 result type, and it is wired into the settings changes history, so compatibility = '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(...))) observe UInt64 there, while the initiator still converts the top-level result to its own UInt32 header. To keep such queries fully unchanged during the upgrade, set array_count_legacy_uint32_result = 1 on the upgraded servers for the users under which shard-side queries execute (with an interserver secret configured that is the initiator's current user; otherwise it is the user from the cluster definition or the remote table 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 the arrayCount documentation and in the setting's description, and both directions of the mixed-version scenario are pinned by the integration test test_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 of length(arrayFilter(...)); in the default UInt64 mode arrayCount now returns a full column there, and in legacy mode the old constant column is kept, so array_count_legacy_uint32_result = 1 restores the old contract of arrayCount completely.

Measured with the setting toggled on the same binary (release, aarch64), best of five, before the CAST was removed:

query setting off setting on
one 30M-element array, half the elements pass 0.38 s 0.33 s 1.15x
one 30M-element array, all elements pass 0.40 s 0.31 s 1.29x
one 10M-element String array 0.40 s 0.37 s 1.08x
5M rows x 32-element arrays, unpredictable predicate 1.42 s 1.29 s 1.10x
1M rows x 8-element String arrays 0.25 s 0.22 s 1.14x
5M rows x 32-element arrays, half the elements pass 1.41 s 1.48 s 0.95x

The gain grows with the array length, which is where the copy that arrayFilter does starts to cost something. The last row loses 5%: for short arrays the copy is cheap, ArrayCountImpl counts the filter with a scalar loop while arrayFilter copies with vectorized code, and the cast to UInt64 added a column of its own - that cast is no longer generated. I did try replacing that scalar loop with countBytesInFilter, 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):

  • Backward Incompatible Change

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

arrayCount now returns UInt64 instead of UInt32, so that it is exact for arrays with more than 4294967295 matching elements; set the new setting array_count_legacy_uint32_result to true (or use compatibility = '26.9') to restore the previous result type. During a rolling upgrade, set array_count_legacy_uint32_result = 1 on 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 to arrayCount(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 the optimize_rewrite_array_filter_length_to_array_count setting.


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

Version info

  • Merged into: 26.10.1.1190-master (included in 26.10 and later)

`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
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b345f12]

Summary: ✅


AI Review

Summary

This PR makes arrayCount exact by default by switching it to UInt64, adds the array_count_legacy_uint32_result compatibility path, and rewrites length(arrayFilter(...)) to arrayCount(...) when the analyzer can prove the result type stays unchanged. The implementation and the compatibility coverage are in good shape overall, but one user-visible part of the backward-incompatible constness change is still under-documented.

Findings

⚠️ Majors

  • [src/Functions/array/arrayCount.cpp:125-130] / [src/Core/Settings.cpp:5029-5033] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/113023#discussion_r4046508690] The compatibility note still says only a predicate folding to constant false changed constness, but x -> NULL goes through the same changed path: FunctionArrayMapped turns Nothing / Nullable(Nothing) into a constant UInt8(0) filter, and default-mode arrayCount now materializes that filter into a full zero column. Users reading either doc surface still miss part of the 26.10 behavior change and of what array_count_legacy_uint32_result restores.
    Suggested fix: mention constant NULL (including typed NULL) alongside constant false in both texts; ideally also extend 04759_array_count_legacy_uint32_result with the x -> NULL constness check so the documented compatibility contract is pinned directly.
Final Verdict

Status: ⚠️ Request changes
Minimum required action: update the arrayCount function note and the array_count_legacy_uint32_result setting description so they document the NULL predicate constness change as well as the false case.

LLVM Coverage Report

Measured on commit b345f12.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 96/101 (95.05%) · 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
`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)".
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed:

  • Fixed the AI-review blocker: arrayCount now counts into UInt64 and returns UInt64, so the rewrite is value-preserving for arrays with more than 4294967295 matching elements (this also fixes the same silent overflow in arrayCount itself, which predates this pull request). The CAST around the rewritten node is no longer needed and was removed.
  • Fixed 04692_rewrite_array_filter_length_to_array_count: it uses EXPLAIN QUERY TREE, which is analyzer-only, so it needs SET enable_analyzer = 1 to run in the old analyzer job.
  • Merged master.

The remaining failure, "Hung check failed, possible deadlock found" in Stress test (arm_release), is unrelated: the hung queries are TRUNCATE TABLE ... replicated_truncate1 SYNC and DROP DATABASE ... SYNC from 00623_replicated_truncate_table_zookeeper_long, and the same hung check fails on master and across dozens of unrelated pull requests every day.

@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.
Comment thread src/Functions/array/arrayCount.cpp Resolved
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Investigated. This is a real, self-inflicted deadlock in tryWaitForReplicaToProcessLogEntry, not infrastructure, and it is not the same cause as the other recent arm_release hung checks. Timeline from clickhouse-server.stress.log.zst, all times 2026.08.02:

  1. 23:36:05.197 the server-side AST fuzzer, running as the finish callback of TRUNCATE TABLE replicated_truncate1 SETTINGS replication_alter_partitions_sync=2 (line 20 of the test), emits one more TRUNCATE ... SYNC SETTINGS replication_alter_partitions_sync = 2 as an internal query 0fc6ef4d.
  2. 23:36:05.234 the test runner's cleanup DROP DATABASE IF EXISTS test_h7r1m2n2g6h4 SYNC (7d86b9f0) arrives 37 ms later over HTTP, takes the database-level DDL guard, and calls flushAndPrepareForShutdown on both tables. Log: replicated_truncate2 ... Start preparing for shutdown / Stopped being leader / Restarting thread finished at .257-.261.
  3. 23:36:05.455 the fuzzed TRUNCATE reaches Waiting for all replicas to process log-0000000006 and then Waiting for r2 to pull log-0000000006 to queue. r2 never pulls it: flushAndPrepareForShutdown already deactivated queue_updating_task for replicated_truncate2, and queueUpdatingTask now returns early on is_readonly && shutdown_prepared_called. log-0000000006 is the last log entry either replica ever touches.
  4. The wait never gives up. stop_waiting in tryWaitForReplicaToProcessLogEntry breaks only on is_dropped, on waiting_itself && (partial_shutdown_called || shutdown_prepared_called || shutdown_called), or on is_active disappearing. Our own shutdown_prepared_called is already true (replicated_truncate1 was prepared for shutdown at .248, before the wait even started), but that disjunct is gated on waiting_itself, which is false here because we are r1 waiting on r2. And is_active for r2 is still present: flushAndPrepareForShutdown does not clear replica_is_active_node - only partialShutdown does, and it is not on this path. replication_wait_for_inactive_replica_timeout was randomized to 30, but that timeout is only consulted inside stop_waiting_inactive, which is itself gated on is_active being gone, so it can never fire while the node exists.
  5. So DROP DATABASE holds the database DDL guard and waits for the table, and the fuzzed TRUNCATE waits for a replica that DROP DATABASE has already silenced. 23:36:15.267 the max_execution_time = 10 deadline fires (CancellationChecker: Cancelling the task because of the timeout) and 23:36:33.631 / 23:37:47 explicit KILL QUERY land - all no-ops, since the wait loop consults no cancellation state at all. system.processes shows is_cancelled: 1, elapsed: 2937 for both. Four later DROP DATABASE ... SYNC and one DETACH DATABASE pile up behind the same guard on getDDLGuard, giving the 7 hung rows.

The bug is that tryWaitForReplicaToProcessLogEntry is an unbounded, uninterruptible wait: it ignores query cancellation, and its liveness test for a remote replica (is_active) does not cover a replica that has been prepared for shutdown by an in-flight DROP/DETACH DATABASE. alter_sync = 2 is not required for that - any SYNC-mode partition operation racing a database drop can reach it. The fuzzer is only the thing that makes it frequent here: it re-issues the test's own TRUNCATE right into the cleanup window.

I am working on the fix in a separate PR and will link it here. Direction I am validating: drop the waiting_itself gate on the shutdown-flag disjunct, so a table that is being shut down stops waiting for any replica rather than only for itself, and make the loop honour the query's cancellation state so a KILL or max_execution_time terminates it with UNFINISHED instead of hanging. Nothing here is caused by #113023.

One note on breadth, since it affects how the check reads: Hung check failed, possible deadlock found has 477 CIDB rows in 30 days (89 on master, 316 distinct pull requests), but that string is a single bucket over unrelated deadlocks. I could not filter it to this signature, because for a hung check CIDB truncates test_context_raw to the last 32 KiB and the processlist dump is cut off, so the artifacts are the only evidence. The 00623 pair is a distinct sub-signature from the ParquetBlockOutputFormat::finalizeImpl one fixed by #112959, and it had no owner before this.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Fix is up: #113228.

It does both halves I described. shutdown_prepared_called and shutdown_called are now checked independently of waiting_itself, since they are terminal latches after which no replica will process the entry, while partial_shutdown_called stays local-only because it is reset when the ZooKeeper session is restored. The wait also consults QueryStatus::checkTimeLimit, as the sibling waitMutationToFinishOnReplicas already does, so KILL QUERY and max_execution_time terminate it.

SYSTEM STOP PULLING REPLICATION LOG gives a deterministic repro. On master the statement hangs, KILL QUERY ... SYNC hangs too, and the concurrent DROP DATABASE ... SYNC deadlocks exactly as in the report; with the fix all three return within seconds and the statement reports UNFINISHED. Reverting either half alone reddens only its own assertion.

alexey-milovidov and others added 2 commits August 4, 2026 21:38
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]>
@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Aug 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed:

  • Addressed the AI-review blocker about the backward-incompatible arrayCount result-type change: the previous behavior is now kept behind the new compatibility setting array_count_legacy_uint32_result (default false). Setting it to true restores the UInt32 result type, and it is recorded in the settings changes history, so compatibility = '26.7' (or older) restores it automatically, including for mixed-version distributed queries. Covered by the new test 04759_array_count_legacy_uint32_result. The changelog category is now Backward Incompatible Change.
  • Merged master, which pulls in Fix a spurious AST fuzzer abort on a recycled node address #113114 — the fix for the Stress test (amd_debug) failure Received signal 6 (internal) in QueryFuzzer::fuzz (it failed on master and across ~130 unrelated pull requests on the same day).

The remaining failures are unrelated:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red on the last run, Stateless tests (amd_msan, WasmEdge, parallel, 2/2), is the known job-budget timeout #113164 — the job was killed at the 9000 s limit at test 6160/6231 with every executed test OK and no failing test. The fix (splitting the msan suite into 3 shards) is in progress: #113414. Merged master and pushed to retrigger CI.

…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`).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed:

The remaining red, AST fuzzer (arm_asan_ubsan) (Logical error: 'Not-ready Set is passed as the second argument for function 'in'' on SELECT ... FROM merge('') WHERE toLowCardinality(0) IN (SELECT ...)), is unrelated to this pull request: it is the known fleet-wide family tracked in #107619, with the fix in progress in #109722.

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b345f123a1c05b9f1ccd4f0d418b063700b0c93e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 2 commits August 7, 2026 06:37
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed:

  • Extended test_backward_compatibility/test_array_count_return_type.py as requested by the review: the mixed-cluster query now also runs from the old coordinator. The old initiator resolves arrayCount as UInt32 and sends no settings, the upgraded shard computes UInt64, and the initiator converts the remote block to its UInt32 header. Verified locally against a real 25.3 container — correct value, UInt32, no header mismatch. Note that the narrowing conversion is modular — exactly the truncation the pre-26.8 implementation performed itself (it counted in size_t and narrowed with static_cast<UInt32>), so an old coordinator over a mixed cluster observes bit-for-bit the pre-upgrade semantics; the exact UInt64 behavior turns on only once the coordinator that resolves the type is upgraded.
  • Merged master.

The previous CI run aborted mid-flight (dozens of jobs ERROR/cancelled, including plain build jobs — an infrastructure event, not test failures); the new push triggers a fresh run.

alexey-milovidov and others added 3 commits August 7, 2026 19:44
…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]>
…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]>
…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.
Comment thread src/Functions/array/arrayCount.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI on 5e8fb16 — all four reds are unrelated to this PR (none of the failing paths involves arrayCount, arrayFilter, or the analyzer pass):

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
alexey-milovidov and others added 2 commits September 9, 2026 05:44
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status on 972e4de8fe83: all four reds are unrelated to this PR and already tracked.

Pushed in this pass:

  • Addressed the AI Review "Request changes" action: test_backward_compatibility/test_array_count_return_type.py now also asserts the shard-local byteSize(arrayCount(...)) wrapper under compatibility = '26.8', so the settings-changes-history path is pinned end to end and not just via the coordinator-side header. Verified locally (integration test passes).
  • Merged master (GitHub reported CONFLICTING, but the merge applied with zero conflicted files — a stale flag). Incremental ninja clickhouse green; both settings remain in the 26.9 block, which still matches master's version.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~4600 commits behind). The only conflict was in SettingsChangesHistory.cpp: master has opened the 26.10 block, so the entries for optimize_rewrite_array_filter_length_to_array_count and array_count_legacy_uint32_result moved from 26.9 to 26.10. Accordingly, the version boundary in the arrayCount documentation, the setting description, the PR description, the integration test and 04759_array_count_legacy_uint32_result is now 26.10, and compatibility = '26.9' (or older) restores the UInt32 result. Verified locally after an incremental build: both stateless tests match their references and test_backward_compatibility/test_array_count_return_type.py passes.

Comment thread src/Functions/array/arrayCount.cpp Outdated

:::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`.

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.

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.

@alexey-milovidov alexey-milovidov Sep 24, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

NULL still belongs in the compatibility note. The current code routes it through the same changed path as x -> 0:

  • FunctionArrayMapped turns a Nothing / Nullable(Nothing) lambda result into a constant UInt8(0) filter (src/Functions/array/FunctionArrayMapped.h:406-410).
  • In default mode, ArrayCountImpl now materializes any constant-false filter as a full zero column instead of a ColumnConst (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.

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.

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.

alexey-milovidov and others added 3 commits September 24, 2026 20:55
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (one conflict in SettingsChangesHistory.cpp, both entries kept in the 26.10 block) and pushed 466a2847b153. The reds on the previous head a9629b1451d8 are unrelated to this PR:

…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
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into master with commit 0da3d28 Oct 1, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the rewrite-array-filter-length-to-array-count branch October 1, 2026 16:46
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — title/description suggestions:

Description (currently incomplete):

  • Why: Says 'the values are unchanged' and treats only distributed queries as affected. Does not mention that MergeTree stores arrayCount key/index values in binary form with the old type, or that MV aggregate states are typed by it.

  • Suggested addition:

    MergeTree tables created before 26.10 with arrayCount in a partition key, sorting key or skip index store UInt32 values in partition.dat, primary.idx and skip-index granules. Materialized views with *State(arrayCount(...)) have AggregateFunction(..., UInt32) columns. These tables need array_count_legacy_uint32_result = 1 (or compatibility = '26.9') in the server's default profile before the first start of the new version, and for as long as the tables exist.

Ignore if intentional.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

The fix is #114053 (merged 2026-08-13). CIDB has no STID 1464-* reports since then, against 11 in the five days before it.

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

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). 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