spark-test commented on code in PR #58619:
URL: https://github.com/apache/spark/pull/58619#discussion_r4508227043


##########
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/shuffle/KubernetesLocalDiskShuffleExecutorComponents.scala:
##########
@@ -123,7 +128,14 @@ object KubernetesLocalDiskShuffleExecutorComponents 
extends Logging {
         }
         oldDirs
           .flatMap(listEntriesOrEmpty).filter(_.isDirectory) // executor-xxx
-          .flatMap(listEntriesOrEmpty).filter(_.isDirectory) // blockmgr-xxx
+          .flatMap { executorDir =>
+            val children = 
listEntriesOrEmpty(executorDir).filter(_.isDirectory)
+            // Kubernetes puts blockmgr directly below executor; standalone 
adds an app dir.
+            children.filter(_.getName.startsWith("blockmgr-")) ++
+              children.flatMap(listEntriesOrEmpty).filter { f =>

Review Comment:
   **Blocking (P1):** On the documented recovery layout 
(`spark.kubernetes.executor.volumes.persistentVolumeClaim.spark-local-dir-1.mount.path=/data/spark-x/executor-x`),
 the children of `executor-x` are the `blockmgr-*` dirs themselves. Line 134 
keeps them, but this `flatMap` also lists each of them and calls `isDirectory` 
on every `%02x` entry before the name test discards it, and line 139 then lists 
the same `blockmgr-*` dirs again; before this PR each one was listed once. 
Because `KubernetesLocalDiskShuffleDataIO` requires 
`spark.kubernetes.driver.reusePersistentVolumeClaim`, every executor start with 
the plugin pays one extra directory listing and up to 
`spark.diskStore.subDirectories` (default 64) extra stats per `blockmgr-*` dir 
left on the PVC, and that grows with executor churn while the recovered files 
stay the same. The cost per start is small next to the per-file checksum reads 
and block-info RPCs, but a same-result change removes it: partition `children` 
by the `blockmgr
 -` prefix, keep those directly, descend only into the others, and test the 
name before `isDirectory`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58619#discussion_r3985592321).
   
   **Verification:**
   - **Regression:** For the documented Kubernetes layout with several 
blockmgr-* dirs and populated subdirectories, recovery lists each blockmgr-* 
dir exactly once.
   - **Behavior:** Recovery still finds the shuffle files in both the 
Kubernetes layout and the app-scoped standalone layout.



##########
core/src/main/scala/org/apache/spark/deploy/ExternalShuffleService.scala:
##########
@@ -83,18 +83,26 @@ class ExternalShuffleService(sparkConf: SparkConf, 
securityManager: SecurityMana
 
   /** Create a new shuffle block handler. Factored out for subclasses to 
override. */
   protected def newShuffleBlockHandler(conf: TransportConf): 
ExternalBlockHandler = {
-    // Constrain registered localDirs to the configured local directories.
+    // Constrain registered localDirs to the configured local directories and, 
when
+    // spark.shuffle.service.requireAppScopedLocalDirs is enabled, to the 
registering
+    // application's own per-app directory 
(spark-*/executor-*/<url-encoded-appId>, with an
+    // optional blockmgr-* child).
+    // The check is opt-in: executors launched by Workers that predate the 
per-app layout
+    // register unscoped paths and would be rejected, so enable it only after 
every Worker
+    // in the cluster is upgraded.
     val localDirs = Utils.getConfiguredLocalDirs(sparkConf)
+    val requireAppScopedLocalDirs =
+      sparkConf.get(config.SHUFFLE_SERVICE_REQUIRE_APP_SCOPED_LOCAL_DIRS)
     if (sparkConf.get(config.SHUFFLE_SERVICE_DB_ENABLED) && enabled) {
       val shuffleDBName = sparkConf.get(config.SHUFFLE_SERVICE_DB_BACKEND)
       logInfo(
         log"Use ${MDC(SHUFFLE_DB_BACKEND_NAME, shuffleDBName.name())} as the 
implementation of " +
         log"${MDC(SHUFFLE_DB_BACKEND_KEY, 
config.SHUFFLE_SERVICE_DB_BACKEND.key)}")
       new ExternalBlockHandler(conf,
         
findRegisteredExecutorsDBFile(shuffleDBName.fileName(registeredExecutorsDB)),
-        localDirs, false)
+        localDirs, requireAppScopedLocalDirs)

Review Comment:
   **Nit (P3):** Every test that turns on 
`spark.shuffle.service.requireAppScopedLocalDirs` also sets 
`spark.shuffle.service.db.enabled=false` 
(`ExternalShuffleServiceLocalDirsSuite` lines 61 and 108), so only the 
construction at line 105 is exercised. This branch is the one standalone 
services take by default, because `spark.shuffle.service.db.enabled` defaults 
to `true`, and passing `false` here again would keep every test green while 
silently disabling the check for operators who enable the flag with the default 
database setting. A flag-on test that leaves the database enabled would cover 
it.
   
   **Verification:**
   - **Regression:** With the database enabled and the flag on, the 
application's own leaf is accepted and a local dir outside the app-scoped 
layout is rejected; passing false in the database branch makes this coverage 
fail.



##########
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/LocalDirValidator.java:
##########
@@ -36,10 +38,12 @@
  * operates on validated paths.
  *
  * Each entry must canonicalize to a path contained under one of the 
configured roots (YARN passes
- * {@code yarn.nodemanager.local-dirs}; standalone passes the configured local 
directories) and,
- * when app scoping is required, within the registering application's own 
directory (the
- * {@code appId} must appear as a path segment). When no roots are configured 
there is nothing to
- * contain the entries against and they are accepted. An empty array is always 
allowed.
+ * {@code yarn.nodemanager.local-dirs}; standalone passes the configured local 
directories). When
+ * app scoping is required, YARN entries must be below {@code 
appcache/<appId>}, while standalone
+ * entries must have the exact form
+ * {@code 
spark-&#42;/executor-&#42;/&lt;url-encoded-appId&gt;[/blockmgr-&#42;]} below 
that root.

Review Comment:
   **Nit (P3):** `{@code}` shows its content literally, without interpreting 
HTML entities, so rendered Javadoc and IDE hovers display 
`spark-&#42;/executor-&#42;/&lt;url-encoded-appId&gt;[/blockmgr-&#42;]` instead 
of the layout. The entities are needed to keep `*/` from closing the comment, 
but `<code>...</code>` with the same entities, or separate `{@code}` tags that 
never contain `*/`, keeps that protection and renders as intended.
   
   **Verification:**
   - **Inspection:** The class Javadoc contains no HTML entity inside {@code} 
and no '*/' sequence before the comment ends.
   - **Compile:** The network-shuffle module and its Javadoc build without 
errors.



##########
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/LocalDirValidator.java:
##########
@@ -80,15 +84,29 @@ private void validateContained(String localDir, String 
appId) {
         "localDirs entry is not under any of the service's local directories: 
" + localDir);
     }
     if (requireAppScopedLocalDirs &&
-        (appId == null || appId.isEmpty() || !pathContainsSegment(canonical, 
appId))) {
+        (appId == null || appId.isEmpty() || 
allowedLocalDirRoots.stream().noneMatch(
+          root -> isStandaloneAppDir(root, canonical, appId) ||

Review Comment:
   **Nit (P3):** This `noneMatch` accepts an entry when either 
`isStandaloneAppDir` or `isYarnAppDir` holds, and the validator only receives a 
boolean, so both services apply both layouts. With 
`spark.shuffle.service.requireAppScopedLocalDirs=true` and 
`spark.local.dir=/data`, the standalone service accepts 
`/data/foo/appcache/<appId>/x/y`: the standalone check fails on depth, but the 
YARN check matches `appcache/<appId>`. The new config doc and 
`docs/spark-standalone.md` say only `spark-*/executor-*/<url-encoded-appId>`, 
optionally followed by `blockmgr-*`, is accepted. In the other direction, a 
NodeManager accepts `<nm-dir>/spark-a/executor-b/<appId>/blockmgr-c`, which the 
class Javadoc rules out by requiring YARN entries to be below 
`appcache/<appId>`. Another application's leaf and the legacy 
`spark-*/executor-*/blockmgr-*` dirs are still rejected, so in practice the 
check is weaker than its documentation only for paths that standalone Workers 
never create.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58619#issuecomment-5840449059).
   
   See **Shared repair plan 1** in the review body.



##########
core/src/test/scala/org/apache/spark/deploy/ExternalShuffleServiceLocalDirsSuite.scala:
##########
@@ -49,4 +54,100 @@ class ExternalShuffleServiceLocalDirsSuite extends 
SparkFunSuite {
       Utils.deleteRecursively(contained)
     }
   }
+
+  test("requireAppScopedLocalDirs restricts localDirs to the registering app's 
directory") {
+    val sparkConf = new SparkConf()
+      .set(SHUFFLE_SERVICE_ENABLED, true)
+      .set(SHUFFLE_SERVICE_DB_ENABLED, false)
+      .set(SHUFFLE_SERVICE_REQUIRE_APP_SCOPED_LOCAL_DIRS, true)
+      .set("spark.local.dir", System.getProperty("java.io.tmpdir"))
+    val service = new ExternalShuffleService(sparkConf, new 
SecurityManager(sparkConf))
+    val handler = service.getBlockHandler
+
+    val root = new File(Utils.getConfiguredLocalDirs(sparkConf).head)
+    val appId = s"app-${UUID.randomUUID()}"
+    val otherAppId = s"app-${UUID.randomUUID()}"
+    // The layout the Worker creates: <root>/spark-*/executor-*/<appId>.
+    val workerRoot = new File(root, s"spark-${UUID.randomUUID()}")
+    val executorRoot = new File(workerRoot, s"executor-${UUID.randomUUID()}")
+    val appScoped = new File(executorRoot, appId)
+    val otherAppScoped = new File(executorRoot, otherAppId)
+    // The pre-upgrade Worker layout: directly under a root, no appId segment.
+    val unscoped = new File(root, s"blockmgr-${UUID.randomUUID()}")
+    assert(appScoped.mkdirs() && otherAppScoped.mkdirs() && unscoped.mkdirs())
+    try {
+      // A localDir inside the registering application's own directory is 
accepted.
+      handler.validateLocalDirs(Array(appScoped.getAbsolutePath), appId)
+
+      // A directory under a different application id is rejected even though 
it is contained
+      // under a configured root.
+      intercept[IllegalArgumentException] {
+        handler.validateLocalDirs(Array(otherAppScoped.getAbsolutePath), appId)
+      }
+
+      // A contained directory without the appId as a path segment (what a 
Worker without
+      // the per-app layout would report) is rejected.
+      intercept[IllegalArgumentException] {
+        handler.validateLocalDirs(Array(unscoped.getAbsolutePath), appId)
+      }
+
+      // Root containment is still enforced with app scoping on.
+      intercept[IllegalArgumentException] {
+        handler.validateLocalDirs(Array("/etc"), appId)
+      }
+    } finally {
+      Utils.deleteRecursively(workerRoot)
+      Utils.deleteRecursively(unscoped)
+    }
+  }
+
+  test("local-cluster executors register app-scoped local dirs end to end") {
+    val root = Utils.createTempDir(namePrefix = "ess-e2e-root")
+    val serviceConf = new SparkConf()
+      .set(SHUFFLE_SERVICE_ENABLED, true)
+      .set(SHUFFLE_SERVICE_DB_ENABLED, false)
+      .set(SHUFFLE_SERVICE_REQUIRE_APP_SCOPED_LOCAL_DIRS, true)
+      .set(SHUFFLE_SERVICE_PORT, 0)
+      .set("spark.local.dir", root.getAbsolutePath)
+    val service = new ExternalShuffleService(serviceConf, new 
SecurityManager(serviceConf))
+    var sc: SparkContext = null
+    try {
+      service.start()
+      val conf = new SparkConf()
+        .setAppName("app-scoped-local-dirs-e2e")
+        .setMaster("local-cluster[2,1,1024]")
+        .set(SHUFFLE_SERVICE_ENABLED, true)
+        .set(SHUFFLE_SERVICE_PORT, service.boundPort)
+        .set("spark.local.dir", root.getAbsolutePath)
+      sc = new SparkContext(conf)
+      val appId = sc.applicationId
+      // One core per worker, so the application's two executors land on 
different Workers.
+      // If the shuffle service rejected the registrations, the executors 
would never come up.

Review Comment:
   **Nit (P3):** `TestUtils.waitUntilExecutorsUp` counts executors in the 
status store, and the driver adds an executor there as soon as it registers 
with the driver (`CoarseGrainedSchedulerBackend`, on `RegisterExecutor`), 
before `BlockManager.initialize` registers with the external shuffle service. 
Executors whose registration is rejected can therefore show up here before they 
exit; the test would still fail, but through the `groupByKey` job. Saying that 
a rejected registration makes the executors exit after they register with the 
driver, so the shuffle job fails, would match the startup order.
   
   **Verification:**
   - **Inspection:** The comment matches the startup order: the driver adds an 
executor before that executor registers with the shuffle service.



##########
core/src/main/scala/org/apache/spark/deploy/worker/Worker.scala:
##########
@@ -767,6 +751,32 @@ private[deploy] class Worker(
     registerWithMaster()
   }
 
+  private[deploy] def createExecutorLocalDirs(appId: String): Seq[String] = {
+    val localRootDirs = Utils.getOrCreateLocalRootDirs(conf)
+    val dirs = localRootDirs.flatMap { dir =>
+      try {
+        // Keep the random root and executor directories (and their 
shutdown-hook cleanup),
+        // adding a URL-encoded app id leaf for the shuffle service's 
app-scope check.
+        val executorDir = Utils.createDirectory(dir, namePrefix = "executor")
+        val appDir = new File(executorDir, URLEncoder.encode(appId, 
StandardCharsets.UTF_8))
+        if (!Utils.createDirectory(appDir)) {

Review Comment:
   **Nit (P3):** If creating the application leaf fails here (for example a 
quota or inode limit is hit between the two directory creations), the 
`IOException` is caught below and this root is skipped, but the 
`executor-<uuid>` directory created on line 760 is neither deleted nor 
recorded. Application cleanup only reaches executor directories through 
recorded leaves, so these empty directories stay under `spark-*` until the 
Worker exits, and each retried launch leaves another one per failing root. 
Before this PR nothing could fail after the executor directory was created. 
Deleting `executorDir` before skipping the root would close this.
   
   **Verification:**
   - **Regression:** When the application leaf cannot be created, for example 
for an application ID of a few hundred characters whose URL-encoded leaf 
exceeds the 255-byte file-name limit of common Linux filesystems, 
createExecutorLocalDirs fails and leaves no executor-* directory behind under 
any local root.



##########
core/src/test/scala/org/apache/spark/deploy/ExternalShuffleServiceLocalDirsSuite.scala:
##########
@@ -49,4 +54,100 @@ class ExternalShuffleServiceLocalDirsSuite extends 
SparkFunSuite {
       Utils.deleteRecursively(contained)
     }
   }
+
+  test("requireAppScopedLocalDirs restricts localDirs to the registering app's 
directory") {
+    val sparkConf = new SparkConf()
+      .set(SHUFFLE_SERVICE_ENABLED, true)
+      .set(SHUFFLE_SERVICE_DB_ENABLED, false)
+      .set(SHUFFLE_SERVICE_REQUIRE_APP_SCOPED_LOCAL_DIRS, true)
+      .set("spark.local.dir", System.getProperty("java.io.tmpdir"))
+    val service = new ExternalShuffleService(sparkConf, new 
SecurityManager(sparkConf))
+    val handler = service.getBlockHandler
+
+    val root = new File(Utils.getConfiguredLocalDirs(sparkConf).head)
+    val appId = s"app-${UUID.randomUUID()}"
+    val otherAppId = s"app-${UUID.randomUUID()}"
+    // The layout the Worker creates: <root>/spark-*/executor-*/<appId>.
+    val workerRoot = new File(root, s"spark-${UUID.randomUUID()}")
+    val executorRoot = new File(workerRoot, s"executor-${UUID.randomUUID()}")
+    val appScoped = new File(executorRoot, appId)
+    val otherAppScoped = new File(executorRoot, otherAppId)
+    // The pre-upgrade Worker layout: directly under a root, no appId segment.
+    val unscoped = new File(root, s"blockmgr-${UUID.randomUUID()}")

Review Comment:
   **Nit (P3):** Workers before this PR handed executors 
`<root>/spark-*/executor-*`, so their registrations look like 
`<root>/spark-*/executor-*/blockmgr-*`, not `<root>/blockmgr-*`. This fixture 
is rejected by its depth alone, so a rule change that accepted `blockmgr-*` in 
the application-leaf position (the real legacy shape, with three segments like 
the new leaf) would leave the test green, and the comment above misdescribes 
the legacy layout. The `/etc` case below has the same problem: it fails both 
shape checks as well as containment, so a change that skipped containment while 
app scoping is on would not be caught, even though the YARN shape check would 
then accept an out-of-root path such as `/var/x/appcache/<appId>`. Registering 
a real `spark-*/executor-*/blockmgr-*` dir and an out-of-root path that holds 
`appcache/<appId>` would make both cases fail for the behavior they name.
   
   **Verification:**
   - **Regression:** If a blockmgr-* entry in the application-leaf position 
were accepted, the pre-upgrade case would fail.
   - **Regression:** With app scoping on, an out-of-root entry that matches a 
layout shape is rejected, and the case fails if neither root containment nor 
containing-root matching rejects it.



##########
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/LocalDirValidator.java:
##########
@@ -80,15 +84,29 @@ private void validateContained(String localDir, String 
appId) {
         "localDirs entry is not under any of the service's local directories: 
" + localDir);
     }
     if (requireAppScopedLocalDirs &&
-        (appId == null || appId.isEmpty() || !pathContainsSegment(canonical, 
appId))) {
+        (appId == null || appId.isEmpty() || 
allowedLocalDirRoots.stream().noneMatch(
+          root -> isStandaloneAppDir(root, canonical, appId) ||
+            isYarnAppDir(root, canonical, appId)))) {
       throw new IllegalArgumentException(
         "localDirs entry is not within application " + appId + "'s directory: 
" + localDir);
     }
   }
 
-  private static boolean pathContainsSegment(Path path, String segment) {
-    for (Path part : path) {
-      if (part.toString().equals(segment)) {
+  private static boolean isStandaloneAppDir(Path root, Path path, String 
appId) {
+    Path relative = root.relativize(path);
+    int count = relative.getNameCount();
+    return (count == 3 || count == 4) &&
+      relative.getName(0).toString().startsWith("spark-") &&
+      relative.getName(1).toString().startsWith("executor-") &&
+      relative.getName(2).toString().equals(URLEncoder.encode(appId, 
StandardCharsets.UTF_8)) &&
+      (count == 3 || relative.getName(3).toString().startsWith("blockmgr-"));
+  }
+
+  private static boolean isYarnAppDir(Path root, Path path, String appId) {
+    Path relative = root.relativize(path);
+    for (int i = 0; i + 1 < relative.getNameCount(); i++) {
+      if (relative.getName(i).toString().equals("appcache") &&

Review Comment:
   **Nit (P3):** `YarnShuffleService` always enables app scoping, so this loop 
is now the live YARN rule, but no test distinguishes it from the any-segment 
rule it replaces. `acceptsYarnAppScopedDir` registers app0's own directory, and 
`rejectsAnotherApplicationsDir` uses `usercache/u/appcache/app1/blockmgr-x`, 
which contains no `app0` segment, so both rules give the same answers there; 
`YarnShuffleServiceSuite` only registers own-application paths. Reverting to a 
plain segment search would keep everything green and again accept 
`<nm-dir>/usercache/u/appcache/app1/blockmgr-x/app0` for app0, a path inside 
another application's directory.
   
   See **Shared repair plan 1** in the review body.



##########
core/src/test/scala/org/apache/spark/deploy/worker/WorkerSuite.scala:
##########
@@ -443,4 +443,44 @@ class WorkerSuite extends SparkFunSuite with Matchers with 
BeforeAndAfter with P
     assert(getHeartbeatTask(worker) == heartbeatTask)
     assert(getWorkDirCleanupTask(worker) == workDirCleanupTask)
   }
+
+  test("app cleanup uses the LaunchExecutor local dir layout") {
+    val externalShuffleServiceSupplier = new Supplier[ExternalShuffleService] {
+      override def get: ExternalShuffleService = shuffleService
+    }
+    val worker = makeWorker(new SparkConf(), externalShuffleServiceSupplier)
+    val appId = "app:20260922000000/0001"
+    val appDir = new File(worker.createExecutorLocalDirs(appId).head)
+    val executorDir = appDir.getParentFile
+    val secondAppId = "app-empty-parent"
+    val secondAppDir = new 
File(worker.createExecutorLocalDirs(secondAppId).head)
+    val secondExecutorDir = secondAppDir.getParentFile
+    try {
+      // Exercise the production helper rather than hand-building the 
directory layout.
+      assert(appDir.getName === "app%3A20260922000000%2F0001")
+      assert(executorDir.getName.startsWith("executor-"))
+      assert(executorDir.getParentFile.getName.startsWith("spark-"))
+      val sibling = new File(executorDir, "sibling")
+      assert(sibling.mkdir())
+      worker.appDirectories(appId) = Seq(appDir.getAbsolutePath)
+      worker.finishedApps += appId
+      worker.handleExecutorStateChanged(
+        ExecutorStateChanged(appId, 0, ExecutorState.EXITED, None, None))
+      eventually(timeout(1.second), interval(10.milliseconds)) {
+        assert(!appDir.exists())
+      }
+      assert(sibling.exists())

Review Comment:
   **Nit (P3):** The `eventually` above only waits for `appDir` to disappear, 
but the cleanup task deletes the leaf first and then calls 
`appDir.getParentFile.delete()` (`Worker.scala` lines 789-793), so this 
one-shot check can run before the parent step. If cleanup regressed to deleting 
the executor directory recursively after the leaf, the test could still pass by 
timing. Both applications' cleanups run in order on the single 
`worker-cleanup-thread`, so checking `sibling.exists()` again after the second 
application's `eventually` would make the assertion deterministic.
   
   **Verification:**
   - **Regression:** If cleanup recursively deleted the executor directory 
after the leaf, the test would fail deterministically instead of depending on 
timing.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to