Skip to content

fix: keep room for an integer's digits when it is wider than the decimal's variant - #27474

Open
cool9850311 wants to merge 3 commits into
apache:mainfrom
cool9850311:fix-27424-int-decimal32-64-coercion
Open

cool9850311 wants to merge 3 commits into
apache:mainfrom
cool9850311:fix-27424-int-decimal32-64-coercion

Conversation

@cool9850311

@cool9850311 cool9850311 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

#27095 already has #27124 open against it, which fixes it with the same variant-selection
idea this takes (credit to @namanjain24-sudo). Whether this PR should close #27095, or whether
that issue should stay with #27124, is a call for the maintainers: say which you prefer and I
will edit the description. If #27124 lands first, I am happy to rebase this onto it and keep
only the part that removes the ?.

Rationale for this change

An integer compared with or added to a Decimal32 or Decimal64 value returns wrong
rows instead of an error. A Decimal32(9, 2) holding 5.50 compares equal to 5, is
not greater than 5, and 5.50 + 1 returns 6 as an Int64. The same values as
Decimal128 give the right answers.

How many digits an integer needs is known exactly, so the common type of an integer and
a decimal has to keep room for them. It did not, in two ways:

  • coerce_numeric_type_to_decimal32 had no arm for Int32 or wider and
    coerce_numeric_type_to_decimal64 none for Int64, since those integers do not fit
    the variant. Both callers treated that None as "not a decimal case" and fell through
    to the integer rules, which coerce the decimal to an integer and drop its fraction.
  • When the required precision passed the variant's maximum, it was capped while the
    scale was kept, leaving a type the integer could not be cast into at all
    (Failed to cast field 'a' from Int32 to Decimal128(38, 38), Comparison of an integer with a wide decimal fails: common decimal type caps precision but keeps scale #27095).

Both are the same hole, so one rule closes both: an integer's precision and scale are
now computed independently of any variant, and the common type is the narrowest variant
that holds the required precision and is no narrower than the decimal's own.
Decimal32(9, 2) with Int64 becomes Decimal128(22, 2); Decimal128(38, 38) with
Int32 becomes Decimal256(48, 38). Where no variant holds the required precision --
only a Decimal256 whose scale is large in either direction can reach that -- the
precision is still capped, so the comparison stays in decimals.

A float keeps the previous behaviour. The scale a float coerces to is an approximation of
its own (Float64 becomes Decimal128(30, 15)), and widening on that basis would move
ordinary comparisons like WHERE price = 4.00 onto a wider variant.

What changes are included in this PR?

In datafusion/expr-common/src/type_coercion/binary.rs:

  • integer_decimal_precision gives an integer's precision and scale without choosing a
    variant; narrowest_decimal_variant picks the narrowest variant that holds a precision
    and is no narrower than a given one.
  • get_common_decimal_type uses them for an integer, and the four
    coerce_numeric_type_to_decimal* helpers are now float-only
    (coerce_float_type_to_decimal*), since an integer no longer goes through them.
  • math_decimal_coercion's eight integer arms become two guarded on
    is_decimal() && is_integer(): both operands move to the variant that holds them, each
    keeping its own precision and scale, so the result keeps the precision arrow derives
    from them.
  • decimal_precision_and_scale replaces the two inline matches in
    get_wider_decimal_type_cross_variant.

In datafusion/expr-common/src/casts.rs, the cast-unwrap rewrite accepts a
Decimal256 literal, so CAST(d AS Decimal256(44, 24)) != 5.0… becomes
d != 5.0… as it did before this coercion change. A literal whose value or scale is
beyond i128 is still rejected, which keeps the cast.

What is the testing strategy for this PR?

Unit tests for the coerced types, and sqllogictest for what a query returns:

  • type_coercion/binary/tests/comparison.rs: the common type of Decimal32/Decimal64
    against each integer width, of each integer width against a wide-scale Decimal128, a
    scale of 9 and a scale of -2 on a Decimal32, the Decimal256 whose precision is
    capped, the cases that already fitted (which must not move), and a float against both.

  • type_coercion/binary/tests/arithmetic.rs: the operand pair for each arithmetic case in
    both operand orders, plus integer_decimal_precision itself;
    test_decimal_mathematics_op_type now covers the float-only helpers.

  • interval_arithmetic.rs: contains_value of a Decimal32 interval against an integer,
    whose bounds used to be coerced to the integer and lose their fraction, which put 1
    inside [1.50, 2.50].

  • decimal.slt: the five queries from Comparing or adding an integer to a Decimal32/Decimal64 value casts the decimal to Int64 and drops its fraction #27424 with arrow_typeof pinned, the Comparison of an integer with a wide decimal fails: common decimal type caps precision but keeps scale #27095
    queries, which return rows instead of failing, an IN list, greatest/least and a
    UNION ALL, and a Decimal256(76, 70) compared with integers.

  • asof_join.slt: a Decimal32 ASOF equality key against an Int64 one, which used to
    make 1.50 and 1 the same key, and a match condition across the two types.

  • casts.rs: the Decimal256 literal preimage, the literal that has no room in the
    column's type (5 against Decimal128(38, 38)), and the value and the scale that are
    beyond i128.

  • simplify_expr.slt: a decimal(38, 24) column in the existing decimal-unwrap table,
    whose <> 5 and IN (4, 5) plans must carry no cast. Without the casts.rs change
    both explains fail with the Decimal256 cast in the plan, and the unit test above
    fails alone.

Each of those tests was run against this branch and against its base: every one fails on
the base for the value it pins. The To Reproduce queries of both issues were also run by
hand on both builds, and on the base they reproduce the reported output word for word.

Are there any user-facing changes?

Comparing or combining an integer with a Decimal32 or Decimal64 value now stays in
decimal arithmetic instead of truncating the decimal, and comparing an integer with a
wide-scale decimal returns rows instead of failing. Everything that asks for a common type
sees this, not just a comparison in WHERE:

  • an IN list: d32 IN (5, 6) with d32 at 5.50 returned true, now returns false;
  • greatest/least: greatest(d32, 5) returned 5 as an Int64, now 5.50;
  • UNION ALL of such a column with an integer: the fraction was dropped silently;
  • an ASOF join key of the two types: 1.50 and 1 were the same key;
  • interval and statistics containment, which read the same common type;
  • gcd/lcm: gcd(<Decimal32>, 4) used to be a plan error.

A Decimal128 column whose scale is 19 or more also changes the type it reports, where
it worked before. DECIMAL(38, 20) with an integer -- an Int64, which every integer
literal is -- now has Decimal256(40, 20) as its common type instead of
Decimal128(38, 20), so COALESCE(d, 0), a CASE arm, a UNION ALL branch, a
CREATE TABLE AS and a client reading the schema all see the wider type. The values are
the same; Decimal128(38, 20) is the type that had no room for an Int64's digits,
which is the hole this closes. The threshold is exactly a scale of 19 against an Int64:
an Int8 at that scale still fits Decimal128(38, 19).

That wider common type also made the literal in WHERE d <> 5 a Decimal256, which left
the cast on the column: 113 ms in FilterExec over 40M rows of DECIMAL(38, 24), where
the plan without the cast takes 24 ms. With the casts.rs change the plan is d != 5.0…
again, and so is the time.

No API changes.

Notes for reviewers

  • A product's precision is still capped at the variant's maximum, so
    Decimal32(9, 2) * Int32 has Decimal64 operands and a Decimal64(18, 2) result. That
    is what every decimal pair already gets: Decimal32 + Decimal32 caps the same way, and
    Decimal128 * Int64 caps at 38 rather than widening to Decimal256. Widening a variant
    to fit a result would be a change of policy for all decimal arithmetic, so it is not
    here.
  • narrowest_decimal_variant checks the precision only. A variant's maximum scale equals
    its maximum precision and the required precision already leaves room for the scale, so a
    scale check would never change the answer.

🤖 Generated with Claude Code

@github-actions github-actions Bot added logical-expr Logical plan and expressions sqllogictest SQL Logic Tests (.slt) labels Nov 16, 2026
@namanjain24-sudo

Copy link
Copy Markdown
Contributor

Heads up: Rust (fork) here reads "No fork run for this commit", so the full Rust suite hasn't run on this PR. Enabling workflows in your fork's Actions tab and pushing again fixes it.

@jayzhan211 jayzhan211 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.

@cool9850311 thanks for fixing both issues. The wrong rows from #27424 are gone in every place I tried (filter, join key, IN, CASE, COALESCE, UNION ALL, window, aggregate, dictionary input). One change is needed before merge, on the Decimal256 widening (inline).

Could the user-facing section also say that results change type for Decimal128 columns that already worked? COALESCE(d, 0), CASE and UNION ALL of a DECIMAL(38, 20) column with an integer now return Decimal256(40, 20) instead of Decimal128(38, 20), so a CREATE TABLE AS or a client reading the schema sees the new type. It happens for any scale of 19 or more against an Int64, which every integer literal is.

integer_scale,
);
let common_scale = scale.max(integer_scale);
if let Some(variant) = narrowest_decimal_variant(decimal_type, common_precision) {

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.

A DECIMAL(p, s) column with s >= 19 compared with an integer literal now goes through Decimal256, and the cast stays on the column: WHERE d <> 5 on a DECIMAL(38, 24) column runs CAST(d AS Decimal256(44, 24)) != 5.0…, and its FilterExec takes 80–99 ms on 40M rows against 17–20 ms on main, where the plan is d != 5.0…. The literal fits the column's own type, so letting unwrap-cast accept a Decimal256 literal brings back the old plan and time (17–19 ms), while integer columns still get the wider type. With this change the expr-common and optimizer unit tests and the full sqllogictest suite pass:

--- a/datafusion/expr-common/src/casts.rs
+++ b/datafusion/expr-common/src/casts.rs
@@ fn is_decimal_type(dt: &DataType) -> bool {
     matches!(
         dt,
-        DataType::Decimal128(_, _)
+        DataType::Decimal256(_, _)
+            | DataType::Decimal128(_, _)
             | DataType::Decimal64(_, _)
             | DataType::Decimal32(_, _)
     )
@@ fn decimal_precision_scale(dt: &DataType) -> (u8, i8) {
     match dt {
-        DataType::Decimal128(p, s)
+        DataType::Decimal256(p, s)
+        | DataType::Decimal128(p, s)
         | DataType::Decimal64(p, s)
         | DataType::Decimal32(p, s) => (*p, *s),
@@ fn is_supported_numeric_type(data_type: &DataType) -> bool {
             | DataType::Decimal128(_, _)
+            | DataType::Decimal256(_, _)
             | DataType::Timestamp(_, _)
@@ fn try_cast_numeric_literal(
+        ScalarValue::Decimal256(Some(v), _, scale) => {
+            let v = v.to_i128()?;
+            let lit_scale_mul = 10_i128.checked_pow(u32::try_from(*scale).ok()?)?;
+            if mul >= lit_scale_mul {
+                v.checked_mul(mul / lit_scale_mul)
+            } else if v % (lit_scale_mul / mul) == 0 {
+                Some(v / (lit_scale_mul / mul))
+            } else {
+                None
+            }
+        }
         ScalarValue::Decimal128(Some(v), _, scale) => {
Unit test for casts.rs, and the queries behind the numbers
#[test]
fn test_cast_predicate_preimage_decimal256_literal() {
    use arrow::datatypes::i256;

    // `DECIMAL(38, 20) > 5` coerces both sides to `Decimal256(40, 20)`
    let five = 5 * 10_i128.pow(20);
    assert_preimage_exact(
        &DataType::Decimal128(38, 20),
        &DataType::Decimal256(40, 20),
        Operator::Gt,
        &ScalarValue::Decimal256(Some(i256::from_i128(five)), 40, 20),
        ScalarValue::Decimal128(Some(five), 38, 20),
    );

    // 5 has no room in `Decimal128(38, 38)`, so the cast stays
    let five = i256::from_i128(5).wrapping_mul(i256::from_i128(10).wrapping_pow(38));
    assert_preimage_none(
        &DataType::Decimal128(38, 38),
        &DataType::Decimal256(58, 38),
        Operator::Lt,
        &ScalarValue::Decimal256(Some(five), 58, 38),
    );

    // 10^70 does not fit in i128, so the cast stays instead of overflowing
    assert_preimage_none(
        &DataType::Decimal128(38, 20),
        &DataType::Decimal256(76, 70),
        Operator::Gt,
        &ScalarValue::Decimal256(Some(i256::ZERO), 76, 70),
    );
}
-- release-nonlto datafusion-cli
SET datafusion.execution.parquet.max_row_group_size = 1000000;
COPY (SELECT CAST(value AS DECIMAL(38, 20)) / 1000 AS d FROM generate_series(1, 10000000) ORDER BY value)
  TO 'wide.parquet' STORED AS PARQUET;
SET datafusion.execution.target_partitions = 1;
CREATE EXTERNAL TABLE w STORED AS PARQUET LOCATION 'wide.parquet';
CREATE TABLE m AS SELECT d FROM w UNION ALL SELECT d FROM w UNION ALL SELECT d FROM w UNION ALL SELECT d FROM w;
EXPLAIN ANALYZE SELECT count(*) FROM m WHERE d <> 5;                             -- FilterExec 80-99 ms
EXPLAIN ANALYZE SELECT count(*) FROM m WHERE d <> CAST(5 AS DECIMAL(38, 24));  -- 17-20 ms, main's plan

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thank you -- this reproduces here, and your diff is the right place for it. My numbers, on
10M rows of DECIMAL(38, 24) unioned four times (40M), target_partitions = 1,
release-nonlto, with the same binary for both rows so the plan is the only difference:

query plan FilterExec elapsed_compute
d <> 5 CAST(d@0 AS Decimal256(44, 24)) != 5.0… 112.95 ms
d <> CAST(5 AS DECIMAL(38,24)) d@0 != 5.0… 31.89 ms

On the pushed commit d <> 5 plans as d@0 != 5.0… and takes 24-27 ms, against 23-25 ms
for that same plan on the base.

An IN list is the same rewrite and comes back with it: d IN (4, 5) kept the cast as
CAST(d@0 AS Decimal256(44, 24)) IN (SET) (…) and is an unwrapped OR chain again.

I took the diff as is, with one addition: the comment above the Decimal256 rejection in
test_decimal_scale_up_preimages said the scale-only rule rejects Decimal256, which
after this holds only for a Decimal256 target, so it says that.

Nothing pinned this, so your three cases are now
test_cast_predicate_preimage_decimal256_literal, plus a value beyond i128 for the
to_i128 guard and the integer side of the same comparison, which is a different arm of
the target match. simplify_expr.slt gets a decimal(38, 24) column in its
decimal-unwrap table whose <> 5 and IN (4, 5) plans must carry no cast. Without the
casts.rs change the unit test fails alone (1 of 251) and both explains fail with the
Decimal256 cast in the plan.

This is the second commit, 8d4db4cac, so the change since your review is those three
files. The branch is rebased onto main, so it also sits on top of #27148, which landed in
casts.rs meanwhile.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching, done fix.

cool9850311 and others added 2 commits November 22, 2026 19:38
…mal's variant

An integer compared with or added to a `Decimal32` or `Decimal64` value
returned wrong rows rather than an error: a `Decimal32(9, 2)` holding
`5.50` compared equal to `5`, and `5.50 + 1` returned `6` as an `Int64`.
The helper that turned an integer into a decimal was bound to a single
variant and had no arm for an integer too wide for it -- `Int32` or wider
for `Decimal32`, `Int64` for `Decimal64` -- so both callers read that
`None` as "not a decimal case" and fell through to the integer rules,
which coerce the decimal to an integer and drop its fraction.

How many digits an integer needs is known exactly, so its precision and
scale are now computed independently of any variant, and the common type
is the narrowest variant that holds them and is no narrower than the
decimal's own. The same rule covers the case where the required precision
passed the variant's maximum and was capped while the scale was kept,
leaving a type with no room for the integer's digits at all (apache#27095, for
which apache#27124 proposes a narrower fix). Where no variant holds the
required precision, the capped type stands.

A float keeps its previous behaviour. The scale it coerces to is an
approximation of its own, and widening on that basis would move ordinary
comparisons like `WHERE price = 4.00` onto a wider variant.

Everything that asks for a common type follows: an `IN` list,
`greatest`/`least`, a `UNION ALL`, an ASOF join key, interval containment
and `gcd`/`lcm`. Each of those has a test here, as do a scale of 9 and a
scale of -2 on a `Decimal32`.

Closes apache#27424.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A `Decimal128` whose scale is 19 or more needs a `Decimal256` common type
with an integer, and the cast-unwrap rewrite in `casts.rs` did not accept
a `Decimal256` literal, so the cast stayed on the column:
`WHERE d <> 5` on a `DECIMAL(38, 24)` column ran
`CAST(d AS Decimal256(44, 24)) != 5.0…`, 113 ms of `FilterExec` over 40M
rows against 24 ms without the cast. Found in review, with this diff.

It accepts one whose value and scale fit `i128` now; one that does not,
such as 5 against a `Decimal128(38, 38)` column, keeps its cast as before.
An `IN` list is the same rewrite and comes back with it.

Nothing pinned this, so the preimage has a unit test and
`simplify_expr.slt` gets the column shape whose plan must carry no cast.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cool9850311
cool9850311 force-pushed the fix-27424-int-decimal32-64-coercion branch from fc77d22 to 8d4db4c Compare November 22, 2026 12:46
@cool9850311

cool9850311 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased and pushed, with the casts.rs fix as its own commit (8d4db4cac) so the change
since your review stands alone; the numbers are in the inline thread.

"Are there any user-facing changes?" now covers the type change you asked about: a
Decimal128 column whose scale is 19 or more has Decimal256(s + 20, s) as its common
type with an integer, where it stayed Decimal128(38, s), so COALESCE(d, 0), a CASE
arm, a UNION ALL branch, a CREATE TABLE AS and a client reading the schema all see the
wider type. The values are unchanged, and Decimal128(38, s) is the type that had no room
for an Int64's digits. The threshold is exactly a scale of 19 against an Int64: an
Int8 at that scale still fits Decimal128(38, 19).

@jayzhan211 jayzhan211 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.

@cool9850311 thanks for applying the unwrap change; the plain DECIMAL(38, 24) filters are back to the no-cast plan, and the full sqllogictest suite passes locally (your fork's Rust CI was skipped). Approving with one follow-up: dictionary-encoded columns still keep the cast (inline, fine to handle in a separate PR).

4.000000000000000000000000

query TT
explain select price38_24 from decimal_prices where price38_24 <> 5;

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.

@cool9850311 thanks for the quick turnaround; plain columns unwrap again. The same cast still stays on a dictionary-encoded column, though: with d as Dictionary(Int32, Decimal128(38, 24)), d = 5 plans as CAST(d AS Decimal256(44, 24)) = 5.0…, where main plans d = Dictionary(Int32, Decimal128(5.0…, 38, 24)), and the same goes for IN (4, 5). The cause is that try_cast_dictionary only wraps a literal whose type equals the dictionary's value type. This arm fixes it, and the full sqllogictest suite plus the expr-common, optimizer and physical-expr tests pass with it:

         (_, DataType::Dictionary(index_type, inner_type))
             if **inner_type == lit_value_type =>
         {
             ScalarValue::Dictionary(index_type.clone(), Box::new(lit_value.clone()))
         }
+        (_, DataType::Dictionary(index_type, inner_type)) => ScalarValue::Dictionary(
+            index_type.clone(),
+            Box::new(try_cast_numeric_literal(lit_value, inner_type)?),
+        ),

It changes what try_cast_literal_to_type documents for dictionaries of every value type, so it's fine to handle in a follow-up PR with its own tests.

Repro
create table td as select arrow_cast(column1, 'Dictionary(Int32, Decimal128(38, 24))') as d
from (values (cast(4 as decimal(38,24))), (cast(5 as decimal(38,24))), (NULL));
explain select d from td where d = 5;
explain select d from td where d in (4, 5);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Will open follow-up PR

Comment thread datafusion/expr-common/src/casts.rs Outdated
None
}
}
ScalarValue::Decimal256(Some(v), _, scale) => {

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.

Optional cleanup: this arm is now the fourth copy of the rescale body. With one helper, each decimal arm becomes a single line (47 fewer lines). Using checked_pow in the helper also means a bad scale returns None in the older arms instead of overflowing:

+/// Rescales the unscaled decimal `v` at `scale` to the scale whose multiplier is
+/// `mul`, or `None` if that drops digits or overflows `i128`.
+fn rescale_decimal_literal(v: i128, scale: i8, mul: i128) -> Option<i128> {
+    let lit_scale_mul = 10_i128.checked_pow(u32::try_from(scale).ok()?)?;
+    if mul >= lit_scale_mul {
+        v.checked_mul(mul / lit_scale_mul)
+    } else if v % (lit_scale_mul / mul) == 0 {
+        Some(v / (lit_scale_mul / mul))
+    } else {
+        None
+    }
+}
        ScalarValue::Decimal32(Some(v), _, scale) => {
            rescale_decimal_literal(*v as i128, *scale, mul)
        }
        ScalarValue::Decimal64(Some(v), _, scale) => {
            rescale_decimal_literal(*v as i128, *scale, mul)
        }
        ScalarValue::Decimal128(Some(v), _, scale) => {
            rescale_decimal_literal(*v, *scale, mul)
        }
        ScalarValue::Decimal256(Some(v), _, scale) => {
            rescale_decimal_literal(v.to_i128()?, *scale, mul)
        }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied.

`rescale_decimal_literal` replaces the body each decimal arm of
`try_cast_numeric_literal` had its own copy of. Its `checked_pow` also
rejects a negative literal scale, where `10_i128.pow(scale as u32)`
overflowed: `try_cast_literal_to_type` panicked on a `Decimal32`,
`Decimal64` or `Decimal128` literal of negative scale, which
`test_try_decimal_cast_out_of_range` now pins. A negative scale on the
target type still overflows, since its multiplier is computed before any
arm runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@jayzhan211
jayzhan211 added this pull request to the merge queue Nov 27, 2026
@jayzhan211

Copy link
Copy Markdown
Contributor

Thanks @cool9850311 !

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

logical-expr Logical plan and expressions sqllogictest SQL Logic Tests (.slt)

Projects

None yet

3 participants