cloud-fan commented on code in PR #59857:
URL: https://github.com/apache/spark/pull/59857#discussion_r4549317365


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -620,56 +634,59 @@ class CacheManager extends Logging with 
AdaptiveSparkPlanHelper {
     val qualifiedPath = fs.makeQualified(resourcePath)
     recacheByCondition(
       spark,
-      _.plan.exists(lookupAndRefresh(_, fs, qualifiedPath, includeTimeTravel)))
+      entry => lookupAndRefresh(entry.plan, fs, qualifiedPath, 
includeTimeTravel))
   }
 
   /**
-   * Traverses a given `plan` and searches for the occurrences of 
`qualifiedPath` in the
-   * [[org.apache.spark.sql.execution.datasources.FileIndex]] of any 
[[HadoopFsRelation]] nodes
-   * in the plan. If found, we refresh the metadata and return true. 
Otherwise, this method returns
-   * false.
+   * Searches `plan`, including its subqueries, for the
+   * [[org.apache.spark.sql.execution.datasources.FileIndex]] of file-backed 
relations under
+   * `qualifiedPath`, refreshes each distinct matching index once, and returns 
whether any was
+   * found. Every match is refreshed because the rebuilt cache entry reuses 
these indexes.
    */
   private def lookupAndRefresh(
       plan: LogicalPlan,
       fs: FileSystem,
       qualifiedPath: Path,
       includeTimeTravel: Boolean): Boolean = {
-    plan match {
-      case lr: LogicalRelation => lr.relation match {
-        case hr: HadoopFsRelation =>
-          refreshFileIndexIfNecessary(hr.location, fs, qualifiedPath, 
includeTimeTravel)
-        case _ => false
-      }
+    def fileIndexToRefresh(node: LogicalPlan): Option[FileIndex] = {
+      val fileIndex: Option[FileIndex] = node match {
+        case lr: LogicalRelation => lr.relation match {
+          case hr: HadoopFsRelation => Some(hr.location)
+          case _ => None
+        }
 
-      case relation @ ExtractV2Table(fileTable: FileTable)
-          if includeTimeTravel || relation.timeTravelSpec.isEmpty =>
-        refreshFileIndexIfNecessary(
-          fileTable.fileIndex,
-          fs,
-          qualifiedPath,
-          includeTimeTravel)
+        case relation @ ExtractV2Table(fileTable: FileTable)
+            if includeTimeTravel || relation.timeTravelSpec.isEmpty =>
+          Some(fileTable.fileIndex)
 
-      case _ => false
+        case _ => None
+      }
+      fileIndex.filter(needToRefresh(_, fs, qualifiedPath, includeTimeTravel))
     }
+
+    // Deduplicate by reference: InMemoryFileIndex equality compares root 
paths only.
+    val fileIndexes = (plan +: 
subqueryPlans(plan)).flatMap(_.flatMap(fileIndexToRefresh))

Review Comment:
   **Non-blocking (P2):** Deduplication here is scoped to one cache entry, but 
`recacheByPath` evaluates this method once for each cached entry inside 
`recacheByCondition`'s filter. When several matched entries hold the same 
`FileIndex` instance, one write re-lists it once per entry. A catalog table's 
relation comes from the session relation cache, and a temp view over one 
`spark.read` call shares its relation, so cached queries in one session readily 
share an index. `InMemoryFileIndex.refresh()` clears its file status cache and 
lists every file under its root paths, so each repeat is a full listing.
   
   The earlier review kept per-entry deduplication on the grounds that the base 
branch already repeats the listing. That is true only for an index that is each 
entry's first main-plan match. The reworked walk repeats the listing for every 
index it newly reaches as well. For example, by the code: x and y are two 
separate reads of path p, and the cached queries are A = `SELECT * FROM x WHERE 
id IN (SELECT id FROM y)` and B = `SELECT * FROM y`. After an append to p, the 
base branch lists x and y once each, and both rebuilt entries are correct. This 
change lists x once and y twice, for the same result. For J cached queries that 
read one table only inside subqueries, each write to that table lists it J 
times where once is enough. Results stay correct. The cost is J-1 extra full 
listings per write, and it grows with the table's file count. Every predicate 
call finishes before any matched entry is removed or rebuilt, so refreshing 
each index once per call already gives every rebuilt entry t
 he current files.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59857#discussion_r4508843528).
   
   **Recommended change:** Keep one reference-identity set of FileIndex 
instances already refreshed during a recacheByPath call and pass it to 
lookupAndRefresh. Each entry still collects the eligible indexes in its main 
plan and subqueries, refreshes only those not yet in the set, and adds them. It 
still selects itself whenever it found any eligible index, including one an 
earlier entry already refreshed. Add a path-route cache test in which two 
cached entries share one index.
   
   **Why this works:** All lookupAndRefresh calls of one recacheByPath run 
inside cachedData.filter, before any matched entry is removed or rebuilt. So an 
index refreshed for an earlier entry already lists the current files when every 
later entry is rebuilt. Scoping the deduplication to the call therefore 
refreshes each distinct eligible index once per call, without changing which 
entries are selected or what their rebuilt plans read.
   
   **Scope:** Deduplicate FileIndex refreshes across a whole refresh by path 
instead of per cache entry, and cover indexes shared by several cached entries.
   
   **Compatibility:** Which entries a refresh by path selects and rebuilds, and 
the per-node time-travel skip, stay exactly as this PR implements them.
   
   **Risks:** Writes also list fewer times when several entries share an index 
that is each one's first main-plan match, which the base branch already 
re-listed once per entry. Results are unchanged, and dropping the call-scoped 
set restores the current listing count. A FileIndex implementation outside 
Spark now receives one refresh call per instance per refresh by path instead of 
one per sharing entry. A refresh is an idempotent re-listing, so only the 
number of calls changes.
   
   **Constraints:** The set compares instances by reference, never by equals, 
because InMemoryFileIndex equality compares only root paths. The set lives for 
one recacheByPath call and is never stored on CacheManager or shared across 
calls, so concurrent writes each refresh what they need. An entry whose only 
eligible index was refreshed earlier in the same call is still selected and 
rebuilt. The per-node eligibility rules, including the time-travel skip, stay 
unchanged.
   
   **Exclusions:**
   - The write command's own refresh of its target index before it calls the 
cache refresh by path stays as is, because it happens outside the call this 
repair scopes.
   
   **Success:** Within one refresh by path, each distinct eligible FileIndex 
instance that any matched entry reads is refreshed exactly once. The set of 
entries a refresh by path selects and rebuilds is unchanged, and every rebuilt 
entry scans current files. Indexes pinned to a time-travel version are still 
not refreshed by write-driven invalidation.
   
   **Verification:**
   - **Regression:** Cache two entries over refresh-counting file indexes under 
one path: one reads index X in its main plan and index Y inside a subquery, and 
the other reads Y in its main plan. After a write-driven refresh by path, both 
entries are rebuilt, X is refreshed once, and Y is refreshed once in total.
   - **Behavior:** Two cached queries that read the same live index only inside 
subqueries are both rebuilt by a write-driven refresh by path, and that index 
is refreshed once.
   - **Compatibility:** Existing single-entry path-route cases keep their 
refresh counts: one for a single live index, none for pinned indexes, and one 
for an index read in both the main plan and a subquery. A cached query that 
reads a Parquet path through two separate reads, one inside a subquery, still 
returns current rows after an append and an overwrite.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -369,11 +369,25 @@ 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,
+   * so that an entry reading the target only inside a subquery is selected 
like one reading it in
+   * the main plan. For example, 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 =
+    plan.exists(f) || subqueryPlans(plan).exists(_.exists(f))
+
+  /** All subquery plans of `plan`, including nested ones, or none if it has 
no subquery. */
+  private def subqueryPlans(plan: LogicalPlan): Seq[LogicalPlan] =
+    if (plan.containsPattern(PLAN_EXPRESSION)) plan.subqueriesAll else Nil

Review Comment:
   **Nit (P3):** Every subquery-aware route reaches subqueries nested inside 
other subqueries only through `subqueriesAll` here, but every new test query 
uses a single subquery level. If this line became `plan.flatMap(_.subqueries)`, 
which still finds every one-level subquery in the main plan, all the new tests 
would still pass. Yet by the code, a cached `SELECT id FROM range(5) WHERE id 
IN (SELECT id FROM s WHERE id IN (SELECT id FROM t))` would then stay stale 
after `REFRESH TABLE t` or a write to `t`, and would survive a cascading 
uncache of `t`. The recursion is correct today. It just has no failure signal. 
One nested-subquery query through `assertWriteDrivenRecacheByPathClearsCache`, 
plus a nested variant of the new `REFRESH TABLE` or cascading-uncache test in 
`CachedTableSuite`, would cover it.
   
   **Verification:**
   - **Regression:** If subquery collection is limited to one nesting level, 
the nested cases fail: the nested reader stays cached with its buffers loaded, 
or its nested index is not refreshed.
   - **Behavior:** With recursive subquery collection, the nested reader's 
buffers are cleared or the entry is removed, and re-running the query returns 
the current data.



-- 
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]

Reply via email to