James Xu created SPARK-62339:
--------------------------------

             Summary: Preserve intermediate projection inputs during CTE column 
pruning
                 Key: SPARK-62339
                 URL: https://issues.apache.org/jira/browse/SPARK-62339
             Project: Spark
          Issue Type: Bug
          Components: SQL
    Affects Versions: 5.0.0
            Reporter: James Xu


Problem:
A nested materialized CTE can fail during execution when column pruning 
considers only the final projection and overlooks attributes required by an 
intermediate projection.

For example:

```sql
WITH c3 AS MATERIALIZED (
  SELECT id, id % 10 AS k, id % 7 AS d
  FROM range(100)
)
SELECT (
  WITH c7 AS MATERIALIZED (
    SELECT id, k FROM c3
  )
  SELECT min(k) FROM c7
) AS x;
```

This query should return `0`. Instead, it fails with an error such as:

```text
INTERNAL_ERROR_ATTRIBUTE_NOT_FOUND: Could not find id#... in [k#...]
```

The failure occurs with both adaptive and non-adaptive execution.

After optimization, `c7` can contain a projection chain conceptually equivalent 
to:

```text
Project [k]
+- Project [id, k]
   +- CTERelationRef [c3]
```

The inner projection still requires `id` to calculate `k`. However, a later 
pruning pass reduces `c3` to `k`, making the inner projection invalid.

Root Cause:
`PushdownPredicatesAndPruneColumnsForCTEDef` gathers required attributes 
through `PhysicalOperation`.

`PhysicalOperation` collapses the projection and filter chain for pattern 
matching but returns only the final merged project list. The rule then gathers 
attributes using `projects.flatMap(_.references)`, which captures `k` but 
misses the intermediate projection's input reference to `id`.

`needsPruning` subsequently checks only whether the gathered attributes are a 
subset of the CTE output. Since `{k}` is a subset of `{id, k, d}`, the rule 
prunes `c3` without verifying the references required by projection nodes 
remaining in the plan.

Proposed Fix:
When gathering required attributes, walk the original projection chain and 
include the input references of every intermediate `Project` that can remain 
after the rewrite, in addition to the final projection and predicate references.

This ensures that pruning preserves every attribute needed by downstream plan 
nodes. In the example, `id` and `k` must remain available to the inner 
projection, while `d` may still be pruned.

Regression Test:
Add the query above to `CTEInlineSuite` and verify that it returns `0` with AQE 
both enabled and disabled. The test should also verify that the optimized CTE 
plan retains the attributes required by the intermediate projection.




--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to