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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala:
##########
@@ -167,7 +167,10 @@ case class FromProtobuf(
       case bytes: Array[Byte] => Some(bytes)
       case null => None
     }
-    val optionsValue: Map[String, String] = options.eval() match {
+    // Concurrent canonicalization can evaluate the same CreateMap and corrupt 
its map builder.
+    // Copy stateful options to avoid duplicate-key errors and mismatched 
key/value array lengths.
+    val freshOptions = options.freshCopyIfContainsStatefulExpression()

Review Comment:
   **Blocking (P1):** This fresh copy builds a new `ArrayBasedMapBuilder` on 
every canonicalization, and that builder reads `spark.sql.mapKeyDedupPolicy` 
from whichever session runs the cache lookup (`ArrayBasedMapBuilder.scala` line 
62). Before this change, canonicalization copies shared the original 
`CreateMap`, whose builder kept the policy from when the plan was analyzed.
   
   That breaks options that repeat a key, which only LAST_WIN accepts. Tracing 
the code: session A sets LAST_WIN and caches `SELECT from_protobuf(value, 'M', 
'/path/m.desc', map('mode', 'PERMISSIVE', 'mode', 'FAILFAST')) AS m FROM t` 
while nothing else is cached, so the cache key is stored without being 
canonicalized. If session B, on the default EXCEPTION, then runs `SELECT 1`, 
B's cache lookup canonicalizes A's plan under B's policy, the second put of 
`mode` throws `DUPLICATED_MAP_KEY`, and B's query fails. A failed 
canonicalization is not cached, so B keeps failing until a LAST_WIN lookup 
succeeds. On the base branch B's query succeeds. The same failure reaches 
queries that the base branch serves from such a cache entry after the session 
switches to EXCEPTION, the cache check that `recacheByPlan` runs after a write, 
and streaming micro-batches planned under EXCEPTION for a query analyzed under 
LAST_WIN while anything is cached.
   
   Running such a plan without a cache hit under EXCEPTION already fails on the 
base branch, because the optimizer evaluates a fresh copy of the options there 
too (`QueryExecution.scala` line 351), so the regression is limited to these 
canonicalization paths. `to_protobuf` behaves the same at lines 342-343.
   
   **Recommended change:** Capture `spark.sql.mapKeyDedupPolicy` when each 
expression is created, and keep it as a persisted field that is not a child, so 
that every copy, including every canonicalization copy, carries it. Then 
evaluate the replacement's constant arguments, including the fresh options 
copy, with that policy in effect instead of the evaluating session's. Follow 
the FromAvro pattern. The Expression-only constructors that FunctionRegistry 
and other callers use read the active value. The field stays out of 
`stringArgs`, so EXPLAIN output does not change. The existing two-, three-, and 
four-argument forms keep working. Add protobuf function tests, for both 
functions, that evaluate the options under LAST_WIN and canonicalize them later 
under EXCEPTION.
   
   **Why this works:** The builder the fresh copy creates reads the policy from 
`SQLConf.get` when it is constructed. Run the argument evaluations inside a 
conf scope that carries the captured policy, for example 
`SQLConf.withExistingConf` over a clone of the active conf with only that entry 
changed, used only when the two differ. Every recomputation then uses the 
policy the expression was analyzed with. A plan that analyzed successfully 
canonicalizes to the same options in any later session, as on the base branch, 
and each evaluation still owns its builder.
   
   **Scope:** Persist the analysis-time map-key policy in the two protobuf 
wrappers and evaluate their constant arguments under it. Add tests in which the 
policy changes between evaluations.
   
   **Compatibility:** Every evaluation still uses a private copy of the 
options, so concurrent canonicalizations and retries after a failed evaluation 
keep returning the complete options map.
   
   **Risks:** Adding a persisted field changes the case-class shape. Code that 
constructs or pattern-matches the four-argument form needs updating, and the 
field must stay out of stringArgs, or EXPLAIN output and plan strings change. 
Two expressions created under different policies are no longer equal as plain 
expressions. Cache matching is unaffected, because their canonical forms 
compare only the replacement. Cloning the active conf for an evaluation whose 
captured policy differs from the active one adds a small planning-time cost, 
limited to evaluations that need it. It also changes execution after a policy 
change. On the base branch the optimizer evaluates a fresh copy of the options 
under the executing session's policy, so a plan analyzed under LAST_WIN whose 
options repeat a key fails with DUPLICATED_MAP_KEY when it runs under EXCEPTION 
without a cache hit. With the pin it runs with the options it was analyzed 
with, as FromAvro's persisted flags already make its replacement do.
  That only removes a failure, so it needs no rollback flag; keeping the 
failure would need the copies made for execution to capture the policy again.
   
   **Constraints:** Each evaluation must still use its own fresh copy of the 
options, so the overlapping-canonicalization and failed-evaluation fixes keep 
holding. Only the map-key policy is pinned. Any other setting an options 
evaluation reads still comes from the active session.
   
   **Exclusions:**
   - Applying the same fix to from_avro, which the author is tracking 
separately.
   
   **Success:** A from_protobuf or to_protobuf plan whose options repeat a key 
and that was analyzed under LAST_WIN canonicalizes to the LAST_WIN options when 
a later cache lookup, cache check, or streaming micro-batch runs under 
EXCEPTION, in the same session or in another one. Options that repeat a key 
still fail with DUPLICATED_MAP_KEY when the expression is analyzed under 
EXCEPTION. Under a single map-key policy, single evaluations, overlapping 
canonicalizations, and retries after a failed evaluation return the same 
options as with the current change, and EXPLAIN output is unchanged. A plan 
analyzed under LAST_WIN whose options repeat a key runs under EXCEPTION with 
its LAST_WIN options instead of failing during optimization.
   
   **Verification:**
   - **Regression:** For both functions, analyze an expression whose options 
repeat a key under LAST_WIN, then canonicalize it under EXCEPTION, as another 
session's cache lookup does. The canonical options equal the LAST_WIN result, 
and no DUPLICATED_MAP_KEY is raised.
   - **Behavior:** For both functions, an expression whose options repeat a key 
and that is created under EXCEPTION still fails with DUPLICATED_MAP_KEY.
   - **Compatibility:** The overlapping-canonicalization and failed-evaluation 
coverage keeps passing under both policies, and the plans and EXPLAIN text of 
from_protobuf and to_protobuf queries, including the recorded Connect explain 
output, are unchanged.
   - **Behavior:** For both functions, a plan whose options repeat a key, 
analyzed under LAST_WIN and then executed under EXCEPTION without a cache hit, 
runs with the LAST_WIN options instead of failing with DUPLICATED_MAP_KEY.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/toFromProtobufSqlFunctions.scala:
##########
@@ -167,7 +167,10 @@ case class FromProtobuf(
       case bytes: Array[Byte] => Some(bytes)
       case null => None
     }
-    val optionsValue: Map[String, String] = options.eval() match {
+    // Concurrent canonicalization can evaluate the same CreateMap and corrupt 
its map builder.
+    // Copy stateful options to avoid duplicate-key errors and mismatched 
key/value array lengths.
+    val freshOptions = options.freshCopyIfContainsStatefulExpression()

Review Comment:
   **Non-blocking (P2):** Only `options` is copied here, but the same 
`replacement` still evaluates `messageName.eval()` and `descFilePath.eval()` in 
place (lines 156 and 162, and lines 328 and 334 in `ToProtobuf`). 
Canonicalization copies share those subtrees too, and `checkInputDataTypes` 
accepts any foldable string message name and any foldable string or binary 
descriptor, so SQL can pass a stateful expression there. With 
`from_protobuf(value, element_at(map('m', 'OtherExample'), 'm'), 
'/path/m.desc', map('mode', 'PERMISSIVE'))`, two overlapping canonicalizations 
would interleave puts on the shared map builder: under EXCEPTION the second put 
of `m` throws `DUPLICATED_MAP_KEY`, and under LAST_WIN one evaluation can build 
an empty map, so the lookup returns null and `replacement` fails with `Message 
name cannot be null`. A message-name evaluation that fails partway also leaves 
its entries behind for the next copy, the same residue the new retry test 
covers for options. These inputs 
 are unusual and the failures are loud, but it is the failure this PR fixes, in 
the same function. Copying these two arguments the way the options are copied, 
under the same map-key policy as the options copy, closes it.
   
   **Verification:**
   - **Regression:** For both functions, with a message name computed by a map 
lookup, pause one canonicalization inside the map's evaluation while a second 
one completes. Both resolve the expected message, with no DUPLICATED_MAP_KEY 
and no missing message name.
   - **Regression:** For both functions, after a message-name evaluation fails 
partway, retrying the canonicalization of the same expression resolves the 
expected message.
   - **Inspection:** The message-name and descriptor copies are evaluated 
inside the same pinned map-key policy scope as the options copy.



-- 
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