Vivek1106-04 commented on code in PR #59437:
URL: https://github.com/apache/spark/pull/59437#discussion_r4653419728
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -519,17 +531,23 @@ case class Add(
copy(left = newLeft, right = newRight)
override lazy val canonicalized: Expression = {
- val reorderResult = buildCanonicalizedPlan(
- { case Add(l, r, em) if em == evalContext => Seq(l, r) },
- { case (l: Expression, r: Expression) => Add(l, r, evalContext)},
- Some(evalContext)
- )
- if (resolved && reorderResult.resolved && reorderResult.dataType ==
dataType) {
- reorderResult
+ if (resolved && BinaryArithmetic.isNonAssociative(dataType)) {
Review Comment:
Makes sense. I added
`spark.sql.legacy.canonicalization.reassociateInexactArithmetic` in 39e41a3. It
is internal and off by default, and turning it on brings back the old
flattening for these types. It uses `SESSION` binding, so a reader can set it
to read an existing view, and the migration note now mentions persisted views
and the config. There is a new `SQLQuerySuite` test where a view of this shape
fails to read with the config off and works with it on.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -1473,6 +1476,19 @@ trait CommutativeExpression extends Expression {
f: PartialFunction[CommutativeExpression, Seq[Expression]]):
Seq[Expression] =
gatherCommutative(this, f).sortBy(_.hashCode())
+ /**
+ * Reorders only the two direct children of a binary commutative operator,
without flattening
+ * adjacent operators. Used when the operator is commutative but not
associative, e.g.
+ * floating-point and maximum-precision decimal addition and multiplication.
+ */
+ protected def orderBinaryCommutative(
+ left: Expression,
+ right: Expression,
+ buildBinaryOp: (Expression, Expression) => Expression): Expression = {
+ val Seq(l, r) = Seq(left.canonicalized,
right.canonicalized).sortBy(_.hashCode())
Review Comment:
You are right, a 10000-operand `DOUBLE` sum overflowed the stack in
`canonicalized`. `orderBinaryCommutative` now collects the nested operators
with an explicit stack and canonicalizes them bottom-up, including the
`resolved`/`dataType` check, so nothing recurses once per level anymore. I
added a `CanonicalizeSuite` test with 10000-operand left-deep and right-deep
`+` and `*` chains, and it overflows on the previous commit. It compares
`semanticHash` rather than calling `semanticEquals`, because `deterministic`
still recurses once per level on any deep tree, integral chains included. These
chains still do not build a `MultiCommutativeOp`, since that needs flattened
operands, but the binary form is one node per operator, so it stays linear.
##########
docs/sql-migration-guide.md:
##########
@@ -101,6 +101,7 @@ license: |
- Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT`
adds to a Data Source V2 table, and whose condition reads the current time,
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db =
current_database()`, is checked against their values at the time of each write.
Previously, it was checked against their values at the time of the `ALTER
TABLE`, unless a write could not read back a predicate for its condition, such
as one with a lambda function or one that passes a column to `datediff`, `year`
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so
each write parses and analyzes its SQL text under the session of the write, as
it does for a constraint without a predicate that `CREATE TABLE` adds. A
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it
fail to parse the text or read it differently. A row-level operation
that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A
condition that Spark detects a write could resolve differently is stored as
before, so a write accepts and rejects the same rows for it as before. Examples
are conditions that also read a variable, a `CHAR` column, a name with more
than one part such as a column qualified by the table name, or a constant that
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a
timestamp. So are conditions with a name such as `current_date` or `user`
without parentheses, which a write can read as a column name, and conditions
whose text the parser settings of the `ALTER TABLE`, such as
`spark.sql.ansi.doubleQuotedIdentifiers` or
`spark.sql.parser.escapedStringLiterals`, r
ead differently from their default values. ANSI mode,
`spark.sql.timestampType` and the session time zone are taken from the session
for this comparison, as for a generation expression. A condition that reads the
current date or time only through a typed literal such as `DATE 'today'` is
also stored as before. An existing constraint keeps its stored predicate until
it is dropped and added again. `Check.predicate()` is null for a constraint
stored without a predicate, so a connector that validates or enforces it itself
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding
the constraint. A constraint added without it is not changed.
- Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'`
whose class implements
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends
either a Hive UDF class (such as `UDF` or `GenericUDF`) or
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions
created in earlier versions. Its result type, argument coercion, and null
handling are defined by the V2 implementation selected by
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic`
property do not control the V2 path. For scalar functions, determinism uses
`BoundFunction.isDeterministic()` (default `true`) and the arguments'
determinism. A call with constant arguments can therefore become eligible for
constant folding during query planning instead of being evaluated per row.
- Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW`
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc`
fails with it when the result is earlier than the minimum `DATE`,
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these
functions silently returned a wrong date, in most cases one at the other end of
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`.
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday,
and now return `-5877641-06-29`.
+- Since Spark 4.4, chains of `FLOAT` or `DOUBLE` addition or multiplication,
and chains of `DECIMAL` addition or multiplication whose result has the maximum
precision of 38 digits, that are associated differently are no longer treated
as semantically equal, because such steps round or overflow, so these
expressions can evaluate to different values. Reordering the two operands of a
single operator, such as `a + b` and `b + a`, is still treated as equal, and
`DECIMAL` chains whose result has a lower precision are exact and keep being
treated as equal. As a result, a query that selects such an expression grouped
by a differently associated form of it, for example `SELECT a + b + c FROM t
GROUP BY c + b + a` on `DOUBLE` or `DECIMAL(38, 18)` columns, now fails
analysis with `MISSING_AGGREGATION`. Previously, the query passed analysis and
returned the grouping expression's value, which could differ from the selected
expression's value. To keep such a query working, write the selected expr
ession the same way as the grouping expression.
Review Comment:
Moved it to the 4.4 to 4.5 section as "Since Spark 4.5", and the new config
is version 4.5.0.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CanonicalizeSuite.scala:
##########
@@ -480,6 +480,38 @@ class CanonicalizeSuite extends SparkFunSuite {
}
}
+ test("SPARK-60178: Do not re-associate floating-point Add/Multiply in
canonicalization") {
Review Comment:
Renamed both to say "floating-point and maximum-precision decimal" and fixed
the comment. I also renamed the subexpression elimination test in
`SQLQuerySuite`, since it covers `DECIMAL(38, 7)` and `DECIMAL(38, 10)` too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]