apache / apache/kyuubi

[Bug] A cached permanent view is re-read when referenced twice in one query

Open
#7,738 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Scala
Stars
2.4k
Forks
1k
PR merge metrics
No merged PRs in 30d

Description

### Code of Conduct

- [x] I agree to follow this project's [Code of Conduct](https://www.apache.org/foundation/policies/conduct)

### Search before asking

- [x] I have searched in the [issues](https://github.com/apache/kyuubi/issues?q=is%3Aissue) and found no similar issues.

### Describe the bug

Caching a permanent view and referencing it twice in one query makes the second reference miss
the cache and read the view down to its base tables.

```scala
sql("CREATE TABLE t (id int, k int)")
sql("CREATE VIEW v AS SELECT id, k FROM t")

val df = spark.table("v")
df.cache()
df.count()

val optimized = df.join(df.select("k").distinct(), "k").queryExecution.optimizedPlan
assert(optimized.collect { case r: InMemoryRelation => r }.size === 2) // 1 did not equal 2
```

`PermanentViewMarker` is a `MultiInstanceRelation`, so the analyzer calls `newInstance()` on the
second occurrence. The contract is that a new instance stays `sameResult` with the original,
which is what lets `CacheManager` find it. It does not: `newInstance()` wraps the child in a
`Project` that survives canonicalization, for three reasons.

- The `Cast` in `Alias(Cast(attr, attr.dataType), attr.name)` makes Spark's own rename-only
`Project` stripping not apply.
- `doCanonicalize`'s guard reads a `TreeNodeTag[Unit]` with `.contains(true)`, which is always
false, so it never runs.
- That guard also matches only one `Project` layer and only under a `View`, and neither holds
for subquery markers or for a renewed marker that is reused in another query.

Reproduced on Spark 3.5, 4.0 and 4.1.

### Affects Version(s)

master, 1.11.x, 1.10.0

### Additional context

The first point came in with #5884, the other two with #5937, which shipped without a test.
A PR with the fix and unit tests follows.

### Are you willing to submit PR?

- [x] Yes. I would be willing to submit a PR with guidance from the Kyuubi community to fix.

Contributor guide

Open the contributing guide

Research direction

Start by running the SQL reproduction and inspecting PermanentViewMarker.newInstance(), doCanonicalize, and the CacheManager sameResult lookup. Trace the optimizedPlan and the InMemoryRelation instances for the two references, then add unit coverage for the regression. Done means both references resolve to cached relations and the tests pass on the affected Spark versions.

Written by the indexing model from the issue text.

Assessment

Tech stack
scala, spark
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.