Yibo Dong created SPARK-62277:
---------------------------------
Summary: Correlated LIMIT/OFFSET is incorrectly applied globally
when the outer key is an expression
Key: SPARK-62277
URL: https://issues.apache.org/jira/browse/SPARK-62277
Project: Spark
Issue Type: Bug
Components: SQL
Affects Versions: 5.0.0
Environment: Stock Apache Spark 5.0.0-SNAPSHOT at commit
082cf160890a0a0a748f70ffb5a993144b0de079, Java 25.0.1, macOS 15.7.4 aarch64,
local[2], in-memory session catalog, built-in Parquet data source (V1), default
SQL configuration.
Reporter: Yibo Dong
A correlated subquery with ORDER BY and LIMIT returns incorrect results when
its equality predicate compares an inner column with an expression of an outer
column, such as s.k = o.k || ''.
Instead of applying LIMIT separately for each outer row, Spark applies it
globally to the inner relation before joining the results. Consequently, some
outer rows lose their matching results.
The same issue affects SQL table functions, where the analyzer can introduce an
implicit cast around an outer parameter.
h2. How to reproduce
Run the following SQL in a fresh Spark SQL session:
{code:sql}
CREATE TEMPORARY VIEW o AS
SELECT * FROM VALUES (1, 'a'), (2, 'b') AS o(oid, k);
CREATE TEMPORARY VIEW s AS
SELECT * FROM VALUES
('a', 1), ('a', 2), ('b', 3), ('b', 4) AS s(k, x);
CREATE TEMPORARY FUNCTION top1(p STRING)
RETURNS TABLE (x INT)
RETURN SELECT x FROM s
WHERE s.k = p ORDER BY x DESC LIMIT 1;
-- Direct function calls.
SELECT * FROM top1('a');
SELECT * FROM top1('b');
-- Q1: Lateral SQL table function.
SELECT o.oid, t.x
FROM o, LATERAL top1(o.k) AS t
ORDER BY o.oid;
-- Q2: Lateral subquery with an expression of the outer key.
SELECT o.oid, t.x
FROM o, LATERAL (
SELECT x FROM s
WHERE s.k = o.k || ''
ORDER BY x DESC LIMIT 1
) AS t
ORDER BY o.oid;
-- Q3: Correlated scalar subquery.
SELECT o.oid,
(SELECT x FROM s
WHERE s.k = o.k || ''
ORDER BY x DESC LIMIT 1) AS x
FROM o ORDER BY o.oid;
-- Control: direct outer-column reference.
SELECT o.oid,
(SELECT x FROM s
WHERE s.k = o.k
ORDER BY x DESC LIMIT 1) AS x
FROM o ORDER BY o.oid;
{code}
Save as tmp.sql and execute:
{code:bash}
spark-sql --master 'local[2]' --conf spark.sql.catalogImplementation=in-memory
-f tmp.sql
{code}
h2. Expected result
The direct calls top1('a') and top1('b') return 2 and 4, respectively.
Since o.k || '' is equivalent to o.k for these values, Q1, Q2, Q3, and the
control should all return:
{noformat}
oid | x
----+---
1 | 2
2 | 4
{noformat}
h2. Actual result
The direct function calls and the control return the expected results.
Q1 and Q2 return only:
{noformat}
oid | x
----+---
2 | 4
{noformat}
Q3 returns:
{noformat}
oid | x
----+-----
1 | NULL
2 | 4
{noformat}
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]