Fabian Hueske created FLINK-41672:
-------------------------------------
Summary: ScanReuser reads nested fields twice when one reused scan
projects a whole ROW field and another projects its sub-fields
Key: FLINK-41672
URL: https://issues.apache.org/jira/browse/FLINK-41672
Project: Flink
Issue Type: Improvement
Components: Table SQL / Planner
Reporter: Fabian Hueske
h3. Problem
When the planner reuses a source scan that supports nested projection push-down
({{SupportsProjectionPushDown#supportsNestedProjection}}), {{ScanReuser}}
merges the projections of the reused scans by putting their index paths into
one set ({{ScanReuser.java}}, the {{allProjectFieldSet}} {{TreeSet}}). That
only removes paths that are exactly equal. It doesn't remove a path such as
{{[nested, i]}} when another scan also reads all of {{[nested]}}. The merged
scan then reads the same data twice: once inside the whole ROW and once more as
separate leaf columns.
The redundant paths can't simply be dropped at the moment: after merging, each
original scan maps its fields back to the merged scan by an exact path match
({{ScanReuserUtils#indexOf}}).
h3. Reproduction
The existing batch test {{ScanReuseTest#testProjectNestedWithWholeField}}
already shows the problem:
{code:sql}
CREATE TABLE MyTable (
a INT, b VARCHAR, c VARCHAR,
nested ROW<i INT, j INT, s STRING>,
...
) WITH ('connector' = 'values', 'nested-projection-supported' = 'true', ...);
SELECT * FROM
(SELECT a, nested.i FROM MyTable) T1,
(SELECT a, nested FROM MyTable) T2
WHERE T1.a = T2.a
{code}
Current plan:
{noformat}
: +- Calc(select=[a, nested_i])
: +- TableSourceScan(table=[[..., MyTable, project=[a, nested, nested_i]]],
fields=[a, nested, nested_i])(reuse_id=[1])
+- Calc(select=[a, nested])
+- Reused(reference_id=[1])
{noformat}
{{nested_i}} is redundant because {{nested}} already contains it.
h3. Impact
The results are correct, but every emitted row carries duplicate copies of the
nested fields. That costs extra serialization, memory and network for
downstream operators. It can make a reused scan more expensive than separate
scans with well-pruned projections.
h3. Proposed fix
In {{ScanReuser}}:
# After collecting the projected paths of all reused scans, drop every path
that has a shorter path in the set as a prefix, e.g. drop {{[3, 0]}} when
{{[3]}} is present.
# When building the Calc for each original scan, resolve a field path whose
prefix is projected as a field access on that prefix column, e.g. {{nested.i}},
instead of looking up an exact path match.
# Remap the field references of the adjusted {{WatermarkPushDownSpec}} the same
way. They are currently remapped by field name ({{ScanReuserUtils}}), so a
reference such as {{nested_s}} would have to become {{nested.s}}.
Expected plan for the reproduction query: {{project=[a, nested]}}, with T1
reading {{nested.i}} from {{nested}}.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)