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 588b01a6d990 [SPARK-61419][SQL] Copy stateful options before
evaluating from_avro/schema_of_avro
588b01a6d990 is described below
commit 588b01a6d990da1383efd50fa76e54b8f64208e4
Author: charlhhhh <[email protected]>
AuthorDate: Fri Nov 13 14:29:45 2026 +0900
[SPARK-61419][SQL] Copy stateful options before evaluating
from_avro/schema_of_avro
### What changes were proposed in this pull request?
`FromAvro`, `ToAvro` and `SchemaOfAvro` now evaluate a fresh copy
(`freshCopyIfContainsStatefulExpression()`) of each argument their
`replacement` evaluates: the
schema and, for `from_avro` and `schema_of_avro`, the options. This is the
same fix as SPARK-60945
(#60148) for `from_protobuf`/`to_protobuf`.
All three expressions also record `spark.sql.mapKeyDedupPolicy` when they
are created, as a
persisted non-child parameter like `FromAvro`'s CHAR/VARCHAR flags, and
evaluate their 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 `FromAvro` 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, cache
lookups while several queries run 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`. The builder only resets
after a successful build,
so a failed evaluation leaves its entries behind and later evaluations of
the same expression keep
failing with `DUPLICATED_MAP_KEY`. With
`spark.sql.mapKeyDedupPolicy=LAST_WIN`, the race can
instead silently drop options.
`SchemaOfAvro` has no attribute input, so canonicalization does not copy
it, but it evaluates its
options the same way and a failed evaluation can leave a partial map
behind, so it gets the same
change. The schema argument can also contain a stateful expression, for
example
`element_at(map(...), 'key')`, so it is copied the same way, including for
`to_avro`.
Copying alone would change behavior: each copy builds its map with a new
`ArrayBasedMapBuilder`,
which reads `spark.sql.mapKeyDedupPolicy` from the current session.
Arguments 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.
### 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 `AvroFunctionsSuite` for `from_avro`, `to_avro` and
`schema_of_avro`, each with a
stateful schema (e.g. `element_at(map(...), 'key1')`) and, where the
function takes options, with
stateful options:
- overlapping canonicalization under both `EXCEPTION` and `LAST_WIN` (not
for `schema_of_avro`,
which canonicalization does not copy): one evaluation pauses after
inserting its first key while
a second canonicalization runs. Both evaluations now return the complete
expected value.
- failed evaluation: one evaluation fails halfway. Before this fix,
retrying the same expression
failed with `DUPLICATED_MAP_KEY`; it now returns the expected value.
- map key policy: an expression created under LAST_WIN with a repeated key
keeps the LAST_WIN
result when a copy of it is evaluated or the query is executed under
EXCEPTION, including a
cache lookup from another session; an expression created under EXCEPTION
still fails with
`DUPLICATED_MAP_KEY` when a copy of it is evaluated under LAST_WIN.
### Was this patch authored or co-authored using generative AI tooling?
Drafted-by: Claude Code
Closes #60354 from charlhhhh/SPARK-61419.
Authored-by: charlhhhh <[email protected]>
Signed-off-by: Jungtaek Lim <[email protected]>
skip-checks: true
---
.../apache/spark/sql/avro/AvroFunctionsSuite.scala | 333 ++++++++++++++++++++-
.../catalyst/expressions/avroSqlFunctions.scala | 116 ++++++-
2 files changed, 436 insertions(+), 13 deletions(-)
diff --git
a/connector/avro/src/test/scala/org/apache/spark/sql/avro/AvroFunctionsSuite.scala
b/connector/avro/src/test/scala/org/apache/spark/sql/avro/AvroFunctionsSuite.scala
index b30e92c28731..d12d9659eca0 100644
---
a/connector/avro/src/test/scala/org/apache/spark/sql/avro/AvroFunctionsSuite.scala
+++
b/connector/avro/src/test/scala/org/apache/spark/sql/avro/AvroFunctionsSuite.scala
@@ -18,7 +18,11 @@
package org.apache.spark.sql.avro
import java.io.ByteArrayOutputStream
+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 org.apache.avro.{Schema, SchemaBuilder}
@@ -27,15 +31,38 @@ import org.apache.avro.generic.{GenericDatumReader,
GenericDatumWriter, GenericR
import org.apache.avro.io.{DecoderFactory, EncoderFactory}
import org.apache.spark.{SparkException, SparkRuntimeException}
-import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
import org.apache.spark.sql.avro.{functions => Fns}
import org.apache.spark.sql.avro.functions.{from_avro, to_avro}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{AttributeReference,
CreateMap, ElementAt, Expression, ExprId, FromAvro, LeafExpression, Literal,
RuntimeReplaceable, SchemaOfAvro => SchemaOfAvroExpression, ToAvro}
+import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
+import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.execution.LocalTableScanExec
import org.apache.spark.sql.functions.{col, lit, map, struct}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types.{
- BinaryType, CharType, IntegerType, MapType, StringType, StructField,
StructType, VarcharType
+ BinaryType, CharType, DataType, IntegerType, MapType, StringType,
StructField, StructType,
+ VarcharType
+}
+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 AvroFunctionsSuite extends SharedSparkSession {
@@ -1022,4 +1049,306 @@ class AvroFunctionsSuite extends SharedSparkSession {
assert(!ex.isInstanceOf[NullPointerException],
s"Should not throw NPE, but got: ${ex.getClass.getName}:
${ex.getMessage}")
}
+
+ private val avroIntSchema = """{"type": "int"}"""
+
+ private def avroExpression(
+ functionName: String,
+ argument: String,
+ onEval: () => Unit,
+ duplicateKey: Boolean = false): (Expression, AttributeReference) = {
+ val secondKey = StringLiteralWithEvalHook(if (duplicateKey) "key1" else
"key2", onEval)
+ val value1 = if (argument == "schema") avroIntSchema else "value1"
+ val value2 = if (argument == "schema") avroIntSchema else "value2"
+ val mapExpression = CreateMap(Seq(
+ Literal("key1"), Literal(value1), secondKey, Literal(value2)))
+ val schema = if (argument == "schema") {
+ ElementAt(mapExpression, Literal("key1"))
+ } else {
+ Literal(avroIntSchema)
+ }
+ val options = if (argument == "options") mapExpression else Literal(null)
+ avroExpressionOf(functionName, schema, options)
+ }
+
+ // 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 avroExpressionWithSignedZeroKeys(
+ functionName: String,
+ argument: String): (Expression, AttributeReference) = {
+ val schema =
+ if (argument == "schema") signedZeroKeyLookup(avroIntSchema) else
Literal(avroIntSchema)
+ val options = if (argument == "options") {
+ CreateMap(Seq(Literal("key1"), signedZeroKeyLookup("value1")))
+ } else {
+ Literal(null)
+ }
+ avroExpressionOf(functionName, schema, options)
+ }
+
+ private def avroExpressionOf(
+ functionName: String,
+ schema: Expression,
+ options: Expression): (Expression, AttributeReference) = {
+ val dataType = if (functionName == "TO_AVRO") IntegerType else BinaryType
+ val data = AttributeReference("data", dataType)(exprId = ExprId(1))
+ val expression = functionName match {
+ case "FROM_AVRO" => new FromAvro(data, schema, options)
+ case "TO_AVRO" => new ToAvro(data, schema)
+ case "SCHEMA_OF_AVRO" => new SchemaOfAvroExpression(schema, options)
+ }
+ (expression, data)
+ }
+
+ private def avroOptions(expression: Expression): Map[String, String] =
expression match {
+ case from: AvroDataToCatalyst =>
+ assert(from.jsonFormatSchema == avroIntSchema)
+ from.options
+ case to: CatalystDataToAvro =>
+ assert(to.jsonFormatSchema.contains(avroIntSchema))
+ Map.empty
+ case schema: SchemaOfAvro =>
+ assert(schema.jsonFormatSchema == avroIntSchema)
+ schema.options
+ case other => fail(s"Unexpected Avro expression:
${other.getClass.getName}")
+ }
+
+ private def canonicalizedOptions(
+ expression: Expression,
+ data: AttributeReference): Map[String, String] = {
+ avroOptions(QueryPlan.normalizeExpressions(expression, Seq(data)))
+ }
+
+ private def replacementOptions(expression: Expression): Map[String, String]
= {
+ avroOptions(expression.asInstanceOf[RuntimeReplaceable].replacement)
+ }
+
+ // SCHEMA_OF_AVRO has no column input, so canonicalization keeps it; clone
it to get a copy.
+ private def copyOptions(
+ functionName: String,
+ expression: Expression,
+ data: AttributeReference): Map[String, String] = {
+ if (functionName == "SCHEMA_OF_AVRO") {
+ replacementOptions(expression.clone())
+ } else {
+ canonicalizedOptions(expression, data)
+ }
+ }
+
+ private def avroDataFrame(
+ functionName: String,
+ argument: String,
+ signedZeroKeys: Boolean = false): DataFrame = {
+ val schema = (argument, signedZeroKeys) match {
+ case ("schema", false) =>
+ s"element_at(map('schema', '$avroIntSchema', 'schema',
'$avroIntSchema'), 'schema')"
+ case ("schema", true) =>
+ s"element_at(map(0.0D, '$avroIntSchema', -0.0D, '$avroIntSchema'),
0.0D)"
+ case _ => s"'$avroIntSchema'"
+ }
+ val options = (argument, signedZeroKeys) match {
+ case ("options", false) => "map('mode', 'PERMISSIVE', 'mode',
'FAILFAST')"
+ case ("options", true) =>
+ "map('mode', element_at(map(0.0D, 'PERMISSIVE', -0.0D, 'PERMISSIVE'),
0.0D))"
+ case _ => "map()"
+ }
+ functionName match {
+ case "FROM_AVRO" =>
+ spark.range(1).select(lit(Array[Byte](2)).as("data"))
+ .selectExpr(s"FROM_AVRO(data, $schema, $options)")
+ case "TO_AVRO" =>
+ spark.range(1).select(lit(1).as("data")).selectExpr(s"TO_AVRO(data,
$schema)")
+ case "SCHEMA_OF_AVRO" =>
+ spark.range(1).selectExpr(s"SCHEMA_OF_AVRO($schema, $options)")
+ }
+ }
+
+ private def avroDataFrameResult(functionName: String): Row = functionName
match {
+ case "FROM_AVRO" => Row(1)
+ case "TO_AVRO" => Row(Array[Byte](2))
+ case "SCHEMA_OF_AVRO" => Row("INT")
+ }
+
+ Seq("FROM_AVRO", "TO_AVRO", "SCHEMA_OF_AVRO").foreach { functionName =>
+ val arguments = if (functionName == "TO_AVRO") Seq("schema") else
Seq("schema", "options")
+ arguments.foreach { argument =>
+ val expectedOptions = if (argument == "options") {
+ Map("key1" -> "value1", "key2" -> "value2")
+ } else {
+ Map.empty[String, String]
+ }
+
+ // Skip SCHEMA_OF_AVRO: it has no column input, so canonicalization
reuses the same instance,
+ // whose lazy replacement runs once, instead of copying it.
+ if (functionName != "SCHEMA_OF_AVRO") {
+ gridTest(s"SPARK-61419: $functionName $argument survives 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) = avroExpression(functionName, argument, ()
=> {
+ if (pauseOnNextEval.compareAndSet(true, false)) {
+ firstEvaluationPaused.countDown()
+ assert(resumeFirstEvaluation.await(1, TimeUnit.MINUTES),
+ "first evaluation was never resumed")
+ }
+ })
+ val sqlConf = SQLConf.get
+ val executor =
ThreadUtils.newDaemonSingleThreadExecutor("avro-argument-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-61419: $functionName $argument survives a failed
evaluation") {
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION") {
+ val failOnNextEval = new AtomicBoolean(true)
+ val expectedFailure = new RuntimeException(s"first $argument
evaluation failed")
+ val (expression, _) = avroExpression(functionName, argument, () => {
+ if (failOnNextEval.compareAndSet(true, false)) {
+ throw expectedFailure
+ }
+ })
+ val failure = intercept[RuntimeException] {
+ replacementOptions(expression)
+ }
+ assert(failure eq expectedFailure)
+
+ // Retrying must not reuse the partial map left by the failed
evaluation.
+ assert(replacementOptions(expression) == expectedOptions)
+ }
+ }
+
+ gridTest(s"SPARK-61419: a copy of $functionName uses the analysis-time
map key policy " +
+ s"for $argument")(
+ Seq("LAST_WIN", "EXCEPTION")) { capturedPolicy =>
+ val expectedDuplicateOptions = if (argument == "options") {
+ Map("key1" -> "value2")
+ } else {
+ Map.empty[String, String]
+ }
+ val (expression, data) = withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key
-> capturedPolicy) {
+ val result = avroExpression(functionName, argument, () => (),
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.
+ assert(replacementOptions(result._1) == expectedDuplicateOptions)
+ }
+ result
+ }
+ val currentPolicy = if (capturedPolicy == "LAST_WIN") "EXCEPTION" else
"LAST_WIN"
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> currentPolicy) {
+ if (capturedPolicy == "LAST_WIN") {
+ assert(copyOptions(functionName, expression, data) ==
expectedDuplicateOptions)
+ } else {
+ checkError(
+ exception = intercept[SparkRuntimeException] {
+ copyOptions(functionName, 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)
+ }
+ }
+
+ test(s"SPARK-61419: $functionName $argument executes after the map key
policy changes") {
+ val df = withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "LAST_WIN") {
+ avroDataFrame(functionName, argument)
+ }
+ withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION") {
+ checkAnswer(df, Seq(avroDataFrameResult(functionName)))
+ }
+ }
+
+ gridTest(s"SPARK-61419: a copy of $functionName uses the analysis-time
map key " +
+ s"normalization for $argument")(Seq(true, false)) { capturedDisabled =>
+ val policy = SQLConf.MAP_KEY_DEDUP_POLICY.key -> "EXCEPTION"
+ val normalization = SQLConf.DISABLE_MAP_KEY_NORMALIZATION.key
+ val expectedOptions = if (argument == "options") {
+ Map("key1" -> "value1")
+ } else {
+ Map.empty[String, String]
+ }
+ val (expression, data) = withSQLConf(policy, normalization ->
capturedDisabled.toString) {
+ val result = avroExpressionWithSignedZeroKeys(functionName, argument)
+ 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.
+ assert(replacementOptions(result._1) == expectedOptions)
+ }
+ result
+ }
+ withSQLConf(policy, normalization -> (!capturedDisabled).toString) {
+ if (capturedDisabled) {
+ assert(copyOptions(functionName, expression, data) ==
expectedOptions)
+ } else {
+ checkError(
+ exception = intercept[SparkRuntimeException] {
+ copyOptions(functionName, expression, data)
+ },
+ condition = "DUPLICATED_MAP_KEY",
+ parameters = Map(
+ "key" -> "-0.0",
+ "mapKeyDedupPolicy" ->
s"\"${SQLConf.MAP_KEY_DEDUP_POLICY.key}\""))
+ }
+ }
+ }
+
+ test(s"SPARK-61419: $functionName $argument 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 df = withSQLConf(policy, normalization -> "true") {
+ avroDataFrame(functionName, argument, signedZeroKeys = true)
+ }
+ withSQLConf(policy, normalization -> "false") {
+ checkAnswer(df, Seq(avroDataFrameResult(functionName)))
+ }
+ }
+
+ // Skip SCHEMA_OF_AVRO for the same reason: a cache lookup does not copy
it.
+ if (functionName != "SCHEMA_OF_AVRO") {
+ test(s"SPARK-61419: $functionName $argument cached plan retains its
map key policy " +
+ "across sessions") {
+ val cached = withSQLConf(SQLConf.MAP_KEY_DEDUP_POLICY.key ->
"LAST_WIN") {
+ avroDataFrame(functionName, argument).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)
+ }
+ }
+ }
+ }
+ }
+ }
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala
index d35178d4e3b9..89e6e9d12d2a 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala
@@ -78,11 +78,13 @@ case class FromAvro(
child: Expression,
jsonFormatSchema: Expression,
options: Expression,
- // PERSISTED: copy()/views keep analysis-time CHAR/VARCHAR flags. FromAvro
is
+ // PERSISTED: copy()/views keep analysis-time settings. FromAvro is
// RuntimeReplaceable, so a new replacement would otherwise re-read
SQLConf.
// FunctionRegistry matches Expression-only ctors; keep 2-arg and 3-arg.
charVarcharStandardSemantics: Boolean,
- charVarcharFirstClassTypes: Boolean)
+ charVarcharFirstClassTypes: Boolean,
+ mapKeyDedupPolicy: SQLConf.MapKeyDedupPolicy.Value,
+ disableMapKeyNormalization: Boolean)
extends TernaryExpression with RuntimeReplaceable {
override def first: Expression = child
override def second: Expression = jsonFormatSchema
@@ -95,7 +97,9 @@ case class FromAvro(
jsonFormatSchema,
options,
SQLConf.get.charVarcharStandardSemantics,
- SQLConf.get.charVarcharFirstClassTypes)
+ SQLConf.get.charVarcharFirstClassTypes,
+ SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY),
+ SQLConf.get.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION))
def this(child: Expression, jsonFormatSchema: Expression) =
this(child, jsonFormatSchema, Literal.create(null))
@@ -134,13 +138,32 @@ case class FromAvro(
}
override lazy val replacement: Expression = {
- val schemaValue: String = jsonFormatSchema.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 freshSchema = jsonFormatSchema.freshCopyIfContainsStatefulExpression()
+ val schemaValue: String = freshSchema.eval() match {
case s: UTF8String =>
s.toString
case null =>
""
}
- 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)
@@ -171,7 +194,7 @@ case class FromAvro(
override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("from_avro")
- // Persist flags are not user arguments; omit them from EXPLAIN / Connect
goldens.
+ // Persisted settings are not user arguments; omit them from EXPLAIN /
Connect goldens.
override protected def stringArgs: Iterator[Any] = super.stringArgs.take(3)
}
@@ -211,9 +234,23 @@ case class FromAvro(
since = "4.0.0"
)
// scalastyle:on line.size.limit
-case class ToAvro(child: Expression, jsonFormatSchema: Expression)
+case class ToAvro(
+ child: Expression,
+ jsonFormatSchema: Expression,
+ // PERSISTED: the map builder settings at analysis time,
spark.sql.mapKeyDedupPolicy and
+ // spark.sql.legacy.disableMapKeyNormalization. Constructor parameters, so
that copies keep
+ // them and evaluate the arguments the same way.
+ mapKeyDedupPolicy: SQLConf.MapKeyDedupPolicy.Value,
+ disableMapKeyNormalization: Boolean)
extends BinaryExpression with RuntimeReplaceable {
+ def this(child: Expression, jsonFormatSchema: Expression) =
+ this(
+ child,
+ jsonFormatSchema,
+ SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY),
+ SQLConf.get.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION))
+
def this(child: Expression) = this(child, Literal(null))
override def left: Expression = child
@@ -240,7 +277,25 @@ case class ToAvro(child: Expression, jsonFormatSchema:
Expression)
}
override lazy val replacement: Expression = {
- val schemaValue: Option[String] = jsonFormatSchema.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 freshSchema = jsonFormatSchema.freshCopyIfContainsStatefulExpression()
+ val schemaValue: Option[String] = freshSchema.eval() match {
case null =>
None
case s: UTF8String =>
@@ -256,6 +311,9 @@ case class ToAvro(child: Expression, jsonFormatSchema:
Expression)
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(2)
+
override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("to_avro")
}
@@ -288,7 +346,14 @@ case class ToAvro(child: Expression, jsonFormatSchema:
Expression)
since = "4.0.0"
)
// scalastyle:on line.size.limit
-case class SchemaOfAvro(jsonFormatSchema: Expression, options: Expression)
+case class SchemaOfAvro(
+ jsonFormatSchema: Expression,
+ options: Expression,
+ // PERSISTED: the map builder settings at analysis time,
spark.sql.mapKeyDedupPolicy and
+ // spark.sql.legacy.disableMapKeyNormalization. Constructor parameters, so
that copies keep
+ // them and evaluate the arguments the same way.
+ mapKeyDedupPolicy: SQLConf.MapKeyDedupPolicy.Value,
+ disableMapKeyNormalization: Boolean)
extends BinaryExpression with RuntimeReplaceable {
override def left: Expression = jsonFormatSchema
@@ -298,6 +363,13 @@ case class SchemaOfAvro(jsonFormatSchema: Expression,
options: Expression)
newLeft: Expression, newRight: Expression): Expression =
copy(jsonFormatSchema = newLeft, options = newRight)
+ def this(jsonFormatSchema: Expression, options: Expression) =
+ this(
+ jsonFormatSchema,
+ options,
+ SQLConf.get.getConf(SQLConf.MAP_KEY_DEDUP_POLICY),
+ SQLConf.get.getConf(SQLConf.DISABLE_MAP_KEY_NORMALIZATION))
+
def this(jsonFormatSchema: Expression) =
this(jsonFormatSchema, Literal.create(null))
@@ -329,13 +401,32 @@ case class SchemaOfAvro(jsonFormatSchema: Expression,
options: Expression)
}
override lazy val replacement: Expression = {
- val schemaValue: String = jsonFormatSchema.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 = {
+ // Copy stateful arguments so a failed evaluation cannot leave a partial
map in the CreateMap's
+ // map builder, which, under the default EXCEPTION policy, makes every
later evaluation fail.
+ val freshSchema = jsonFormatSchema.freshCopyIfContainsStatefulExpression()
+ val schemaValue: String = freshSchema.eval() match {
case s: UTF8String =>
s.toString
case null =>
""
}
- 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)
@@ -354,6 +445,9 @@ case class SchemaOfAvro(jsonFormatSchema: Expression,
options: Expression)
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(2)
+
override def prettyName: String =
getTagValue(FunctionRegistry.FUNC_ALIAS).getOrElse("schema_of_avro")
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]