Skip to content

Expression simplifier treats arithmetic negation as bitwise NOT #24665

Description

@Amogh-2404

Describe the bug

Expr::Negative represents unary minus, but the expression simplifier applies bitwise-NOT identities to it. This produces wrong results for expressions combining unary minus with bitwise AND, OR, or XOR.

To Reproduce

SELECT i, (-i) & i, i | (-i), (-i) ^ i
FROM (VALUES (5), (6)) AS t(i);

Current result:

5  0  -1  -1
6  0  -1  -1

Expected result:

5  1  -1  -2
6  2  -2  -4

Double negation can also hide overflow:

SELECT -(-CAST(-128 AS TINYINT));

This returns -128 after simplification instead of reporting overflow.

Expected behavior

The optimiser should only apply rewrites that are valid for arithmetic negation.

Additional context

Both cases behave correctly when datafusion.optimizer.max_passes is set to 0.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions