[llvm] [lit] Migrate lit to ProcessPoolExecutor (PR #202681)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 11 09:51:02 PDT 2026


https://github.com/prasoon054 updated https://github.com/llvm/llvm-project/pull/202681

>From ce7b7c42acfd60c1ef3ff2eec0566679855c465d Mon Sep 17 00:00:00 2001
From: Prasoon Kumar <prasoonkumar054 at gmail.com>
Date: Tue, 9 Jun 2026 20:13:17 +0530
Subject: [PATCH] [lit] Migrate lit to ProcessPoolExecutor

This patch replaces multiprocessing.Pool with concurrent.futures.ProcessPoolExecutor in lit's core test execution to address bugs related to stale per-iteration timeouts and submission index result coupling.

Signed-off-by: Prasoon Kumar <prasoonkumar054 at gmail.com>
---
 llvm/utils/lit/lit/main.py |   2 +
 llvm/utils/lit/lit/run.py  | 118 +++++++++++++++++++++++--------------
 2 files changed, 75 insertions(+), 45 deletions(-)

diff --git a/llvm/utils/lit/lit/main.py b/llvm/utils/lit/lit/main.py
index a3bd153040a69..54ae2fceb7775 100755
--- a/llvm/utils/lit/lit/main.py
+++ b/llvm/utils/lit/lit/main.py
@@ -278,6 +278,8 @@ def run_tests(tests, lit_config, opts, discovered_tests):
         error = "warning: reached maximum number of test failures"
     except lit.run.TimeoutError:
         error = "warning: reached timeout"
+    except lit.run.WorkerCrashError as e:
+        lit_config.error(f"a worker process crashed: {e}")
 
     display.clear(interrupted)
     if error:
diff --git a/llvm/utils/lit/lit/run.py b/llvm/utils/lit/lit/run.py
index 6c6d464a6881a..1df1281891d43 100644
--- a/llvm/utils/lit/lit/run.py
+++ b/llvm/utils/lit/lit/run.py
@@ -2,6 +2,10 @@
 import os
 import platform
 import time
+from concurrent.futures import ProcessPoolExecutor, as_completed
+from concurrent.futures import TimeoutError as FuturesTimeoutError
+from concurrent.futures.process import BrokenProcessPool
+import concurrent.futures.process
 
 import lit.Test
 import lit.util
@@ -16,6 +20,7 @@
 def _ceilDiv(a, b):
     return (a + b - 1) // b
 
+
 class MaxFailuresError(Exception):
     pass
 
@@ -24,6 +29,12 @@ class TimeoutError(Exception):
     pass
 
 
+class WorkerCrashError(Exception):
+    """A worker process died abrupty (segfault, OOM-kill, abort) instead of returning a result."""
+
+    pass
+
+
 class Run:
     """A concrete, configured testing run."""
 
@@ -71,6 +82,38 @@ def execute(self):
                 if test.result is None:
                     test.setResult(skipped)
 
+    def _abort_executors(self, executors):
+        """SIGKILL all workers on abort (ctrl-C, --max-failures, --max-time,
+        worker crash). Pre-3.14 ProcessPoolExecutor has no force-stop."""
+        try:
+            # Killing worker processes can corrupt the executor's queues, which makes it
+            # unsafe for its atexit hooks to join their threads. Disable those hooks
+            # before terminating workers (a second ctrl-C should not bypass this cleanup).
+            # This applies to call-queue feeder threads and management threads.
+            # Otherwise, a thread blocked on a partially written pipe may require multiple
+            # ctrl-C to unblock.
+            # See: https://github.com/python/cpython/issues/125886
+            # These threads are daemonic on Python 3.8, so disabling them is harmless.
+            for ex in executors:
+                if hasattr(ex, "_call_queue") and ex._call_queue is not None:
+                    ex._call_queue.cancel_join_thread()
+            if hasattr(concurrent.futures.process, "_threads_wakeups"):
+                concurrent.futures.process._threads_wakeups.clear()
+            tree_kill_ok, _ = lit.util.killProcessAndChildrenIsSupported()
+            for ex in executors:
+                for pid, proc in list((ex._processes or {}).items()):
+                    if tree_kill_ok:
+                        lit.util.killProcessAndChildren(pid)
+                    else:
+                        proc.kill()
+            # Avoid cancel() and shutdown() as both can hang after queue corruption.
+            # cancel() is fixed in 3.10 / 3.11, but not in 3.8 / 3.9:
+            # https://github.com/python/cpython/issues/94440
+            # TODO: re-enable cancel() on >=3.11; use kill_workers() on >=3.14:
+            # https://github.com/python/cpython/issues/128041
+        except Exception:
+            pass
+
     def _execute(self, deadline):
         self._increase_process_limit()
 
@@ -103,59 +146,44 @@ def _execute(self, deadline):
                 % (num_pools, self.workers, workers_per_pool_list)
             )
 
