Skip to content

Fix Logical error 'Arguments of plus have incorrect data types' for Array(LowCardinality(...)) sort keys - #103701

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/array-lowcard-plus-monotonicity
Apr 29, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/array-lowcard-plus-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

When a MergeTree table has Array(LowCardinality(...)) in its sort key and a WHERE clause invokes plus / minus between that column and an Array constant of a different element type, the server raises a logical error from FunctionBinaryArithmetic::executeImpl2:

Logical error: 'Arguments of 'plus' have incorrect data types:
'...' of type 'Int16', '...' of type 'LowCardinality(Float64)''.

Reproduction (provided by @vitlibar in #103691):

SET allow_suspicious_low_cardinality_types = 1;
CREATE TABLE t (a Array(LowCardinality(Float64))) ENGINE = MergeTree() ORDER BY a;
INSERT INTO t VALUES ([1.0]), ([3.0]);
SELECT * FROM t WHERE plus(CAST([0] AS Array(Int16)), a) < CAST([5.0] AS Array(Float64));

Root cause

KeyCondition::getMonotonicityForRange for the sort key builds synthetic Array(...) constant columns and calls Base::executeImpl directly. This bypasses the framework's LowCardinality default implementation (which would otherwise call convertLowCardinalityColumnsToFull -> recursiveRemoveLowCardinality).

The pre-existing removeLowCardinality calls strip only the top-level LowCardinality wrapper; an inner one nested inside Array survives. When executeImpl2 enters executeArraysImpl, it strips Array and recurses on the inner element types. The recursive executeImpl then dispatches via castBothTypes / castTypeToEither, which does not recognize DataTypeLowCardinality. The valid flag stays false and the LOGICAL_ERROR is thrown.

Fix

Use recursiveRemoveLowCardinality (which traverses Array, Tuple, Map, Nullable, ...) when normalising the synthetic types in getMonotonicityForRange, so Array(LowCardinality(Float64)) becomes Array(Float64) before Base::executeImpl is invoked. The numeric dispatch then succeeds normally.

Both branches that call Base::executeImpl are covered: const + variable (lines 3217-3253) and variable + const (lines 3255-3277). The fix applies to plus and minus. The multiply / divide branches in the same method only use ret_type for a WhichDataType::isUInt8/... check (no recursive executeImpl call), so they are not affected by this bug and are unchanged.

Verification

  • Pre-fix: server aborts with the logical error above (verified locally with the reproduction from the issue and with the new test).
  • Post-fix: 5/5 runs of the new test pass with full settings randomization.

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 logical error Arguments of 'plus' have incorrect data types thrown by FunctionBinaryArithmetic::executeImpl2 when a MergeTree table had Array(LowCardinality(...)) in its sort key and a WHERE clause used plus / minus between that column and an Array constant of a different element type. KeyCondition::getMonotonicityForRange now strips LowCardinality recursively before invoking the inner numeric dispatch.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Closes #103691.

Version info

  • Merged into: 26.5.1.172

… `Array(LowCardinality(...))` sort keys

When a `MergeTree` table had `Array(LowCardinality(...))` in its sort key
and a WHERE clause invoked `plus` / `minus` between that column and an
`Array` constant of a different element type, the server raised
`LOGICAL_ERROR` from `FunctionBinaryArithmetic::executeImpl2`:

    Logical error: 'Arguments of 'plus' have incorrect data types:
    '...' of type 'Int16', '...' of type 'LowCardinality(Float64)''.

`KeyCondition::getMonotonicityForRange` builds synthetic `Array(...)`
constant columns and invokes `Base::executeImpl` directly, bypassing the
framework's `LowCardinality` default implementation. The pre-existing
`removeLowCardinality` call only strips a top-level `LowCardinality`
wrapper; an inner one inside `Array` survives, and the recursive
`executeArraysImpl` -> `executeImpl` chain eventually reaches the inner
numeric dispatch (`castBothTypes` / `castTypeToEither`) with
`LowCardinality(...)` element types, which the dispatch does not
recognize.

Fix: use `recursiveRemoveLowCardinality` (which traverses `Array`,
`Tuple`, `Map`, `Nullable`, etc.) when normalising the synthetic types
in `getMonotonicityForRange`, so the elements are stripped before
`Base::executeImpl` is invoked.

Closes ClickHouse#103691.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Session id: cron:clickhouse-ci-task-worker:20260429-051500

a) Deterministic repro? Yes. Pre-fix, the exact 4-statement script from #103691 (SET allow_suspicious_low_cardinality_types = 1; CREATE TABLE t (a Array(LowCardinality(Float64))) ENGINE = MergeTree() ORDER BY a; INSERT INTO t VALUES ([1.0]), ([3.0]); SELECT * FROM t WHERE plus(CAST([0] AS Array(Int16)), a) < CAST([5.0] AS Array(Float64));) aborts with exit 134 on every run; the local server log records Logical error: 'Arguments of 'plus' have incorrect data types: '' of type 'Int16', '' of type 'LowCardinality(Float64)''.

