Repository navigation
Conversation
… with other elements `value IN (e1, e2, ...)` must return what `value = e1 OR value = e2 OR ...` returns. When the value is a CHAR column, each of these comparisons pads its sides on its own: against a CHAR column of another length, or a string literal, the shorter side is padded; against a STRING or VARCHAR column nothing is padded. ApplyCharTypePadding instead pads the value and all the elements of an IN list together, and it gives up when the list mixes elements that are padded differently: - `char3_col IN (char5_col, string_col)` and `char3_col IN (char5_col, varchar_col)` pad nothing, so the CHAR(3) and CHAR(5) values are compared unpadded and do not match, although `char3_col = char5_col` is true. NOT IN then keeps rows that it should drop. - `char_col IN (other_char_col, 'literal')` pads nothing either. - The same happens for structs with CHAR fields. This change splits such an IN into one IN per group of elements that are padded the same way (the string literals, the columns of each type with CHAR, and the elements that are not padded), and pads each group as before, e.g. `rpad(char3_col, 5) IN (char5_col) OR char3_col IN (string_col)`. An IN whose elements are all padded the same way is unchanged. Splitting the IN references the value more than once. When the value is an outer reference, the fixed-point analyzer collects the outer references of the subquery after ApplyCharTypePadding has run on it, while the single-pass resolver collected them before its post-resolution rules ran, so the two analyzers disagreed on the subquery's outer attributes. This already happened when padding a struct outer reference, e.g. `EXISTS (SELECT 1 FROM t2 WHERE t1.struct_char2 = t2.struct_char5)`. PlanRewriter now collects the outer references again when a post-resolution rule changes the plan of a subquery. Co-authored-by: Isaac <no-reply@databricks.com>
…r stale implicit names - Split a mixed CHAR IN list into contiguous runs in written order when an element cannot be evaluated unconditionally, so an element that can fail or is non-deterministic is never evaluated before an earlier element that matches. - Parse the IN value's raw type once per IN instead of once per element. - Make the single-pass PlanRewriter fall back to the fixed-point Analyzer when the recollected outer references change the SQL of a subquery under an auto-generated select-list alias. - Correct the comments of the new IN case and mark outer-reference list elements as deferred. - Strengthen the CHAR IN-list test and add a single-pass fallback test. Co-authored-by: Isaac <no-reply@databricks.com>
spark-test
left a comment
There was a problem hiding this comment.
Review summary
The most serious problem is on the written-order path, which a list takes when it holds an element that can fail: a constant element that can raise, such as element_at(array('a'), 10) under the default ANSI mode, lands in a run that the literal-IN padding evaluates during analysis. Reading the code, a query such as SELECT CASE WHEN i > 0 THEN c IN (c2, element_at(array('a'), 10)) END FROM t, which the base branch runs, now fails to analyze. That path's only test matches on an element that needs no padding, so nothing checks how its runs are padded. The new classification also parses the raw types again for every IN on a CHAR or VARCHAR value, including lists whose plan does not change, and no test reaches the branch that keeps an IN whose split pads nothing.
In the single-pass resolver, the new fallback for implicitly named subquery columns recognizes only names generated for SQL select items, so a classic DataFrame column named after the same subquery keeps a stale name, and dual run would fail on the schema mismatch. No test pins the fallback's other boundary either: a subquery whose plan changes while its SQL stays the same. One new comment sends readers to the wrong place for the list of elements that are not padded yet.
The review also covered the grouping path that lists of only columns and literals take, and PlanRewriter's recollection of subquery outer references, and found nothing to change in either.
Cross-cutting observations
-
The analysis-time failure for an IN element that can raise and the repeated raw-type parsing both start at the same step of the new split case in ApplyCharTypePaddingHelper.scala (lines 111-120), where each group is handed back to the generic padding dispatch.
Their fixes change different things in those lines, so either can land without the other, but it is easiest to make both in one pass over the split case.
Related:
- A constant IN element that can raise is now evaluated during analysis
- CHAR raw types are parsed again for every CHAR or VARCHAR IN
Findings
7 total: 0 P0, 1 P1, 2 P2, 4 P3.
Blocking (P1)
- A constant IN element that can raise is now evaluated during analysis —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:196— see inline.
Non-blocking (P2)
- The only test of the written-order runs path matches without padding —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:746— see inline. - The implicit-name fallback misses classic DataFrame column names —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/PlanRewriter.scala:111— see inline.
Nit (P3)
- No test checks that the fallback skips subqueries whose SQL is unchanged —
sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/ExplicitlyUnsupportedResolverFeatureSuite.scala:158— see inline. - CHAR raw types are parsed again for every CHAR or VARCHAR IN —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:229— see inline. - No test covers keeping the original IN when a split pads nothing —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:669— see inline. - Comment sends readers to the wrong place for the unpadded elements —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:109-110— see inline.
Shared repair plans
Shared repair plan 1
Covered findings:
- A constant IN element that can raise is now evaluated during analysis —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:196 - The only test of the written-order runs path matches without padding —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:746
Verification:
- Regression: With ANSI mode on, compare a CHAR column inside a CASE WHEN branch with an IN list holding a same-length CHAR column that matches, followed by a constant element_at with an out-of-range index. The query returns true instead of failing during analysis. Without the CASE WHEN, the same IN still analyzes, for example when its DataFrame schema is read.
- Behavior: Use IN and NOT IN lists that take the runs path because they hold an element that can fail, and whose matching element is a CHAR column of another length or a string literal shorter than the value. They return what the OR of their equalities and its negation return, including a NULL outcome. Make the element that can fail a non-constant one, such as element_at over an array column, so the OR form runs as well.
- Behavior: A constant element that may raise but evaluates successfully, such as element_at(array('a'), 1), is padded like a string literal inside an IN list that also holds a CHAR column of another length.
Shared repair plan 2
Covered findings:
- CHAR raw types are parsed again for every CHAR or VARCHAR IN —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:229 - No test covers keeping the original IN when a split pads nothing —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:669
Verification:
- Inspection: Each raw-type string reaches the type parser at most once per padding pass, including for split groups, and an IN whose elements are all constant reaches it only in the literal-IN case.
- Regression: An IN that mixes padding kinds but pads nothing keeps the original IN in the analyzed plan, and an unaliased correlated EXISTS over it is named exists(c). One example is c IN (c2, s) where c and c2 are both CHAR(2) and read-side padding is on.
- Compatibility: The analyzed plans of literal-only lists, column-only lists and lists that split are the same as before the repair.
Shared repair plan 3
Covered findings:
- The implicit-name fallback misses classic DataFrame column names —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/PlanRewriter.scala:111 - No test checks that the fallback skips subqueries whose SQL is unchanged —
sql/core/src/test/scala/org/apache/spark/sql/analysis/resolver/ExplicitlyUnsupportedResolverFeatureSuite.scala:158
Recommended change: In AliasResolver, tag an Alias when AliasResolution.resolve returns one whose child contains a subquery expression and whose name equals the child's toPrettySQL, the rule both the generic branch and the DataFrame naming function follow. Use a new ResolverTag, set on the alias the resolver registers after the expression-ID mapping. In PlanRewriter.checkNoImplicitNameOfChangedSubquery, fall back for an alias over a changed subquery that carries either that tag or AUTO_GENERATED_ALIAS. Add tests to the single-pass fallback suite. A classic DataFrame built from a CHAR table's rows and schema that selects the unaliased correlated EXISTS falls back, and under dual run it is named exists(c, c), while the same DataFrame with an explicit alias resolves in single pass. An implicitly named subquery whose plan the post-resolution rules change but whose SQL stays the same also resolves in single pass, for example SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c = n2.c5) FROM n1 or the uncorrelated SELECT EXISTS (SELECT 1 FROM n2) FROM n1.
Why this works: AliasResolver is where an unnamed select-list expression receives its column name. Comparing that name with the child's SQL there marks the names, from either naming branch, that the post-resolution rules can make stale. PlanRewriter then falls back for those columns as it already does for SQL text. An explicit alias reaches AliasResolver already named, through handleResolvedAlias rather than from an UnresolvedAlias, and a name from the stable derived-column alias is taken from the query text rather than from toPrettySQL, so neither is tagged and both keep resolving in single pass. The negative-boundary tests pin that the trigger still compares the subquery's SQL rather than its plan.
Compatibility: Three things stay exactly as they are: the fixed-point analyzer's column names and metadata, explicit aliases, and names derived from the query text under the stable derived-column alias setting.
Risks: The tag is lost if a resolver step rebuilds the Alias through a case-class copy that does not copy tags. The fallback would then silently miss those columns again, as it does for DataFrames now. The repair must therefore check that the tag survives from AliasResolver to PlanRewriter, including through lateral column alias rewriting. Rendering the child's SQL is extra work for each unnamed select item; limiting it to children that contain a subquery expression keeps it off every other column. In the internal single-pass-only mode, a PIVOT with several aggregates names each output column after an aggregate's SQL, so an aggregate holding a correlated subquery whose CHAR IN is split could still get a different name from the default analyzer. The review did not settle whether single pass accepts such an aggregate, and this repair does not cover it.
Constraints: Explicitly aliased subqueries, including one named like the old generated name, and subqueries outside the select list must keep resolving in single pass, as the existing fallback test requires. Column names and column metadata produced by the fixed-point analyzer must not change.
Exclusions:
- Aliases that the single-pass resolver creates for internal expressions are not output column names and stay outside this change. Grouping or aggregate expressions extracted for HAVING or ORDER BY are examples.
Verification:
- Regression: Create a DataFrame from a CHAR table's rows and schema and select an unaliased correlated EXISTS whose IN on the outer CHAR column is split. The single-pass resolver raises its unsupported-feature fallback, and under dual run the column is exists(c, c).
- Behavior: Some unaliased select-list subqueries have plans that the post-resolution rules change while their SQL stays the same. Examples are an EXISTS whose only correlated predicate is a padded equality on the outer CHAR column, and an uncorrelated EXISTS over a CHAR table. Such a subquery resolves in single pass without the fallback.
- Compatibility: Explicit aliases over a changed subquery, from SQL and from a DataFrame, still resolve in single pass. The schema metadata of an unaliased DataFrame column is unchanged.
Generated by Omnigent on Databricks
|
|
||
| private def inElementPadding(valueIsChar: Boolean, element: Expression): InElementPadding = | ||
| element match { | ||
| case e if e.foldable => if (valueIsChar) PaddedLiteral else NotPadded |
There was a problem hiding this comment.
Blocking (P1): This classifies every constant element of a CHAR-valued list as a padded literal, including one whose evaluation can raise. When the list also holds an element that is not safe to evaluate unconditionally, it is split into written-order runs, and each run goes back through singleNodePaddingForStringComparison (line 113). A run of constants then reaches the literal-IN case, which calls lit.eval() on every element during analysis (lines 131-132).
Reading the code, SELECT CASE WHEN i > 0 THEN c IN (c2, element_at(array('a'), 10)) END FROM t, with c and c2 both CHAR(2) and equal, now fails to analyze with INVALID_ARRAY_INDEX_IN_ELEMENT_AT under the default ANSI mode, in both analyzers. On the base branch the same query returns true: the mixed list is not padded, ConstantFolding keeps a failing element inside a conditional branch, and In stops at the c2 match. A view whose text has such an IN would fail on its next read.
One fix that keeps the padding: before padding a run of constants, evaluate under a non-fatal guard each element that ExprUtils.canEvaluateUnconditionally rejects, and give one that raises an IN of its own at its written position, left unpadded and outside the padding cases. Such an element can never match, so leaving it unpadded changes no result.
See Shared repair plan 1 in the review body.
There was a problem hiding this comment.
Fixed in acda41b. I confirmed it first: SELECT CASE WHEN i > 0 THEN c IN (c2, element_at(array('a'), 10)) END FROM t returned [true] before this PR and failed to analyze with it, and so did reading the schema of c IN (c2, element_at(array('a'), 10)). A list of only constants, c IN ('a', element_at(array('a'), 10)), already failed the same way on master, as the literal-IN padding evaluates every element.
I went with a smaller fix than the separate-IN one: the literal-IN padding now evaluates each element under a non-fatal guard, and an element that fails gets no length and is left unpadded, like a NULL. It can never match, so this changes no result. The fix covers both cases. The comparison of a CHAR column with a constant had the same eval(), so it uses the same guard.
| sql(s"CREATE TABLE t(c CHAR(2), c2 CHAR(2), c5 CHAR(5), s STRING, arr ARRAY<STRING>) " + | ||
| s"USING $format") | ||
| sql("INSERT INTO t VALUES ('a', 'a', 'b', 'x', array('y'))") | ||
| val cond = "c IN (s, c2, element_at(arr, 10), c5)" |
There was a problem hiding this comment.
Non-blocking (P2): This row matches c2, which has the value's own CHAR(2) length, so both assertions pass whether or not the runs path pads anything; they only catch reordering. checkInAsOr's lists hold only columns and literals, so they take the grouping path instead. A padding regression on the runs path, which any list with an element that can fail or is non-deterministic takes, would bring back the wrong IN and NOT IN results without a failing test. A case whose matching run needs padding, for example c IN (s, c5, element_at(arr, 10)) with c5 holding 'a', together with its NOT IN form and a NULL outcome, would cover it.
See Shared repair plan 1 in the review body.
There was a problem hiding this comment.
Added in acda41b. c IN (s, c5a, element_at(arr, 10)), where c5a is a CHAR(5) holding 'a', and c IN (s, 'a', c5, element_at(arr, 10)), together with their NOT IN forms and a NULL outcome. The written-order path already padded these correctly, so they pass on the previous commit too; before this PR they failed at runtime, since the unpadded match is missed and element_at is reached.
The IN and NOT IN are checked in separate queries: with both in one SELECT list, the shared element_at(arr, 10) is evaluated for both and fails, and the plain OR form of the equalities does the same on master.
| plan.foreach { operator => | ||
| operator.expressions.foreach(_.foreach { | ||
| case alias: Alias | ||
| if alias.metadata.contains(AUTO_GENERATED_ALIAS) && alias.child.exists { |
There was a problem hiding this comment.
Non-blocking (P2): Only aliases with AUTO_GENERATED_ALIAS metadata count as implicit names here, and AliasResolution.resolve adds that marker only for SQL select items. Classic DataFrame columns get their names from the same toPrettySQL rule through the optGenAliasFunc branch (AliasResolution.scala lines 65-66), which adds no metadata.
So, reading the code, a DataFrame built with createDataFrame from a CHAR table's rows and schema that selects EXISTS (SELECT 1 FROM n2 WHERE c IN (n2.c5, n2.s)) without an alias keeps exists(c) in the single-pass resolver, while the default analyzer names it exists(c, c). Under dual run, on by default in Spark's tests, that program would fail with a schema mismatch, and in tentative or single-pass mode it gets a name the default analyzer does not give. Only the internal, default-off single-pass modes are affected; the default analyzer and Spark Connect, whose projections use a marked alias, are not.
See Shared repair plan 3 in the review body.
There was a problem hiding this comment.
Fixed in acda41b. I reproduced it: the unaliased DataFrame column failed with HYBRID_ANALYZER_EXCEPTION.OUTPUT_SCHEMA_COMPARISON_MISMATCH under dual run. Instead of a new resolver tag, the check now also treats an alias as implicit if its name is the SQL of its expression, which covers both naming paths, and it runs on the plan before the rewrite, whose aliases still have the expressions they were named after. An explicit alias that happens to equal that SQL falls back too, which is safe. The test checks the DataFrame column gets exists(c, c) under dual run, and an explicit alias keeps its name.
| shouldPass = false, | ||
| expectedMessage = Some("an implicitly named column whose subquery has its outer references") | ||
| ) | ||
| checkResolution(s"SELECT $exists AS e, $scalar AS `exists(c)` FROM n1", shouldPass = true) |
There was a problem hiding this comment.
Nit (P3): These passing cases use explicit aliases or a WHERE-clause EXISTS, so none has an implicitly named column for the check to consider. If the trigger fired on any rewritten subquery plan instead of comparing the subquery's SQL (PlanRewriter.scala line 82), every check in this test would still pass, and dual run would hide the over-trigger by returning the fixed-point result. Read-side padding changes the plan of nearly every subquery over a CHAR table, so such a regression would push most unaliased select-list subqueries over CHAR tables out of single pass. A shouldPass = true case such as SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c = n2.c5) FROM n1, or the uncorrelated SELECT EXISTS (SELECT 1 FROM n2) FROM n1, would pin that boundary.
See Shared repair plan 3 in the review body.
There was a problem hiding this comment.
Added both in acda41b: SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c = n2.c5) FROM n1 and SELECT EXISTS (SELECT 1 FROM n2) FROM n1 resolve in single pass.
| def unapply(in: In): Option[Seq[Seq[Expression]]] = in.value match { | ||
| case AttrOrOuterRef(attr) if in.resolved => | ||
| // Parse the raw type of the value once, not once per element. | ||
| CharVarcharUtils.getRawType(attr.metadata).flatMap { valueRawType => |
There was a problem hiding this comment.
Nit (P3): This parse runs for every IN whose value has a CHAR or VARCHAR raw type, before the existing IN cases (line 111). For a uniform list unapply then returns None, and the literal-IN case (line 125) or CharVarcharUtils.addPaddingInStringComparison parses the same strings again. For a split IN, each group re-enters this extractor (line 113) and is parsed once more before the IN case parses it a third time. So a literal list such as TPC-DS's i_category IN ('Books', 'Home', 'Sports'), whose plan does not change, now parses char(50) twice, and c IN (c5, s) parses c five times where the base branch parses it once. getRawType builds a new parser on every call, so this is extra analysis work, bounded per IN, on inputs the PR leaves alone. Parsing each raw-type string once per padding pass, for example through a map kept for one paddingForStringComparison call, and returning None before any parsing when every element is constant, would remove it without changing any plan.
See Shared repair plan 2 in the review body.
There was a problem hiding this comment.
Done in acda41b: InWithMixedPadding now returns before parsing any raw type when every element is a constant, so a literal list like i_category IN ('Books', 'Home', 'Sports') is parsed only by the literal-IN padding, as before. I left the few extra parses for a split IN, which only happen for the lists this PR changes.
There was a problem hiding this comment.
Thanks, the early return for constant lists works: i_category IN ('Books', 'Home', 'Sports') now parses only in the literal-IN padding. The remaining extra parses are not limited to the lists this PR changes, though. InWithMixedPadding parses the raw type of the value and of each CHAR or VARCHAR column element before it decides whether to split, and when it returns None the existing IN padding parses the same strings again. So c IN (c5, c10) over CHAR columns, whose plan does not change, now makes 6 parses instead of 3, and c IN (c2, s) with c and c2 both CHAR(2) and read-side padding on, which keeps its single IN, makes 8 instead of 2. A split IN also sends each group back through singleNodePaddingForStringComparison, where InWithMixedPadding runs again but can only return None, so the value is parsed up to twice more per group or run. Passing each group straight to the existing IN padding, and reusing the raw types the classification has already parsed, would remove this without changing any plan. It is a small analysis-time cost, so this stays a non-blocking nit.
| // A list of only columns and literals keeps all its literals in one IN. | ||
| val ins = spark.table("t").selectExpr("c IN (c5, 'x', s, 'y')").queryExecution.analyzed | ||
| .flatMap(_.expressions.flatMap(_.collect { case i: In => i })) | ||
| assert(ins.length == 3 && ins.exists(i => i.list.length == 2 && i.list.forall(_.foldable))) |
There was a problem hiding this comment.
Nit (P3): This is the only plan assertion, and every mixed list in the new tests pads something, so no test reaches the branch that keeps the original IN when the split pads nothing (ApplyCharTypePaddingHelper.scala lines 115-120). If that branch always emitted the OR, the result checks would still pass, while c IN (c2, s) with c and c2 both CHAR(2) would get a new plan, and an unaliased correlated EXISTS over it would be renamed from exists(c) to exists(c, c) and leave the single-pass resolver. An assertion that such an IN keeps its plan, or that the EXISTS keeps the name exists(c), would catch it.
See Shared repair plan 2 in the review body.
There was a problem hiding this comment.
Added in acda41b: c IN (c2, s) with c and c2 both CHAR(2) keeps a single IN with both elements in the analyzed plan.
| // elements of each IN on its own. `InWithMixedPadding` describes how the list is split, and | ||
| // which elements are not padded yet. |
There was a problem hiding this comment.
Nit (P3): InWithMixedPadding's scaladoc (lines 213-224) describes only how the list is grouped or split into runs. The elements that are not padded yet, outer references used as list elements, IN subqueries, and a literal value with a list of CHAR columns, are listed in the TODO inside inElementPadding (lines 207-209):
| // elements of each IN on its own. `InWithMixedPadding` describes how the list is split, and | |
| // which elements are not padded yet. | |
| // elements of each IN on its own. `InWithMixedPadding` describes how the list is split, and | |
| // the TODO in `inElementPadding` lists the elements that are not padded yet. |
Verification:
- Inspection: The comment above the split case in ApplyCharTypePaddingHelper.scala sends readers to the TODO in inElementPadding for the elements that are not padded yet. That TODO lists outer references used as list elements, IN subqueries, and a literal value with a list of CHAR columns.
…ll back for DataFrame names
- The literal-IN padding computed the length of every constant element with `eval()` during
analysis, so a constant that fails, such as `element_at(array('a'), 10)` with ANSI mode on,
failed the analysis. The split of a mixed list now sends such a constant to that padding, so
e.g. `CASE WHEN i > 0 THEN c IN (c2, element_at(array('a'), 10)) END` stopped working. Evaluate
under a non-fatal guard, and leave an element that fails unpadded, as it can never match. The
comparison of a CHAR column with a constant uses the same guard.
- Return early for a list of only constants, before parsing any raw type.
- The single-pass fallback for stale implicit names also recognizes an alias whose name is the
SQL of its expression, as for an unaliased DataFrame column, and checks the plan before the
rewrite.
- Tests: padding on the written-order path, a NULL outcome, constants that fail or can fail, an
IN that pads nothing keeps its plan, an unaliased DataFrame column, and subqueries whose plans
but not SQL change. Fix a comment that pointed to the wrong place.
Co-authored-by: Isaac <no-reply@databricks.com>
spark-test
left a comment
There was a problem hiding this comment.
Review summary
Since the previous review, most of what it raised is fixed. A constant IN element that cannot be evaluated, such as element_at(array('a'), 10) with ANSI mode on, no longer fails the analysis, because literalCharLength now evaluates constants under a non-fatal guard. The written-order runs path has tests whose matching element needs padding, with NOT IN and a NULL outcome. The single-pass fallback now also covers unaliased DataFrame columns and has tests for subqueries whose SQL does not change. A test pins that a split that pads nothing keeps its IN, and the comment above the split case now points to the TODO in inElementPadding. The repeated raw-type parsing was fixed only for lists of constants: lists of columns, mixed lists that keep their IN, and split groups still parse the same raw types again, so that point stays open in its earlier thread.
This round adds three smaller points. The new scaladoc of literalCharLength says a failing constant is not evaluated after an IN element that matches, which the optimizer's constant folding contradicts outside a conditional branch. No test runs a failing constant that the query reaches, so a guard that swallowed the error instead of deferring it would go unnoticed. And no test lists two struct columns whose CHAR fields have different shapes, the case that the new padding key keeps apart.
The review also covered the single-pass resolver's recollection of subquery outer references and its fallback for implicitly named columns, and found nothing to change there.
Cross-cutting observations
-
The repeated raw-type parsing and the untested struct-shape key both sit in the new classification that groups IN elements by how they are padded, so the missing struct-shape test is also the check that would catch a rework of that classification, such as the one that removes the repeated parsing, merging differently shaped CHAR-bearing columns into one IN.
Each of the two findings listed below still has its own fix and can land without the other.
Related:
- CHAR raw types are still parsed again for IN lists whose plan does not change
- No test mixes struct columns whose CHAR fields have different shapes
Findings
4 total: 0 P0, 0 P1, 0 P2, 4 P3.
Nit (P3)
- literalCharLength scaladoc claims a matching IN element defers a failing constant —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:258-261— see inline. - CHAR raw types are still parsed again for IN lists whose plan does not change (still raised) —
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:231— unresolved in existing discussion. - No test runs a failing constant that the query reaches —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:778— see inline. - No test mixes struct columns whose CHAR fields have different shapes —
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:720— see inline.
Re-review status
Prior AI findings: 6 no longer raised, 1 still raised; additional unresolved findings in this review: 3.
Of these: 2 in code changed since the previous review; 1 in code the previous review already covered.
PR description suggestions
- In the list of user-facing changes, say that the corrected IN and NOT IN padding also applies to the conditions of UPDATE, DELETE and MERGE statements, so such a statement can now change a different set of rows than before.
- In the bullet about constants that fail to evaluate, say that outside a conditional branch the optimizer's constant folding still raises the constant's error, also after an element that matches, so the change only lets such a constant pass when it sits in a CASE or IF branch, where it fails only if the query reaches it, or when the query is only analyzed, such as when reading its schema. This follows up on an existing discussion.
Decision challenges
Unaliased subquery columns are renamed and IN results change with no migration note or legacy configuration
Location: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:113
Code that refers to the generated name of an unaliased select-list EXISTS or scalar subquery whose correlated IN on an outer CHAR column is split stops resolving after an upgrade, and users whose IN and NOT IN results change find no migration-guide entry and no setting that keeps the old behavior while they adapt. The review leans toward a migration-guide entry together with an internal legacy configuration that restores the base branch's unsplit IN, because a behavior change that users can lose should ship with a rollback flag and a migration note; it does not decide this itself, because whether Spark wants a legacy configuration for this correction depends on project practice and on whether the change also lands on branch-4.x.
Reading the code: on the base branch, SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c IN (n2.c5, n2.s)) FROM n1 keeps one IN, so its column is named exists(c), but the IN compares n1.c with n2.c5 unpadded and can miss rows. With this change the IN is split into one IN per padding kind, each repeating the outer n1.c, and the fixed-point analyzer collects outer references after padding and keeps duplicates, so the column is named exists(c, c), and the scalar form scalarsubquery(c, c), as the PR's dual-run test asserts; the single-pass resolver falls back so that both analyzers agree. A permanent view such as CREATE VIEW v AS SELECT CAST(x.`exists(c)` AS INT) AS e FROM (SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c IN (n2.c5, n2.s)) FROM n1) x, created on the base branch, passes the auto-generated alias check because its own output column is e, and after an upgrade it can no longer be read, since its text is analyzed again and the inner column is now exists(c, c). The description accepts the new name as the one the equivalent OR of equalities already gets, but that holds only when each split IN has one element: n1.c IN (n2.c5, n2.c10, n2.s) becomes two INs and is named exists(c, c), while its OR is named exists(c, c, c), and a list of only CHAR columns such as n1.c IN (n2.c5, n2.c10) keeps exists(c). Top-level IN columns keep their names, which are assigned before padding. Keeping the old name would need a broader change to how the split references the value or how subqueries are named. Precedent for CHAR padding corrections is mixed: the padded overwrite conditions ship spark.sql.legacy.noCharPaddingInOverwriteCondition with their migration-guide entry, while the entry for outer CHAR columns of correlated subqueries offers only a workaround. branch-4.4 and branch-4.x keep the unsplit IN and the old names.
The answers: accept the change as it is, so the example above is named exists(c, c) and returns the corrected result, with no migration-guide entry and no setting; keep the change and add a migration-guide entry, for the release it first ships in, that describes the corrected IN and NOT IN results, the renamed columns, and that an explicit alias keeps a column's name stable, with no code change; or add that entry plus an internal spark.sql.legacy configuration, false by default, under which the split does not apply, so the example is named exists(c) again and returns the base branch's unpadded result, with the entry naming the configuration and a test that it restores the base branch's plan and column names.
Generated by Omnigent on Databricks
| * `element_at(array('a'), 10)` with ANSI mode on, is only evaluated when the query reaches it, | ||
| * e.g. not in a conditional branch that is not taken, or not after an element of an IN list | ||
| * that matches, so evaluating it here must not fail the analysis. Such an expression can | ||
| * never match, so it does not need to be padded. |
There was a problem hiding this comment.
Nit (P3): In and Or are not conditional expressions, so the optimizer's constant folding evaluates a foldable IN element outside a CASE or IF and raises its error, whatever the earlier elements match. Reading the code, SELECT c IN ('a', element_at(array('a'), 10)) FROM t with ANSI mode on still fails with INVALID_ARRAY_INDEX_IN_ELEMENT_AT during optimization although 'a' matches; only inside a conditional branch, as in the new tests' CASE WHEN i > 0 THEN ..., is such an element left to the IN's short-circuit at run time. The guard is still needed for conditional branches and for operations that only analyze the query, so only the stated reason is off, but a maintainer reading it could rely on a deferral the optimizer does not give. The comment above the failing-constant checks in CharVarcharTestSuite.scala (lines 767-768) generalizes the same way.
| * `element_at(array('a'), 10)` with ANSI mode on, is only evaluated when the query reaches it, | |
| * e.g. not in a conditional branch that is not taken, or not after an element of an IN list | |
| * that matches, so evaluating it here must not fail the analysis. Such an expression can | |
| * never match, so it does not need to be padded. | |
| * `element_at(array('a'), 10)` with ANSI mode on, must not fail the analysis: constant folding | |
| * raises its error outside a conditional branch but leaves it to execution inside one, which may | |
| * never be taken, and an operation that only analyzes the query never evaluates it. Such an | |
| * expression can never match, so it does not need to be padded. |
Verification:
- Inspection: The scaladoc of literalCharLength in ApplyCharTypePaddingHelper.scala and the comment above the failing-constant checks in CharVarcharTestSuite.scala describe a failing constant as deferred only inside a conditional branch, which constant folding leaves to execution, or by an operation that only analyzes the query, and neither says that an earlier matching IN element keeps it from being evaluated.
| checkAnswer( | ||
| sql("SELECT CASE WHEN i < 0 THEN c = element_at(array('a'), 10) END FROM t"), | ||
| Row(null)) | ||
| assert(sql("SELECT c IN (c5, element_at(array('a'), 10)) FROM t").schema.length == 1) |
There was a problem hiding this comment.
Nit (P3): This assertion only reads the schema, and every other failing constant in this test sits in a CASE branch after a matching element or in a branch that is not taken, so no check runs a failing constant that the query reaches. If the literal-IN padding or padAttrLitCmp later replaced such a constant with NULL, or dropped it as one that can never match, this query would return NULL instead of raising INVALID_ARRAY_INDEX_IN_ELEMENT_AT, and so would SELECT c = element_at(array('a'), 10) FROM t, while every test still passes. Running both queries outside a conditional branch and expecting that error would show that the guard in literalCharLength only defers the failure instead of hiding it.
Verification:
- Behavior: With ANSI mode on and a table row holding c CHAR(2) = 'a' and c5 CHAR(5) = 'b', running
SELECT c IN (c5, element_at(array('a'), 10)) FROM tandSELECT c = element_at(array('a'), 10) FROM tfails with INVALID_ARRAY_INDEX_IN_ELEMENT_AT in each case, while the IN query still analyzes, so its schema can be read.
|
|
||
| // CHAR fields nested in structs. | ||
| withTable("t") { | ||
| sql(s"CREATE TABLE t(c STRUCT<f: CHAR(2)>, c5 STRUCT<f: CHAR(5)>, s STRUCT<f: STRING>) " + |
There was a problem hiding this comment.
Nit (P3): The list elements in this case are single-field structs and only c5 has a CHAR field, so no IN in the new tests lists two CHAR-bearing structs of different shapes, the case that the padding key in inElementPadding keeps apart. Reading the code, if the key only recorded whether a type contains CHAR, c STRUCT<f: CHAR(2), g: CHAR(2)> IN (x STRUCT<f: CHAR(5), g: STRING>, y STRUCT<f: CHAR(5), g: CHAR(5)>) would pad c against both in one IN, typeWithWiderCharLength would turn g into NullType, and the IN would be false where c = y is true, as on the base branch, with every new and existing test still passing. A case with such a pair, checked against the OR of its equalities, would catch it.
Verification:
- Behavior: With read-side padding on, for c STRUCT<f: CHAR(2), g: CHAR(2)>, x STRUCT<f: CHAR(5), g: STRING> and y STRUCT<f: CHAR(5), g: CHAR(5)> holding ('a', 'b'), ('z', 'z') and ('a', 'b'),
c IN (x, y)andc IN (y, x)return true andc NOT IN (x, y)returns false, the same asc = x OR c = yand its negation.
What changes were proposed in this pull request?
value IN (e1, e2, ...)should return the same result asvalue = e1 OR value = e2 OR .... When the value is a CHAR column, each of those equalities pads its two sides independently:ApplyCharTypePaddinghandles an IN list differently. It pads the value and all the elements together, and it gives up when the elements need different padding:char_col IN (other_char_col, string_col)andchar_col IN (other_char_col, varchar_col)pad nothing.CharVarcharUtils.addPaddingInStringComparisonbails out when one element has no CHAR raw type, or when CHAR and VARCHAR are mixed.char_col IN (other_char_col, 'literal')matches neither of the two IN cases (all literals, or all columns), so it is not padded either.This PR adds a case to
ApplyCharTypePaddingHelper.singleNodePaddingForStringComparison. It groups the IN list elements by how each one is padded against the value, and the existing IN padding then pads each group as before. There are three kinds of group:The groups are combined with OR. For example,
c IN (c5, s)becomesrpad(c, 5) IN (c5) OR c IN (s). An IN whose elements are all padded the same way, or whose split would pad nothing, is left unchanged.Grouping changes the order in which the elements are evaluated, so it is only used when every element can be evaluated on any row (
ExprUtils.canEvaluateUnconditionally), e.g. columns and literals. Then all the string literals stay in one IN, which the optimizer can still turn into anInSet. Otherwise, e.g. withelement_at(arr, 10)in ANSI mode, the list is split into runs of consecutive elements that are padded the same way, in the order written. Each element is then evaluated only on the rows where no element written before it matched, as in the OR of the equalities.Splitting the IN references the value more than once. When the value is an outer reference, the two analyzers then disagree on the subquery's outer attributes:
ApplyCharTypePadding) have run on the subquery plan.PlanRewriterruns those rules on the subquery plan but keeps the outer references it collected before.This mismatch already exists on master when a struct outer reference is padded, e.g.
EXISTS (SELECT 1 FROM t2 WHERE t1.struct_char2 = t2.struct_char5). This PR makesPlanRewritercollect the outer references again when the rules change a subquery plan, matching the fixed-point analyzer.An unaliased subquery in a select list is named after its SQL, which includes its outer references, so the new outer references can also change the column name, e.g. from
exists(c)toexists(c, c). The single-pass resolver names the column before these rules run, and renaming it would mean renaming every reference to it. So in that casePlanRewriterthrowsExplicitlyUnsupportedResolverFeature, and the query falls back to the fixed-point analyzer, which gives the column the new name. Subqueries under an explicit alias, or in a WHERE clause, still run in single pass.These related cases need different code and are left out of this PR:
char_col IN (SELECT other_char_col FROM ...).'a' IN (char_col, ...).Why are the changes needed?
They fix wrong results: IN and NOT IN disagree with the equalities they are made of.
Does this PR introduce any user-facing change?
Yes.
rpad(c, 5) IN (c5) OR c IN (s). If the list has an element that can fail or is non-deterministic, there is one IN per run of consecutive elements padded the same way, so a list whose padding kinds interleave can get more INs than groups.SELECT EXISTS (SELECT 1 FROM n2 WHERE n1.c IN (n2.c5, n2.s)) FROM n1used to be namedexists(c)and is now namedexists(c, c), the name that the equivalentn1.c = n2.c5 OR n1.c = n2.salready gets.element_at(array('a'), 10)with ANSI mode on. It is left unpadded, as it can never match. Previously, a list of only constants with such an element failed the analysis, even in a conditional branch that is not taken, or after an element that matches.spark.sql.analyzer.singlePassResolver.enabled: an unaliased select-list subquery whose outer references the padding changes, as above, fails with the single-pass analyzer's unsupported-feature error instead of running. Giving the subquery an explicit alias avoids it. The default analyzer and the dual-run and tentative modes are not affected, because they fall back to the fixed-point analyzer.How was this patch tested?
Added the test
char type comparison: IN list mixing CHAR columns with other elementstoCharVarcharTestSuite. It covers read-side padding enabled and disabled, a correlated subquery whose IN value is an outer reference, and structs with CHAR fields, including a padded struct outer reference. It also checks every IN and NOT IN against the OR of its equalities, including data where the STRING and VARCHAR elements equal the CHAR value without extra padding, and that a list of only columns and literals keeps its literals in one IN. Without the fix, the test fails inFileSourceCharVarcharTestSuiteandDSV2CharVarcharTestSuite.Also added:
char type comparison: IN list keeps the order of elements that can failinCharVarcharTestSuite, in ANSI mode:element_atwith an out-of-range index returns true instead of raising, in a projection and in a filter, also when the matching element is a CHAR column of another length or a shorter string literal, which need padding. NOT IN and a NULL outcome match the OR of the equalities.element_atwith an out-of-range index in an IN list, or compared with a CHAR column, does not fail the analysis, and a constantelement_atthat succeeds is padded like a string literal.ExplicitlyUnsupportedResolverFeatureSuite: unaliased EXISTS and scalar subqueries in a select list hit the single-pass fallback, the same subqueries under explicit aliases (including one namedexists(c)) and a correlated EXISTS in WHERE still resolve in single pass, and dual run returns the columnsexists(c, c)andscalarsubquery(c, c). An unaliased DataFrame column over such a subquery falls back too, and subqueries whose plans the post-resolution rules change without changing their SQL still resolve in single pass.Also ran:
FileSourceCharVarcharTestSuite,DSV2CharVarcharTestSuiteandBasicCharVarcharTestSuiteSubquerySuiteorg.apache.spark.sql.analysis.resolverSQLQueryTestSuitefiltered tosubqueryandcharHiveCharVarcharTestSuitecould not run locally because of a classpath issue in my environment (NoClassDefFoundError: org/apache/commons/logging/LogFactory).Was this patch authored or co-authored using generative AI tooling?
Generated-by: Isaac (Claude Opus 5.5)
This pull request and its description were written by Isaac.