Repository navigation
feat(arrow-cast): configurable rounding mode for casts to decimal - #11332
Open
bhaskargurram-ai wants to merge 4 commits into
Open
bhaskargurram-ai wants to merge 4 commits into
bhaskargurram-ai wants to merge 4 commits into
Conversation
Casts and parsing into decimal types always round half away from zero when they drop digits. Some applications need banker's rounding (half to even) or truncation instead, which was the remaining request from apache#5068 after the parser consolidation in apache#10850. Add a `DecimalRoundingMode` enum (`HalfAwayFromZero` (default), `HalfToEven`, `TowardZero`) and a `CastOptions::decimal_rounding` field that selects it for casts from strings, from floats, and from decimals with a larger scale. The existing default behaviour is unchanged, and precision is still validated after rounding. The consolidated string parser now tracks whether any discarded digit after the first one is non-zero, so it can tell an exact tie from a value above halfway; the mode is also exposed for standalone parsing via `parse_decimal_with_rounding`. Float casts select `f64::round`, `f64::round_ties_even` or `f64::trunc` once per array, and the decimal downscaler rounds ties to the even quotient for `HalfToEven`. Adding a public field to `CastOptions` is an API change: struct literals that list every field need `..Default::default()` or the new field. CSV/JSON reader options are left for a follow-up. Closes apache#11308
Select the rounding mode with a private `DecimalRounding` trait instead of a runtime argument, and dispatch once per array in string-to-decimal casts. Each mode gets its own copy of the parser, so the default mode compiles to the same code as before this change, and only `HalfToEven` tracks whether any discarded digit after the first one is non-zero.
Write the default-mode rounding checks the same way as before (`get_or_insert` for the first discarded digit, and a non-short-circuit `&` for the round-up decision) so that the default instantiation of the parser stays as close as possible to the previous code.
The decimal-to-decimal downscaler matched on the rounding mode for every value. Move the rounding of the quotient into the `DecimalRounding` policy and select it once per array, so the default mode runs the same per-value code as before this PR.
Contributor
|
i havent taken a look at the PR yet, but since it has public API changes itll need to wait for v61.0.0, which is likely targeted for december at this rate |
Member
|
I'll try to take a look at it soon as it's useful for #11309 |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Which issue does this PR close?
Rationale for this change
Casts and parsing into decimal types always round half away from zero when they drop digits. Configurable rounding was a stretch goal of #5068. #10850 consolidated string-to-decimal parsing into one code path and settled the default rounding, and #11308 tracks what was left: letting callers pick a different rounding mode, such as half to even or truncation toward zero, while keeping the current default.
The main concern raised in #5068 was not to regress decimal parsing performance. So the default mode is designed to run exactly the code it runs today, with no per-value check of the mode (see the performance notes below).
What changes are included in this PR?
DecimalRoundingModeenum inarrow-cast(re-exported asarrow_cast::DecimalRoundingModeandarrow::compute::DecimalRoundingMode). It has three variants:HalfAwayFromZero(the default, same as today),HalfToEvenandTowardZero. The enum is#[non_exhaustive]so that other modes (floor, ceiling, ...) can be added later without a breaking change.CastOptions::decimal_roundingfield. These cast paths use it:HalfToEvenit now also records whether any later discarded digit is non-zero, so it can tell an exact tie (2.5) from a value just above one (2.50001). Ties then go to the even last kept digit. The mode is a compile-time parameter of the parser (a privateDecimalRoundingtrait), and the cast picks the right copy once per array. This keeps the per-value cost of the default mode the same as before. It also works with exponents and negative scales.f64::round,f64::round_ties_evenorf64::trunc) is chosen once per array and inlined into the loop. As before, it is applied tovalue * 10^scalecomputed inf64, so the result follows the binary value. For example,1.005_f64becomes1.00at scale 2 in every mode. This is noted in the field docs.HalfToEvenand drops the remainder forTowardZero. The rounding of the quotient goes through the sameDecimalRoundingtrait and is chosen once per array, so the default per-value code is the same as before.arrow_cast::parse::parse_decimal_with_roundingfor standalone parsing.parse_decimalkeeps its signature and behaviour.99.995fitsDecimal(4, 2)only withTowardZero.Out of scope here, possible follow-ups:
parse_decimaltoday. Withparse_decimal_with_roundingin place, they would only need aReaderBuilderoption. I left that out to keep this PR to one crate and to settle the API first.rescale_decimal(the public single-value helper) and the Variant conversions still use the default mode.Int32 150toDecimal(5, -2)is1), unlike the other paths, which round half away from zero. I did not change that default here. It could take the mode too if you want the paths to be consistent.Are these changes tested?
Yes.
parse.rs:test_parse_decimal_with_roundingcovers all three modes for Decimal128 and Decimal256. Cases include positive and negative ties, a non-zero digit after the 5, long inputs that span several accumulator chunks, exponents, negative scales, and inputs with no discarded digits. It also checks that the default matchesparse_decimal.test_parse_decimal_with_rounding_checks_precision_after_roundingcovers precision and native-type overflow.cast/mod.rs:test_cast_string_to_decimal_rounding(Utf8, LargeUtf8 and Utf8View into all four decimal types, safe and unsafe),test_cast_float_to_decimal_rounding(Float16/32/64),test_cast_decimal_to_decimal_rounding(Decimal128/256 into all four decimal types, on both the infallible and the precision-checked path) andtest_cast_to_decimal_rounding_checks_precision_after_rounding.HalfToEvenrounds ties up.cargo test -p arrow-castpasses (406 unit, 4 integration and 13 doc tests).cargo clippy -p arrow-cast --all-targets --all-features -- -D warnings,cargo clippy -p parquet-variant-compute --tests -- -D warningsandcargo fmt --all -- --checkare clean.Performance: in the default mode, every path runs the same per-value logic as on
main. The mode is chosen once per array (string parsing, float and decimal downscaling), and onlyHalfToEventracks the extra "any later non-zero digit" flag while parsing. In an earlier revision the downscaler matched on the mode for every value, and the benchmark below showed that as +7% ondecimal128 to decimal128 512 with lower scale (infallible). With the mode chosen once per array, that case measures -1.6%.I measured on a shared, noisy 4-core VM, so please treat the numbers as indicative. I built the
mainand branch benchmark binaries, ran them alternately 3 times, and took the best time of each. These are the decimal cases ofcargo bench -p arrow --features test_utils --bench cast_kernels -- decimal(times in µs):The geometric mean is +1.4%. Paths this PR does not touch (decimal to int/float, int to decimal, same scale) moved between -6% and +6%, which is roughly the noise on this machine. Three cases were about +7% to +10% in both of my runs:
string to decimal256,float64 to decimal128and the Decimal256 downscales. Their per-value logic in the default mode is unchanged, so I suspect code layout or inlining differences, but I could not confirm that here.cargo bench -p arrow-cast --bench parse_decimal, run the same way, had a geometric mean of -0.2% over its 38 cases. Individual cases ranged from -21% (string decimal32 9 digits) to +22% (string decimal128 exponent). I compared the disassembly ofparse_decimal::<Decimal128Type>in the two benchmark binaries: the instruction mix is nearly identical, with about 25 more instructions out of roughly 700, mostly register moves.Given the concern in #5068, it would help if a maintainer could run the benchmark bot on
parse_decimalandcast_kernels. An earlier revision passed the mode as a runtime argument instead of a type parameter. I am happy to go back to that if you prefer the simpler code.Are there any user-facing changes?
Yes:
DecimalRoundingMode,CastOptions::decimal_roundingandparse_decimal_with_rounding.CastOptionsgets a new public field, so code that builds it with a struct literal listing every field must add..Default::default()or the new field. AconstCastOptionsneedsdecimal_rounding: DecimalRoundingMode::HalfAwayFromZerobecauseDefault::default()is not const. This PR updates the struct literals in this repository that way (most of the diff incast/mod.rstests and two inparquet-variant-compute).Note: #11302 (open) also changes
cast_floating_point_to_decimal. Whichever PR merges second will need a small rebase. The float change here is only the choice of rounding function.AI usage
I used Claude Code while working on this PR. It drafted the
DecimalRoundingModeimplementation and tests, ran the benchmarks, and helped write this description. I have reviewed the whole diff, checked each rounding mode's behaviour against the tests, and can debug and maintain these changes myself.