Repository navigation
[SPARK-62678][SQL] Compare row values field by field so NULL fields make comparisons and IS [NOT] NULL follow SQL - #61190
Draft
linhongliu-db wants to merge 6 commits into
Conversation
…ake comparisons and IS [NOT] NULL follow SQL Co-authored-by: Isaac <no-reply@databricks.com>
…the docs Row value ordering comparisons are built through internal functions once the fields resolve, so every field but the last is bound once with With, as BETWEEN does. A row value with a star field keeps the struct comparison. The conf and migration note move to 4.5, and the note now names what stays unchanged and the stream-stream join restart. Co-authored-by: Isaac <no-reply@databricks.com>
Build the ordering as IF(a = x, rest, a < x), so subexpression elimination does not evaluate a field early that an enclosing AND or OR guards, and bind only nondeterministic leading fields with With. Report wrong-arity calls of the internal functions with WRONG_NUM_ARGS, and make the conf doc and migration note name what is unchanged, the column names and the streaming restart. Co-authored-by: Isaac <no-reply@databricks.com>
Two reads of a nondeterministic field can disagree, and a With is computed out of a lambda or a short-circuiting parent, so such ordering comparisons keep the struct comparison, marked with a TODO. Correct the docs on which field decides equality and the test name. Co-authored-by: Isaac <no-reply@databricks.com>
…once When a field before the last is nondeterministic, RowValueOrdering compares the coerced fields with RowValueOrderingOnce, which reads each field at most once and only while the earlier pairs are equal, instead of falling back to the struct comparison. Add STRUCT column and Column API controls under both values of the legacy conf. Co-authored-by: Isaac <no-reply@databricks.com>
RowValueOrdering is foldable when its comparison is, so a comparison of constant rows can be an argument that must be foldable. Add a streaming golden for row value predicates, IS [NOT] NULL and a stream-stream join on row values, under both values of the legacy conf. Co-authored-by: Isaac <no-reply@databricks.com>
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.
What changes were proposed in this pull request?
The parser turns a row value constructor
(a, b)into a struct (AstBuilder.visitRowConstructorbuildsCreateStruct), andvisitComparisonthen compares the two structs. Struct ordering treats a NULL field as an ordinary value that sorts first. ISO/IEC 9075-2 compares row values field by field instead (8.2), and definesIS [NOT] NULLon a row value per field (8.8).This PR changes how the parser builds these predicates:
=,==,<>,!=,<,<=,>,>=are row value constructors of the same degree, they are compared field by field:(a, b) = (x, y)becomesa = x AND b = y, and<>becomesNOT (a = x AND b = y). A join on row values therefore plans as a multi-key equi-join.(a, b) < (x, y)meansa < x OR (a = x AND b < y).<=,>and>=work the same way: every field but the last uses the strict operator, and the last field uses the operator as written. The parser emits an internal function (row_value_lt,row_value_le,row_value_gt,row_value_ge, in the internal function registry) that builds a newRuntimeReplaceableexpression,RowValueOrdering, once the fields are resolved. It is built asIF(a = x, b < y, a < x), which gives the same result, NULL included. Only the predicate ofIFis always evaluated, so subexpression elimination does not evaluate a field early that an enclosingAND/ORoperand guards. For example,x = 0 OR (10 / x, b) < (5, 1)does not fail with DIVIDE_BY_ZERO under ANSI mode. Every field but the last can be read twice, and two reads of a nondeterministic field can disagree. So when such a field is nondeterministic, such as(rand(), b) < (0.5, 1), the coerced fields are compared byRowValueOrderingOnce, asRightdoes for nondeterministic arguments. It reads each field at most once, and only while the earlier pairs are equal, so it is still field-wise and NULL-aware, and stays lazy underAND/ORand in lambdas. AWithwould have computed the field in a project below the operator. Like the struct comparison it replaces, an ordering comparison is not pushed down to data sources. Equality is.((a, b)),(a AS p, b)) are looked through.IS NULL/IS NOT NULLis a row value constructor,(a, b) IS NULLbecomesa IS NULL AND b IS NULLand(a, b) IS NOT NULLbecomesa IS NOT NULL AND b IS NOT NULL. So(1, NULL)is neither NULL nor NOT NULL.NOT ((a, b) IS NULL)keeps theNOTover the expandedIS NULL.spark.sql.legacy.rowValueComparison.asStruct(defaultfalse). Setting it totruerestores the struct semantics.Unchanged: real
STRUCTvalues (columns,struct(...),named_struct(...), structs built with the DataFrame API) and<=>/IS [NOT] DISTINCT FROM. Also unchanged:(t.*, c), because its degree is not known until the star is expanded;BETWEENandCASE (a, b) WHEN;((a, b), c) = ((x, y), z)still compares(a, b)and(x, y)as structs;MATCH_CONDITION;IN (subquery)and[NOT] INlists.A TODO in
AstBuilderlists these remaining struct comparisons.Known gap:
[NOT] INlists over row values are left as they are.(w, b) NOT IN ((1, 2))still keeps(1, NULL). They need their own design:(a, b) = (1, 2) OR (a, b) = (3, 4) OR ...) cannot keep the hashedInSetpath for a probe with a NULL field. Measured on a prototype, a probe with a NULL field ran 40-67x slower at 100-200 list rows. At 500 rows the generated filter exceeded the 64 KB JVM method limit and fell back to non-whole-stage execution.That question applies to this PR too, so here is the answer. ISO/IEC 9075-2 8.2 (comparison predicate) defines
(x1, ..., xn) = (y1, ..., yn)as true when everyxi = yiis true, false when somexi <> yiis true, and unknown otherwise.<and the other ordering operators are decided by the first pair that is not equal, and are unknown when that pair involves a NULL. 8.8 (null predicate) saysR IS NULLis true when every field ofRis NULL, andR IS NOT NULLis true when no field ofRis NULL. 8.4 definesINas= ANY, so it inherits the 8.2 rules. PostgreSQL implements exactly this ("Row Constructor Comparison" and the row-wiseIS NULLnotes in its documentation):ROW(1, NULL) < ROW(1, 3)andROW(1, NULL) = ROW(1, 2)are NULL,ROW(1, NULL) < ROW(2, 0)is true,ROW(NULL, NULL) IS NULLis true, andROW(1, NULL) IS NOT NULLis false. Returning false (or true) for a NULL field turns an unknown result into a definite one, soWHERE,JOIN ONandNOTkeep or drop rows that the standard leaves unknown.Why are the changes needed?
They return wrong results. With
t(id INT, w INT, b INT)holding(1, 1, NULL), (2, 1, 2), (3, NULL, 1), (4, 2, 0):SELECT id FROM t WHERE (w, b) < (1, 3)SELECT id FROM t WHERE (w, b) <> (1, 2)SELECT (w, b) = (1, 2) FROM t WHERE id = 1SELECT l.id FROM t l JOIN t r ON (l.w, l.b) = (r.w, r.b)SELECT (NULL, NULL) IS NULLSELECT (1, NULL) IS NOT NULLDoes this PR introduce any user-facing change?
Yes:
IS [NOT] NULLon a row value constructor, can return NULL (or a different boolean) where it returned true or false before. This also applies to SQL strings passed to DataFrame methods such asfilterandselectExpr.(rand(), id) < (0.5, 3)no longer fails with the struct type-mismatch error (DOUBLEvsDECIMAL(1,1)).((w, b) < (1, 3))and((w = 1) AND (b = 2))instead of(named_struct(w, w, b, b) < named_struct(col1, 1, col2, 3)).spark.sql.legacy.rowValueComparison.asStruct=truerestores the previous behavior. The SQL migration guide entry (under 4.5) covers both changes and the streaming restart.How was this patch tested?
sql-tests/inputs/row-value-comparison.sql, over a parquet table. It covers each operator over rows with NULL fields, rows where an earlier field decides the result, projections that return NULL, three-field rows, aJOIN ... ONrow values, andIS [NOT] NULLon(NULL, NULL),(1, NULL)and(1, 2). It has controls for<=>,named_structcomparisons andIS NULL, a STRUCT column compared withnamed_structunder both conf values, nested rows, star fields, an IN list,NOT IN(the known gap) and different degrees. It also checks that the legacy conf brings back the old rows. With theAstBuilderchange reverted, the test fails for the bug:(w, b) <> (1, 2)returns1, 3, 4, and the plans compare structs.SQLQuerySuitetests:SPARK-62678: row value ordering comparisons keep fields lazy and read each once. Under ANSI mode,x = 0 OR (f, 1) < (100, 2)andx <> 0 AND (f, 1) >= (10, 1)over a parquet table do not divide by zero, forf = 10 / xandf = 10 / x + rand(). A nondeterministic leading field is read once: onerandin the optimized plan, andfilter(sequence(1, 1000), x -> (rand() + x * 0 > 0.5, 0) < (true, 1))keeps every element. It is still field-wise:(rand() * 0, 1) < (0, CAST(NULL AS INT))is NULL. Aggregates, window functions and scalar subqueries as leading fields are covered too.SPARK-62678: STRUCT values and the Column API keep struct comparisons. Column API comparisons (struct(...) === / =!= / < / >= struct(...),isNull,isNotNull) and SQL comparisons of a STRUCT column withnamed_struct, over rows with NULL fields, return the same struct-semantics results withspark.sql.legacy.rowValueComparison.asStructset tofalseand totrue.sql-tests/inputs/streaming/row-value-comparison.sql(StreamingSQLQueryTestSuite): row value comparisons andIS [NOT] NULLin a streaming projection and filter, and a stream-stream join on row values, which matches no NULL keys. With the legacy conf they give the struct results again, and the join matches every row to itself.round(1.234D, IF((1, 2) < (1, 3), 2, 1))returns 1.23.ExpressionParserSuitecases for the parser shapes: each operator, three fields, aliases, redundant parentheses, nested rows, star fields,IS [NOT] NULL,NOT (... IS NULL), the unchanged cases, and the legacy conf. A newPlanParserSuitecase checks that an ASOFMATCH_CONDITIONover row values, also in redundant parentheses, stays a struct comparison while itsONclause is compared field by field.build/sbt "catalyst/testOnly *ExpressionParserSuite *PlanParserSuite": all pass.build/sbt "sql/testOnly org.apache.spark.sql.SQLQuerySuite -- -z SPARK-62678": both new cases pass.build/sbt "sql/testOnly org.apache.spark.sql.SQLQueryTestSuite org.apache.spark.sql.StreamingSQLQueryTestSuite org.apache.spark.sql.expressions.ExpressionInfoSuite *AsOfJoinSQLSuite *AsOfJoinSortMergeSQLSuite": all 1043 pass, with no changes to existing golden files. That includes the ASOF goldens that compare row values and the IN-list goldens.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.