Artem Kupchinskiy created SPARK-61192:
-----------------------------------------
Summary: Non-deterministic or MATERIALIZED CTE whose body ends in
COALESCE is evaluated once per reference
Key: SPARK-61192
URL: https://issues.apache.org/jira/browse/SPARK-61192
Project: Spark
Issue Type: Bug
Components: SQL
Affects Versions: 4.1.4, 4.0.1, 4.3.0, 5.0.0
Reporter: Artem Kupchinskiy
A CTE that is not inlined (non-deterministic and referenced more than once, or
{{AS MATERIALIZED}}) should be evaluated once: {{ReplaceCTERefWithRepartition}}
puts a round-robin shuffle on top of the definition and all references reuse
it. The shuffle is skipped when the definition already ends in any
{{RepartitionOperation}} ({{canSkipExtraRepartition}}). A coalesce is
{{Repartition(n, shuffle = false)}}, planned as {{CoalesceExec}}, so there is
no exchange to reuse and every reference evaluates the body again.
{code:python}
import uuid
from pyspark.sql.functions import udf
spark.udf.register("random_uuid", udf(lambda:
str(uuid.uuid4())).asNondeterministic())
spark.sql("""
WITH t AS (SELECT /*+ COALESCE(1) */ id, random_uuid() AS u FROM range(0,
1000, 1, 4))
SELECT count(*) FROM t a JOIN t b ON a.u = b.u
""").show()
# expected 1000, returns 0 (AQE on and off; 4.0.1, 4.1.4, 4.3.0, master)
{code}
The same with {{WITH t AS MATERIALIZED (...)}} on master, and in plain SQL with
{{reflect('java.util.UUID', 'randomUUID')}} instead of the UDF. The physical
plan has two {{Coalesce 1}} subtrees, each with its own {{Range}}, and no
{{ReusedExchange}}.
Proposed fix: for a coalesce root, put the round-robin shuffle below the
coalesce and keep the coalesce on top, so the CTE still has at most n
partitions. Cost: such CTEs now go through one round-robin shuffle.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]