linhongliu-db commented on code in PR #60412:
URL: https://github.com/apache/spark/pull/60412#discussion_r4590045758
##########
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:
Rebuilding under the entry's recorded context isn't feasible here:
`current_user()` comes from the thread-local `CurrentUserContext` of the
invalidating command. So 50353a1 takes your fallback: if the rebuilt plan's
session context differs from the entry's, the entry is dropped rather than
re-keyed (legacy conf keeps the old behavior). The migration note now says such
an entry is uncached instead of re-cached. Covered by a new `CachedTableSuite`
test.
##########
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:
Fixed in 50353a1. The caller's context is computed before
`this.synchronized` (in `cacheQueryInternal`, and in `tryRebuildCacheEntry` for
recache), and the in-lock lookups only compare precomputed maps. No catalog
call runs under the `CacheManager` lock anymore.
##########
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:
Fixed in 50353a1: it now fails closed. `CurrentPath` is covered, the clock
functions are skipped explicitly, and any other `CURRENT_LIKE` leaf gets a
unique value, so a plan that calls it never matches another lookup. A unit test
pins this with a stand-in 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:
Done in 50353a1: version `4.4.0`, and the note moved to `Upgrading from
Spark SQL 4.3 to 4.4` with `Since Spark 4.4`.
##########
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:
Removed the default in 50353a1.
##########
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:
Fixed in 50353a1. The by-name value function is gone: a lookup computes the
caller's context from its own plan and compares maps by equality (plans with
the same result read the same keys), so each key is defined once, in
`sessionContextOf`.
##########
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:
Done in 50353a1: the context is evaluated lazily, only when a plan matches,
and `useCachedData` memoizes the session values for the whole call, including
subqueries.
--
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]