dongjoon-hyun commented on code in PR #60412:
URL: https://github.com/apache/spark/pull/60412#discussion_r4560160649


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -412,7 +417,8 @@ class CacheManager extends Logging with 
AdaptiveSparkPlanHelper {
             refreshPhaseEnabled = false)
           val newKey = qe.normalized
           val newCache = 
InMemoryRelation(cd.cachedRepresentation.cacheBuilder, qe)
-          Some(cd.copy(plan = newKey, cachedRepresentation = newCache))
+          Some(cd.copy(plan = newKey, cachedRepresentation = newCache,
+            sessionContext = 
CacheManager.sessionContextOf(sessionWithConfigsOff, newKey)))

Review Comment:
   This is related to the P3 note at line 397, but it is a separate problem. A 
recache moves the entry to the writer's context, so the session that ran `CACHE 
TABLE` can lose its own entry.
   
   `tryRebuildCacheEntry(spark, cd)` plans the entry in a clone of the session 
that ran the invalidating command, and these lines key the entry with that 
clone's context. For example, on the Thrift server:
   
   1. User A runs `CACHE TABLE mine AS SELECT * FROM t WHERE owner = 
current_user()`.
   2. User B runs `INSERT INTO t ...`.
   3. The entry is rebuilt and keyed as `user=B`.
   
   After that, every query of A that reads `mine` misses and recomputes, and 
`isCached` returns false in A's session. Only B, who never cached anything, 
matches the entry, and the entry still uses the memory. The same thing happens 
with `current_timezone()` when the two sessions use different time zones.
   
   Correctness is preserved, but the entry no longer serves the session that 
created it. After a recache, the migration guide's statement that the entry is 
reused only under "the ones in effect when it was cached" is also no longer 
accurate. Could the rebuild use the entry's recorded context? If that is not 
feasible, could it drop the entry instead of silently moving it to the writer?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -165,11 +169,12 @@ class CacheManager extends Logging with 
AdaptiveSparkPlanHelper {
       }
 
       this.synchronized {
-        if (lookupCachedDataInternal(normalizedPlan).nonEmpty) {
+        if (lookupCachedDataInternal(normalizedPlan, session = 
Some(spark)).nonEmpty) {
           logWarning("Data has already been cached.")
         } else {
           // the cache key is the normalized plan
-          val cd = CachedData(normalizedPlan, inMemoryRelation)
+          val cd = CachedData(normalizedPlan, inMemoryRelation,
+            CacheManager.sessionContextOf(spark, normalizedPlan))

Review Comment:
   `sessionContextOf` here, and `isSameSessionContext` in the lookups at lines 
172 and 397, now run inside `this.synchronized`, which is the global 
`CacheManager` lock. Both read live catalog state:
   
   - `currentCatalog` takes the `CatalogManager` lock and may load and 
initialize a catalog plugin.
   - `currentNamespace` calls `defaultNamespace()` on a v2 catalog.
   - `getCurrentDatabase` takes the `SessionCatalog` lock.
   
   As a result, connector code runs while the `CacheManager` lock is held, and 
a slow catalog call blocks cache, uncache, and recache in every other session. 
This also adds a new lock order, `CacheManager` -> 
`CatalogManager`/`SessionCatalog`. SPARK-56939 recently fixed a lock-order 
inversion in this area.
   
   Could we compute the entry's context and the caller's values before entering 
`this.synchronized`, and compare only the precomputed maps inside it?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -714,4 +737,35 @@ object CacheManager extends Logging {
   def logCacheOperation(f: => MessageWithContext): Unit = {
     logBasedOnLevel(SQLConf.get.dataframeCacheLogLevel)(f)
   }
+
+  /**
+   * Returns the session values read by the session-context functions in 
`plan` (including its
+   * subqueries), keyed by what they read. The optimizer binds these functions 
only after the
+   * cache lookup. Clock functions read no session value; their time zone is 
part of the plan.
+   */
+  private[execution] def sessionContextOf(
+      spark: SparkSession, plan: LogicalPlan): Map[String, String] = {
+    if (plan.containsPattern(CURRENT_LIKE)) {
+      val keys = scala.collection.mutable.Set[String]()
+      plan.foreachWithSubqueries(_.expressions.foreach(_.foreach {
+        case CurrentTimeZone() => keys += "timeZone"
+        case CurrentCatalog() => keys += "catalog"
+        case CurrentDatabase() => keys += "namespace"
+        case CurrentUser() => keys += "user"
+        case _ =>

Review Comment:
   The missing `CurrentPath` is already noted on this line. Separately, this 
allowlist with a `case _ =>` catch-all fails open for any unlisted 
`CURRENT_LIKE` leaf. A plan that calls only such a function records an empty 
context, so it is reused under every session context. That is exactly the bug 
this PR fixes. `CurrentPath` already ended up this way, and any future 
session-context function will too unless someone remembers to update this match.
   
   Could this fail closed instead? Two options:
   
   - Treat every `CURRENT_LIKE` leaf as context-dependent, except the clock 
functions that are known not to be, so an unknown leaf is never reused across 
contexts.
   - Derive the bound values with the same code the optimizer uses 
(`ReplaceCurrentLike` / `ComputeCurrentTime`), so the key set cannot drift from 
those rules.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -57,7 +58,10 @@ import org.apache.spark.storage.StorageLevel.MEMORY_AND_DISK
 case class CachedData(
     // A normalized resolved plan (See QueryExecution#normalized).
     plan: LogicalPlan,
-    cachedRepresentation: InMemoryRelation) {
+    cachedRepresentation: InMemoryRelation,
+    // Session values read by the session-context functions in `plan`, which 
the plan leaves
+    // unbound until after the cache lookup. See 
`CacheManager.sessionContextOf`.
+    sessionContext: Map[String, String] = Map.empty) {

Review Comment:
   The `Map.empty` default fails open. A `CachedData(plan, relation)` 
construction that forgets the context still compiles, and the resulting entry 
matches every session context. Line 176 is the only construction site, so 
removing the default costs nothing now and lets the compiler catch a missed 
call site later.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -522,6 +533,18 @@ class CacheManager extends Logging with 
AdaptiveSparkPlanHelper {
     result
   }
 
+  // Plan matching ignores the session context that the session-context 
functions in a matching
+  // plan read, so an entry cached under a different context must not be 
reused -- unless the
+  // legacy gate restores the previous context-insensitive matching.
+  private def isSameSessionContext(cd: CachedData, session: 
Option[SparkSession]): Boolean = {
+    cd.sessionContext.forall { case (key, value) =>
+      session.exists(CacheManager.sessionContextValue(_, key) == value)

Review Comment:
   Nit: `sessionContextValue` is re-evaluated for every `sameResult`-matching 
entry on every lookup, and `useCachedData` runs a lookup for each plan fragment 
and subquery. A single value can call UGI (`Utils.getCurrentUserName`) or take 
the `CatalogManager` lock. With this PR, the same plan can also have one entry 
per context, so one lookup may evaluate the same values several times. The 
caller's values do not change during a `useCachedData` call, so computing them 
lazily once per call would be enough.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -714,4 +737,35 @@ object CacheManager extends Logging {
   def logCacheOperation(f: => MessageWithContext): Unit = {
     logBasedOnLevel(SQLConf.get.dataframeCacheLogLevel)(f)
   }
+
+  /**
+   * Returns the session values read by the session-context functions in 
`plan` (including its
+   * subqueries), keyed by what they read. The optimizer binds these functions 
only after the
+   * cache lookup. Clock functions read no session value; their time zone is 
part of the plan.
+   */
+  private[execution] def sessionContextOf(
+      spark: SparkSession, plan: LogicalPlan): Map[String, String] = {
+    if (plan.containsPattern(CURRENT_LIKE)) {
+      val keys = scala.collection.mutable.Set[String]()
+      plan.foreachWithSubqueries(_.expressions.foreach(_.foreach {
+        case CurrentTimeZone() => keys += "timeZone"
+        case CurrentCatalog() => keys += "catalog"
+        case CurrentDatabase() => keys += "namespace"
+        case CurrentUser() => keys += "user"
+        case _ =>
+      }))
+      keys.map(key => key -> sessionContextValue(spark, key)).toMap
+    } else {
+      Map.empty
+    }
+  }
+
+  // The value each session-context function returns (see the optimizer's 
ReplaceCurrentLike).
+  private[execution] def sessionContextValue(spark: SparkSession, key: 
String): String =
+    key match {
+      case "timeZone" => spark.sessionState.conf.sessionLocalTimeZone
+      case "catalog" => spark.sessionState.catalogManager.currentCatalog.name()
+      case "namespace" => 
spark.sessionState.catalogManager.currentNamespace.quoted
+      case "user" => CurrentUserContext.getCurrentUser
+    }

Review Comment:
   The four keys are string literals defined in two places, `sessionContextOf` 
and here, and this `match` is not exhaustive. If a key is added on one side 
only, or a key is mistyped, the code still compiles. Then either query planning 
throws `scala.MatchError` in the cache lookup, or the key silently never 
matches. Defining each key once would keep the two sides in sync, for example 
with a small sealed type or a single `Map[String, SparkSession => String]` from 
key to value function.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2654,6 +2654,19 @@ object SQLConf {
       .booleanConf
       .createWithDefault(Utils.isTesting)
 
+  val CACHE_IGNORE_SESSION_CONTEXT_IN_PLAN_MATCHING =
+    buildConf("spark.sql.legacy.cache.ignoreSessionContextInPlanMatching")
+      .internal()
+      .doc("When false, a cached query that calls a session-context function " 
+
+        "(current_timezone(), current_catalog(), 
current_schema()/current_database(), " +
+        "current_user()) is reused only under the session context values it 
read when cached. " +
+        "When true, it is reused under any session context, returning the 
caching session's " +
+        "values; rollback only.")
+      .version("5.0.0")

Review Comment:
   This is a correctness fix with a legacy flag, not a breaking change, so I 
expect it to be backported to `branch-4.x` as well. In that case, the version 
should be `4.4.0` (`dev/next_version_candidates.py` currently prints 
`branch-4.x 4.4.0`). The migration guide entry should also move to `Upgrading 
from Spark SQL 4.3 to 4.4` and say `Since Spark 4.4`. If this change is meant 
to be master-only, `5.0.0` is correct.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -507,13 +514,17 @@ class CacheManager extends Logging with 
AdaptiveSparkPlanHelper {
    */
   def lookupCachedData(session: SparkSession, plan: LogicalPlan): 
Option[CachedData] = {
     val normalized = QueryExecution.normalize(session, plan)
-    lookupCachedDataInternal(normalized)
+    lookupCachedDataInternal(normalized, session = Some(session))
   }
 
   private def lookupCachedDataInternal(
       plan: LogicalPlan,
-      canUse: CachedData => Boolean = _ => true): Option[CachedData] = {
-    val result = cachedData.find(cd => plan.sameResult(cd.plan) && canUse(cd))
+      canUse: CachedData => Boolean = _ => true,
+      // The session whose context a matching entry must share; the active one 
by default.
+      session: Option[SparkSession] = SparkSession.getActiveSession): 
Option[CachedData] = {

Review Comment:
   Every call site of `lookupCachedDataInternal` now passes the session 
explicitly except `useCachedData`, which relies on this 
`SparkSession.getActiveSession` default. That works today because 
`QueryExecution.lazyWithCachedData` runs inside `sparkSession.withActive`. 
However, the session that decides cache reuse is now hidden in thread-local 
state. A future caller outside `withActive`, or on a thread where another 
session is active, would compare against the wrong context. With no active 
session at all, every entry that has a context would miss. Could 
`useCachedData` take the session as a parameter, e.g. `useCachedData(plan, 
session, canUse)`, as the other lookups do?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -57,7 +58,10 @@ import org.apache.spark.storage.StorageLevel.MEMORY_AND_DISK
 case class CachedData(
     // A normalized resolved plan (See QueryExecution#normalized).
     plan: LogicalPlan,
-    cachedRepresentation: InMemoryRelation) {
+    cachedRepresentation: InMemoryRelation,
+    // Session values read by the session-context functions in `plan`, which 
the plan leaves
+    // unbound until after the cache lookup. See 
`CacheManager.sessionContextOf`.
+    sessionContext: Map[String, String] = Map.empty) {
   override def toString: String =

Review Comment:
   `toString` does not include `sessionContext`, so the "Added", "Re-cached", 
and "cache hit" logs controlled by `spark.sql.dataframeCache.logLevel` do not 
show an entry's context. The miss log in `useCachedData` prints only the plans 
of the last 20 entries. It does not distinguish "no plan matched" from "a plan 
matched, but the context differed". This PR introduces the second kind of miss, 
so including the context here would help debugging, and ideally the miss log 
would show the mismatched keys too.



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