Ramin Gharib created FLINK-41726:
------------------------------------
Summary: ROUND and TRUNCATE return wrong DECIMAL values when
digits isn't a literal
Key: FLINK-41726
URL: https://issues.apache.org/jira/browse/FLINK-41726
Project: Flink
Issue Type: Bug
Components: Table SQL / Planner, Table SQL / Runtime
Affects Versions: 2.3.0
Reporter: Ramin Gharib
Assignee: Ramin Gharib
ROUND and TRUNCATE return a wrong DECIMAL value when {{digits}} isn't a literal
and is below the scale of {{x}}. The query succeeds, and the value is off by a
power of ten.
{code:sql}
SELECT d, n, ROUND(d, n) AS r, TRUNCATE(d, n) AS t
FROM (VALUES (12.345, 1), (12.345, 2), (12.345, -1), (99.995, 2), (12.345, 3))
AS t(d, n);
{code}
||d||n||Expected r||Actual r||Expected t||Actual t||
|12.345|1|12.3|0.123|12.3|0.123|
|12.345|2|12.35|1.235|12.34|1.234|
|12.345|-1|10|0.010|10|0.010|
|99.995|2|100.00|10.000|99.99|9.999|
|12.345|3|12.345|12.345|12.345|12.345|
The same in batch and streaming mode, and in the Table API with
{{$("d").round($("n"))}}.
* A constant expression is not a literal either: {{ROUND(d, 1 + 0)}} and
{{ROUND(d, CAST('1' AS INT))}} return {{0.123}} for {{12.345}}, while
{{ROUND(d, 1)}} returns {{12.3}}.
* The value is wrong wherever the result is stored in a row as it is: in the
query result, in a sink, and as a GROUP BY key. A calculation, comparison or
cast on the result sees the right value, so {{CAST(ROUND(d, n) AS STRING)}} is
{{12.3}} and {{ROUND(d, n) = 12.3}} is TRUE.
* A one-row VALUES hides the bug, since the planner folds the call into a
literal.
h3. Cause
When {{digits}} isn't a literal, the result type is the type of {{x}}, here
{{DECIMAL(5, 3)}}: {{FlinkReturnTypes#ROUND_FUNCTION}} for SQL and
{{RoundTypeStrategy}} for the Table API. At runtime,
{{DecimalDataUtils#sround}} and {{SqlFunctionUtils#struncate}} return a
{{DecimalData}} with the scale {{digits}}, here {{12.3}} with scale 1.
{{AbstractBinaryWriter#writeDecimal}} stores only the unscaled value, 123, and
the row reads it back at scale 3, as {{0.123}}.
FLINK-23614 fixed the result type of TRUNCATE for a literal {{digits}}.
h3. Proposal
* When {{digits}} isn't a literal, return the value at the scale of the result
type, such as {{12.300}} for {{ROUND(12.345, n)}}. The result type needs one
more integer digit, {{DECIMAL(p + 1, s)}}, since {{ROUND(99.995, 2)}} is
{{100.00}}, as for a literal {{digits}}.
* Version both functions, as FLINK-41438 does for ITEM and ELEMENT with the
versioning of FLINK-41530. New plans compile to {{$ROUND$2}} and
{{$TRUNCATE$2}}. {{$ROUND$1}} and {{$TRUNCATE$1}} keep the current behavior for
plans compiled before, because such a plan stores the old result type in every
node after the call, and its state can hold the wrong values as keys, such as
for a GROUP BY on the result. A release note says to compile the statement
again to get the fix.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)