Skip to content

Fix arrayFold LOGICAL_ERROR over non-const Array(LowCardinality(T)) - #109462

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-arrayfold-nonconst-lowcardinality
Jul 11, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-arrayfold-nonconst-lowcardinality

Conversation

@groeneai

@groeneai groeneai commented Jul 6, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a LOGICAL_ERROR in arrayFold over a non-const Array(LowCardinality(T)) argument (for example arrayFold((acc, x) -> acc + x, materialize([1, 2, 3]::Array(LowCardinality(Int64))), toInt64(0))), which failed with "Arguments of 'plus' have incorrect data types" (a server abort in debug and sanitizer builds).

Description

Found by the AST fuzzer: Stress test (arm_msan), STID 2735-474b, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109085&sha=2e6b5fbdcbf4ff2a37ec0c006d3775d15bd695f6&name_0=PR&name_1=Stress%20test%20%28arm_msan%29

Root cause: in FunctionArrayFold::executeImpl, the non-const branch built the nested data column passed to the lambda as array_col_concrete->getDataPtr() (the raw LowCardinality column) while stripping LowCardinality from its type via recursiveRemoveLowCardinality. The column and type then diverged: a LowCardinality column carrying a non-LowCardinality type. When the lambda body's binary function (e.g. plus) resolved to a non-LowCardinality result, the default LowCardinality function adaptor did not unwrap the argument, so the function received a LowCardinality column dispatched as its plain type and raised LOGICAL_ERROR. The const branch already avoided this by calling recursiveRemoveLowCardinality(...->convertToFullColumn()) on the column too.

Fix: unwrap LowCardinality from the nested data column in lockstep with its type on the non-const path. recursiveRemoveLowCardinality is a no-op for non-LowCardinality columns and recurses through wrappers, so nested cases like Array(LowCardinality(Nullable(T))) are covered as well.

Version info

  • Merged into: 26.7.1.805 (included in 26.7 and later)

In FunctionArrayFold::executeImpl, the non-const branch passed the nested
data column to the lambda as array_col_concrete->getDataPtr() (the raw
LowCardinality column) while stripping LowCardinality from its type via
recursiveRemoveLowCardinality. The column and type then diverged: a
LowCardinality column carrying a non-LowCardinality type.

