This is an automated email from the ASF dual-hosted git repository.
HeartSaVioR pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 54ce19cd36a0 [SPARK-60945][SQL][PROTOBUF] Copy stateful protobuf
arguments and preserve map key policy
54ce19cd36a0 is described below
commit 54ce19cd36a0ec05808a3d3d62e4029481e3c914
Author: charlhhhh <[email protected]>
AuthorDate: Fri Nov 13 14:21:38 2026 +0900
[SPARK-60945][SQL][PROTOBUF] Copy stateful protobuf arguments and preserve
map key policy
### What changes were proposed in this pull request?
`FromProtobuf.replacement` and `ToProtobuf.replacement` now evaluate a
fresh copy
(`freshCopyIfContainsStatefulExpression()`) of each argument they evaluate:
the options, the
message name and the descriptor.
Both expressions also record `spark.sql.mapKeyDedupPolicy` when they are
created, and evaluate these arguments under that policy. The parameter is kept
out of `stringArgs`, so EXPLAIN output does not change.
### Why are the changes needed?
The options argument (e.g. `map('mode', 'PERMISSIVE')`) is a stateful
`CreateMap` with a single
`ArrayBasedMapBuilder`. Canonicalization renumbers attribute ids, so each
canonicalization creates
a new `FromProtobuf`/`ToProtobuf` copy, but all copies share the unchanged
options child, and the
`replacement` lazy val only locks its own copy. Concurrent
canonicalizations of one plan (for
example, `CacheManager` re-caching while several queries write tables at
the same time) therefore
evaluate the same `CreateMap` concurrently and race on its builder, failing
with
`IllegalArgumentException: requirement failed` from `ArrayBasedMapData` or
`DUPLICATED_MAP_KEY`.
With `spark.sql.mapKeyDedupPolicy=LAST_WIN`, the same race can silently
drop options
instead of throwing a duplicate-key error.
Copying alone would change behavior: each copy builds its map with a new
`ArrayBasedMapBuilder`,
which reads `spark.sql.mapKeyDedupPolicy` from the current session. Options
that repeat a key and
were analyzed under LAST_WIN could then fail with `DUPLICATED_MAP_KEY` when
another session, or the
same session after switching to EXCEPTION, canonicalizes the plan, for
example during a cache
lookup. Recording the policy at analysis time keeps the semantics the query
was analyzed with. It
also fixes executing such a plan after the session switches to EXCEPTION,
which already failed
before this change.
The message name and descriptor can also contain a stateful expression, for
example
`element_at(map(...), 'key')`, so they are copied the same way.
### Does this PR introduce _any_ user-facing change?
No, other than fixing the failures and missing options described above.
### How was this patch tested?
New tests in `ProtobufFunctionsSuite`, for both `from_protobuf` and
`to_protobuf`:
- overlapping canonicalization under both `EXCEPTION` and `LAST_WIN`: one
options evaluation
pauses after inserting its first key while a second canonicalization
runs. Before this fix,
`EXCEPTION` produced a duplicate-key error, while `LAST_WIN` could return
options missing the
first key. Both evaluations now return the complete expected options map.
- failed evaluation: one evaluation of the options fails halfway. Before
this fix, the half-built
map stayed in the shared `CreateMap`, so retrying the same expression
failed with
`DUPLICATED_MAP_KEY`; now each evaluation uses a fresh copy, so the retry
returns the expected
options.
- the same two cases with a stateful message name and descriptor, e.g.
`element_at(map(...), 'key1')`.
- map key policy: an expression created under LAST_WIN with a repeated key
keeps the LAST_WIN
result when it is canonicalized or executed under EXCEPTION, including a
cache lookup from
another session; an expression created under EXCEPTION still fails with
`DUPLICATED_MAP_KEY`
when it is canonicalized under LAST_WIN.
### Was this patch authored or co-authored using generative AI tooling?
Drafted-by: Claude Code
Closes #60148 from charlhhhh/SPARK-60945.
Authored-by: charlhhhh <[email protected]>
Signed-off-by: Jungtaek Lim <[email protected]>
skip-checks: true
---
.../sql/protobuf/ProtobufFunctionsSuite.scala | 301 +++++++++++++++++++++
.../expressions/toFromProtobufSqlFunctions.scala | 103 ++++++-
2 files changed, 396 insertions(+), 8 deletions(-)
diff --git
a/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
b/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
index 9541cda406b3..b06b80cd3030 100644
---
a/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
+++
b/connector/protobuf/src/test/scala/org/apache/spark/sql/protobuf/ProtobufFunctionsSuite.scala
@@ -18,14 +18,22 @@ package org.apache.spark.sql.protobuf
import java.sql.Timestamp
import java.time.{Duration, LocalTime}
+import java.util.concurrent.{CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.AtomicBoolean
+import scala.concurrent.{ExecutionContext, Future}
+import scala.concurrent.duration._
import scala.jdk.CollectionConverters._
import com.google.protobuf.{Any => AnyProto, BoolValue, ByteString,
BytesValue, DoubleValue, DynamicMessage, FloatValue, Int32Value, Int64Value,
StringValue, UInt32Value, UInt64Value}
import org.json4s.jackson.JsonMethods
+import org.apache.spark.SparkRuntimeException
import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Row}
import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference,
CreateMap, ElementAt, Expression, ExprId, FromProtobuf, LeafExpression,
Literal, ToProtobuf}
+import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
+import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.functions.{array, lit, map, struct, typedLit}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.protobuf.protos.Proto2Messages.Proto2AllTypes
@@ -37,6 +45,23 @@ import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
import org.apache.spark.sql.util.{ProtobufUtils => CommonProtobufUtils}
import org.apache.spark.unsafe.types.UTF8String
+import org.apache.spark.util.ThreadUtils
+
+/** A test string literal that runs onEval before returning, to pause or fail
evaluation. */
+private case class StringLiteralWithEvalHook(
+ value: String,
+ onEval: () => Unit)
+ extends LeafExpression with CodegenFallback {
+
+ override def foldable: Boolean = true
+ override def nullable: Boolean = false
+ override def dataType: DataType = StringType
+
+ override def eval(input: InternalRow): Any = {
+ onEval()
+ UTF8String.fromString(value)
+ }
+}
class ProtobufFunctionsSuite extends SharedSparkSession with ProtobufTestBase
with Serializable {
@@ -99,6 +124,104 @@ class ProtobufFunctionsSuite extends SharedSparkSession
with ProtobufTestBase
}
}
+ private def protobufExpression(
+ functionName: String,
+ options: Expression,
+ messageName: Expression = Literal("OtherExample"),
+ descFilePath: Expression = Literal(testFileDesc)): (Expression,
AttributeReference) = {
+ val dataType = if (functionName == "FROM_PROTOBUF") {
+ BinaryType
+ } else {
+ StructType(Seq(StructField("other", StringType)))
+ }
+ val data = AttributeReference("data", dataType)(exprId = ExprId(1))
+ val expression = if (functionName == "FROM_PROTOBUF") {
+ new FromProtobuf(data, messageName, descFilePath, options)
+ } else {
+ new ToProtobuf(data, messageName, descFilePath, options)
+ }
+ (expression, data)
+ }
+
+ private def canonicalizedOptions(
+ expression: Expression,
+ data: AttributeReference): Map[String, String] = {
+ val (messageName, descriptor, options) =
+ QueryPlan.normalizeExpressions(expression, Seq(data)) match {
+ case from: ProtobufDataToCatalyst =>
+ (from.messageName, from.binaryFileDescriptorSet, from.options)
+ case to: CatalystDataToProtobuf =>
+ (to.messageName, to.binaryFileDescriptorSet, to.options)
+ case other => fail(s"Unexpected canonicalized expression:
${other.getClass.getName}")
+ }
+ assert(messageName == "OtherExample")
+ assert(descriptor.exists(_.sameElements(testFileDesc)))
+ options
+ }
+
+ private def protobufExpressionWithStatefulArgument(
+ functionName: String,
+ argumentName: String,
+ onEval: () => Unit = () => (),
+ duplicateKey: Boolean = false): (Expression, AttributeReference) = {
+ val value = argumentName match {
+ case "options" => "value1"
+ case "messageName" => "OtherExample"
+ case "descFilePath" => testFileDescFile
+ }
+ val secondKey = StringLiteralWithEvalHook(if (duplicateKey) "key1" else
"key2", onEval)
+ val secondValue = if (argumentName == "options") "value2" else value
+ val map = CreateMap(Seq(Literal("key1"), Literal(value), secondKey,
Literal(secondValue)))
+ argumentName match {
+ case "options" => protobufExpression(functionName, map)
+ case "messageName" =>
+ protobufExpression(functionName, Literal(null),
+ messageName = ElementAt(map, Literal("key1")))
+ case "descFilePath" =>
+ protobufExpression(functionName, Literal(null),
+ descFilePath = ElementAt(map, Literal("key1")))
+ }
+ }
+
+ // A lookup in a map whose keys are 0.0 and -0.0, which are one key unless
+ // spark.sql.legacy.disableMapKeyNormalization is true.
+ private def signedZeroKeyLookup(value: String): Expression = ElementAt(
+ CreateMap(Seq(Literal(0.0D), Literal(value), Literal(-0.0D),
Literal(value))),
+ Literal(0.0D))
+
+ private def protobufExpressionWithSignedZeroKeys(
+ functionName: String,
+ argumentName: String): (Expression, AttributeReference) = argumentName
match {
+ case "options" =>
+ protobufExpression(
+ functionName, CreateMap(Seq(Literal("key1"),
signedZeroKeyLookup("value1"))))
+ case "messageName" =>
+ protobufExpression(functionName, Literal(null),
+ messageName = signedZeroKeyLookup("OtherExample"))
+ case "descFilePath" =>
+ protobufExpression(functionName, Literal(null),
+ descFilePath = signedZeroKeyLookup(testFileDescFile))
+ }
+
+ private def protobufDataFrame(
+ functionName: String,
+ options: String = "map('mode', 'PERMISSIVE', 'mode', 'FAILFAST')"):
DataFrame = {
+ val input = if (functionName == "FROM_PROTOBUF") {
+ lit(OtherExample.newBuilder().setOther("value").build().toByteArray)
+ } else {
+ struct(lit("value").as("other"))
+ }
+ spark.range(1).select(input.as("data")).selectExpr(
+ s"$functionName(data, 'OtherExample', '$testFileDescFile', $options) AS
value")
+ }
+
+ private def protobufDataFrameResult(functionName: String): Row =
+ if (functionName == "FROM_PROTOBUF") {
+ Row(Row("value"))
+ } else {
+ Row(OtherExample.newBuilder().setOther("value").build().toByteArray)
+ }
+
test("roundtrip in to_protobuf and from_protobuf - struct") {
val df = spark
.range(1, 10)
@@ -2443,6 +2566,184 @@ class ProtobufFunctionsSuite extends SharedSparkSession
with ProtobufTestBase
}
}
+ Seq("FROM_PROTOBUF", "TO_PROTOBUF").foreach { functionName =>
+ Seq("options", "messageName", "descFilePath").foreach { argumentName =>
+ gridTest(s"SPARK-60945: $functionName $argumentName survive overlapping
canonicalization")(
+ Seq("EXCEPTION", "LAST_WIN")) { policy =>
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> policy) {
+ val firstEvaluationPaused = new CountDownLatch(1)
+ val resumeFirstEvaluation = new CountDownLatch(1)
+ val pauseOnNextEval = new AtomicBoolean(true)
+ val (expression, data) = protobufExpressionWithStatefulArgument(
+ functionName, argumentName, () => {
+ if (pauseOnNextEval.compareAndSet(true, false)) {
+ firstEvaluationPaused.countDown()
+ assert(resumeFirstEvaluation.await(1, TimeUnit.MINUTES),
+ "first evaluation was never resumed")
+ }
+ })
+ val expectedOptions = if (argumentName == "options") {
+ Map("key1" -> "value1", "key2" -> "value2")
+ } else {
+ Map.empty[String, String]
+ }
+ val sqlConf = SQLConf.get
+ val executor =
ThreadUtils.newDaemonSingleThreadExecutor("protobuf-arguments-race-test")
+ val executionContext = ExecutionContext.fromExecutorService(executor)
+ try {
+ val firstEvaluation = Future {
+ SQLConf.withExistingConf(sqlConf) {
+ canonicalizedOptions(expression, data)
+ }
+ }(executionContext)
+ assert(firstEvaluationPaused.await(1, TimeUnit.MINUTES),
+ "first canonicalization never paused")
+ // The first evaluation has inserted key1 and is paused while
evaluating key2.
+ assert(canonicalizedOptions(expression, data) == expectedOptions)
+ resumeFirstEvaluation.countDown()
+ assert(ThreadUtils.awaitResult(firstEvaluation, 1.minute) ==
expectedOptions)
+ } finally {
+ resumeFirstEvaluation.countDown()
+ executor.shutdownNow()
+ assert(executor.awaitTermination(10, TimeUnit.SECONDS))
+ }
+ }
+ }
+
+ test(s"SPARK-60945: $functionName $argumentName survive a failed
evaluation") {
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION") {
+ val failOnNextEval = new AtomicBoolean(true)
+ val expectedFailure = new RuntimeException("first argument
evaluation failed")
+ val (expression, data) = protobufExpressionWithStatefulArgument(
+ functionName, argumentName, () => {
+ if (failOnNextEval.compareAndSet(true, false)) {
+ throw expectedFailure
+ }
+ })
+ val expectedOptions = if (argumentName == "options") {
+ Map("key1" -> "value1", "key2" -> "value2")
+ } else {
+ Map.empty[String, String]
+ }
+ val failure = intercept[RuntimeException] {
+ QueryPlan.normalizeExpressions(expression, Seq(data))
+ }
+ assert(failure eq expectedFailure)
+
+ // Retrying must not reuse the partial map left by the failed
evaluation.
+ assert(canonicalizedOptions(expression, data) == expectedOptions)
+ }
+ }
+
+ gridTest(s"SPARK-60945: canonicalizing $functionName uses the
analysis-time " +
+ s"map key policy for $argumentName")(
+ Seq("LAST_WIN", "EXCEPTION")) { capturedPolicy =>
+ val (expression, data) = withSQLConf(
+ SQLConf.MAP_KEY_DEDUP_POLICY.key -> capturedPolicy) {
+ val result = protobufExpressionWithStatefulArgument(
+ functionName, argumentName, duplicateKey = true)
+ if (capturedPolicy == "LAST_WIN") {
+ // Like analysis, evaluate the expression once before the conf
changes. Under EXCEPTION
+ // this would already fail on the duplicate key, so only the
LAST_WIN run does it.
+ result._1.dataType
+ }
+ result
+ }
+ val currentPolicy = if (capturedPolicy == "LAST_WIN") "EXCEPTION" else
"LAST_WIN"
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> currentPolicy) {
+ if (capturedPolicy == "LAST_WIN") {
+ val expectedOptions = if (argumentName == "options") {
+ Map("key1" -> "value2")
+ } else {
+ Map.empty[String, String]
+ }
+ assert(canonicalizedOptions(expression, data) == expectedOptions)
+ } else {
+ checkError(
+ exception = intercept[SparkRuntimeException] {
+ canonicalizedOptions(expression, data)
+ },
+ condition = "DUPLICATED_MAP_KEY",
+ parameters = Map(
+ "key" -> "key1",
+ "mapKeyDedupPolicy" ->
s"\"${SQLConf.MAP_KEY_DEDUP_POLICY.key}\""))
+ }
+ assert(SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY).toString ==
currentPolicy)
+ }
+ }
+
+ gridTest(s"SPARK-60945: canonicalizing $functionName uses the
analysis-time map key " +
+ s"normalization for $argumentName")(Seq(true, false)) {
capturedDisabled =>
+ val policy = SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION"
+ val normalization = SQLConf.DISABLE_MAP_KEY_NORMALIZATION.key
+ val (expression, data) = withSQLConf(policy, normalization ->
capturedDisabled.toString) {
+ val result = protobufExpressionWithSignedZeroKeys(functionName,
argumentName)
+ if (capturedDisabled) {
+ // Like analysis, evaluate the expression once before the conf
changes. With
+ // normalization, 0.0 and -0.0 are one key, so only the disabled
run does it.
+ result._1.dataType
+ }
+ result
+ }
+ withSQLConf(policy, normalization -> (!capturedDisabled).toString) {
+ if (capturedDisabled) {
+ val expectedOptions = if (argumentName == "options") {
+ Map("key1" -> "value1")
+ } else {
+ Map.empty[String, String]
+ }
+ assert(canonicalizedOptions(expression, data) == expectedOptions)
+ } else {
+ checkError(
+ exception = intercept[SparkRuntimeException] {
+ canonicalizedOptions(expression, data)
+ },
+ condition = "DUPLICATED_MAP_KEY",
+ parameters = Map(
+ "key" -> "-0.0",
+ "mapKeyDedupPolicy" ->
s"\"${SQLConf.MAP_KEY_DEDUP_POLICY.key}\""))
+ }
+ }
+ }
+ }
+
+ test(s"SPARK-60945: $functionName cached plan retains its map key policy
across sessions") {
+ val cached = withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "LAST_WIN")
{
+ protobufDataFrame(functionName).cache()
+ }
+ try {
+ val otherSession = spark.newSession()
+ otherSession.conf.set(SQLConf.MAP_KEY_DEDUP_POLICY.key, "EXCEPTION")
+ checkAnswer(otherSession.range(1).toDF(), Seq(Row(0L)))
+ } finally {
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "LAST_WIN") {
+ cached.unpersist(blocking = true)
+ }
+ }
+ }
+
+ test(s"SPARK-60945: $functionName executes after the map key policy
changes") {
+ val df = withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "LAST_WIN") {
+ protobufDataFrame(functionName)
+ }
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION") {
+ checkAnswer(df, Seq(protobufDataFrameResult(functionName)))
+ }
+ }
+
+ test(s"SPARK-60945: $functionName executes after the map key normalization
changes") {
+ val policy = SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION"
+ val normalization = SQLConf.DISABLE_MAP_KEY_NORMALIZATION.key
+ val options = "map('mode', element_at(map(0.0D, 'PERMISSIVE', -0.0D,
'PERMISSIVE'), 0.0D))"
+ val df = withSQLConf(policy, normalization -> "true") {
+ protobufDataFrame(functionName, options)
+ }
+ withSQLConf(policy, normalization -> "false") {
+ checkAnswer(df, Seq(protobufDataFrameResult(functionName)))
+ }
+ }
+ }
+
test("SPARK-54156: boolean Protobuf options reject non-boolean values") {
Seq(
"emit.default.values",
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala
index 1e480792a98a..85897e5ea026 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala
@@ -22,6 +22,7 @@ import org.apache.spark.sql.catalyst.analysis.TypeCheckResult
import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData,
ProtobufDescriptorFileReader}
import org.apache.spark.sql.errors.DataTypeErrors.toSQLType
import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{
BinaryType, CharType, MapType, NullType, StringType, StructType, VarcharType
}
@@ -79,7 +80,27 @@ case class FromProtobuf(
data: Expression,
messageName: Expression,
descFilePath: Expression,
- options: Expression) extends QuaternaryExpression with RuntimeReplaceable {
+ options: Expression,
+ // PERSISTED: the map builder settings at analysis time,
spark.sql.mapKeyDedupPolicy and
+ // spark.sql.legacy.disableMapKeyNormalization. Constructor parameters, so
that copies such as
+ // canonicalization's keep them and evaluate the arguments the same way.
+ mapKeyDedupPolicy: SQLConf.MapKeyDedupPolicy.Value,
+ disableMapKeyNormalization: Boolean)
+ extends QuaternaryExpression with RuntimeReplaceable {
+
+ def this(
+ data: Expression,
+ messageName: Expression,
+ descFilePath: Expression,
+ options: Expression) = {
+ this(
+ data,
+ messageName,
+ descFilePath,
+ options,
+ SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY),
+ SQLConf.get.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION))
+ }
def this(data: Expression, messageName: Expression, descFilePathOrOptions:
Expression) = {
this(
@@ -153,13 +174,32 @@ case class FromProtobuf(
}
override lazy val replacement: Expression = {
- val messageNameValue: String = messageName.eval() match {
+ val conf = SQLConf.get
+ if (conf.getConf(SQLConf.MAP_KEY_DEDUP_POLICY) == mapKeyDedupPolicy &&
+ conf.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION) ==
disableMapKeyNormalization) {
+ createReplacement()
+ } else {
+ val evalConf = conf.clone()
+ evalConf.setConf(SQLConf.MAP_KEY_DEDUP_POLICY, mapKeyDedupPolicy)
+ evalConf.setConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION,
disableMapKeyNormalization)
+ SQLConf.withExistingConf(evalConf) {
+ createReplacement()
+ }
+ }
+ }
+
+ private def createReplacement(): Expression = {
+ // Concurrent canonicalization can evaluate the same CreateMap and corrupt
its map builder.
+ // Copy stateful arguments to avoid duplicate-key errors and mismatched
key/value array lengths.
+ val freshMessageName = messageName.freshCopyIfContainsStatefulExpression()
+ val messageNameValue: String = freshMessageName.eval() match {
case null =>
throw new IllegalArgumentException("Message name cannot be null")
case s: UTF8String =>
s.toString
}
- val descFilePathValue: Option[Array[Byte]] = descFilePath.eval() match {
+ val freshDescFilePath =
descFilePath.freshCopyIfContainsStatefulExpression()
+ val descFilePathValue: Option[Array[Byte]] = freshDescFilePath.eval()
match {
case s: UTF8String if s.toString.isEmpty => None
case s: UTF8String =>
Some(ProtobufDescriptorFileReader.readDescriptorFileContent(s.toString))
@@ -167,7 +207,8 @@ case class FromProtobuf(
case bytes: Array[Byte] => Some(bytes)
case null => None
}
- val optionsValue: Map[String, String] = options.eval() match {
+ val freshOptions = options.freshCopyIfContainsStatefulExpression()
+ val optionsValue: Map[String, String] = freshOptions.eval() match {
case a: ArrayBasedMapData if a.keyArray.array.nonEmpty =>
val keys: Array[String] = a.keyArray.array.map(_.toString)
val values: Array[String] = a.valueArray.array.map(_.toString)
@@ -186,6 +227,9 @@ case class FromProtobuf(
expr.asInstanceOf[Expression]
}
+ // The map builder settings are not user arguments; keep them out of EXPLAIN
output.
+ override protected def stringArgs: Iterator[Any] = super.stringArgs.take(4)
+
override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("from_protobuf")
}
@@ -234,7 +278,27 @@ case class ToProtobuf(
data: Expression,
messageName: Expression,
descFilePath: Expression,
- options: Expression) extends QuaternaryExpression with RuntimeReplaceable {
+ options: Expression,
+ // PERSISTED: the map builder settings at analysis time,
spark.sql.mapKeyDedupPolicy and
+ // spark.sql.legacy.disableMapKeyNormalization. Constructor parameters, so
that copies such as
+ // canonicalization's keep them and evaluate the arguments the same way.
+ mapKeyDedupPolicy: SQLConf.MapKeyDedupPolicy.Value,
+ disableMapKeyNormalization: Boolean)
+ extends QuaternaryExpression with RuntimeReplaceable {
+
+ def this(
+ data: Expression,
+ messageName: Expression,
+ descFilePath: Expression,
+ options: Expression) = {
+ this(
+ data,
+ messageName,
+ descFilePath,
+ options,
+ SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY),
+ SQLConf.get.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION))
+ }
def this(data: Expression, messageName: Expression, descFilePathOrOptions:
Expression) = {
this(
@@ -322,19 +386,39 @@ case class ToProtobuf(
}
override lazy val replacement: Expression = {
- val messageNameValue: String = messageName.eval() match {
+ val conf = SQLConf.get
+ if (conf.getConf(SQLConf.MAP_KEY_DEDUP_POLICY) == mapKeyDedupPolicy &&
+ conf.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION) ==
disableMapKeyNormalization) {
+ createReplacement()
+ } else {
+ val evalConf = conf.clone()
+ evalConf.setConf(SQLConf.MAP_KEY_DEDUP_POLICY, mapKeyDedupPolicy)
+ evalConf.setConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION,
disableMapKeyNormalization)
+ SQLConf.withExistingConf(evalConf) {
+ createReplacement()
+ }
+ }
+ }
+
+ private def createReplacement(): Expression = {
+ // Concurrent canonicalization can evaluate the same CreateMap and corrupt
its map builder.
+ // Copy stateful arguments to avoid duplicate-key errors and mismatched
key/value array lengths.
+ val freshMessageName = messageName.freshCopyIfContainsStatefulExpression()
+ val messageNameValue: String = freshMessageName.eval() match {
case null =>
throw new IllegalArgumentException("Message name cannot be null")
case s: UTF8String =>
s.toString
}
- val descFilePathValue: Option[Array[Byte]] = descFilePath.eval() match {
+ val freshDescFilePath =
descFilePath.freshCopyIfContainsStatefulExpression()
+ val descFilePathValue: Option[Array[Byte]] = freshDescFilePath.eval()
match {
case s: UTF8String =>
Some(ProtobufDescriptorFileReader.readDescriptorFileContent(s.toString))
case bytes: Array[Byte] => Some(bytes)
case null => None
}
- val optionsValue: Map[String, String] = options.eval() match {
+ val freshOptions = options.freshCopyIfContainsStatefulExpression()
+ val optionsValue: Map[String, String] = freshOptions.eval() match {
case a: ArrayBasedMapData if a.keyArray.array.nonEmpty =>
val keys: Array[String] = a.keyArray.array.map(_.toString)
val values: Array[String] = a.valueArray.array.map(_.toString)
@@ -353,6 +437,9 @@ case class ToProtobuf(
expr.asInstanceOf[Expression]
}
+ // The map builder settings are not user arguments; keep them out of EXPLAIN
output.
+ override protected def stringArgs: Iterator[Any] = super.stringArgs.take(4)
+
override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("to_protobuf")
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]