cloud-fan commented on code in PR #59857:
URL: https://github.com/apache/spark/pull/59857#discussion_r4508843522
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -377,11 +377,19 @@ class CacheManager extends Logging with
AdaptiveSparkPlanHelper {
includeTimeTravel: Boolean = true): Unit = {
val resolver = spark.sessionState.conf.resolver
def shouldInvalidate(entry: CachedData): Boolean = {
- entry.plan.exists(isMatchedTableOrView(_, name, resolver,
includeTimeTravel))
+ existsWithSubqueries(entry.plan)(isMatchedTableOrView(_, name, resolver,
includeTimeTravel))
}
recacheByCondition(spark, shouldInvalidate)
}
+ /**
+ * Returns whether `f` holds for any node of `plan`, including nodes inside
subquery expressions.
+ * Write-driven invalidation skips time-travel relations, so an entry that
reads a table at a
+ * pinned version and live only inside a subquery must still match through
the subquery.
+ */
+ private def existsWithSubqueries(plan: LogicalPlan)(f: LogicalPlan =>
Boolean): Boolean =
Review Comment:
**Non-blocking (P2):** This helper is only used by `recacheTableOrView` and
`recacheByPath`. The other routes that pick the cache entries depending on
changed data still use children-only `exists`: `recacheByPlan`
(`_.plan.exists(_.sameResult(normalized))`) and the cascade branch of
`uncacheByCondition` (`_.exists(isMatchedPlan)`). So a cached query that reads
a table only inside a subquery is still left stale after writes and refreshes
that go through those routes:
- inserts into an `InsertableRelation` such as a JDBC table
(`InsertIntoDataSourceCommand` -> `recacheByPlan`)
- `CreatableRelationProvider` saves (`SaveIntoDataSourceCommand`)
- writes to V2 relations without a catalog identifier
(`DataSourceV2Strategy.refreshCache`)
- inserts into Hive tables that are not converted to data source relations
(`InsertIntoHiveTable` -> `uncacheTableOrView(cascade = true)`)
- `REFRESH TABLE` / `Catalog.refreshTable` on V1 tables, Hive tables, and
views (`CommandUtils.recacheTableOrView` -> `recacheByPlan`)
For example, by the code, a cached `SELECT * FROM s WHERE id IN (SELECT id
FROM j)` keeps returning its pre-insert result with no error after `INSERT INTO
j` on a JDBC table, while the same query over a parquet or catalog V2 table is
now rebuilt. The PR description's statement that cached plans reading the
written table inside a subquery are rebuilt after a write holds only for the
two routes changed here.
**Recommended change:** Use the existsWithSubqueries helper for the
per-entry predicates in recacheByPlan and in uncacheByCondition's cascade
branch, so both also match the target inside subquery expressions. Widen the
helper's scaladoc so its stated reason covers any entry that reads the data
inside a subquery, with the time-travel case as one example. Add Dataset cache
invalidation tests in which a query reads a table only inside a subquery and is
invalidated through recacheByPlan and through a cascading uncache by name.
**Why this works:** Both predicates keep their per-node test (`sameResult`
against the normalized target, or `isMatchedPlan`), but now apply it through
the helper. The helper visits the main plan and then every subquery plan, so an
entry that reads the target only inside a subquery is selected exactly as one
that reads it in the main plan. The existing rebuild and removal paths then
handle it unchanged.
**Scope:** Extend the PR's subquery-aware matching to CacheManager's
remaining write, refresh, and DDL invalidation predicates, and cover them with
cache tests.
**Risks:** Cascading uncache now also removes cached entries that read the
object only inside a subquery. It is used by UNCACHE TABLE and
Catalog.uncacheTable on tables, DROP TABLE, ALTER TABLE and other table DDL,
view replacement and drop, Hive inserts, and the legacy V2 write invalidation.
Those entries then recompute on next use, as entries that read the object in
the main plan already do on the base branch. For UNCACHE TABLE and the
schema-only DDL this drops a cache whose data is still current, which matches
the documented cascade contract to uncache every entry that refers to the plan,
and reverting the predicate restores the base-branch selection. recacheByPlan,
and the cascading uncache, now walk subquery plans of every cached entry on
each call. The added cost per entry is one walk of its subquery plans, and
entries without subqueries pay nothing extra once the helper's subquery-free
guard is in place.
**Constraints:** The per-node predicates stay unchanged, so recacheByPlan's
sameResult comparison and the name-based matching of uncacheTableOrView keep
their base-branch rules for every node they now also see inside subqueries. The
helper's subquery-free guard applies to these new call sites as well, so
adopting the helper does not add a second plan walk for entries without
subqueries.
**Exclusions:**
- The non-cascade dependent recompile in uncacheByCondition keeps its
children-only predicate. A dependent that reads the removed entry only through
a subquery is not a stale result after a write, the gap existed before this PR,
and it can follow separately if consistent dependency matching is wanted there
too.
**Success:** After an invalidation through recacheByPlan, a cached entry
that reads the target relation only inside a subquery expression is cleared and
rebuilt, the same way an entry that reads it in the main plan already is. After
uncacheTableOrView or uncacheQuery with cascade = true, an entry that reads the
named object or plan only inside a subquery expression is removed from the
cache. Entries that read the target only in the main plan, and entries that do
not read it at all, are selected exactly as on the base branch.
**Verification:**
- **Regression:** Cache and materialize a query that reads a table only
inside an IN subquery, invalidate that table through the recacheByPlan route
(for example an insert into an InsertableRelation-backed table or REFRESH TABLE
on a V1 table), and assert that the entry is still cached with its buffers
cleared and that re-running the query reflects the new data.
- **Regression:** Cache a query that reads a table only inside a subquery,
uncache that table by name with cascade, and assert the dependent entry is no
longer cached.
- **Compatibility:** Existing cache tests where the invalidated relation
appears in the main plan, or not at all, keep their outcomes on recacheByPlan
and on cascading uncache.
##########
sql/core/src/test/scala/org/apache/spark/sql/V1TimeTravelCacheSuite.scala:
##########
@@ -305,6 +331,33 @@ class V1TimeTravelCacheSuite extends QueryTest with
SharedSparkSession {
}
}
+ /**
+ * Caches a query that reads the table at a pinned version and reads it live
only inside an IN
+ * subquery, then passes the materialized cache and both file indexes to `f`.
Review Comment:
**Nit (P3):** The callback also gets the table root path as its second
argument (`f(cached, rootPath, pinnedIndex, liveIndex)`), which the
`recacheByPath` test uses to build the file system; the comment leaves it out.
```suggestion
* subquery, then passes the materialized cache, the root path, and both
file indexes to `f`.
```
**Verification:**
- **Inspection:** The helper comment lists the cached Dataset, the root
path, the pinned index, and the live index, matching the callback's parameter
list.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -636,7 +644,9 @@ class CacheManager extends Logging with
AdaptiveSparkPlanHelper {
val qualifiedPath = fs.makeQualified(resourcePath)
recacheByCondition(
spark,
- _.plan.exists(lookupAndRefresh(_, fs, qualifiedPath, includeTimeTravel)))
+ entry => existsWithSubqueries(entry.plan) {
Review Comment:
**Non-blocking (P2):** `lookupAndRefresh` refreshes the file index it
matches, but `existsWithSubqueries` stops at the first match, so each entry
refreshes only the first live `FileIndex` under the path that the traversal
reaches. The rebuild does not reload V1 relations, so any other live index the
entry reads keeps its pre-write file listing, and separate path reads (for
example two `spark.read.parquet(p)` calls) create separate indexes.
For example, by the code: cache `SELECT * FROM other WHERE id IN (SELECT id
FROM a) AND id IN (SELECT id FROM b)` where `a` and `b` are separate reads of
`p`, then append to `p`. The walk matches `a` in the first subquery, refreshes
its index, and stops, so the entry is rebuilt while `b` still lists the old
files. The rebuilt cache silently misses the appended rows in the second
subquery, and after an overwrite, materializing it fails with
`FileNotFoundException`. `SELECT * FROM a WHERE id IN (SELECT id FROM b)`
behaves the same way, because the main-plan match ends the walk before the
subquery. Entries whose subquery reads go through a single index, like the case
the new test covers, are fixed.
**Recommended change:** Make recacheByPath's per-entry predicate visit every
node of the entry's main plan and of each subquery plan instead of stopping at
the first match, refresh each distinct live FileIndex under the path that the
entry reads exactly once, and match the entry when at least one was found. Keep
the time-travel skip as a per-node rule, and enter subquery plans only when the
entry contains a subquery expression. Add path-route cache tests with two
distinct live file indexes over one path, at least one inside a subquery, plus
an end-to-end append test over parquet files read through two separate path
reads.
**Why this works:** Separate the path test from the refresh. Walk the main
plan, and every subquery plan when the root carries PLAN_EXPRESSION, use the
existing per-node rules of lookupAndRefresh and refreshFileIndexIfNecessary to
collect each live FileIndex under the path, deduplicate them by reference
identity within the entry, refresh each one once, and return whether any was
found. Every live index the rebuilt entry scans then lists the current files,
and an index the entry reads several times is still re-listed only once.
**Scope:** Rework the path route's per-entry predicate so it refreshes every
distinct live file index the entry reads under the written path, and cover it
with path-route cache tests.
**Compatibility:** The set of entries the path route rebuilds does not
change: an entry is rebuilt exactly when at least one live FileIndex under the
path is found in its main plan or its subqueries.
**Risks:** An entry that reads the written path through several distinct
live indexes, including one with no subquery at all, now re-lists each index
instead of only the first. That extra listing is exactly what brings its
results back to current data, and reverting the predicate restores the
base-branch behavior. Explicit Catalog.refreshByPath keeps time-travel indexes
eligible (includeTimeTravel = true), so it now refreshes every matching pinned
index an entry reads, not only the first.
**Constraints:** The time-travel skip stays a per-node rule. With
includeTimeTravel = false, a time-travel FileIndex or a DSv2 relation with a
time-travel spec is never refreshed and never makes the entry match. Subquery
plans are entered only when the entry's root contains a subquery expression, so
entries without subqueries keep a single walk, consistent with the guard on the
shared subquery helper.
**Exclusions:**
- A file index shared by several cache entries is still refreshed once per
matching entry, as on the base branch.
**Success:** After write-driven or explicit recacheByPath, every distinct
live FileIndex under the path that a matched entry reads, in the main plan or
inside any subquery, has been refreshed exactly once, and the rebuilt entry
scans the current files. Under includeTimeTravel = false, an entry whose only
reads under the path are pinned still stays cached, and its pinned indexes are
not refreshed. An entry that reads one FileIndex instance several times
refreshes it once, as on the base branch.
**Verification:**
- **Regression:** Cache an entry that reads the path through two distinct
live test file indexes, one in the main plan and one only inside a subquery,
run write-driven recacheByPath, and assert that the entry is rebuilt and each
index was refreshed once. Repeat with the two live indexes in separate
subqueries and a pinned index in the main plan, and assert the pinned index is
not refreshed.
- **Regression:** Over real parquet files, cache a query that reads the same
path through two separate path reads, one of them inside an IN subquery. Append
rows through a V1 file write, and assert that the cached query's answer
reflects the appended rows on both sides of the subquery.
- **Compatibility:** Existing path-route tests keep their refresh counts
(one refresh for a single live index, none for pinned indexes), and an entry
that reads one shared index in both the main plan and a subquery refreshes it
exactly once.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]