← Back to Pull requests

[SPARK-61972][SQL] Pad CHAR columns of a UNION to the widest length of its children #60756

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 20, 2026 11:37 UTC
Author

What changes were proposed in this pull request?

A Union builds 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, and ApplyCharTypePadding pads 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:

Filter (c#70 = rpad(a, 3,  ))           <- padded to the CHAR(3) of the first child
+- Union false, false
   :- Project [id#64, readSidePadding(c#65, 3) AS c#70]   <- 'a  '
   +- Project [id#66, readSidePadding(c#67, 5) AS c#71]   <- 'a    ', never matches

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) and SELECT c FROM t3 INTERSECT SELECT c FROM t5 return 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:

  • Set operations, during analysis. A set operation is padded once it is resolved except for its CHAR lengths (resolvedExceptCharLengths, the definition of resolved before 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, ResolveUnion after it turns a by-name union into a positional one, and ResolveReferences and DeduplicateRelations after they deduplicate. A new analyzer rule, PadSetOperationCharLengths, runs right after the type-coercion rules and pads the others. Padding only happens during analysis, so V2Writes, which reuses the type-coercion rules on optimized plans, doesn't pad. When the children of a Union, Intersect or Except have 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, as WidenSetOperationTypes casts 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 in SetOperationLikeResolver, with the same helper (SetOperationCharPadding.padChildren). CharVarcharUtils.widerCharRawTypes reads 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 as SimplifyConditionals turning an expression into a column, so outside of analysis the CHAR lengths don't affect resolved. The phase is AnalysisHelper.isInAnalyzer: every run of the analyzer is in it (Analyzer.execute now opens markInAnalyzer, as executeAndCheck does), and the optimizers are not, also when an analyzer rule optimizes another query (Optimizer.execute and AQEOptimizer.execute run in the new markOutsideAnalyzer). CheckAnalysis.checkAnalysis runs 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. WidenSetOperationTypes keys off resolvedExceptCharLengths, 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, so char(5) and char(5) collate UTF8_BINARY are 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.ReadSidePadding matches the padding of a set operation over the scan's padding, readSidePadding(readSidePadding(c, 3), 5), as readSidePadding(c, 5), the same for every value, so the V2 translation and the filter statistics still see one padding of the column.
  • Subquery comparisons. ApplyCharTypePaddingHelper.paddingForStringComparison pads each IN value (column or string literal) and the matching column of the subquery, the column in a Project over 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, as ConstantFolding leaves it. These go through the same addPaddingInStringComparison as 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.

  • Recursive CTEs and views. Their columns keep other lengths, so ApplyCharTypePadding brings the values of the recursive term of a UnionLoop to 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 with named_struct. Only the union of the anchor and the recursive term isn't padded, before it becomes the UnionLoop; a set operation inside the recursive term is padded once it reads the UnionLoopRef. UnionLoopExec tags 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 view WITH SCHEMA TYPE EVOLUTION evolves to the wider CHAR type: ViewSyncSchemaToMetaStore stores the query's CHAR type for a column that the narrowing narrowed. A view WITH SCHEMA EVOLUTION stores 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.

  • Streaming. The padding changes the values that the stateful operators of a streaming query key on. spark.sql.legacy.noCharWideningInSetOperations is recorded in the offset log, with true for 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 (tagged CHAR_PADDED) or would be, StreamingQueryManager.createQuery analyzes 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 new STREAMING_SET_OPERATION_CHAR_PADDING_CHANGED, which names the flag and the value to set.

  • Legacy behavior. The internal, session-bound spark.sql.legacy.noCharWideningInSetOperations restores the behavior before this change for set operations, their widening casts, and the narrowing of views and recursive CTEs. spark.sql.legacy.noCharPaddingInSubqueryComparisons does the same for IN subqueries and scalar subqueries. The migration guide describes both changes.
  • These are left as before:

  • Everything, in the legacy mode where CHAR is a STRING (spark.sql.legacy.charVarcharAsString without standard semantics), as ApplyCharTypePadding does.

  • Children that are not all CHAR types at a position, such as CHAR and STRING, or CHAR and VARCHAR.

  • Comparisons with CHAR values that come out of other expressions, such as coalesce(c, ...) or CASE, which aren't padded before or after this PR.

  • Set operations of structs built with named_struct from CHAR columns, whose raw types are in the metadata of their fields rather than of the column (TODO in widerCharRawType).

  • Comparisons of two columns, or of a column and a string literal, which pad with rpad as before, including its truncation of values longer than their CHAR length.

  • SequentialStreamingUnion, which is not a Union (TODO in PadSetOperationCharLengths).
  • Why are the changes needed?

    A filter above a UNION ALL of CHAR columns of different lengths drops matching rows, and reversing the children changes which rows it returns:

    CREATE TABLE t3 (id INT, c CHAR(3)) USING PARQUET;
    CREATE TABLE t5 (id INT, c CHAR(5)) USING PARQUET;
    INSERT INTO t3 VALUES (1, 'A');
    INSERT INTO t5 VALUES (2, 'A');
    SELECT id FROM (SELECT id, c FROM t3 UNION ALL SELECT id, c FROM t5) u WHERE c = 'A';  -- 1
    SELECT id FROM (SELECT id, c FROM t5 UNION ALL SELECT id, c FROM t3) u WHERE c = 'A';  -- 2
    SELECT id FROM t3 WHERE c IN (SELECT c FROM t5);                                       -- nothing
    SELECT id FROM t5 WHERE c = (SELECT c FROM t3);                                         -- nothing
    SELECT c FROM t3 INTERSECT SELECT c FROM t5;                                            -- nothing
    

    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.

  • The output of a UNION, INTERSECT or EXCEPT of 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.

  • IN subqueries and scalar subqueries match CHAR values of different lengths. The queries above return the results listed.

  • When the first child of a set operation is padded, the set operation's output gets new attribute ids, as when WidenSetOperationTypes widens a child to another type. So a Classic DataFrame reference to a column of that child, such as a.union(b).select(a("c")), no longer resolves. References to the set operation's own output, such as a.union(b).select("c"), still work, and have the widest length.

  • A widening cast of a child of a set operation keeps the CHAR and VARCHAR types it doesn't change, so a table created from the UNION ALL of a MAP<INT, CHAR(3)> and a MAP<BIGINT, CHAR(3)> column stores MAP<BIGINT, CHAR(3)> instead of MAP<BIGINT, STRING>.

  • The values of the recursive term of a recursive CTE get the CHAR lengths of its anchor: a recursive term that reads a CHAR(5) column under a CHAR(3) anchor returns 'y ' instead of 'y ', and one that reads a CHAR(3) column under a CHAR(5) anchor returns padded values.

  • A view whose stored CHAR length is shorter than its query's, for any reason, returns the values at the stored length. A filter on such a column is no longer pushed down to V2 and JDBC sources, which the base branch did for the shorter first child (as CHAR_READ_SIDE_PADDING); recreating the view stores the widest length and restores the pushdown (TODO in narrowViewColumns).

  • A streaming query restored from an older checkpoint keeps the previous padding. Its Classic DataFrame fails to start unless the flag is set to true before it is built.

  • spark.sql.legacy.noCharWideningInSetOperations restores the previous behavior of set operations, and spark.sql.legacy.noCharPaddingInSubqueryComparisons the 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 ALL with 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 correlated EXISTS.

  • 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, LIKE and 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 a LIMIT that 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. OffsetSeqLogSuite checks 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 a named_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, with spark.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 scalastyle is clean for catalyst and sql (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.

  • catalyst SetOperation, Union, CharVarchar, TypeCoercion, AnalysisSuite, Resolver, Optimizer, PushProjectionThroughUnion, CombineUnions: 724 passed.

  • SQLQueryTestSuite files for cte-recursion, view-schema-*, union, charvarchar, intersect, except, subquery, create-view, view-conf and cte: 157 passed.
  • Was this patch authored or co-authored using generative AI tooling?

    Co-authored by: Claude Sonnet 4.5

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: shivadarshan-devadiga Review duration: 15965m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 46.7% · Lower = rushed or shallow review
    46.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 27.7% · Safe to merge
    27.7%
    Repository