[SPARK-61972][SQL] Pad CHAR columns of a UNION to the widest length of its children #60756
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.344
Real PR Conversation Timeline
1 comments
"Review active on #60756"
general
weight: 0.35
shivadarshan-devadiga
What changes were proposed in this pull request?
A
Unionbuilds each output column from its first child (Union.mergeChildOutputs), metadata included, so the CHAR length of the output is the one of the first child. With the default read-side padding, the values of each child are padded to the CHAR length of their own table, andApplyCharTypePaddingpads a string literal compared with the output to the output's CHAR length. When the children have different CHAR lengths, the values of the other children have another length, and the comparison misses them. The rows that match depend on the order of the children:INTERSECT, EXCEPT, IN subqueries and scalar subqueries compare CHAR values of different lengths without padding either, so
SELECT id FROM t3 WHERE c IN (SELECT c FROM t5),SELECT id FROM t5 WHERE c = (SELECT c FROM t3)andSELECT c FROM t3 INTERSECT SELECT c FROM t5return nothing.This PR gives a set operation of CHAR(n) and CHAR(m) the length max(n, m), as the SQL standard does, and pads the shorter side of set operations and subquery comparisons to the longer length:
resolvedExceptCharLengths, the definition ofresolvedbefore this PR), so after the widening of the types and the deduplication of the output. The rules that do these rewrites pad it in the same step (SetOperationCharPadding.padResolved), so that a chain of set operations resolves in one traversal:WidenSetOperationTypes, which also pads a set operation that needs no widening and returns both mappings as one,ResolveUnionafter it turns a by-name union into a positional one, andResolveReferencesandDeduplicateRelationsafter they deduplicate. A new analyzer rule,PadSetOperationCharLengths, runs right after the type-coercion rules and pads the others. Padding only happens during analysis, soV2Writes, which reuses the type-coercion rules on optimized plans, doesn't pad. When the children of aUnion,IntersectorExcepthave CHAR columns or fields of different lengths at the same position (CharVarcharUtils.widerCharRawTypes), it pads the shorter children to the widest length in a Project over each child that needs it, asWidenSetOperationTypescasts them to the widest type. The output, which comes from the first child, then has the widest length. The single-pass resolver does the same inSetOperationLikeResolver, with the same helper (SetOperationCharPadding.padChildren).CharVarcharUtils.widerCharRawTypesreads the outputs by index, returns early when the first child has no raw type, and parses each raw-type string once.- CHAR columns of different lengths have the same
StringType, so such a set operation would otherwise be resolved at once, and the operators above it with the first child's length. Like a set operation whose types differ, it isn't resolved during analysis until its children are padded (SetOperationCharPadding.isAligned). Only analysis pads, and optimizer rules can make the metadata of the children differ, such asSimplifyConditionalsturning an expression into a column, so outside of analysis the CHAR lengths don't affectresolved. The phase isAnalysisHelper.isInAnalyzer: every run of the analyzer is in it (Analyzer.executenow opensmarkInAnalyzer, asexecuteAndCheckdoes), and the optimizers are not, also when an analyzer rule optimizes another query (Optimizer.executeandAQEOptimizer.executerun in the newmarkOutsideAnalyzer).CheckAnalysis.checkAnalysisruns in it too, so a set operation that the check copies, such as by inlining a CTE of a view body analyzed under a legacy flag the view captured, is resolved as before.WidenSetOperationTypeskeys offresolvedExceptCharLengths, so a CHAR mismatch alone doesn't make it cast. When it does cast, such as a struct with an INT field to one with a BIGINT field, the alias of the cast keeps the CHAR types that the cast doesn't change (CharVarcharUtils.rawTypeOfCast), here and in the single-pass resolver, so a set operation over another one can still pad them. It keeps them only where every child has a raw type and the raw types are the same or can be padded to the same lengths (keepsCharTypesInCast); elsewhere, such as for VARCHAR(3) and VARCHAR(10), the cast drops them as before.- The padding uses
readSidePadding, as the scan does, so it doesn't truncate over-length values that a CHAR column of an external table can hold. Without read-side padding, it pads the widest children too, whose values the scan didn't pad.- It covers CHAR fields of structs, next to fields of other types, and elements of arrays. A rebuilt struct reads the fields of a nullable struct through
KnownNotNull, so it keeps the nullability of its fields. It compares raw types by their lengths and effective collations, sochar(5)andchar(5) collate UTF8_BINARYare the same. Each position of a column that a child outputs more than once gets the widest length of the children at that position, so the column is padded once per length it needs.-
CharVarcharUtils.ReadSidePaddingmatches the padding of a set operation over the scan's padding,readSidePadding(readSidePadding(c, 3), 5), asreadSidePadding(c, 5), the same for every value, so the V2 translation and the filter statistics still see one padding of the column.ApplyCharTypePaddingHelper.paddingForStringComparisonpads each IN value (column or string literal) and the matching column of the subquery, the column in aProjectover the subquery. It also treats a scalar subquery of one CHAR column like that column: against a string literal, a column, or another scalar subquery. It also pads a scalar subquery of a CHAR column compared with a list of constants (IN), and any string constant in an IN subquery. A scalar subquery is padded only for a CHAR column itself, a comparison whose types don't match is left to CheckAnalysis, and a constant that fails to evaluate, such as one in a branch that is never evaluated, is left as it is, asConstantFoldingleaves it. These go through the sameaddPaddingInStringComparisonas a comparison of two columns, so both sides are padded when read-side padding is off, but they pad like read-side padding, which keeps longer values instead of truncating them.ApplyCharTypePaddingbrings the values of the recursive term of aUnionLoopto the anchor's CHAR lengths, narrowing longer values and padding shorter ones, such as when the anchor is a set operation padded to a longer length than the recursive term reads, and narrows the values of a view's query to the lengths the view stores (compared after the view's cast to its stored type), which can be shorter for a view of a set operation created before this change. It removes the trailing spaces past the length (CharVarcharCodegenUtils.charTypeNarrowing), which keeps values with other characters past it, and includes CHAR fields of structs whose raw types are in the metadata of their fields, such as a struct built withnamed_struct. Only the union of the anchor and the recursive term isn't padded, before it becomes theUnionLoop; a set operation inside the recursive term is padded once it reads theUnionLoopRef.UnionLoopExectags the set operations of the plans it builds from the optimized anchor and recursive term (SetOperationCharPadding.SKIP_CHAR_PADDING), so that their analysis doesn't pad them again. A viewWITH SCHEMA TYPE EVOLUTIONevolves to the wider CHAR type:ViewSyncSchemaToMetaStorestores the query's CHAR type for a column that the narrowing narrowed. A viewWITH SCHEMA EVOLUTIONstores the CHAR and VARCHAR types of its query when they differ. When such an update fails, the read still succeeds and a warning is logged.spark.sql.legacy.noCharWideningInSetOperationsis recorded in the offset log, withtruefor checkpoints that predate it. When a query is restored with another value than the session's, and a streaming set operation in it was padded (taggedCHAR_PADDED) or would be,StreamingQueryManager.createQueryanalyzes the DataFrame's unanalyzed plan again with the recorded value, as for a query written as one SQL statement or sent by Spark Connect. If the set operation was analyzed already, as for a Classic DataFrame, it fails with the newSTREAMING_SET_OPERATION_CHAR_PADDING_CHANGED, which names the flag and the value to set.spark.sql.legacy.noCharWideningInSetOperationsrestores the behavior before this change for set operations, their widening casts, and the narrowing of views and recursive CTEs.spark.sql.legacy.noCharPaddingInSubqueryComparisonsdoes the same for IN subqueries and scalar subqueries. The migration guide describes both changes.These are left as before:
spark.sql.legacy.charVarcharAsStringwithout standard semantics), asApplyCharTypePaddingdoes.coalesce(c, ...)orCASE, which aren't padded before or after this PR.named_structfrom CHAR columns, whose raw types are in the metadata of their fields rather than of the column (TODO inwiderCharRawType).rpadas before, including its truncation of values longer than their CHAR length.SequentialStreamingUnion, which is not aUnion(TODO inPadSetOperationCharLengths).Why are the changes needed?
A filter above a
UNION ALLof CHAR columns of different lengths drops matching rows, and reversing the children changes which rows it returns:The first two should return 1 and 2, the third 1, the fourth 2, and the last
'A '.Does this PR introduce _any_ user-facing change?
Yes. The migration guide has two new entries for them.
UNION,INTERSECTorEXCEPTof CHAR columns or fields of different lengths now has the widest CHAR type, in either order of the children, and its values are padded to that length.UNION(distinct) treats'A 'and'A 'as the same value.WidenSetOperationTypeswidens a child to another type. So a Classic DataFrame reference to a column of that child, such asa.union(b).select(a("c")), no longer resolves. References to the set operation's own output, such asa.union(b).select("c"), still work, and have the widest length.UNION ALLof aMAP<INT, CHAR(3)>and aMAP<BIGINT, CHAR(3)>column storesMAP<BIGINT, CHAR(3)>instead ofMAP<BIGINT, STRING>.'y 'instead of'y ', and one that reads a CHAR(3) column under a CHAR(5) anchor returns padded values.CHAR_READ_SIDE_PADDING); recreating the view stores the widest length and restores the pushdown (TODO innarrowViewColumns).spark.sql.legacy.noCharWideningInSetOperationsrestores the previous behavior of set operations, andspark.sql.legacy.noCharPaddingInSubqueryComparisonsthe one of subquery comparisons.How was this patch tested?
New tests in
CharVarcharTestSuite, which fail without this change:SPARK-61972: union of char columns of different lengths: both orders of the children,UNION ALLwith a filter, the CHAR type of the output,UNION, and unions of structs with CHAR fields, alone, next to an INT field, and with a NOT NULL field in one child, and an INTERSECT and EXCEPT over such a union whose INT field is widened to BIGINT.SPARK-61972: every reference to a union of char columns gets the widest length: a union of a union with a CHAR(4) child that keeps a five-character value, a renamed column, a CTE with two references, and an outer reference in a correlatedEXISTS.SPARK-61972: set operations and IN subqueries of char columns of different lengths: IN, NOT IN and multi-column IN subqueries, string literals IN a subquery, scalar subqueries in both orders, INTERSECT and EXCEPT in both orders and against a union, a child that outputs a column twice, at each position with its own length, also when another position of it has a STRING child or another column needs its type widened, unions in the recursive term of a recursive CTE (directly and through a nested CTE), the default collation given explicitly, an alias with explicit metadata pushed through a union and a conditional simplified into a column by the optimizer, the legacy CHAR-as-STRING mode, the new legacy flag (also for views and widening casts), widening casts that keep or drop CHAR and VARCHAR types (VARCHAR(3) and VARCHAR(10), maps), scalar subqueries in IN lists, constants that fail to evaluate, type mismatches with scalar subqueries, NOT NULL array elements in a recursive term, a view with type evolution, a union of nullable structs with a NOT NULL field, the qualifier of a DataFrame union, a DataFrame Project over a union,length,LIKEand a correlated subquery inside a child, and the padding of the shorter child's scan.SPARK-61972: chains of set operations that need padding resolve in one iteration: chains of 151 branches that need widening and padding, a repeated column and padding, and nested by-name unions, with the default iteration limit.SPARK-61972: set operations of char arrays and of structs with other field names:ARRAY<CHAR>, arrays of structs, structs whose fields have other names, and a transpose of a union.SPARK-61972: recursive CTEs over char columns of different lengths: a union in the recursive term with a filter on the CTE and with aLIMITthat stops the loop, an anchor padded to a longer length than the recursive term with a filter and with joins, an anchor longer than the recursive term, a widening cast in the recursive term, and the legacy flag.SPARK-61972: subquery comparisons of char columns of different lengths: nested CHAR fields and elements, a correlated IN subquery, failing constants in IN lists and IN subqueries, and the new legacy flag.SPARK-61972: a view or SQL function body analyzed under a legacy CHAR flag: a view and a SQL table function created under each legacy flag, read from a session without it.SPARK-61972: charTypeNarrowing pads values that fit and narrows trailing spaces(BasicCharVarcharTestSuite).SPARK-61972: a restored streaming query keeps the CHAR padding of its set operations(StreamingQueryManagerSuite): a SQL query and a Classic DataFrame restored from a checkpoint without the flag, and a new query, which records it.OffsetSeqLogSuitechecks the default for old checkpoints.SPARK-61972: a view of a union that stores a shorter char length(FileSourceCharVarcharTestSuite): the stored CHAR(3) type, the narrowed values, and filters on them, for a column, a CHAR field next to INT and VARCHAR fields of anamed_struct, a nullable struct with a NOT NULL field, and a struct whose INT field the view casts to its stored BIGINT.SPARK-61972: a view of a union of VARCHAR columns under standard semantics(FileSourceCharVarcharTestSuite): the view stores the widest VARCHAR length and returns the longer value.SPARK-61972: char columns of different lengths without read-side padding(FileSourceCharVarcharTestSuite): external CHAR(3) and CHAR(5) tables over the same unpadded value, withspark.sql.readSideCharPadding=false: IN subqueries in both directions and with a literal, INTERSECT, EXCEPT and UNION, and a UNION ALL with CHAR(5) COLLATE UTF8_BINARY.SPARK-61972: a union of char columns does not truncate over length values(FileSourceCharVarcharTestSuite): an external CHAR(2) table over'123456', and IN and scalar subqueries of external CHAR(3) and CHAR(5) tables over'abcdef', including(SELECT c FROM e3) IN ('abcde').These pass, and
scalastyleis clean forcatalystandsql(main and test):CharVarcharTestSuite,DataFrameSetOperationsSuite,SubquerySuite,Resolver,HybridAnalyzer,WriteDistributionAndOrderingSuite,DataFrameTransposeSuite,PlanStability,DataFrameSuite,StreamingQueryManagerSuite,OffsetSeqLogSuite: 1316 passed (no plan-stability changes).SQLViewSuite,SQLViewTestSuite,CTEInlineSuite,StreamSuite,StreamingDeduplicationSuite,StreamingAggregationSuite,StreamingQueryManagerSuite: 352 passed.SetOperation,Union,CharVarchar,TypeCoercion,AnalysisSuite,Resolver,Optimizer,PushProjectionThroughUnion,CombineUnions: 724 passed.SQLQueryTestSuitefiles forcte-recursion,view-schema-*,union,charvarchar,intersect,except,subquery,create-view,view-confandcte: 157 passed.Was this patch authored or co-authored using generative AI tooling?
Co-authored by: Claude Sonnet 4.5