Repository navigation
Conversation
d763e01 to
907e2e2
Compare
|
We're closing this PR because it hasn't been updated in a while. This isn't a judgement on the merit of the PR in any way. It's just a way of keeping the PR queue manageable. |
|
I've got some time to work on this again, lets see :) |
26839a7 to
92ae9af
Compare
|
CC @JoshRosen what are your thoughts / do you have some cycles to review? |
|
CC @ivoson any thoughts? |
There was a problem hiding this comment.
Pull Request Overview
This pull request implements a Time-To-Live (TTL) mechanism for blocks in Spark, allowing automatic cleanup of RDD and shuffle blocks after a configurable time period. This addresses the issue where blocks persist indefinitely when DataFrames or RDDs are held at global scope and garbage collection doesn't occur.
Key Changes
- Added configurable TTL settings (
spark.cleaner.ttl.allandspark.cleaner.ttl.shuffle) for controlling block lifetimes - Implemented background cleaner threads in
BlockManagerMasterEndpointandMapOutputTrackerMasterto periodically remove expired blocks - Added access time tracking for RDD and shuffle blocks to support TTL-based cleanup
Reviewed Changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 16 comments.
Show a summary per file
| File | Description |
|---|---|
core/src/test/scala/org/apache/spark/storage/BlockTTLIntegrationSuite.scala |
New integration test suite validating TTL tracking and cleanup behavior for cache and shuffle blocks |
core/src/main/scala/org/apache/spark/storage/BlockManagerMasterEndpoint.scala |
Adds RDD access time tracking, TTL cleaner thread, and hooks to update access times on block operations |
core/src/main/scala/org/apache/spark/storage/BlockId.scala |
Introduces ShuffleId trait to enable uniform access to shuffle IDs across different shuffle block types |
core/src/main/scala/org/apache/spark/internal/config/package.scala |
Defines two new configuration options for TTL-based block cleanup |
core/src/main/scala/org/apache/spark/MapOutputTracker.scala |
Adds shuffle access time tracking, TTL cleaner thread, and integration with shuffle lifecycle operations |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
@ivoson yeah those are only for SQL jobs. |
|
We're closing this PR because it hasn't been updated in a while. This isn't a judgement on the merit of the PR in any way. It's just a way of keeping the PR queue manageable. |
|
Converting to a draft while I get this back up on the latest branch |
c7fc32d to
1e126c3
Compare
HyukjinKwon
left a comment
There was a problem hiding this comment.
Reviewed the current head (the post-rebase rewrite), focusing on the design and concurrency.
The design is solid and the concurrency story is handled carefully: the shared BlockTTLCleaner engine with per-domain veto/reap closures, @volatile-published hooks that default to refusing every reap until SparkContext wires them, the CAS accessTimes.remove(id, atime) (plus putIfAbsent on a failed reap) so an id that comes back into use mid-sweep is never lost, and a bounded awaitTermination join on shutdown. Reaping through the same ContextCleaner.doCleanupShuffle/unpersistRDD entry points as GC-driven cleanup (with an added epoch bump for the still-referenced case) keeps the behavior consistent, and the removeShuffle refactor that snapshots shuffle locations on the caller thread nicely sidesteps the SPARK-36782-style dispatcher lock-ordering cycle. BlockTTLCleanerSuite and BlockTTLIntegrationSuite cover the sweep engine and the end-to-end wiring (including the locally-checkpointed veto and the delete-before-unregister ordering) well.
The earlier Copilot comments (non-concurrent JHashMap, while (true) with no graceful stop, the stale config docs, the BlockId spacing, the s"..." test names) all appear to be addressed by the rewrite.
One small non-blocking nit inline. Separately: the "How was this patch tested?" section still reads "Work in progress", though the two suites now provide real coverage — worth refreshing when this comes out of draft.
1838822 to
65a2e86
Compare
spark-test
left a comment
There was a problem hiding this comment.
Review summary
This is a design-only review: the detailed code review did not run, so these findings come from the design review alone. That also means the one part of the change that applies without either setting has not had a line-level review here: BlockManagerMaster.removeShuffle now collects the shuffle's map-output and push-merger locations on the calling thread and sends them in the new RemoveShuffleFromMaster message.
The PR's stated goal is that a TTL that is too short only makes a later use recompute the data, never fail. By the review's reading of the code, both new cleaners can remove data that is still needed:
- With
spark.cleaner.ttl.rddset, the local-checkpoint veto is lost for an RDD that the TTL has already reaped once. If that RDD is later locally checkpointed through the RDD API, its next expiry deletes the only copy of its data, and every later action on it fails withCHECKPOINT_RDD_BLOCK_ID_NOT_FOUND. - With
spark.cleaner.ttl.shuffleset, the reap does not know whether a running or newly submitted job still uses a shuffle. A reduce stage that reads for longer than the TTL in cluster mode, or a job that reuses a shuffle while its removal is in flight, aborts instead of recomputing.
Both settings are unset by default, and neither problem arises without its setting.
Spec as reviewed
Motivation: On the base branch, cached RDD blocks and shuffle files are freed only when user code unpersists or cleans them, or when the driver garbage-collects the owning RDD or ShuffleDependency. RDDs and DataFrames that stay reachable, as at global scope in a notebook session, are never collected, so their blocks occupy executor memory and disk for the rest of the application.
Target use cases: Long-running applications, notebooks in particular, that set spark.cleaner.ttl.rdd or spark.cleaner.ttl.shuffle and keep RDDs or DataFrames reachable after they stop using them: the idle cached RDD blocks and idle shuffle files of those objects. Data that a running job or query is still reading, broadcast blocks, and applications that set neither key are outside them.
Decisions
- Clean up only the blocks, not the RDD or DataFrame itself, so a reaped object stays usable and its data is recomputed on the next use. — stated by the author; reviewed, no concern
- over: A TTL that cleans the RDD or DataFrame itself, measured from creation, like the Spark 1.x spark.cleaner.ttl
- why: Evicting storage while keeping the object usable is what lets a later use recompute instead of failing, which the rule against turning working code into failures favors over removing the object.
- Provide a TTL rather than rely on SQL's ShuffleCleanupMode, which removes a query's shuffles when the query ends but only applies to SQL jobs. — author's answer (#49032 (comment)); reviewed, no concern
- over: Rely on SQL's ShuffleCleanupMode for shuffle cleanup
- why: The stated problem covers RDD jobs and DataFrames reused across notebook cells, which a query-end cleanup either does not reach or would defeat by deleting shuffles a later cell could reuse.
- RDD use is recorded per RDD id at the BlockManagerMaster: a driver-side location lookup for one of its blocks (the DAGScheduler's cache-location lookups at stage submission, remote block fetches) or the first report of a stored block stamps the id, and a reap removes every partition of the RDD. — inferred from the code; reviewed, no concern
- over: Report executor-local cache hits to the driver so every read refreshes the access time
- why: Every job that reads a cached RDD resolves its cache locations on the driver, so active reuse refreshes the id and a reap during a long job only costs recomputation, without the per-read driver traffic that reporting every local hit would add.
- An RDD reap goes through the garbage-collection cleanup entry point, ContextCleaner.doCleanupRDD, or SparkContext.unpersistRDD when reference tracking is off. It frees the blocks and leaves the RDD's storage level, so a later action re-caches it, but it also removes the RDD from the SparkContext's persistent-RDD registry (which a later persist does not refill), posts an unpersist event, and runs the cleaner listeners' rddCleaned. — inferred from the code; kept with a concern
- over: Free only the blocks through BlockManagerMaster.removeRdd and keep the RDD registered
- why: Dropping the RDD from the registry takes away the only record the local-checkpoint veto consults, and nothing restores it when the same RDD is locally checkpointed later.
- The local-checkpoint veto is asked of the RDD itself: the endpoint's reapable hook and a re-check in the reaper look the id up in the persistent-RDD registry and refuse an RDD that is locally checkpointed; until SparkContext wires the hook, the endpoint refuses every reap. — inferred from the code; kept with a concern
- over: Record locally checkpointed RDD ids in their own set when localCheckpoint() marks them
- why: The registry it reads is cleared by the RDD reap itself, so an RDD reaped once and then locally checkpointed is reported as reapable.
- Shuffle use is judged at MapOutputTrackerMaster from the time of the shuffle's last registration, map-output registration or migration update, driver-served map-status request, or local-mode read; a registered shuffle with no map output yet is vetoed. Nothing asks the DAGScheduler whether an active job depends on the shuffle, and the reap is not ordered against job submission. — inferred from the code; challenged
- over: Pin the shuffles that active jobs depend on and start the idle clock when the last such job ends, as ExecutorMonitor does for dynamic allocation's shuffle-tracking timeout; Run the reap through the DAGScheduler event loop so it is ordered against job submission and stage retries
- why: Executors cache map statuses, so a running reduce stage stops stamping its shuffle after the first fetch, and the tracker cannot see a job that starts during a reap, so shuffles still in use get removed.
- A shuffle reap bumps the map-output epoch, deletes the files with a blocking ShuffleDriverComponents.removeShuffle while the map statuses are still registered (so the external shuffle service is told which blocks of departed executors to delete), then unregisters the shuffle from MapOutputTrackerMaster and notifies the ContextCleaner listeners so shuffle-tracking dynamic allocation can release executors. — inferred from the code; challenged
- over: Delete the files but keep the shuffle registered with its map outputs dropped, as SQL's RemoveShuffleFiles cleanup keeps the shuffle registered so stage retries recompute it; Remove asynchronously, as the garbage-collection cleaner does by default
- why: Unregistering the whole shuffle makes any use that overlaps the reap abort instead of recomputing.
- One BlockTTLCleaner class serves both caches: a daemon thread per enabled TTL scans an id-to-access-time concurrent map, reaps expired ids after a veto and a compare-and-remove, restamps an id whose reap throws so it is retried one TTL later, and sleeps until the oldest live entry can expire (at least a tenth of the TTL). The RDD cleaner starts with the BlockManagerMasterEndpoint and the shuffle cleaner with MapOutputTrackerMaster; SparkContext wires the reap hooks once the components they call exist and stops both cleaners at the start of stop(), waiting at most 2 seconds for an in-flight reap. — inferred from the code; reviewed, no concern
- over: Poll at a fixed interval from a scheduled executor, as ContextCleaner's periodic GC does; One cleaner thread sweeping both maps
- why: One sweep implementation for both caches is the simplest shape that meets the requirement, and the hooks refuse to reap until SparkContext wires them, so an early sweep removes nothing.
- Every shuffle removal, not only a TTL reap, now reads the shuffle's map-output and push-merger locations on the calling thread in BlockManagerMaster.removeShuffle and sends them to the block-manager master in a new driver-local RemoveShuffleFromMaster message, instead of the master's single dispatcher thread reading them from MapOutputTrackerMaster under the shuffle's status lock; this is not behind either TTL setting. — inferred from the code; reviewed, no concern
- over: Do the read in a Future on the endpoint's ask thread pool, as SPARK-36782 did for updateMapOutput; Keep reading on the dispatcher
- why: On the base branch the dispatcher can wait on a status lock held by a thread that is broadcasting map statuses and needs that same dispatcher, whenever the external shuffle service and spark.shuffle.service.removeShuffle (on by default) are enabled; reading on the caller breaks that cycle where the ask-pool alternative would read dispatcher-only executor state off the dispatcher, and the synchronous ask keeps the base branch's read-before-unregister order, so the gated-changes rule asks for no flag (the PR description does not mention this default-path change).
- spark.cleaner.ttl.rdd and spark.cleaner.ttl.shuffle are separate optional time settings, read as seconds when no unit is given, rejected below 10 minutes, read once at startup, and versioned 4.4.0. — inferred from the code; reviewed, no concern
- over: One TTL for both caches; Milliseconds as the default unit; No minimum
- why: Separate keys let users enable RDD eviction without the shuffle one, seconds match the pre-2.0 spark.cleaner.ttl, the minimum keeps TTLs above ordinary stage runtimes, and 4.4.0 is branch-4.x's version, where master changes normally also land.
Assumptions
- Users set spark.cleaner.ttl.shuffle longer than any shuffle's useful life, longer than both the longest gap between uses and the longest stage runtime, because executors cache map-output locations and use is recorded only when a map task registers output or the driver serves locations; removing a shuffle that a running job still needs fails that job, and retrying does not recover it. — stated by the author; challenged
Behavior changes
- With spark.cleaner.ttl.shuffle set, a shuffle with map output whose last recorded use is older than the TTL has its files deleted on executors and the external shuffle service and its map output dropped from the driver; a later job registers and recomputes it, and a job still reading it fails. — inferred from the code; challenged
Interactions
- The access-time maps are concurrent maps written by the block-manager dispatcher, the map-output dispatcher threads and the DAGScheduler, and pruned by each cleaner's own thread; a sweep removes an id only if its access time is unchanged, so an access during the sweep keeps it; the wired hooks are volatile and read at reap time; an RDD reap's block removal runs on the dispatcher through a RemoveRdd message; a shuffle reap runs on the cleaner thread concurrently with DAGScheduler job submission and stage retries, with no ordering between them. — inferred from the code; challenged
- A TTL under 10 minutes fails SparkConf reads with an IllegalArgumentException that names the minimum. A failed reap logs a warning and is retried one TTL later, and a dying cleaner logs an error. A job whose shuffle is reaped while it is still reading or reusing it fails with a stage abort naming MapOutputTracker.unregisterMapOutput or registerMapOutput, and a locally checkpointed RDD whose blocks were reaped fails with CHECKPOINT_RDD_BLOCK_ID_NOT_FOUND; neither message mentions the TTL. — inferred from the code; challenged
- Adaptive execution runs each shuffle query stage as its own map-stage job, so between that job and the job that reads the stage the shuffle's only stamps are its own map-output registrations: a query stage that waits longer than the TTL (for example for the other side of a join) is reaped and recomputed by the reading job, and a reading stage that outlasts the TTL has the same exposure as any reduce stage. Coalescing and skew specs address reducers and map ranges, which a recomputation of the same dependency keeps. — inferred from the code; challenged
25 spec items reviewed with no concern
Scope and non-goals
- Broadcast blocks are not TTL-cleaned; only RDD cache blocks and shuffle data are. — stated by the author; reviewed, no concern
- Both TTLs must be set before the SparkContext is created; setting or changing them on a running application has no effect. — stated by the author; reviewed, no concern
Assumptions
- Each job that reads a cached RDD resolves its cache locations through the driver, whether or not the blocks are then read locally, so an actively reused RDD keeps being stamped. — inferred from the code; reviewed, no concern
- Access times only need to be approximately right: concurrent writers may overwrite each other's nearby timestamps. — author's answer (#49032 (comment)); reviewed, no concern
Blast radius
- The RDD TTL reaches every RDD cache block the BlockManagerMaster tracks, including Dataset and SQL table caches; the shuffle TTL reaches every regular shuffle registered with MapOutputTrackerMaster, for every session of the application; the removal-path change reaches every shuffle removal: the garbage-collection cleaner, SQL's query-end shuffle cleanup, RDD.cleanShuffleDependencies and the TTL. The dispatcher-side map-status read it replaces is also on branch-4.x and branch-4.3 (older branches could not be read in this checkout). The feature itself is new; its 4.4.0 version matches branch-4.x (4.4.0-SNAPSHOT). — inferred from the code; reviewed, no concern
Requirements
- Two new configuration parameters enable TTL-based cleaning that removes blocks which have not been used for a configured period of time. — stated by the author; reviewed, no concern
- If the TTL is too short and the RDD or DataFrame is used again later, the code does not fail; the removed blocks are re-created. — stated by the author; reviewed, no concern
- The TTL counts from the last reference to the blocks, not from their creation as the Spark 1.x spark.cleaner.ttl did. — stated by the author; reviewed, no concern
- Locally checkpointed RDDs are never removed by the RDD TTL, because local checkpointing truncates lineage and leaves their cache blocks as the only copy of the data. — stated by the author; reviewed, no concern
Behavior changes
- With spark.cleaner.ttl.rdd set, an RDD whose blocks get no driver-side location lookup or new block report for the TTL loses every cached partition, and it no longer appears in SparkContext.getPersistentRDDs, even after a later action recomputes and re-caches it. — inferred from the code; reviewed, no concern
- Every shuffle removal (garbage-collection cleanup, SQL's query-end shuffle cleanup, RDD.cleanShuffleDependencies, TTL reaps) now reads map-output and merger locations on the caller's thread, so the block-manager dispatcher no longer blocks on a shuffle's status lock; which blocks are deleted, and when, is unchanged. — inferred from the code; reviewed, no concern
Interactions
- TTLs are per application: every SparkSession, and every Spark Connect session served by the same SparkContext, shares one policy; reaping is per RDD id or shuffle id, so one session's reap removes only that id's data. — inferred from the code; reviewed, no concern
- Both TTLs are unset by default; unset, no access time is recorded, no cleaner thread starts, and the TTL code paths behave as on the base branch. The removal-path change (caller-side snapshot and RemoveShuffleFromMaster) is not behind either setting and applies to every shuffle removal. — inferred from the code; reviewed, no concern
- No persisted format changes. The new RemoveShuffleFromMaster message is sent only by BlockManagerMaster on the driver to its own endpoint, which no longer accepts RemoveShuffle from callers (storage endpoints still receive RemoveShuffle); the external shuffle service calls are unchanged; event logs gain unpersist events for reaped RDDs, an existing event type. — inferred from the code; reviewed, no concern
- Driver and executors run the same build and the changed message stays inside the driver, so no mixed-version peer sees it; the external shuffle service protocol, which may run another version, is unchanged. — inferred from the code; reviewed, no concern
- Tenants sharing a SparkContext share the TTL policy and the two cleaner threads; a reap removes only the expired id's blocks, and its one shared side effect is a shuffle reap's epoch bump, which makes running readers in every session refetch map statuses on their next task, the same invalidation an executor loss causes. — inferred from the code; reviewed, no concern
- Nothing is persisted, so rolling back means unsetting the keys or running the previous build: an older Spark ignores the unknown keys, and an application started without them behaves as the base branch apart from the removal-path change. — inferred from the code; reviewed, no concern
- With both TTLs unset nothing is recorded and no thread starts. With a TTL set, each driver location lookup for a tracked RDD block (once per partition per stage through getCacheLocs) and each map-output registration or status request costs one concurrent-map write; each cleaner holds one daemon thread whose sweep scans one entry per tracked RDD or shuffle id and sleeps until the next possible expiry, never less than a tenth of the TTL; each reap costs one cluster-wide removal fan-out, and a shuffle reap also bumps the map-output epoch so executors refetch the statuses of shuffles they are reading. — inferred from the code; reviewed, no concern
- A reap that throws (for example a blocking shuffle removal timing out) restores the id's access time and is retried one TTL later, so a permanently failing reap costs one warning per TTL; a shuffle whose removal failed stays registered, so a later job that hits deleted files recovers through the normal fetch-failure path; an RDD reap whose cleanup logs an error is treated as done, as on the garbage-collection path. — inferred from the code; reviewed, no concern
- A successful reap logs at most at debug level (an RDD reap through ContextCleaner's debug lines, a shuffle reap not at all); a failed reap logs a warning naming the id, a cleaner that dies logs an error, and exit logs at info; existing log lines and metrics are unchanged. — inferred from the code; reviewed, no concern
- Access times and expiry use the wall clock in epoch milliseconds, so time zones and daylight-saving changes have no effect; a wall-clock step shifts every expiry by the step, so a forward step (for example after a laptop resumes) expires entries as if that much idle time had passed. — inferred from the code; reviewed, no concern
- SQL cache entries (Dataset.cache, CACHE TABLE) are cached RDDs to the RDD TTL: a reap frees their blocks while the cache entry and storage level stay, so the next scan recomputes and re-caches them, with partition statistics de-duplicated per partition as after any eviction; a nondeterministic cached plan can yield different values after the recompute, as it can after any eviction. No plan shape, analysis result or output schema changes. — inferred from the code; reviewed, no concern
- The settings are SparkConf keys the driver reads at startup, so Scala, Java, Python and R applications and the Spark Connect server behave the same; there is no new API or SQL syntax. — inferred from the code; reviewed, no concern
- Shuffle files are removed through ShuffleDriverComponents.removeShuffle, the call the garbage-collection cleaner makes, so every shuffle storage plugin is asked the same way; only regular shuffles registered with MapOutputTrackerMaster are tracked, so pipelined shuffles held by the streaming output tracker are never TTL-reaped; RDD blocks are removed through the BlockManagerMaster for every storage level, including blocks served by the external shuffle service. — inferred from the code; reviewed, no concern
Workloads
- In a notebook session with idle cached DataFrames and shuffles held at global scope and both TTLs set, executor memory and disk are reclaimed one TTL after the last recorded use, and the next use pays one recomputation of the reaped data. — inferred from the code; reviewed, no concern
The review also checked 11 other feature interactions that this change does not reach.
The detailed code review has not run: the finding Shuffle TTL removes shuffles that running or starting jobs still need below changes the approach, so it waits until it is settled. Answer it in this PR's conversation, or push a revised design; the next review reads both.
Findings
2 total: 0 P0, 2 P1, 0 P2, 0 P3.
Blocking (P1)
-
Local-checkpoint veto is lost for an RDD the TTL has already reaped —
General
This only applies withspark.cleaner.ttl.rddset. Both halves of the local-checkpoint veto,rddReapableand the re-check inrddReaper, callisLocallyCheckpointedRdd, which answers fromSparkContext.persistentRdds. A reap goes throughContextCleaner.doCleanupRDD(orunpersistRDDwhen reference tracking is off), which removes the RDD from that registry but leaves its storage level set.RDD.persistonly registers an RDD whose current level isNONE, andlocalCheckpoint()on an RDD that still has a level callspersist(..., allowOverride = true). So an RDD that the TTL has reaped once and that is later locally checkpointed is never registered again, and the veto treats it like any other cached RDD.By the review's reading of the code, the following sequence loses data. With
spark.cleaner.ttl.rdd=600, runval rdd = sc.parallelize(data).map(f).cache(); rdd.count()and leave the RDD idle for 10 minutes, so it is reaped as a plain cached RDD. Then callrdd.localCheckpoint(); rdd.count(): the blocks are cached again, which stamps the access time again, and the lineage is truncated. After another 10 idle minutes, the sweep and the reaper's re-check both find no registry entry, so the blocks are removed even though they are now the only copy of the data. The next action onrdd, or on any RDD derived from it, fails inLocalCheckpointRDD.computewithCHECKPOINT_RDD_BLOCK_ID_NOT_FOUND, whose message blames a lost executor or an unpersist rather than the TTL, and nothing can recompute the data.The new documentation says locally checkpointed RDDs are never removed, and on the base branch a locally checkpointed RDD that is still referenced loses its blocks only through an explicit unpersist or an executor loss. The veto does hold for an RDD that is locally checkpointed before it is ever reaped, which is what
Dataset.localCheckpointand the other library callers produce; the new integration test covers only that order. -
Shuffle TTL removes shuffles that running or starting jobs still need —
General
This only applies withspark.cleaner.ttl.shuffleset. The cleaner judges whether a shuffle is in use only from its access-time stamps, which are taken at shuffle and map-output registration, migration updates, driver-served map-status requests, and local-mode reads. Once a shuffle that has map output is older than the TTL, the reap bumps the epoch, deletes its files with a blockingShuffleDriverComponents.removeShuffle, and unregisters it fromMapOutputTrackerMaster. Nothing asks the DAGScheduler whether an active job or a running adaptive query still depends on the shuffle, and job submission is not ordered against the reap. Only the DAGScheduler can tell that a shuffle is still needed or order a reap against job submission; the tracker's map-status traffic shows neither.By the review's reading of the code, this makes jobs abort instead of recomputing, although the same jobs complete on the base branch with the same configuration, where the setting has no effect. This happens in two ways:
- A long read in cluster mode. Each executor fetches a shuffle's map statuses once and caches them until a task carries a higher epoch, so a reduce stage stops producing stamps after each executor's first fetch. With
spark.cleaner.ttl.shuffle=600, a reduce stage that keeps reading for 15 minutes (many task waves or a skewed partition, with no executor loss or fetch failure to bump the epoch) has its shuffle reaped 10 minutes after the last stamp. The next block reads raiseFetchFailed, the DAGScheduler callsunregisterMapOutput, which throwsShuffleStatusNotFoundExceptionbecause the shuffle is no longer registered; the scheduler's event loop catches it and aborts the map stage, failing the job. A rerun fails the same way as long as the stage outlasts the TTL. - Reuse while the removal is running. A notebook reuses an idle DataFrame just as its shuffle expires. While the blocking removal is in flight, the shuffle is still registered with all its outputs, so
createShuffleMapStageneither re-registers nor recomputes it, and the reduce stage reads files that are being deleted. Once the reap unregisters the shuffle, the retry path aborts the job the same way. This case does not depend on how the TTL compares with stage runtimes: it can hit any job that starts using a shuffle while its removal is in flight.
Either way, the user sees
exceptions encountered while invoking MapOutputTracker.unregisterMapOutput(orregisterMapOutput) and a driver warning that suggests the stage is being cancelled, with no mention of the TTL. Separately, an adaptive query whose materialized shuffle stage waits longer than the TTL for its reader recomputes the whole map stage.The new documentation acknowledges that removing a shuffle that a running job still needs fails that job, and asks users to keep the TTL above the longest stage runtime. That conflicts with the PR description's goal that a TTL that is too short only makes a later use recompute, never fail. Users also cannot see when a shuffle was last stamped, and Spark's existing shuffle timeouts ask nothing like this of them:
ExecutorMonitor's shuffle-tracking timeout never applies to a shuffle that an active job needs, and SQL'sRemoveShuffleFilescleanup keeps the shuffle registered, so a later use recomputes it. - A long read in cluster mode. Each executor fetches a shuffle's map statuses once and caches them until a task carries a higher epoch, so a reduce stage stops producing stamps after each executor's first fetch. With
PR description suggestions
- "How was this patch tested?" still says "Work in progress". The PR now adds BlockTTLCleanerSuite, which drives single sweeps of BlockTTLCleaner directly, and BlockTTLIntegrationSuite, which runs a two-executor local cluster, backdates access times, and sweeps by hand; describe those suites there.
- "What changes were proposed in this pull request?" describes only the two TTL settings, but the PR also changes every shuffle removal, with or without them: BlockManagerMaster.removeShuffle now reads the shuffle's map-output and push-merger locations on the calling thread and passes them in a new driver-local RemoveShuffleFromMaster message, rather than having the master's single dispatcher thread read them under the shuffle's status lock, which could stall all block management (the same cycle SPARK-36782 fixed for updateMapOutput). Describe that change and say that it is not behind either setting.
- "Does this PR introduce any user-facing change?" says only that new config parameters are introduced. Name them, spark.cleaner.ttl.rdd and spark.cleaner.ttl.shuffle, and state that they are unset by default, are read as seconds when no unit is given, must be at least 10 minutes, and must be set before the SparkContext is created. Also note that an RDD the TTL reaps keeps its storage level but stops appearing in SparkContext.getPersistentRDDs.
Generated by Omnigent on Databricks
… printed out on failure inside of the eventual block, remove RDD/Shuffle from access time tracking regardless of if RDD/shuffle removal succeeds
…ance to check for them (mostly needed for GHA where we run in rather resource constrained machines).
… faster than we can get to them
…al through the endpoint loop Self-review of the rebased branch turned up two thread-safety bugs in the TTL cleaner threads (both pre-existing in the branch, surfaced by the rebase review): 1. shuffleAccessTime (MapOutputTrackerMaster) and rddAccessTime (BlockManagerMasterEndpoint) were plain java.util.HashMaps written from multiple threads (the map-output dispatcher pool, DAGScheduler, and the TTL cleaner thread) with no synchronization. Concurrent structural mutation of a plain HashMap can corrupt the map, not merely skew a "close enough" atime, so both are now ConcurrentHashMaps. 2. BlockManagerMasterEndpoint is an IsolatedThreadSafeRpcEndpoint whose non-concurrent maps (blockLocations, blockChecksums, sealedChecksums, ...) are only safe because a single dispatcher thread touches them. The cleaner thread called removeRdd directly, racing that dispatcher thread. It now routes removal through the endpoint's own message loop via self.askSync[Future[Seq[Int]]](RemoveRdd(rddId)), keeping removeRdd on the dispatcher thread. MapOutputTrackerMaster is concurrent-by-design (epochLock, ConcurrentHashMap statuses, per-ShuffleStatus locks) so its off-thread unregisterAllMapAndMergeOutput needs no equivalent change. Also drop a doubled shuffleAccessTime.remove in unregisterAllMapAndMergeOutput left over from the rebase. Verified: core main/test compile clean; BlockTTLIntegrationSuite 4/4 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Bugs (Tier B):
- config: new spark.cleaner.ttl.{all,shuffle} tagged .version("5.0.0") (was 4.3.0;
project is 5.0.0-SNAPSHOT).
- MapOutputTracker.unregisterShuffle now drops the shuffleAccessTime entry (mirrors
removeRdd dropping rddAccessTime), so a GC-cleaned shuffle can't leave a stale entry
that later makes the cleaner call unregisterAllMapAndMergeOutput on an absent shuffle
(ShuffleStatusNotFoundException churn).
- BlockManagerMasterEndpoint.updateBlockAtime only records an RDD access when the block is
actually tracked, so a lookup of an absent/evicted block no longer creates a phantom
rddAccessTime entry that the cleaner would later broadcast a RemoveRdd for.
- BlockId.asShuffleId now gates on the ShuffleId trait (isInstanceOf[ShuffleId]) instead of
the narrower isShuffle, so chunk/push/merged shuffle ids are recognized.
- Both cleaners now use ConcurrentHashMap.remove(key, atime) so an entry refreshed between
the snapshot and the removal decision (a concurrent access) is not reaped (TOCTOU).
Cleanup (Tier C):
- Removed the now-dead catch ConcurrentModificationException + retry in both cleaners
(ConcurrentHashMap views are weakly consistent) and the misleading "reduce chance of CME"
comment; fixed a copy-pasted "shuffle" comment in the RDD cleaner.
- BlockManagerMasterEndpoint starts its TTLCleaner in onStart() rather than a val
initializer, since the cleaner uses self (valid only once registered); onStop uses foreach.
- BlockTTLIntegrationSuite no longer calls sc.setLogLevel("DEBUG") (JVM-wide, never reset)
and looks up the tracker via sc.env.mapOutputTracker, so the test-only
getMapOutputTrackerMaster() accessor is removed from the endpoint.
Verified: core main/test compile clean; BlockTTLIntegrationSuite 4/4 pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
… atime on map output (F2/F3) F3 (route shuffle TTL through the real removal path): - The shuffle TTL cleaner previously called unregisterAllMapAndMergeOutput, which only cleared driver-side outputs + bumped the epoch: it never sent RemoveShuffle to executors (so on-disk shuffle files were never freed -- the stated purpose unmet) and never removed the ShuffleStatus (leaking it). It now mirrors ContextCleaner.doCleanupShuffle: reclaim on-disk blocks on executors/ESS first, then drop the driver ShuffleStatus via unregisterShuffle. - MapOutputTrackerMaster lives in SparkEnv and has no ShuffleDriverComponents, so it exposes a shuffleFileRemover hook wired by SparkContext to shuffleDriverComponents.removeShuffle(id, false). This keeps the shuffle TTL feature independent of spark.cleaner.referenceTracking and honors a custom driver-shuffle-components plugin. If the hook is unset the cleaner still unregisters the status (fixing the leak) but cannot reclaim executor disk. F2 (refresh shuffle atime on produce side): - registerMapOutput now calls updateShuffleAtime, so a map stage running longer than the TTL is not reaped mid-production (registerShuffle only stamps the atime once, at stage submission; reduce fetches refresh via handleStatusMessage). This also matters now that F3 deletes files on reap. Test: - New BlockTTLIntegrationSuite case pins down the RDD TTL assumption: re-reading a cached RDD in a new job re-resolves cache locations at the driver (clearCacheLocs -> getCacheLocs -> BlockManagerMaster.getLocations -> updateBlockAtime) and thus refreshes the atime, so an actively-reused cached RDD is not reaped. Verified: core main/test compile clean; BlockTTLIntegrationSuite 5/5 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Correctness: - X1 (regression I introduced with F3): the shuffle reaper now only reaps a shuffle that has actually produced output (numAvailableMapOutputs > 0). A registered-but-not-yet-produced shuffle has no files to reclaim, and removing its ShuffleStatus made the first registerMapOutput throw ShuffleStatusNotFoundException -> abortStage (hard job failure). The old code kept the status (leak) and didn't abort; this keeps F3's disk reclamation without the abort. - updateBlockAtime now branches on asRDDId / asShuffleId instead of the narrow isShuffle, so the ShuffleId trait (chunk/push/merged ids) is actually reachable; access-time UPDATES stay gated on the TTL config being set (so we don't populate maps no cleaner will drain). Cleanup: - Extracted the two byte-identical TTLCleaner loops into a shared BlockTtlCleaner(name, ttl, map, shouldReap, reap); the RDD cleaner passes shouldReap = _ => true, the shuffle cleaner the has-output gate above. - Cache the TTL config (Option[Long]) in a val instead of re-parsing conf.get on every updateBlockAtime/updateShuffleAtime hot-path call. - MapOutputTrackerMaster starts its cleaner after the fail-fast broadcast-size check (was in a field initializer, which orphaned the daemon if that check threw); removeRdd/unregister* use a bare unconditional access-map remove (a no-op when empty) instead of a guarded, dead-try-wrapped one; MOT stop() uses foreach not map. - Rename spark.cleaner.ttl.all -> spark.cleaner.ttl.rdd (it cleans only RDD cache blocks, not all; shuffle uses spark.cleaner.ttl.shuffle) and reword the doc. - Test: long TTL for the tracking/refresh-only tests (avoids racing the 5s reaper on a slow CI); drop dead constants (numExecs, TaskStarted/Ended, JobEnded). Per Holden: kept getShufflePushMergerLocations' updateShuffleAtime (needed for atime) and did not add a minimum-TTL floor (operator's responsibility). Verified: core main/test compile clean; BlockTTLIntegrationSuite 5/5 pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- Wrap 6 comment/doc lines that exceeded the 100-char limit; core/scalastyle and
core/Test/scalastyle now report 0 errors (they failed before, so CI would have rejected this).
- .version("5.0.0") -> .version("4.4.0") for both new configs. Per the repo versioning policy a
normally-backported PR against master ships first in branch-<N>.x;
dev/next_version_candidates.py reports master 5.0.0 / branch-4.x 4.4.0, and an additive pair of
createOptional configs is neither a breaking change nor a dependency upgrade.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…arkContext
Reaping a still-referenced shuffle via unregisterShuffle (introduced with F3) was fatal, and the
numAvailableMapOutputs gate did not cover it -- that gate handles "not yet produced", not "produced
and still needed". The two metadata calls differ in two safety-relevant ways:
unregisterShuffle removes the ShuffleStatus, does NOT incrementEpoch
unregisterAllMapAndMergeOutput keeps the (emptied) status, DOES incrementEpoch
So unregisterShuffle broke reaping twice over:
1. No epoch bump, so executors keep their cached map statuses and go on to fetch the files the
reaper just deleted -> FetchFailed.
2. With the status removed, the DAGScheduler's own FetchFailed recovery
(unregisterAllMapAndMergeOutput / unregisterMapOutput -> getShuffleStatusOrError) throws
ShuffleStatusNotFoundException on the event-loop thread, and
DAGSchedulerEventProcessLoop.onError responds with doCancelAllJobs() + sc.stopInNewThread():
reaping a live shuffle took down the whole application.
Reap now deletes the on-disk blocks (shuffleFileRemover, i.e. the normal removeShuffle path -- still
the point of F3) and then calls unregisterAllMapAndMergeOutput instead of unregisterShuffle. The
epoch bump makes executors re-ask rather than read deleted files; re-asking returns an empty status,
which surfaces as MetadataFetchFailedException -- a FetchFailed -- so the DAGScheduler recomputes the
map stage normally instead of hanging on an unanswered RPC. Keeping the status registered also means
the scheduler's error paths can no longer throw. The cost is that an emptied ShuffleStatus lingers
until the ContextCleaner collects it (the same small leak the original code had); emptying it makes
numAvailableMapOutputs 0, so it is not reaped again.
Verified: core/scalastyle + core/Test/scalastyle 0 errors; BlockTTLIntegrationSuite,
MapOutputTrackerSuite and ContextCleanerSuite 55 succeeded / 0 failed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…reclamation path Four review findings, all reachable with the TTL configs enabled: 1. Data loss: the RDD cleaner reaped any tracked RDD, including a locally-checkpointed one. localCheckpoint truncates lineage and LocalCheckpointRDD.compute always throws, so those cache blocks are the only copy of the data -- reaping them loses it unrecoverably (RDD.localCheckpoint already warns about the same hazard with dynamicAllocation.cachedExecutorIdleTimeout). The endpoint now consults a wired `rddReapable` gate, which SparkContext implements by refusing any RDD whose live instance isLocallyCheckpointed. New test idles such an RDD past the TTL and asserts the data is still readable. 2. A zero or negative TTL was accepted: JavaUtils' time pattern is "(-?[0-9]+)([a-z]+)?", so ttl=-1s parses to -1000 and maxAge = now + 1000, making every entry instantly stale -- the cleaner then reaps everything roughly every 100ms (the delay clamp) for the life of the application. Both configs now .checkValue(_ > 0, ...). This is not a minimum-TTL floor (still deliberately absent, per the operator's-responsibility call): it just rejects input that inverts the comparison. 3. Reaping a shuffle skipped the CleanerListener.shuffleCleaned fan-out that ContextCleaner.doCleanupShuffle ends with. ExecutorMonitor uses it to let an executor holding only that shuffle go idle, so under dynamicAllocation.shuffleTracking the TTL deleted the files but never released the executor. The wired remover now calls ContextCleaner.notifyShuffleCleaned (new, private[spark]) after removeShuffle. 4. The RDD reap sent RemoveRdd directly, which is only the RPC half of SparkContext.unpersistRDD: persistentRdds was never cleared and no SparkListenerUnpersistRDD was posted, so the Storage UI showed the RDD as fully cached forever with stale per-executor block counts. The reap now routes through unpersistRDD (which still removes blocks via the same RemoveRdd RPC). Wiring: SparkEnv retains the driver's BlockManagerMasterEndpoint (captured inside the by-name endpointCreator, so it stays None on executors) so SparkContext can attach the two RDD hooks alongside the existing shuffle one. RDD.isLocallyCheckpointed widens from private[rdd] to private[spark]. Verified: core/scalastyle + core/Test/scalastyle 0 errors; BlockTTLIntegrationSuite, MapOutputTrackerSuite, ContextCleanerSuite and LocalCheckpointSuite 73 succeeded / 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ing it The RDD reap hook duplicated the first half of ContextCleaner.doCleanupRDD (sc.unpersistRDD) and dropped the second (the CleanerListener.rddCleaned fan-out). Call doCleanupRDD instead, so the TTL path and the GC-driven path share one entry point and its error handling. Both in-tree rddCleaned implementations are currently empty, so this is not a behavior fix like the shuffleCleaned one was -- it removes the duplication and stops a third-party CleanerListener from silently missing TTL reaps. Falls back to unpersistRDD when spark.cleaner.referenceTracking is off and there is no cleaner, so reaping still works in that configuration. Also pin the full-RDD removal path, since access times are recorded per RDD id but stamped by individual block accesses while a reap removes the whole RDD. The new test asserts every partition's block is gone from the master (not just idle ones), and that the RDD is still usable afterwards and comes back tracked: the reap frees blocks without resetting the RDD's storage level, so it is an eviction rather than an unpersist. Verified: core/scalastyle + core/Test/scalastyle 0 errors; BlockTTLIntegrationSuite (7 tests) and ContextCleanerSuite 21 succeeded / 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…nd cleaner shutdown The data-loss guard added earlier was defeated by the reap path it guards. rddReapable asked `!persistentRdds.get(rddId).exists(_.isLocallyCheckpointed)`, but reaping calls unpersistRDD, which does persistentRdds.remove(rddId), and RDD.persist only re-registers on the first transition out of StorageLevel.NONE -- which a reap never restores. So: cache, let it be reaped (entry gone), then localCheckpoint (persist(..., allowOverride = true) skips persistRDD), then let it idle -- the gate now reads None, decides the RDD is reapable, and deletes the only copy of the checkpointed data. Reading the live RDD from the cleaner thread was unsound anyway: RDD.checkpointData is not volatile, so a stale None was possible regardless. SparkContext now tracks locally-checkpointed ids in a dedicated concurrent set, written by RDD.localCheckpoint and cleared by unpersistRDD, and the gate reads that. RDD.isLocallyCheckpointed goes back to private[rdd]. Also: - updateBlockInfo stamped an access right after inserting the blockLocations entry, so the containsKey guard was trivially true and a *removal* report (the UpdateBlockInfo(NONE) replies that follow a RemoveRdd broadcast, or a late eviction report) resurrected an access time for an RDD with no blocks -- which one TTL later fires a pointless cluster-wide RemoveRdd. Only stamp when the reported level is valid. - BlockTtlCleaner swallowed the interrupt from shutdownNow when it landed inside a reap: the RPC wraps InterruptedException in a NonFatal SparkException, the throw clears the interrupt flag, and the loop carried on -- leaking a daemon thread per SparkContext in a long-lived JVM. The loop now tests isInterrupted. Reap failures move from logDebug to logWarning: a cleaner that reclaims nothing must not be invisible at the default log level. - updateBlockAtime returns before allocating when neither TTL is set (it runs per block-location lookup on the dispatcher thread, O(partitions) per stage, and both configs are off by default), and matches on the BlockId type instead of allocating two Options. - The unwired reap fallback observes the removal future, matching BlockManagerMaster.removeRdd, instead of discarding it and losing failures. - Document both configs in docs/configuration.md, including that removal is an eviction (the RDD re-caches on next use), that access is observed at the driver so a long single job may not look busy, and that locally checkpointed RDDs are never removed. - Test: use the SparkEnv accessor this PR adds instead of reflecting into RpcEnv internals (deleting a helper copy-pasted from MapOutputTrackerSuite); read atimes through Option, since a ConcurrentHashMap[Int, Long] miss unboxes to 0L and made the refresh assertion able to pass vacuously; wrap a racy tracking assertion in eventually; replace a clock-polling eventually with a plain sleep; drop the unused ResetSystemProperties mixin. Verified: core/scalastyle + core/Test/scalastyle 0 errors; BlockTTLIntegrationSuite, LocalCheckpointSuite, ContextCleanerSuite, MapOutputTrackerSuite 74 succeeded / 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Removing a shuffle that is still being read does not just cost a map-stage recompute: because executors cache map statuses per epoch, an actively-read shuffle may not look busy, and if the resulting fetch failures repeat they exhaust spark.stage.maxConsecutiveAttempts and fail the job. Setting the TTL safely is the operator's call, so say what the worst case actually is. Docs only; no behavior change. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Cut ~190 lines from the diff, most of it comment prose. Code changes: - BlockTtlCleaner sweeps in one pass instead of building an intermediate list. - SparkEnv builds the driver endpoint with a plain if (isDriver), dropping the var captured inside the by-name endpoint creator. - Drop SparkContext.registerLocallyCheckpointedRdd; localCheckpoint adds to the id set directly. Drop the unused BlockId.asShuffleId. - Test suite: one startCluster helper for the conf boilerplate, drop the test the atime-refresh test already covers, fix two copy-pasted app names. - Revert drive-by logDebug/comment/indentation edits in BlockManagerMasterEndpoint that this PR does not need. Also fixes a stale comment: rddReaper is wired to ContextCleaner.doCleanupRDD, not SparkContext.unpersistRDD. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…he sweep stoppable Simplification: - Revert BlockId.scala entirely. The new @DeveloperAPI ShuffleId trait and its 10 case-class mixins served one match arm that cannot be reached in production (receiveAndReply routes shuffle ids to updateShuffleBlockInfo first, and no getLocations caller passes one), and the name collided with ShuffleBlockResolver's `type ShuffleId = Int`. Dropping it also drops the anyTtlEnabled double gate. - BlockTtlCleaner owns its thread, with start()/stop(), so neither owner repeats the pool creation, execute and shutdownNow. - Delete the unwired RemoveRdd fallback: unreachable, and a re-implementation of BlockManagerMaster.removeRdd. All three injected hooks are now total functions with safe defaults instead of two conventions. - Move the configs into the spark.cleaner.* block as CLEANER_TTL_RDD / CLEANER_TTL_SHUFFLE, and updateShuffleAtime out of the field/init region. - Rewrap a 101-char comment (scalastyle error). Correctness: - The sweep could not be stopped: a reap swallows the InterruptedException (doCleanupRDD catches Exception) and that clears the interrupt flag, so shutdownNow lost the signal and the thread outlived its SparkContext. Now gated on a volatile flag too. - Reap the epoch bump BEFORE deleting files, not after, so executors re-ask instead of fetching files that are already gone; unregister the ShuffleStatus explicitly rather than leaving it to the async RemoveShuffle broadcast (which was already removing it, defeating the "keep the status registered" rationale), which also drops the mapStatusesDeleted tombstones. - Honor spark.cleaner.referenceTracking.blocking.shuffle, like doCleanupShuffle does. - rddReapable defaults to refusing everything: fail-open risked reaping a locally-checkpointed RDD's only copy. _cleaner is @volatile, since the sweep threads read it. - Track the atime on the local-mode shuffle read path, and stop stamping it in getShufflePushMergerLocations, which is also called while removing a shuffle. - shouldReap no longer vetoes an id with no ShuffleStatus forever, which leaked its atime. - Reap outside the map iteration, so a blocked reap does not leave the rest of the sweep comparing against a stale clock; scale the sleep floor to the TTL instead of 100ms; log if the sweep ever dies. - Stop both sweeps at the top of SparkContext.stop(), before the ContextCleaner, listener bus and shuffle driver components their reaps use. - Docs no longer promise that reaping a still-needed shuffle recomputes the map stage: the stage cannot re-register its output, so it aborts. Tests: assert the shuffle's map output is actually gone and the epoch bumped, not just that the tracking map emptied -- the cleaner drops the atime before it reaps, so the old assertion passed even with the reap wiring removed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…nd the removal-path lock inversion Follow-up fixes to the block TTL cleaner, from reviewing the feature as a whole. Reclamation correctness: - The shuffle reap emptied the ShuffleStatus before deleting files, but BlockManagerMasterEndpoint.removeShuffle reads the live MapStatuses (to find blocks the external shuffle service still serves for departed executors) and the live push-merger locations. Emptying first hid both, so with the shuffle service enabled the TTL reclaimed no external disk at all. Reordered to incrementEpoch -> remove files -> unregister, which is the ordering, and the reason for it, that ContextCleaner.doCleanupShuffle documents. - The sweep dropped an id's access time before reaping it, so a reap that failed part-way (a blocking shuffle removal timing out on a dead executor, say) left the id untracked and whatever it still held on disk leaked for the life of the driver. The access time is now restored so a later sweep retries. - shuffleFileRemover defaulted to a no-op, so a reap before SparkContext wired it would drop the driver's shuffle state while deleting nothing. It is now an Option the cleaner refuses to reap without, mirroring rddReapable. - A shuffle whose outputs were restored by block migration was never re-stamped, so the TTL would never reclaim it. Lock inversion on the block-manager dispatcher: - removeShuffle took the shuffle's ShuffleStatus read lock on the endpoint's single dispatcher thread, while ShuffleStatus holds that lock for write across RPCs back into the same endpoint (serializedMapStatus broadcasts the statuses; invalidating the cache destroys that broadcast). That cycle stalls all block management until the RPC times out. It is the same cycle SPARK-36782 fixed for updateMapOutput. Both reads are now snapshotted on the caller's thread and passed in a new driver-only RemoveShuffleFromMaster message, so the dispatcher acquires no ShuffleStatus lock. The executor-bound RemoveShuffle is unchanged. Lifecycle: - BlockTTLCleaner.stop now joins briefly, so SparkContext.stop's deliberate ordering (cleaners before the ContextCleaner, listener bus and shuffle driver components) actually holds rather than merely narrowing the race, and the sweep no longer sleeps out a whole TTL after stop when a reap swallowed its interrupt. - BlockManagerMasterEndpoint.onStop stopped askThreadPool before the cleaner, which a reap in flight routes its removal through; swapped. - The CleanerListener fan-out now runs after unregisterShuffle rather than before, and is contained the way doCleanupShuffle contains its own. - The RDD reap re-checks the locally-checkpointed veto at the point of action: the id can be added between the cleaner's check and the reap, and the reap clears that set on its way through unpersistRDD, which would both destroy the only copy of the data and erase the protection against repeating it. Also renames BlockTtlCleaner to BlockTTLCleaner (the only Ttl-cased type in the tree), adds a BlockTTLCleanerSuite covering the sweep directly (a vetoed id, an access time moving mid-sweep, a throwing reap), and corrects a comment that claimed the epoch bump protects already-running reduce tasks -- an executor only picks up a new epoch at task launch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…structured logging, and derive the checkpoint veto from the RDD Follows the review decisions on the block TTL cleaner. Configs: - Both TTLs are now in seconds rather than milliseconds, matching the pre-2.0 spark.cleaner.ttl they restore. A user carrying `spark.cleaner.ttl=3600` forward previously got 3.6 seconds instead of an hour, silently, and a too-short shuffle TTL fails running jobs. The unit is stated in both docs and both .doc() strings, and the components convert to millis at the read site. - Both reject anything under 10 minutes. The TTL has to outlast the longest gap between uses and the longest stage runtime; below that it reclaims blocks a running job still needs. Unset still means disabled. - The shuffle docs now say plainly that keeping the TTL longer than any shuffle's useful life is the user's responsibility, and that a shuffle reaped out from under a running job fails it rather than being recomputed. Logging: BlockTTLCleaner takes a LogKey for the id it reaps (RDD_ID or SHUFFLE_ID) and reports the cleaner name under COMPONENT, so its warnings carry structured fields like the rest of the files it sits between. Locally checkpointed RDDs: the veto stays -- localCheckpoint stores its data as RDD cache blocks under the same RDD id, which is exactly what this cleaner reaps, and it truncates lineage so those blocks are the only copy -- but it is now derived from the RDD itself rather than tracked beside it. RDD.checkpointData is @volatile so the cleaner thread sees a local checkpoint marked on the driver thread, isLocallyCheckpointed widens to private[spark], and SparkContext.locallyCheckpointedRddIds and its two sync points are gone. Tests: the 10 minute minimum makes the integration suite's five second TTLs illegal, so rather than lose that coverage, one sweep is split out of BlockTTLCleaner.run as sweep(). The suite now backdates an access time and drives a sweep directly, which is deterministic and drops its runtime from roughly 50s to 15s, and it stops the background threads so they cannot race the assertions. BlockTTLCleanerSuite covers the thread lifecycle and the sweep's wait arithmetic, and a new test asserts a sub-minimum TTL is rejected while a bare 600 is accepted as seconds. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Wait for shuffle cleanup during TTL eviction so delayed removal cannot erase a new job registration or its files. Keep the existing GC cleanup policy. Co-authored-by: Holden Karau <holden@pigscanfly.ca> Co-authored-by: Holden Karau <holden.karau@snowflake.com>
…s reaped before The RDD TTL cleaner must never reap a locally checkpointed RDD: local checkpointing truncates lineage, so the cache blocks are the only copy of the data. The veto asked SparkContext.persistentRdds for the RDD, but a reap removes the RDD from persistentRdds and nothing puts it back: the storage level is not reset, so RDD.persist never re-registers it. An RDD that was reaped once and locally checkpointed afterwards was therefore invisible to the veto, and the next sweep deleted its checkpoint. Track the RDDs marked for local checkpointing in their own weak-valued map on SparkContext, written by RDD.localCheckpoint. Nothing removes an entry, so neither a reap that races the mark nor an unpersist followed by a re-persist can drop the protection; the entry goes away with the RDD. The cleaner no longer reads the RDD itself, so RDD.checkpointData and RDD.isLocallyCheckpointed go back to what they are on master. The new test fails without the fix. It caches the RDD with an async action so that the first action to reach RDD.doCheckpoint is the one after localCheckpoint(), which is the state a job on a checkpointed child leaves a cached parent in. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TjVfRhwcJob6Z3m1ywMu7N
…the shuffle TTL must exceed branch-4.4 has been cut, so the first release these configs can ship in is 4.5.0. The shuffle TTL cleaner does not check whether a running job still needs a shuffle, and removing one that is still needed aborts the stage instead of recomputing it. Say so in the config doc as well as in docs/configuration.md, and be specific about what the TTL has to exceed. The longest stage is not always enough: an access is only recorded when a map task registers output or an executor first fetches the map output locations, so a finished shuffle also looks idle while it waits for the other stages of its job. Recommend the longest-running job (for SQL, the query). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TjVfRhwcJob6Z3m1ywMu7N
Moving the map output read out of BlockManagerMasterEndpoint.removeShuffle left externalShuffleServiceRemoveShuffleEnabled with no readers. Remove it, and reword the comments that pointed at it. BlockManagerMaster.removeShuffle also evaluated Utils.isPushBasedShuffleEnabled on every call, where the endpoint only did so when it had an external shuffle service client. With push-based shuffle requested but no shuffle service, that logs a warning for every removed shuffle. Check that the shuffle service is enabled first, as the endpoint did. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TjVfRhwcJob6Z3m1ywMu7N
033570c to
d8cb35e
Compare
What changes were proposed in this pull request?
This introduces two new, optional config parameters for TTL based cleaning, which remove blocks that have not been used for a given period of time:
spark.cleaner.ttl.rddremoves the cache blocks of an RDD that has not been accessed for the TTL.spark.cleaner.ttl.shuffleremoves the map output and the shuffle files of a shuffle that has not been accessed for the TTL.Both are unset by default, are interpreted as seconds when no unit is given (like the pre-2.0
spark.cleaner.ttl), must be at least 10 minutes, and must be set before theSparkContextis created. Broadcast blocks are not covered.How it works:
BlockTTLCleanersweeps an id -> last-access-time map on its own daemon thread.BlockManagerMasterEndpointhas one for RDDs andMapOutputTrackerMasterhas one for shuffles. When a config is unset, nothing is tracked and no thread is started.ContextCleaner.doCleanupRDD, the path GC-driven cleanup uses. Its storage level is not reset, so the next action that uses it caches it again. Locally checkpointed RDDs are never reaped: local checkpointing truncates lineage, so their cache blocks are the only copy of the data.ContextCleaner.doCleanupShuffledoes it: delete the files throughShuffleDriverComponents.removeShuffle, unregister the shuffle, then notify theCleanerListeners, so that dynamic allocation with shuffle tracking can release executors that only held it. The epoch is bumped first. A later job that needs the shuffle registers it again and recomputes it.removeShufflechanges for every caller, not only when a TTL is setBlockManagerMaster.removeShufflenow talks to the driver'sBlockManagerMasterEndpointdifferently, whether or not the new configs are set. That covers GC-driven cleanup inContextCleanerand SQL'sRemoveShuffleFilescleanup mode as well as the new TTL cleaner.RemoveShuffle(shuffleId), and the endpoint read the shuffle's map statuses and push-merger locations from theMapOutputTrackeron its own dispatcher thread.removeShufflereads both on the caller's thread and sends them in a new driver-only message,RemoveShuffleFromMaster. The endpoint no longer reads theMapOutputTrackerwhen it removes a shuffle.RemoveShuffleis still what the endpoint fans out to the executors, but the driver endpoint itself no longer accepts it.The reason is a lock cycle. Reading either list takes the shuffle's
ShuffleStatuslock, and that dispatcher is single-threaded.ShuffleStatusholds the same lock for write across RPCs that only that dispatcher can serve: serializing the map statuses creates a broadcast, which reports its blocks to the master, and invalidating the cached statuses destroys that broadcast. Taking the lock on the dispatcher can therefore stall all block management until the RPC times out. SPARK-36782 fixed the same cycle forupdateMapOutput. It is reachable today with the external shuffle service and eitherspark.shuffle.service.removeShuffleor push-based shuffle, and the TTL cleaner makes it easier to hit, because it can remove a shuffle that executors are still asking about.What gets removed does not change. Each list is only gathered when the feature that uses it is on (
spark.shuffle.service.removeShufflefor the map output locations, push-based shuffle for the merger locations), so by default both are empty and the only difference is the message type.Why are the changes needed?
We depend on garbage collection on the driver to tell us when RDDs/DataFrames are no longer referenced, but when those are defined at the global scope, as they usually are in a notebook, they are never collected and their blocks are never cleaned up. Rather than cleaning up the RDD/DataFrame itself based on the TTL, we only clean up its blocks, so that if the TTL is too short and the user does use that RDD or DataFrame again, their code does not fail but instead re-creates those blocks.
There is one case where a too-short TTL does fail: a shuffle that is removed while a job that needs it is still running. The cleaner does not check for that, and the map stage cannot re-register its output, so the stage is aborted rather than recomputed and the job has to be submitted again.
docs/configuration.mdsays so, and says what the shuffle TTL has to exceed: the longest stage and, to be safe, the longest-running job (for SQL, the longest-running query).Does this PR introduce any user-facing change?
Yes, two new config parameters,
spark.cleaner.ttl.rddandspark.cleaner.ttl.shuffle. These are similar to the old Spark 1.xspark.cleaner.ttl, but measure from the last use rather than from creation.With neither set there is no user-facing change. The
removeShufflechange described above is internal: the same blocks are removed under the same configs.How was this patch tested?
New tests:
BlockTTLCleanerSuitecovers the sweep on its own: an idle id is reaped, a live or vetoed id is not, an id that comes back into use during a sweep is not, a failed reap is retried, how long the sweep waits before the next pass, and starting and stopping the thread.BlockTTLIntegrationSuiteruns both cleaners against alocal-cluster: a reaped shuffle's map output is gone and the epoch is bumped, its files are deleted before the map output is dropped, re-reading a cached RDD refreshes its access time, reaped RDDs and shuffles come back when they are used again, a locally checkpointed RDD is never reaped (including one that was reaped before it was checkpointed), nothing is tracked when the configs are unset, and a TTL under 10 minutes is rejected.The smallest TTL the configs accept is 10 minutes, so the integration tests backdate an access time and call
BlockTTLCleaner.sweep()directly rather than wait for an expiry.Existing suites run locally, for the code this touches:
ContextCleanerSuite,MapOutputTrackerSuite,BlockManagerSuite,BlockManagerMasterSuite,ExternalShuffleServiceSuite,LocalCheckpointSuite,CheckpointSuite,SortShuffleSuiteandBlockManagerDecommissionIntegrationSuite, pluscore/scalastyleandcore/Test/scalastyle.Was this patch authored or co-authored using generative AI tooling?
Yes.
Generated-by: Claude Code (mixture of Opus 5.5 Fable 5.2 and Sonnet)