[9.3.2] Fix linux-sandbox actions being killed prematurely when using virtual… (#32342)

… threads (https://github.com/bazelbuild/bazel/pull/31017)

This is a version of https://github.com/bazelbuild/bazel/pull/29007
where the added test should pass for MacOS. The only change in this PR
vs that PR is the location of `true` varies based on OS.

I think this should work, but I don't have a Mac handy to test this. If
anyone has a Mac and can run `bazel test
//src/test/java/com/google/devtools/build/lib/shell:JavaSubprocessFactoryTest`
then that'd be much appreciated.

I forgot to account for the fact that MacOS places `true` at
`/usr/bin/true` instead of `/bin/true`. This was the error during
postsubmit from that test on MacOS:

```
1) createFromVirtualThreadForksOnPlatformThread(com.google.devtools.build.lib.shell.JavaSubprocessFactoryTest)
java.lang.AssertionError: Error running subprocess from virtual thread
	at com.google.devtools.build.lib.shell.JavaSubprocessFactoryTest.createFromVirtualThreadForksOnPlatformThread(JavaSubprocessFactoryTest.java:87)
	... 23 trimmed
Caused by: java.io.IOException: Cannot run program "/bin/true": Exec failed, error: 2 (No such file or directory)
```

Closes #31017.

PiperOrigin-RevId: 977850652
Change-Id: Ideba552c30cb0804c2e8722b31cbaf12c9beb077

<!--
Thank you for contributing to Bazel!
Please read the contribution guidelines: https://bazel.build/contribute
and guidelines for AI-assisted contributions:
https://bazel.build/contribute/ai-assisted-contributions
-->

### Description
<!--
Please provide a brief summary of the changes in this PR.
-->

### Motivation
<!--
Why is this change important? Does it fix a specific bug or add a new
feature?
If this PR fixes an existing issue, please link it here (e.g. "Fixes
#1234").
-->

### Build API Changes
<!--
Does this PR affect the Build API? (e.g. Starlark API, providers,
command-line flags, native rules)
If yes, please answer the following:
1. Has this been discussed in a design doc or issue? (Please link it)
2. Is the change backward compatible?
3. If it's a breaking change, what is the migration plan?
-->

No

### Checklist

- [ ] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (if applicable).

### Release Notes

<!--
If this is a new feature, please add 'RELNOTES[NEW]: <description>'
here.
If this is a breaking change, please add 'RELNOTES[INC]: <reason>' here.
If this change should be mentioned in release notes, please add
'RELNOTES: <reason>' here.
-->

RELNOTES: None

Commit
https://github.com/bazelbuild/bazel/commit/feafed591d08ae69af0f92d35b7b2757ada1e46e

Co-authored-by: James Judd <james@lab-y.com>
diff --git a/src/main/java/com/google/devtools/build/lib/shell/JavaSubprocessFactory.java b/src/main/java/com/google/devtools/build/lib/shell/JavaSubprocessFactory.java
index d81235d..09a96bf 100644
--- a/src/main/java/com/google/devtools/build/lib/shell/JavaSubprocessFactory.java
+++ b/src/main/java/com/google/devtools/build/lib/shell/JavaSubprocessFactory.java
@@ -14,7 +14,10 @@
 
 package com.google.devtools.build.lib.shell;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Throwables;
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Uninterruptibles;
 import com.google.devtools.build.lib.shell.SubprocessBuilder.StreamAction;
 import com.google.devtools.build.lib.util.StringEncoding;
 import java.io.File;
@@ -22,6 +25,10 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.lang.ProcessBuilder.Redirect;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.ReentrantLock;
@@ -113,11 +120,31 @@
     }
   }
 
-  public static final JavaSubprocessFactory INSTANCE = new JavaSubprocessFactory();
-  private final ReentrantLock lock = new ReentrantLock();
+  // Subprocesses fork from this platform thread to ensure the subprocess's parent is long lived,
+  // which prevents actions from being killed erroneously. See the doc comment on
+  // startOnPlatformThread for more details.
+  @VisibleForTesting
+  static final ExecutorService DEFAULT_FORK_EXECUTOR =
+      Executors.newSingleThreadExecutor(
+          runnable -> {
+            Thread thread = new Thread(runnable, "subprocess-fork");
+            thread.setDaemon(true);
+            return thread;
+          });
 
-  private JavaSubprocessFactory() {
-    // We are a singleton
+  private final ReentrantLock lock = new ReentrantLock();
+  private final ExecutorService forkExecutor;
+
+  public static final JavaSubprocessFactory INSTANCE =
+      new JavaSubprocessFactory(DEFAULT_FORK_EXECUTOR);
+
+  private JavaSubprocessFactory(ExecutorService forkExecutor) {
+    this.forkExecutor = forkExecutor;
+  }
+
+  @VisibleForTesting
+  static JavaSubprocessFactory createForTesting(ExecutorService forkExecutor) {
+    return new JavaSubprocessFactory(forkExecutor);
   }
 
   // since we are a singleton, we represent an ideal global lock for
@@ -141,7 +168,7 @@
   private Process start(ProcessBuilder builder) throws IOException {
     lock.lock();
     try {
-      return builder.start();
+      return startOnPlatformThread(builder);
     } catch (IOException e) {
       if (e.getMessage().contains("Failed to exec spawn helper")) {
         // Detect permanent failures due to an upgrade of the underlying JDK version,
@@ -157,6 +184,31 @@
     }
   }
 
+  /**
+   * Starts a subprocess by forking from a long-lived platform thread, which prevents the parent
+   * thread from being killed when using virtual threads.
+   *
+   * <p>A virtual thread forks from its carrier thread. The carrier thread is detached while the
+   * virtual thread waits for the forked process to complete. If there isn't other work for the
+   * carrier thread to do, then it is idle and can be killed due to inactivity. The parent carrier
+   * thread being killed causes the linux-sandbox to die because it self destructs when its parent
+   * dies.
+   *
+   * <p>The default virtual thread scheduler uses a {@link java.util.concurrent.ForkJoinPool} for
+   * its carrier threads with an idle TTL of 30 seconds. Without a long-lived platform thread as the
+   * parent, builds can fail unexpectedly when actions take longer than 30 seconds.
+   */
+  private Process startOnPlatformThread(ProcessBuilder builder) throws IOException {
+    Future<Process> future = forkExecutor.submit(builder::start);
+    try {
+      return Uninterruptibles.getUninterruptibly(future);
+    } catch (ExecutionException e) {
+      Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
+      Throwables.throwIfUnchecked(e.getCause());
+      throw new IllegalStateException("Unexpected error starting subprocess", e.getCause());
+    }
+  }
+
   @Override
   public Subprocess create(SubprocessBuilder params) throws IOException {
     ProcessBuilder builder = new ProcessBuilder();
diff --git a/src/test/java/com/google/devtools/build/lib/shell/BUILD b/src/test/java/com/google/devtools/build/lib/shell/BUILD
index 085d87d..fdc5d9a 100644
--- a/src/test/java/com/google/devtools/build/lib/shell/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/shell/BUILD
@@ -282,6 +282,23 @@
     ],
 )
 
+java_test(
+    name = "JavaSubprocessFactoryTest",
+    srcs = ["JavaSubprocessFactoryTest.java"],
+    tags = [
+        "no_windows",
+        "shell",
+    ],
+    deps = [
+        "//src/main/java/com/google/devtools/build/lib/shell",
+        "//src/main/java/com/google/devtools/build/lib/util:os",
+        "//third_party:guava",
+        "//third_party:junit4",
+        "//third_party:mockito",
+        "//third_party:truth",
+    ],
+)
+
 cc_binary(
     name = "killmyself",
     srcs = ["killmyself.cc"],
diff --git a/src/test/java/com/google/devtools/build/lib/shell/JavaSubprocessFactoryTest.java b/src/test/java/com/google/devtools/build/lib/shell/JavaSubprocessFactoryTest.java
new file mode 100644
index 0000000..8de4ea2
--- /dev/null
+++ b/src/test/java/com/google/devtools/build/lib/shell/JavaSubprocessFactoryTest.java
@@ -0,0 +1,102 @@
+// Copyright 2026 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.shell;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.util.OS;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicReference;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.mockito.ArgumentMatchers;
+
+@RunWith(JUnit4.class)
+public class JavaSubprocessFactoryTest {
+
+  @Test
+  public void createFromVirtualThreadForksOnPlatformThread() throws Exception {
+    ExecutorService mockExecutorService = mock(ExecutorService.class);
+    AtomicReference<Thread> forkThread = new AtomicReference<>();
+
+    // Observe the thread executing the submit function, so we can tell if the fork happens from
+    // the correct thread. We still call the real submit function to actually run the callable.
+    doAnswer(
+            invocation -> {
+              Callable<?> original = invocation.getArgument(0);
+              return JavaSubprocessFactory.DEFAULT_FORK_EXECUTOR.submit(
+                  () -> {
+                    forkThread.set(Thread.currentThread());
+                    return original.call();
+                  });
+            })
+        .when(mockExecutorService)
+        .submit(ArgumentMatchers.<Callable<Process>>any());
+
+    JavaSubprocessFactory subprocessFactory =
+        JavaSubprocessFactory.createForTesting(mockExecutorService);
+
+    AtomicReference<Boolean> callerWasVirtual = new AtomicReference<>();
+    AtomicReference<Integer> exitCode = new AtomicReference<>();
+    AtomicReference<Throwable> error = new AtomicReference<>();
+    CountDownLatch done = new CountDownLatch(1);
+
+    // Create and execute a subprocess on a virtual thread
+    Thread.ofVirtual()
+        .name("test-virtual")
+        .start(
+            () -> {
+              try {
+                SubprocessBuilder subprocessBuilder =
+                    new SubprocessBuilder(ImmutableMap.of(), subprocessFactory);
+                subprocessBuilder.setArgv(
+                    ImmutableList.of(OS.getCurrent() == OS.DARWIN ? "/usr/bin/true" : "/bin/true"));
+
+                Subprocess subprocess = subprocessBuilder.start();
+                callerWasVirtual.set(Thread.currentThread().isVirtual());
+                subprocess.waitFor();
+                exitCode.set(subprocess.exitValue());
+                subprocess.close();
+              } catch (Exception e) {
+                error.set(e);
+              } finally {
+                done.countDown();
+              }
+            });
+
+    done.await();
+    if (error.get() != null) {
+      throw new AssertionError("Error running subprocess from virtual thread", error.get());
+    }
+
+    // The subprocess creation happened successfully on a virtual thread
+    assertThat(callerWasVirtual.get()).isTrue();
+    assertThat(exitCode.get()).isEqualTo(0);
+
+    // The fork was routed through the correct executor and ran on the right thread
+    verify(mockExecutorService).submit(ArgumentMatchers.<Callable<Process>>any());
+    assertThat(forkThread.get().getName()).isEqualTo("subprocess-fork");
+    assertThat(forkThread.get().isVirtual()).isFalse();
+    assertThat(forkThread.get().isDaemon()).isTrue();
+  }
+}