When the lambda body's binary function (e.g. plus) resolved to a
non-LowCardinality result, the default LowCardinality function adaptor did
not unwrap the argument, so the function received a LowCardinality column
dispatched as its plain type and threw LOGICAL_ERROR ("Arguments of 'plus'
have incorrect data types") - a server abort in debug and sanitizer builds.

The const branch already avoided this by calling
recursiveRemoveLowCardinality(...->convertToFullColumn()) on the column.
Strip LowCardinality from the nested data column in lockstep with its type
on the non-const path too. recursiveRemoveLowCardinality is a no-op for
non-LowCardinality columns and recurses through wrappers, so nested cases
such as Array(LowCardinality(Nullable(T))) are covered as well.

Found by the AST fuzzer (Stress test (arm_msan), STID 2735-474b).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET allow_suspicious_low_cardinality_types=1; SELECT arrayFold((acc, x) -> acc + x, materialize([1,2,3]::Array(LowCardinality(Int64))), toInt64(0)); aborts every time (SIGABRT / LOGICAL_ERROR) on unpatched master. No fuzzer or randomized settings needed.
b Root cause explained? Non-const executeImpl bound the lambda's array-data column as array_col_concrete->getDataPtr() (raw LowCardinality column) but stripped LowCardinality from the type. Column and type diverge. When the lambda body's plus result is not LowCardinality, the default LC adaptor does not unwrap the argument, so plus gets a LowCardinality column dispatched as plain Int64 → castBothTypes fails → LOGICAL_ERROR at FunctionBinaryArithmetic.h:3166. Stack matches STID 2735-474b (arrayFold.cpp:291 → ColumnFunction::reduce → plus).
c Fix matches root cause? Yes. Unwrap LowCardinality from the data column in lockstep with its type (recursiveRemoveLowCardinality(getDataPtr())), mirroring what the const path already does via recursiveRemoveLowCardinality(convertToFullColumn()).
d Test intent preserved / new tests added? Yes. Existing LC-accumulator cases kept and still produce correct values. Added plain-accumulator regression cases (single/multi-row, two LC arrays, LC(String), empty LC array) that crashed without the fix. 02718_array_fold and doc examples still pass.
e Both directions demonstrated? Yes. The new queries abort (RC=134) on the pre-fix binary and return correct results on the fixed binary; the committed queries stay correct.
f Fix is general across code paths? Yes. This is the single divergent site (const path already correct); root cause fixed at the column/type binding, not a symptom guard downstream in plus.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. recursiveRemoveLowCardinality is a no-op for non-LC and recurses through wrappers. Verified correct results across LowCardinality(Int64), LowCardinality(String), LowCardinality(Nullable(Int64)), two-array, empty-array, and plain-Array (unchanged); const-array path unchanged.
h Backward compatible? Yes. No setting, format, or wire change; only fixes a crash into correct results.
i Invariants and contracts preserved? Yes. The column now satisfies the invariant that a ColumnWithTypeAndName's column and type agree (LC-wrapped column ⟺ LC type). Offsets/scatter/slice logic is unaffected (offsets come from getOffsetsPtr(), independent of the nested data unwrapping).

Session id: cron:clickhouse-worker-slot-0:20260706-023700

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Avogar — could you review this? It fixes an arrayFold LOGICAL_ERROR over a non-const Array(LowCardinality(T)): the non-const path passed the raw LowCardinality data column to the lambda while stripping LowCardinality from its type, so the lambda's binary function received a LowCardinality column dispatched as its plain type. The fix unwraps LowCardinality from the column in lockstep with the type, mirroring the existing const path. Found by the AST fuzzer (STID 2735-474b).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4523b99]

Summary: ✅


AI Review

Summary

This PR fixes arrayFold on non-const Array(LowCardinality(T)) inputs by unwrapping the nested data column in lockstep with the already-unwrapped lambda argument type, and it extends the regression test with the plain-accumulator cases that previously hit LOGICAL_ERROR. I reviewed the current diff, the full arrayFold implementation, the prior PR discussion, and the sibling higher-order array machinery, and I did not find a remaining correctness, compatibility, or coverage issue worth raising.

Final Verdict

✅ No new findings in the current diff.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 6, 2026
@Avogar Avogar self-assigned this Jul 6, 2026
@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c68ee1a

None of the failures are caused by this PR (the diff only touches src/Functions/array/arrayFold.cpp; all failures are in unrelated code paths / chronic trunk signatures). Every failure below has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Block structure mismatch (STID 0993-27f0) chronic trunk logical error (153 PRs / 14 master, 30d) #107719 (ours, open) / #94517 (ours, open)
AST fuzzer (amd_debug, targeted) / Segfault arrayFirstIndex/arrayLastIndex getReturnTypeImpl removeNullable (STID 1719-3ae5) trunk crash (2 PRs / 0 master) #106271 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Inconsistent AST formatting (STID 1941-1bfa) chronic trunk logical error (91 PRs / 5 master, 30d) #109511 (ours, open)
Stateless tests (amd_debug, parallel) / 04061_spilling_hash_join_overflow_limits flaky (33 PRs / 7 master, 30d) #109334 (ours, open)
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 01418_custom_settings flaky (msan/WasmEdge lane, 0 master) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Stress test (amd_tsan) / ThreadSanitizer data race TwoLevelHashTable emplaceNonZeroImpl (STID 1464-2f74) chronic trunk data race (18 PRs / 3 master, 14d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Upgrade check (amd_release) / Error message in clickhouse-server.log benign 192.0.2.1 DatabasePostgreSQL/MySQL background-pool log noise (fixture 04210) #109350 (ours, open) / #108560 (ours, merged)
CH Inc sync — CH Inc sync (private, not actionable)
Mergeable Check / PR — rollups of the above

Session id: cron:our-pr-ci-monitor:20260706-153000

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress-test TSan UniqExactSet::merge two-level data race (STID 1464-2f74): #109389 (ours, open, approved).

Correction to the finish-ledger line above: STID 1464-2f74's write-of-size-8 stack is src/AggregateFunctions/UniqExactSet.h:233 -> HashSetTable::merge -> emplaceNonZeroImpl, i.e. the same uniqExact two-level parallel-merge COW TOCTOU as STID 1464-31ed, not a generic TwoLevelHashTable race. #109389 replaces the racy shared_ptr::use_count() copy-on-write guard with an is_shared atomic flag on the pointee, which fixes this signature.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Ledger follow-up for the 01418_custom_settings failure on Stateless tests (amd_msan, WasmEdge, parallel, 2/2) (head c68ee1a):

Investigated as a full-effort owner. This is a proven ultra-rare non-reproducible transient on the slow msan/WasmEdge lane, unrelated to this PR (diff only touches src/Functions/array/arrayFold.cpp; the test exercises custom-settings declaration/parsing):

  • CIDB, this exact lane, 30d: 6567 OK / 1 FAIL (0.015%) — the single FAIL is this run.
  • The CI job's own randomized-settings diagnosis re-ran with identical settings 4x, all passed ("not reproducible, likely a transient issue").
  • Local repro: 500 iterations of the failing session sequence (the --- modifying --- system.settings WHERE name LIKE 'custom_%' scan that dropped the custom_b NULL row) on a debug server with custom_settings_prefixes — 0 failures.

Not a randomized-setting interaction (pinning would not help) and not reproducible, so no code change or setting pin is warranted. No fixing PR needed for this line.

@Avogar

Avogar commented Jul 7, 2026

Copy link
Copy Markdown
Member

@groeneai merge with master. Also analyze the unrelated failures, especiallt crashes in ast fuzzers and create issues/fixes

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Merged fresh master (branch head 4523b997bddce), CI is re-running.

Analyzed the unrelated failures on the previous run. All three AST-fuzzer crashes were re-verified to still reproduce on current master, and each now has a public issue + fix:

Crash STID Public issue Fix PR
SIGSEGV in removeNullable via FunctionArrayMapped::getReturnTypeImpl (lambda passed as a non-lambda arg of a higher-order function, e.g. arrayFold accumulator) 1719-3ae5 #109682 (new) #106271 (open)
Inconsistent AST formatting — back-quoted type name / multiIf-in-column-type not round-tripping 1941-1bfa #109501 #109511 (open)
Block structure mismatch in UnionStep stream when a UNION/INTERSECT/EXCEPT branch constant-folds to a Const 0993-27f0 #108142 #107719 (open)

The segfault (1719-3ae5) had a fix PR but no public issue, so I opened #109682 with the reproducer, stack, and root cause.

Non-fuzzer unrelated failures: TSan data race in uniqExact two-level merge (1464-2f74) fixed by merged #109389; 04061_spilling_hash_join_overflow_limits flaky fixed by #109334 (#109593).

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.70% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

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

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This is a narrow fix to arrayFold's LowCardinality unwrapping (column stripped in lockstep with the type); no ClickBench query uses arrayFold, so none of the flagged deltas can plausibly be caused by the PR. The two flagged improvements, Q4 (-13.5%) and Q15 (-19.8%), fall inside master's normal variance band and were correctly suppressed to no_change. The three borderline +5% increases on Q28/Q33/Q34 are test-disagreement not_sure calls that, given the off-path diff, are run-to-run variance. Net: no real performance impact expected from this change.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1034 1090 +5.4% 0.0002 Borderline +5.4% with the two tests disagreeing on an intrinsically noisy query; the arrayFold-only diff can't touch this path, so this is run-to-run variance.
⚠️ 33 not_sure 1365 1437 +5.3% 0.0098 Borderline +5.3% with mixed signals from the two tests; the diff only changes arrayFold, which this query does not use, so it stays not_sure.
⚠️ 34 not_sure 1372 1442 +5.1% 0.0044 Borderline +5.1% with mixed test signals; no arrayFold usage here means the PR can't be the cause, consistent with not_sure.

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: f5f1a746-4755-415b-a986-95b4caf71e8f
  • MIRAI run: 4be5bf8d-25fa-410b-b348-302fca6269b0
  • PR check IDs:
    • clickbench_226339_1783733037
    • clickbench_226353_1783733037
    • clickbench_226359_1783733037
    • tpch_adapted_1_official_226365_1783733037
    • tpch_adapted_1_official_226371_1783733037
    • tpch_adapted_1_official_226382_1783733037

@alexey-milovidov
alexey-milovidov merged commit 47b3e4b into ClickHouse:master Jul 11, 2026
173 of 174 checks passed
alexey-milovidov added a commit that referenced this pull request Jul 11, 2026
Pull in the `arrayFold` `LowCardinality` `LOGICAL_ERROR` fix from #109462
(commit c68ee1a), which resolves the pre-existing `AST fuzzer (amd_debug)`
failure on this branch: `Arguments of '...' have incorrect data types` raised
via `arrayFold.cpp:291` -> `ColumnFunction::reduce` on the non-const
`Array(LowCardinality(T))` path. That failure was previously mis-tracked as
#109682 (a distinct `SIGSEGV` in `removeNullable` via `FunctionArrayMapped`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…onst-lowcardinality

Fix arrayFold LOGICAL_ERROR over non-const Array(LowCardinality(T))
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 pr-bugfix Pull request with bugfix, not backported by default 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