b) Root cause explained? Yes. KeyCondition::getMonotonicityForRange for the sort key builds synthetic constant Array(...) columns and invokes Base::executeImpl directly, deliberately bypassing the framework's LowCardinality default implementation (which would normally call convertLowCardinalityColumnsToFull -> recursiveRemoveLowCardinality on both columns and types). The pre-existing removeLowCardinality calls only strip a top-level LowCardinality wrapper; the inner one inside Array(LowCardinality(Float64)) survives. executeImpl2 then enters executeArraysImpl, which strips Array and recurses on the inner element types. The recursive executeImpl2 reaches castBothTypes / castTypeToEither, which only knows about scalar numeric types — it does not recognise DataTypeLowCardinality. The valid flag stays false and the LOGICAL_ERROR at line 3023 is thrown.

c) Fix matches root cause? Yes. The fix swaps removeLowCardinality for recursiveRemoveLowCardinality in getMonotonicityForRange, in both branches that call Base::executeImpl (const + variable at lines 3217-3253 and variable + const at lines 3255-3277). This normalises Array(LowCardinality(Float64)) -> Array(Float64) before Base::executeImpl is called, so the inner numeric dispatch sees the dictionary type. It is the same transformation the framework would have applied if Base::executeImpl had not been invoked directly. The multiply branch in the same method also uses removeLowCardinality, but its ret_type is consumed only by WhichDataType::isUInt8/... and never feeds into a recursive Base::executeImpl call, so it is not affected by this bug and is unchanged.

d) Test intent preserved? / New tests added? New regression test added: tests/queries/0_stateless/04141_array_lowcard_arithmetic_monotonicity.sql. Covers all four code paths in getMonotonicityForRange for plus and minus: plus(const, var), plus(var, const), minus(const, var), minus(var, const), all over a MergeTree ORDER BY column of type Array(LowCardinality(Float64)). The test would crash the server pre-fix (verified) and produces the expected output post-fix.

e) Both directions demonstrated? Yes.

  • Pre-fix (with this commit's src/Functions/FunctionBinaryArithmetic.h reverted): the new test makes the server abort. tmp/ch-server/log/error.log contains: Logical error: 'Arguments of 'plus' have incorrect data types: '' of type 'Int16', '' of type 'LowCardinality(Float64)''.
  • Post-fix: PATH=build/programs:$PATH tests/clickhouse-test --test-runs 5 04141_array_lowcard_arithmetic_monotonicity passes 5/5 with full settings randomization.

f) Fix is general, not a narrow patch?

  • "Same bug pattern elsewhere?" The getMonotonicityForRange method has three other places that use Base::executeImpl directly: the symmetric variable + const branch is fixed in the same patch. The multiply and divide / intDiv branches do not call Base::executeImpl and only use ret_type for scalar WhichDataType checks, so they are unaffected (verified by re-reading lines 3279-3409). I also grep'd src/Functions for other call sites of Base::executeImpl immediately preceded by removeLowCardinality and did not find another instance.
  • "Root cause vs symptom?" recursiveRemoveLowCardinality is the canonical inverse of the framework's convertLowCardinalityColumnsToFull (src/Functions/IFunction.cpp); using it here makes the direct Base::executeImpl invocation behave like the normal framework path. The fix is at the source of the inconsistency (the missing recursive strip), not a defensive null check at the crash site.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Avogar @vitlibar — could you review this? It fixes a logical error thrown by FunctionBinaryArithmetic::executeImpl2 when KeyCondition::getMonotonicityForRange is asked about plus / minus between an Array constant and an Array(LowCardinality(...)) sort-key column: the synthetic call into Base::executeImpl bypasses the framework's LowCardinality default impl, and the existing removeLowCardinality only strips top-level wrappers, so the inner numeric dispatch sees LowCardinality and rejects it. The fix uses recursiveRemoveLowCardinality.

