Yaoxuan Wu created FLINK-41760:
----------------------------------
Summary: Streaming LATERAL Top-N returns rows for a NULL
correlation key: CorrelateSortToRankRule drops the correlation predicate t.k =
o.k
Key: FLINK-41760
URL: https://issues.apache.org/jira/browse/FLINK-41760
Project: Flink
Issue Type: Bug
Components: Table SQL / Planner
Affects Versions: 2.3.0, 2.0.1
Reporter: Yaoxuan Wu
In streaming mode, a correlated Top-N written with LATERAL returns rows for the
outer key NULL, although the correlation predicate {{t.k = o.k}} is never TRUE
for it.
{code:sql}
CREATE TEMPORARY VIEW t AS SELECT * FROM (VALUES
(1, 'a', 3), (1, 'b', 2), (2, 'd', 5), (CAST(NULL AS INT), 'e', 1)) AS x(k,
s, v);
SELECT o.k, l.s, l.v
FROM (SELECT DISTINCT k FROM t) o,
LATERAL (SELECT s, v FROM t WHERE t.k = o.k ORDER BY v DESC LIMIT 1) l;
{code}
Expected: (1, a, 3), (2, d, 5)
Actual (streaming mode): (1, a, 3), (2, d, 5), (NULL, e, 1)
Reproduced on 2.0, 2.3.0 and the current master. The same query without ORDER
BY ... LIMIT returns the two expected rows on master. (Batch mode fails to plan
the query, see FLINK-41614.)
Cause: CorrelateSortToRankRule rewrites Correlate(Aggregate(k), Sort(fetch,
Project(Filter(k = $cor.k)))) into a ROW_NUMBER Rank partitioned by k over the
filter's input:
{code:java}
RelNode newRel = ((FlinkRelBuilder) (builder.push(filter.getInput())))
.rank(partitionKey, newCollation, RankType.ROW_NUMBER,
new ConstantRankRange(1, ((RexLiteral)
sort.fetch).getValueAs(Long.class)), null, false)
.project(projects)
.build();
{code}
The equality filter is dropped. Partitioning by k is equivalent to it only for
non-NULL keys: the rows with k IS NULL form their own partition and keep their
top rows. Keeping a k IS NOT NULL filter below the Rank (for every nullable
partition key) would fix it.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)