spark-test commented on code in PR #60412:
URL: https://github.com/apache/spark/pull/60412#discussion_r4558068989
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -498,7 +504,8 @@ class CacheManager extends Logging with
AdaptiveSparkPlanHelper {
* Optionally returns cached data for the given [[Dataset]]
*/
def lookupCachedData(query: Dataset[_]): Option[CachedData] = {
- lookupCachedDataInternal(query.queryExecution.normalized)
+ lookupCachedDataInternal(query.queryExecution.normalized,
Review Comment:
**Blocking (P1):** Both public `lookupCachedData` overloads now pass the
caller's session, so the reuse check also gates callers that only ask whether a
plan is cached. Reading the code: after `SET TIME ZONE 'UTC'; CREATE VIEW v AS
SELECT id, current_timezone() AS tz FROM range(3); CACHE TABLE v; SET TIME ZONE
'Asia/Tokyo'`, `ANALYZE TABLE v COMPUTE STATISTICS` reaches
`analyzeTableNotSupportedOnViewsError` in `CommandUtils.analyzeTable` (it
succeeded before this PR), `spark.catalog.isCached("v")` returns false and
`spark.table("v").storageLevel` returns `NONE`, although `UNCACHE TABLE v`
still removes the entry. The same applies to `ANALYZE TABLE ... FOR COLUMNS` on
a cached temp view and to the cache carry-over in `AlterTableRenameCommand` and
`RenameV2ViewExec`; the v1 rename then leaves the old entry registered under
the old name. Code that checks `isCached` or `storageLevel` before
`uncacheTable` or `unpersist` will leave the entry's storage held. Whether an
entry exists does
not depend on the asking session's values, and neither the PR description nor
the migration note mentions this change; only query reuse needs the context
check.
**Recommended change:** Make the public lookupCachedData(Dataset) and
lookupCachedData(session, plan) answer whether the plan is cached at all:
return the entry whose recorded context matches the asking session when there
is one, and otherwise any entry whose plan matches, as on the base branch. Keep
the reuse check alone in the paths that call lookupCachedDataInternal directly:
query substitution in useCachedData and the duplicate checks in
cacheQueryInternal and recacheByCondition. In CommandUtils.analyzeTable,
materialize the cached relation of the entry the lookup returned instead of
table.count(), which reaches an entry only through query substitution. Add
cache-management tests for each identity caller under a changed session context.
**Why this works:** Identity callers ask whether an entry exists for the
plan, which does not depend on the asking session's values, so falling back to
any plan-matching entry restores their documented meaning. Preferring the
asking session's own entry keeps Dataset.storageLevel, ANALYZE TABLE and the
rename carry-over on the entry that session's queries use when several contexts
cached the same plan. Reuse decisions keep the context check because they still
go through the internal lookup. Counting the found entry's own cached relation
lets ANALYZE TABLE materialize and measure that entry even when the analyzing
session could not reuse it for a query.
**Scope:** CacheManager's public lookups find any entry for the plan again,
preferring the asking session's own, reuse keeps the context check, and ANALYZE
TABLE on a cached view measures the entry it found.
**Compatibility:** Query substitution never reuses an entry whose recorded
context differs from the reading session's, unless the legacy conf is set.
**Risks:** Code that relied on the public lookup becoming context-sensitive
would change back; no caller in the repository does, and the base branch
matched by plan only. ANALYZE TABLE on a view cached under another context now
materializes that entry, holding its storage as on the base branch.
**Constraints:** The duplicate checks in cacheQueryInternal and
recacheByCondition must keep distinguishing entries by session context, or
per-context entries could not be created.
**Exclusions:**
- A renamed view is still re-cached under the renaming session's context, as
on the base branch.
**Success:** Catalog.isCached, Dataset.storageLevel, ANALYZE TABLE on cached
views and temp views, and the rename cache carry-over find an entry for the
plan whatever the asking session's time zone, catalog, namespace or user, as on
the base branch. ANALYZE TABLE ... COMPUTE STATISTICS on a cached view
materializes the entry it found even when query substitution would not reuse
that entry in the analyzing session. Query substitution and the duplicate
checks still apply the session-context check. When several contexts cached the
same plan and the asking session has its own entry among them,
Dataset.storageLevel reports that entry's storage level and ANALYZE TABLE
analyzes that entry.
**Verification:**
- **Regression:** A view whose plan calls current_timezone(), cached under
one session time zone, is reported cached by Catalog.isCached and by
Dataset.storageLevel under another time zone, and ANALYZE TABLE ... COMPUTE
STATISTICS on it succeeds and materializes that entry.
- **Regression:** ANALYZE TABLE ... COMPUTE STATISTICS FOR COLUMNS on a temp
view created by CACHE TABLE ... AS SELECT with current_timezone() succeeds
under a different session time zone.
- **Regression:** Renaming such a cached view from a session in another time
zone removes the old name's entry and leaves the new name cached, for the v1
rename and for a v2 view catalog.
- **Behavior:** After those calls, a query over the view in the other time
zone still returns that session's time zone rather than the cached value.
- **Behavior:** With the same view cached at different storage levels under
two session time zones, Dataset.storageLevel in each time zone reports that
zone's own entry's level, and ANALYZE TABLE ... COMPUTE STATISTICS in each time
zone materializes that zone's own entry.
##########
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:
**Non-blocking (P2):** `CurrentPath` falls through this catch-all, but
`ReplaceCurrentLike` binds it after the cache lookup to
`catalogManager.currentPathString`, which depends on `SET PATH`, the path confs
and the current catalog and namespace. Reading the code: `USE db1; CACHE TABLE
p AS SELECT current_path() AS path FROM range(1); USE db2; SELECT
current_path() AS path FROM range(1)` records an empty context, so the second
query is served the path naming `spark_catalog.db1`, while the same queries
with `current_database()` are recomputed. A plan that also calls a keyed
function is still reused when only the path differs. Suggest recording a path
key valued with `catalogManager.currentPathString`, as `ReplaceCurrentLike`
binds it, and listing `current_path()` in the legacy conf's doc.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/CachedTableSuite.scala:
##########
@@ -2882,6 +2882,29 @@ class CachedTableSuite extends SharedSparkSession
}
}
+ test("SPARK-61570: cached query with a session-context function is not
reused " +
+ "under a different session context") {
+ Seq(false, true).foreach { ignoreContext =>
+ withSQLConf(
+ SQLConf.CACHE_IGNORE_SESSION_CONTEXT_IN_PLAN_MATCHING.key ->
ignoreContext.toString) {
+ withTempView("tz_cache") {
+ val query = "SELECT id, current_timezone() AS tz FROM range(3)"
Review Comment:
**Non-blocking (P2):** This query exercises only the `timeZone` arms of
`sessionContextOf` and `sessionContextValue`. Each of these changes would still
pass `CachedTableSuite`: dropping the `CurrentDatabase` arm (an entry for
`SELECT current_database()` cached in `db1` is then reused after `USE db2`),
checking only one recorded key, using `foreach` instead of
`foreachWithSubqueries` (so `SELECT id, (SELECT current_timezone()) AS tz FROM
range(3)` records nothing), reverting the re-keying in `tryRebuildCacheEntry`,
or making the duplicate checks context-free. Suggest adding cases for
`current_database()` across `USE`, `current_catalog()` after `USE` of another
catalog, `current_user()` across two users, a two-key query where only one
value changes, a read that appears only in a subquery, an entry rebuilt by a
write from another time zone, and a second `CACHE` under another time zone that
adds its own entry.
**Verification:**
- **Behavior:** For current_database(), current_catalog() and
current_user(), an entry cached under one value is recomputed under another and
reused under the original.
- **Behavior:** A cached query reading two session values is recomputed when
only one of them changes.
- **Behavior:** A time-zone read that appears only inside a scalar subquery
prevents reuse under another session time zone.
- **Regression:** After a write from a session in another time zone rebuilds
the entry, a read in the original time zone returns its own time zone.
- **Behavior:** Caching the same query under a second time zone adds an
entry that the second time zone then reuses.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala:
##########
@@ -389,7 +394,7 @@ class CacheManager extends Logging with
AdaptiveSparkPlanHelper {
cd.cachedRepresentation.cacheBuilder.clearCache()
tryRebuildCacheEntry(spark, cd).foreach { entry =>
this.synchronized {
- if (lookupCachedDataInternal(entry.plan).nonEmpty) {
+ if (lookupCachedDataInternal(entry.plan, session =
Some(spark)).nonEmpty) {
Review Comment:
**Nit (P3):** When K contexts cached the same plan (for example K
Thrift-server users who each run `CACHE TABLE mine AS SELECT * FROM t WHERE
owner = current_user()`), `recacheByCondition` rebuilds all K in the writing
session, and every rebuild refreshes the tables and plans through
`executedPlan`. They all come out with the same plan and the writer's context,
so this check throws away K-1 of them after planning, inside the write command.
Before this PR K was always 1. Suggest rebuilding only one entry per distinct
plan (the first in cache order, whose storage level and name the survivor
already takes) while still clearing every invalidated entry's buffers.
**Verification:**
- **Regression:** With the same query cached under two session time zones, a
write to its source table leaves one entry for the plan, keyed to the writing
session's context, and the plan is rebuilt once rather than once per cached
copy.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2654,6 +2654,18 @@ object SQLConf {
.booleanConf
.createWithDefault(Utils.isTesting)
+ val CACHE_IGNORE_SESSION_CONTEXT_IN_PLAN_MATCHING =
Review Comment:
**Nit (P3):** This splits the data-source entries, while SQLConf keeps the
Dataset cache settings together about 280 lines below
(`CAN_CHANGE_CACHED_PLAN_OUTPUT_PARTITIONING`, `DEFAULT_CACHE_STORAGE_LEVEL`,
`DATAFRAME_CACHE_LOG_LEVEL`, `DATAFRAME_CACHE_PLAN_ID_NAME_ENABLED`). Suggest
moving it next to those, keeping its key and default.
**Verification:**
- **Inspection:** The entry is among SQLConf's Dataset cache settings and
keeps its key and default value.
##########
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:
**Blocking (P1):** The data is planned in `sessionWithConfigsOff` (lines
161-169), but the context recorded here is read from `spark`, the caller. With
default confs that session is a `cloneSession()`, and a cloned session's
`CatalogManager` is new and copies only the SQL path
(`BaseSessionStateBuilder.catalogManager`), so after `USE testcat` the clone
binds `current_catalog()` to `spark_catalog` while this line records
`catalog=testcat`. Reading the code for `USE testcat; CACHE TABLE t AS SELECT
current_catalog() AS c, id FROM testcat.ns.src`: the caching session still gets
`spark_catalog` from `SELECT c FROM t`, while a session in `spark_catalog` (or
a streaming query, whose micro-batches plan in a clone) now misses an entry
that held its own correct value and recomputes the query every time.
`tryRebuildCacheEntry` records the clone's values instead (420-421) while the
duplicate checks at 158, 172 and 397 compare the caller's live values, so each
cache-then-write cycle from the
caching session adds another identical entry. In the session catalog the clone
copies the current database and the conf, so the mismatch needs a v2 or
non-default current catalog, apart from a `SET TIME ZONE` or `USE` that another
thread runs on the same session between planning and this read.
**Recommended change:** In cacheQueryInternal, compute the entry's context
from sessionWithConfigsOff, the session whose optimizer binds the cached data,
as tryRebuildCacheEntry already does, and record that. Make the duplicate
checks compare like with like: an existing entry is a duplicate when its plan
matches and its recorded context equals the context the new entry would record,
both in cacheQueryInternal (obtain the configs-off session before the first
check when the plan contains a session-context function) and for rebuilt
entries in recacheByCondition. Add cache tests with a v2 test catalog.
**Why this works:** The configs-off session's conf is a snapshot taken when
it is cloned, and its CatalogManager is the one its ReplaceCurrentLike binds
from, so recording from it makes each entry's context exactly the values its
data holds, for a USE'd v2 catalog, for a SET or USE run on the caller after
cloning, and on the rebuild path alike. Comparing recorded contexts in the
duplicate checks then finds an identical entry whichever session asks, so
cache-and-write cycles converge to one entry per plan and context.
**Scope:** Entries record the context of the session that binds their data,
and duplicates are detected by plan and recorded context.
**Compatibility:** Plans without session-context functions, and entries
whose recorded context matches the reader, are reused exactly as on the base
branch; with the legacy conf set, reuse and the duplicate checks match by plan
only, as on the base branch.
**Risks:** After USE of a v2 or non-default catalog, the caching session's
own queries over such an entry recompute instead of reading the cache, because
the cache holds the values a fresh session computes; that is the cost of
correct results for that session. When the plan calls a session-context
function, cacheQueryInternal creates the configs-off session before its first
duplicate check, so a redundant cache() call pays for a session clone it
previously skipped.
**Constraints:** The recorded context and the duplicate checks must use the
same key derivation as query substitution, including the keys for
current_path() and current_time(). When getOrCloneSessionWithConfigsOff returns
the caller itself, the record must still come from that same session object the
plan was optimized in. With
spark.sql.legacy.cache.ignoreSessionContextInPlanMatching set, the duplicate
checks stay plan-only, so caching the same plan from a second context adds no
entry, as on the base branch.
**Exclusions:**
- Making cloned sessions inherit the current catalog and namespace, which
would change what cached entries hold for default-catalog sessions.
**Success:** Every entry's recorded context equals the session values its
cached data was bound with, for entries created by CACHE TABLE,
Dataset.cache()/persist() and Catalog.cacheTable and for rebuilt entries. After
USE of a v2 catalog, a cached plan calling current_catalog() or
current_database() is never served to a session whose values differ from the
cached data, and sessions whose values equal it, including default sessions and
streaming micro-batches, still reuse it. Repeated cache() calls and writes from
any session leave at most one entry per plan and recorded context.
**Verification:**
- **Regression:** With a v2 test catalog in use, a cached query calling
current_catalog() and current_database() returns that session's own catalog and
namespace when read there, and is served from the cache with the default values
to a default-catalog session.
- **Regression:** Alternating cache() of that query with writes to its
source table from the caching session keeps exactly one entry for the plan.
- **Behavior:** A query calling current_timezone() or current_user() cached
in the session catalog is reused and rejected exactly as before.
- **Compatibility:** With the legacy conf set, caching a query that calls
current_timezone() again from a session in another time zone adds no second
entry, and both time zones read the first entry, as on the base branch.
##########
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.
Review Comment:
**Non-blocking (P2):** This premise does not hold for `current_time()`:
`ComputeCurrentTime` builds its value from
`TimeSnapshot.currentTimeOfDayNanos`, which uses `conf.sessionLocalTimeZone`,
the same value it binds `current_timezone()` to, and ignores
`CurrentTime.timeZoneId`. A view analyzes its body under the captured
`spark.sql.session.timeZone`, so its `CurrentTime` keeps the creation zone in
every session and the plan keeps matching. Reading the code: `SET TIME ZONE
'UTC'; CREATE TEMP VIEW v AS SELECT current_time() AS t; CACHE TABLE v; SET
TIME ZONE 'Asia/Tokyo'; SELECT t FROM v` is served the UTC time of day from the
cache, while the uncached view returns the Tokyo time of day; the same view
selecting `current_timezone()` is recomputed. Suggest recording the `timeZone`
key for `CurrentTime` as for `CurrentTimeZone` and correcting this comment.
See **Shared repair plan 1** in the review body.
##########
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).
Review Comment:
**Nit (P3):** `ReplaceCurrentLike` binds `CurrentDatabase`,
`CurrentCatalog`, `CurrentPath` and `CurrentUser`; `CurrentTimeZone`, behind
the `timeZone` key, is bound by `ComputeCurrentTime`. Suggest naming both
rules, for example "see the optimizer's ComputeCurrentTime and
ReplaceCurrentLike".
See **Shared repair plan 1** in the review body.
--
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]