@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [085234c]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness issue in monotonicity evaluation for arithmetic on sort keys containing Array(LowCardinality(...)) by switching to recursive LowCardinality stripping before the internal Base::executeImpl path. The change is focused, aligns with the root cause, and is covered by a targeted stateless regression test for both plus and minus operand orders.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 29, 2026
@@ -3228,7 +3228,9 @@ class FunctionBinaryArithmeticWithConstants : public FunctionBinaryArithmetic<Op

/// This is a bit dangerous to call Base::executeImpl cause it ignores `use Default Implementation For XXX` flags.
/// It was possible to check monotonicity for nullable right type which result to exception.

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.

Small typo in the comment: "which result to exception" should be "which results in an exception".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 085234c. Also backticked Base::executeImpl for consistency with the surrounding code comments.

Address review feedback from clickhouse-gh[bot]:

- 'which result to exception' -> 'which results in an exception'
- Backtick `Base::executeImpl` for consistency with surrounding comments

Comment-only change, no behavior change.

Copilot AI left a comment

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.

Pull request overview

This PR fixes a logical error thrown during key-condition monotonicity checks when plus/minus is used with Array(LowCardinality(...)) in a MergeTree sort key and an Array(...) constant of a different element type. The fix ensures nested LowCardinality wrappers are stripped before calling the inner arithmetic execution path that doesn’t recognize LowCardinality types.

Changes:

  • Use recursiveRemoveLowCardinality (instead of removeLowCardinality) when normalizing argument/return types in FunctionBinaryArithmeticWithConstants::getMonotonicityForRange for plus/minus.
  • Add a stateless regression test covering both const +/- variable and variable +/- const monotonicity branches for Array(LowCardinality(Float64)).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
src/Functions/FunctionBinaryArithmetic.h Recursively strips nested LowCardinality wrappers before calling Base::executeImpl in plus/minus monotonicity checks.
tests/queries/0_stateless/04141_array_lowcard_arithmetic_monotonicity.sql Adds regression test reproducing the Array(LowCardinality(...)) + array-constant mismatch scenario for plus and minus.
tests/queries/0_stateless/04141_array_lowcard_arithmetic_monotonicity.reference Adds expected output for the new stateless regression test.

@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 100.00% (15/15) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Apr 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 29, 2026
Merged via the queue into ClickHouse:master with commit 056e643 Apr 29, 2026
169 checks passed
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: FunctionBinaryArithmeticWithConstants::getMonotonicityForRange in src/Functions/FunctionBinaryArithmetic.h — core code present in all supported branches.

Why: FunctionBinaryArithmeticWithConstants::getMonotonicityForRange and the removeLowCardinality(...) calls predate all currently supported release branches. The LOGICAL_ERROR is reproducible on the unpatched server (version 26.5.1) for Array(LowCardinality(Float64)) sort keys with plus/minus and an Array constant of a different element type. No backport labels are set on the PR; this is a server-side error on valid user SQL and should be backported to all supported branches.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 29, 2026
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.

Unit tests (tsan, function_prop_fuzzer): Logical error: Arguments of 'plus' have incorrect data types

6 participants