spark-test commented on code in PR #60354:
URL: https://github.com/apache/spark/pull/60354#discussion_r4547164711


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala:
##########
@@ -134,13 +136,30 @@ 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) {

Review Comment:
   **Blocking (P1):** This check pins only `spark.sql.mapKeyDedupPolicy`, but 
the fresh copies' `ArrayBasedMapBuilder` also reads 
`spark.sql.legacy.disableMapKeyNormalization`, lazily at its first `put` 
(ArrayBasedMapBuilder.scala:64-69). On the base branch, canonicalization copies 
reused the builder that analysis had already initialized, so both settings kept 
their analysis-time values; now a copy takes the normalization setting from 
whichever session evaluates it. `ToAvro` (line 271) and `SchemaOfAvro` (line 
387) repeat the same check.
   
   Reading the code, this sequence fails at the last line:
   
   ```scala
   spark.conf.set("spark.sql.legacy.disableMapKeyNormalization", "true")
   spark.sql("""SELECT to_avro(id, element_at(map(0.0D, '"long"', -0.0D, 
'"long"'), 0.0D)) AS x
     FROM range(1)""").cache()  // lazy, with no other cache entry
   spark.conf.set("spark.sql.legacy.disableMapKeyNormalization", "false")
   spark.sql("SELECT 1").collect()
   ```
   
   Analysis keeps `0.0` and `-0.0` as distinct keys, and caching into an empty 
cache never canonicalizes the cache key (CacheManager.scala:154, 168). The 
cache lookup for `SELECT 1` then canonicalizes the cached plan for the first 
time: the `ToAvro` copy's fresh map normalizes `-0.0` to `0.0` and, under the 
recorded EXCEPTION policy, throws `DUPLICATED_MAP_KEY`. The lookup calls 
`sameResult` without exception handling (CacheManager.scala:516), and 
`TransientBestEffortLazyVal` stores nothing when its computation throws, so 
every later query in that session fails the same way, `df.unpersist()` 
included, until the setting is restored or the cache is cleared. A query in 
another session that keeps the default fails too, until a lookup computes the 
canonical form under the analysis-time setting. On the base branch the same 
sequence succeeds. Under LAST_WIN, when the two keys map to different values, 
the copy can name a different schema or options than analysis selected. This is 
the same fa
 ilure that the PR's cross-session test guards against for the dedup policy.
   
   **Recommended change:** Record spark.sql.legacy.disableMapKeyNormalization 
when FromAvro, ToAvro and SchemaOfAvro are created, as a persisted non-child 
constructor parameter next to the recorded map key policy. The Expression-only 
constructors set it from the analyzing session, and it stays out of stringArgs. 
Build the replacement under an evaluation conf that carries both recorded 
values whenever either differs from the session's. Add Avro function tests for 
a map whose float or double keys differ only in the sign of zero.
   
   **Why this works:** ArrayBasedMapBuilder reads the dedup policy when a fresh 
copy's map builder is constructed and the normalization switch when its first 
key is put, and both happen while createReplacement evaluates the copied 
arguments. An evaluation conf that carries both recorded values therefore gives 
every copy the map semantics of analysis, which is what the shared builder gave 
canonicalization on the base branch.
   
   **Scope:** Persist the second map-builder setting in the three Avro wrapper 
expressions, and apply it together with the policy when their replacement 
evaluates copied arguments.
   
   **Compatibility:** When the session's map key policy and normalization 
setting both match the recorded values, the replacement is built without a conf 
clone, and every result, EXPLAIN output, generated column name and canonical 
form is the same as before this repair.
   
   **Risks:** Execution after the normalization setting changes also uses the 
analysis-time value. A plan analyzed with normalization disabled therefore no 
longer fails with DUPLICATED_MAP_KEY, or picks a different entry, when it 
executes after the setting is turned back on. This matches how the PR already 
treats the map key policy, and removing the parameter rolls it back. The 
case-class constructors of the three expressions gain another parameter. They 
are internal Catalyst API, and the Expression-only constructors the registry 
uses are unchanged.
   
   **Constraints:** Keep the Expression-only constructors the function registry 
resolves: two and three arguments for from_avro, one and two for to_avro and 
schema_of_avro. Keep the recorded settings out of stringArgs and out of the 
children, so EXPLAIN output, generated column names and canonical forms do not 
include them. Keep building the replacement without a conf clone when both 
recorded values equal the session's.
   
   **Exclusions:**
   - Other settings that a stateful argument reads when first evaluated, such 
as the JSON options to_json reads, keep coming from the evaluating session; the 
review found no supported input where they turn a successful cache lookup into 
a failure.
   - The Protobuf SQL functions, whose fix is tracked separately in SPARK-60945.
   
   **Success:** A cached plan whose to_avro schema or from_avro options contain 
a map with keys 0.0 and -0.0, analyzed with 
spark.sql.legacy.disableMapKeyNormalization=true, canonicalizes without 
DUPLICATED_MAP_KEY after the setting is turned off in the same session and from 
another session that keeps the default, so unrelated queries' cache lookups 
succeed. A copy of from_avro, to_avro or schema_of_avro evaluated under a 
session whose normalization setting differs from the recorded one returns the 
value analysis computed, under both map key policies. EXPLAIN output, generated 
column names and the argument counts the registry accepts are unchanged.
   
   **Verification:**
   - **Regression:** Cache a plan whose to_avro schema argument is element_at 
over a map with keys 0.0D and -0.0D, analyzed with 
spark.sql.legacy.disableMapKeyNormalization=true under the EXCEPTION policy. 
Then run an unrelated query after turning the setting off in the same session, 
and again in another session that keeps the default. Both queries succeed 
instead of failing with DUPLICATED_MAP_KEY, and the cached plan can still be 
unpersisted.
   - **Regression:** Under LAST_WIN, with different values for the two keys, 
canonicalize a copy of from_avro whose options hold such a nested map and a 
copy of to_avro whose schema is built from such a map, after the setting 
changes. Each names the value analysis selected, not the one normalization 
would keep.
   - **Behavior:** A copy of schema_of_avro whose options contain such a map, 
evaluated after the normalization setting changes, returns the value analysis 
computed.
   - **Compatibility:** EXPLAIN output for from_avro, to_avro and 
schema_of_avro shows only their user arguments, and calls with every currently 
accepted argument count still resolve.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala:
##########
@@ -329,13 +383,30 @@ 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) {
+      createReplacement()
+    } else {
+      val evalConf = conf.clone()
+      evalConf.setConf(SQLConf.MAP_KEY_DEDUP_POLICY, mapKeyDedupPolicy)
+      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 would break every later evaluation of this 
expression.

Review Comment:
   **Nit (P3):** This holds only under the EXCEPTION policy. Under LAST_WIN, 
`ArrayBasedMapBuilder.put` overwrites an existing key instead of throwing 
(ArrayBasedMapBuilder.scala:86-95), and `CreateMap.eval` puts every key again 
before `build()` resets the builder, so a retry after a failed evaluation of 
these constant arguments returns the full map. Since these expressions can now 
record LAST_WIN, the comment could say:
   
   ```suggestion
       // map builder, which, under the default EXCEPTION policy, makes every 
later evaluation fail.
   ```
   
   **Verification:**
   - **Inspection:** The comment explaining why SchemaOfAvro copies its 
arguments says that a leftover partial map breaks later evaluations under the 
EXCEPTION policy, and makes no such claim for LAST_WIN.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/avroSqlFunctions.scala:
##########
@@ -134,13 +136,30 @@ 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) {
+      createReplacement()
+    } else {
+      val evalConf = conf.clone()

Review Comment:
   **Nit (P3):** When the policies differ, this clones the whole session conf 
even if neither argument contains a stateful expression. For literal arguments, 
such as `to_avro(col, '<schema>')` or `from_avro` with NULL options, 
`freshCopyIfContainsStatefulExpression()` returns the argument unchanged, and 
evaluating it reads no map setting: the only reader is `ArrayBasedMapBuilder`, 
and only stateful expressions hold one. `SQLConf.clone()` replays every set 
entry through `setConfString` and logs a warning for each deprecated key 
(SQLConf.scala:11028-11034, 10994-10998). For example, a persistent view saved 
without the policy keeps the default EXCEPTION for its body, so a LAST_WIN 
session that queries it while anything is cached pays for a clone, and repeats 
those warnings, on every cache lookup that canonicalizes the view's `to_avro` 
call. Cloning only when an evaluated argument contains a stateful expression, 
for example when the fresh copy is a different instance, gives the same resu
 lts. `ToAvro` (line 274) and `SchemaOfAvro` (line 390) do the same.
   
   **Verification:**
   - **Behavior:** Canonicalize a copy of to_avro and a copy of from_avro with 
literal arguments in a session whose map key policy differs from the recorded 
one and that sets a deprecated SQL config. Each gives the same canonical form 
as before and logs no deprecation warning for that config during 
canonicalization, which shows that no conf clone ran.
   - **Compatibility:** Copies of all three expressions whose schema or options 
contain a map still keep the recorded policy in both directions: one created 
under LAST_WIN with a repeated key returns the LAST_WIN result under EXCEPTION, 
and one created under EXCEPTION still fails with DUPLICATED_MAP_KEY under 
LAST_WIN.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to