-        # Create multiple pools
-        pools = []
-        for pool_size in workers_per_pool_list:
-            pool = multiprocessing.Pool(
-                pool_size, lit.worker.initialize, (self.lit_config, semaphores)
+        executors = [
+            ProcessPoolExecutor(
+                max_workers=pool_size,
+                initializer=lit.worker.initialize,
+                initargs=(self.lit_config, semaphores),
             )
-            pools.append(pool)
-
-        # Distribute tests across pools
-        tests_per_pool = _ceilDiv(len(self.tests), num_pools)
-        async_results = []
-
-        for pool_idx, pool in enumerate(pools):
-            start_idx = pool_idx * tests_per_pool
-            end_idx = min(start_idx + tests_per_pool, len(self.tests))
-            for test in self.tests[start_idx:end_idx]:
-                ar = pool.apply_async(
-                    lit.worker.execute, args=[test], callback=self.progress_callback
-                )
-                async_results.append(ar)
+            for pool_size in workers_per_pool_list
+        ]
 
-        # Close all pools
-        for pool in pools:
-            pool.close()
+        future_to_test = {}
+        for i, test in enumerate(self.tests):
+            ex = executors[i % len(executors)]
+            future_to_test[ex.submit(lit.worker.execute, test)] = test
 
         try:
-            self._wait_for(async_results, deadline)
-        except:
-            # Terminate all pools on exception
-            for pool in pools:
-                pool.terminate()
+            self._wait_for(future_to_test, deadline)
+        except BaseException:
+            self._abort_executors(executors)
             raise
-        finally:
-            # Join all pools
-            for pool in pools:
-                pool.join()
-
-    def _wait_for(self, async_results, deadline):
-        timeout = deadline - time.time()
-        idx = 0
-        while len(async_results) > 0:
-            try:
-                ar = async_results.pop(0)
-                test = ar.get(timeout)
-            except multiprocessing.TimeoutError:
-                raise TimeoutError()
-            else:
-                self._update_test(self.tests[idx], test)
-                if test.isFailure():
+        else:
+            for ex in executors:
+                ex.shutdown(wait=True)
+
+    def _wait_for(self, future_to_test, deadline):
+        try:
+            for future in as_completed(future_to_test, timeout=deadline - time.time()):
+                remote_test = future.result()
+                local_test = future_to_test[future]
+                self._update_test(local_test, remote_test)
+                self.progress_callback(remote_test)
+                if remote_test.isFailure():
                     self.failures += 1
                     if self.failures == self.max_failures:
                         raise MaxFailuresError()
-            idx += 1
+        except FuturesTimeoutError:
+            raise TimeoutError()
+        except BrokenProcessPool as e:
+            raise WorkerCrashError(str(e))
 
     # Update local test object "in place" from remote test object.  This
     # ensures that the original test object which is used for printing test



More information about the llvm-commits mailing list