-
Notifications
You must be signed in to change notification settings - Fork 29.2k
[SPARK-57003][SQL][SS] Widen stateful operator output and state schema nullability #56061
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HeartSaVioR
wants to merge
11
commits into
apache:master
Choose a base branch
from
HeartSaVioR:widen-stateful-op-nullability
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
94c466c
[SPARK-57003][SS] Widen stateful operator output and state schema nul…
HeartSaVioR b7ca2a4
Fix scalastyle: correct import ordering for WidenStatefulOpNullability
HeartSaVioR f69c587
Update sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLC…
HeartSaVioR 74bf471
Address review comments: widen state schemas in all stateful execs, r…
HeartSaVioR e675474
Fix checkError condition in forced-off test
HeartSaVioR ef839c2
Fix duplicate clause in SQLConf doc string
HeartSaVioR 4c19f5d
Fix conf version to 4.3.0
HeartSaVioR 22654b8
Stop widening output schema for stateless operator
HeartSaVioR d9d4452
Fix CI failures: duplicate tests, TWS col family over-widening, confi…
HeartSaVioR 94dda32
Widen TWS grouping key in col family schemas without touching user-de…
HeartSaVioR 0fa91ec
Widen TWS state value schemas for consistency with other stateful ope…
HeartSaVioR File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
174 changes: 174 additions & 0 deletions
174
...la/org/apache/spark/sql/catalyst/analysis/WidenStatefulOperatorAttributeNullability.scala
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.sql.catalyst.analysis | ||
|
|
||
| import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeReference, ExprId} | ||
| import org.apache.spark.sql.catalyst.plans.logical.{LeafNode, LogicalPlan} | ||
| import org.apache.spark.sql.catalyst.rules.Rule | ||
| import org.apache.spark.sql.internal.SQLConf | ||
| import org.apache.spark.sql.types.StructType | ||
|
|
||
| /** | ||
| * Shared helpers for the stateful-operator nullability fix. The fix has three | ||
| * independent components, all gated by | ||
| * [[SQLConf.STATEFUL_OPERATOR_ALWAYS_NULLABLE_OUTPUT]] (pinned per-query via the | ||
| * offset log so existing queries keep their pre-fix behavior on restart): | ||
| * | ||
| * - (a) `widenStateSchema`: explicit `asNullable` at every state-schema construction | ||
| * site in each stateful physical exec. | ||
| * - (b) `widenOutputForStatefulOp`: a per-op `output` override on every stateful logical | ||
| * and physical operator, used by the operator's `output` definition. | ||
| * - (c) [[WidenStatefulOperatorAttributeNullability]] (defined below in this file): a | ||
| * custom optimizer rule that widens `AttributeReference`s inside stateful ops' | ||
| * internal expressions and propagates upward to ancestor expressions. | ||
| */ | ||
| object WidenStatefulOpNullability { | ||
|
|
||
| def isEnabled: Boolean = | ||
| SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALWAYS_NULLABLE_OUTPUT) | ||
|
|
||
| /** | ||
| * Recursively widens an attribute to be fully nullable: outer `nullable = true` plus | ||
| * every nested `StructField.nullable`, `ArrayType.containsNull`, and | ||
| * `MapType.valueContainsNull` flipped to `true` via | ||
| * [[org.apache.spark.sql.types.DataType#asNullable]]. | ||
| */ | ||
| def deepWidenAttribute(a: Attribute): Attribute = a match { | ||
| case ref: AttributeReference => | ||
| AttributeReference( | ||
| ref.name, ref.dataType.asNullable, nullable = true, ref.metadata)( | ||
| ref.exprId, ref.qualifier) | ||
| case other => other.withNullability(true) | ||
| } | ||
|
|
||
| /** | ||
| * Component (a): widens a state schema to fully nullable. Stateful physical execs apply | ||
| * this at every `validateAndMaybeEvolveStateSchema(...)` call site and every | ||
| * `mapPartitionsWith*StateStore(...)` call site. When the conf is off, returns the | ||
| * schema unchanged. | ||
| */ | ||
| def widenStateSchema(schema: StructType): StructType = | ||
| if (isEnabled) schema.asNullable else schema | ||
|
|
||
| /** | ||
| * Component (b): wraps a stateful operator's `output` to be fully nullable. The caller | ||
| * is responsible for only calling this from within an `output` definition on a stateful | ||
| * operator; gating is handled here via [[isEnabled]]. | ||
| */ | ||
| def widenOutputForStatefulOp(base: Seq[Attribute]): Seq[Attribute] = | ||
| if (isEnabled) base.map(deepWidenAttribute) else base | ||
|
|
||
| /** | ||
| * Recursively walks a schema and replaces any nested `StructType` that | ||
| * structurally matches `original` (by field names and base types, ignoring | ||
| * nullability) with `widened`. Used by TransformWithState execs to widen | ||
| * the grouping-key portion of col-family key schemas without touching | ||
| * user-defined key/value portions. | ||
| */ | ||
| def widenGroupingKeyInSchema( | ||
| schema: StructType, | ||
| original: StructType, | ||
| widened: StructType): StructType = { | ||
| if (!isEnabled) return schema | ||
| if (structurallyMatches(schema, original)) { | ||
| widened | ||
| } else { | ||
| StructType(schema.fields.map { field => | ||
| field.dataType match { | ||
| case st: StructType if structurallyMatches(st, original) => | ||
| field.copy(dataType = widened) | ||
| case st: StructType => | ||
| field.copy(dataType = | ||
| widenGroupingKeyInSchema(st, original, widened)) | ||
| case _ => field | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| private def structurallyMatches( | ||
| a: StructType, b: StructType): Boolean = { | ||
| a.length == b.length && a.zip(b).forall { case (fa, fb) => | ||
| fa.name == fb.name && | ||
| fa.dataType.typeName == fb.dataType.typeName | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Component (c) of the stateful-operator nullability fix: a custom optimizer rule that | ||
| * widens `AttributeReference`s inside streaming-stateful operators' internal expressions | ||
| * and propagates the widening upward to ancestor operators' expressions. | ||
| * | ||
| * The rule does NOT introduce any new logical or physical node. It is purely an | ||
| * attribute-rewrite pass using `resolveOperatorsUp` (bottom-up): for every node whose | ||
| * subtree contains a stateful operator, collect `exprId`s from children's output, then | ||
| * deep-widen every `AttributeReference` in the node's expressions whose `exprId` is in | ||
| * that set via [[WidenStatefulOpNullability#deepWidenAttribute]]. | ||
| * | ||
| * At a stateful operator itself, all children's output attributes are included because | ||
| * the operator's internal expressions (e.g. grouping keys) reference them directly. | ||
| * At non-stateful ancestor operators, only children whose subtrees contain a stateful | ||
| * operator are included, to avoid unnecessary widening of non-stateful siblings. | ||
| * The node's own `p.output` is not needed for non-stateful ancestors because the | ||
| * bottom-up traversal guarantees children are already transformed, so their output | ||
| * attributes are already nullable and the ancestor's expressions reference those | ||
| * children's `exprId`s. | ||
| * | ||
| * '''Scope.''' The walk only fires on nodes whose subtree contains a stateful operator. | ||
| * | ||
| * '''Ordering constraint.''' This rule must run AFTER every `UpdateAttributeNullability` | ||
| * invocation in both the main optimizer and AQE. | ||
| * | ||
| * '''Idempotence.''' [[WidenStatefulOpNullability#deepWidenAttribute]] is idempotent. | ||
| */ | ||
| object WidenStatefulOperatorAttributeNullability extends Rule[LogicalPlan] { | ||
|
|
||
| override def apply(plan: LogicalPlan): LogicalPlan = { | ||
| if (!conf.getConf(SQLConf.STATEFUL_OPERATOR_ALWAYS_NULLABLE_OUTPUT) || | ||
| !plan.containsStatefulOperator) { | ||
| return plan | ||
| } | ||
| plan.resolveOperatorsUp { | ||
| case p if !p.resolved => p | ||
| case p: LeafNode => p | ||
| case p if !p.containsStatefulOperator => p | ||
| case p => | ||
| val widenableAttrs = if (p.isStateful) { | ||
| p.output ++ p.children.flatMap(_.output) | ||
| } else { | ||
| p.children.filter(_.containsStatefulOperator).flatMap(_.output) | ||
| } | ||
| val widenableExprIds: Set[ExprId] = widenableAttrs | ||
| .iterator.collect { case ar: AttributeReference => ar.exprId }.toSet | ||
| if (widenableExprIds.isEmpty) { | ||
| p | ||
| } else { | ||
| p.transformExpressions { | ||
| case ar: AttributeReference if widenableExprIds.contains(ar.exprId) => | ||
| val widened = WidenStatefulOpNullability.deepWidenAttribute(ar) | ||
| if (ar.dataType == widened.dataType && ar.nullable == widened.nullable) { | ||
| ar | ||
| } else { | ||
| widened | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
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
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
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
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
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
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Component (a) is described as applying "at every state-schema construction site in each stateful physical exec," but several execs are missing the explicit widening:
FlatMapGroupsWithStateExec.validateAndMaybeEvolveStateSchema(FlatMapGroupsWithStateExec.scala~L203):groupingAttributes.toStructTypeis registered un-widened; and the twoStateStore.get/mapPartitionsWithStateStorecalls indoExecute(~L247-263) open state stores with the un-widened key schema.FlatMapGroupsInPandasWithStateExecinherits the same base, so it has the same gap.TransformWithStateExec:getColFamilySchemas'sdefaultSchema(~L143-145),validateAndMaybeEvolveStateSchema(viavalidateAndWriteStateSchemaat ~L380), and theStateStore.get/mapPartitionsWithStateStorecalls (~L406-417, ~L428-435) all usekeyExpressions.toStructType/keyEncoder.schemaun-widened.TransformWithStateInPySparkExec: same pattern.Grouping attributes are input-derived and subject to the same nullability drift the rest of the fix is preventing. Component (c) may incidentally widen the references via the logical-plan rewrite, but having component (a) skip these execs makes the defense-in-depth claim of the design false and leaves a real gap if (c) misses for any reason (rule excluded, unresolved subplan, etc.). Either add
widenStateSchema(...)at these sites for consistency withStateStoreSaveExec/BaseStreamingDeduplicateExec/StreamingSymmetricHashJoinExec, or tighten the wording here to describe which execs are intentionally exempt and why.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's make sure nullability widening is applied to those operators as well - I thought we did it and looks like we missed it.