From 3720cf72ca0a21f0b638e8daf00a6fe56fc9f65c Mon Sep 17 00:00:00 2001 From: Jan Janssen Date: Tue, 1 Dec 2026 14:57:22 -0500 Subject: [PATCH] [Feature] Restart cancelled block allocation workers in SlurmClusterExecutor Add the restart_limit parameter to the SlurmClusterExecutor for block_allocation=True. When a worker job is cancelled by the queuing system, for example on a preemptible overflow queue, the interrupted task is returned to the queue and a new worker job is submitted, until the restart limit is reached. Fix a hang when a worker is terminated while it is idle: the zmq.PAIR socket blocked on send() with no connected peer. The SocketInterface now waits for the socket to become writable while checking that the client process is still alive, and reports an ExecutorlibSocketError otherwise, which triggers the existing restart logic. Extend the TestClusterExecutor with block_allocation and restart_limit to test the restart of workers locally without a queuing system. Closes #1128 (functionality part) Co-Authored-By: Claude Opus 5.5 --- src/executorlib/executor/single.py | 30 ++++- src/executorlib/executor/slurm.py | 14 +++ .../standalone/interactive/communication.py | 13 +- .../interactive/spawner_pysqa.py | 2 + .../executor/test_api_block_allocation.py | 112 ++++++++++++++++++ tests/unit/executor/test_slurm_cluster.py | 8 ++ 6 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 tests/unit/executor/test_api_block_allocation.py diff --git a/src/executorlib/executor/single.py b/src/executorlib/executor/single.py index aa3cbed7..f2863170 100644 --- a/src/executorlib/executor/single.py +++ b/src/executorlib/executor/single.py @@ -277,6 +277,9 @@ class TestClusterExecutor(BaseExecutor): to be defined on the executor, rather than during the submission of the individual function. init_function (None): optional function to preset arguments for functions which are submitted later + restart_limit (int): The maximum number of restarting worker processes. Only available with + block_allocation=True. Mirrors the restart_limit of the SlurmClusterExecutor, so restarting + workers which were cancelled by the queuing system can be tested locally. Defaults to 0. disable_dependencies (boolean): Disable resolving future objects during the submission. refresh_rate (float): Set the refresh rate in seconds, how frequently the input queue is checked. plot_dependency_graph (bool): Plot the dependencies of multiple future objects without executing them. For @@ -317,6 +320,7 @@ def __init__( hostname_localhost: bool | None = None, block_allocation: bool = False, init_function: Callable | None = None, + restart_limit: int = 0, disable_dependencies: bool = False, refresh_rate: float = 0.01, plot_dependency_graph: bool = False, @@ -368,6 +372,9 @@ def __init__( resources have to be defined on the executor, rather than during the submission of the individual function. init_function (None): optional function to preset arguments for functions which are submitted later + restart_limit (int): The maximum number of restarting worker processes. Only available with + block_allocation=True. Mirrors the restart_limit of the SlurmClusterExecutor, so restarting + workers which were cancelled by the queuing system can be tested locally. Defaults to 0. disable_dependencies (boolean): Disable resolving future objects during the submission. refresh_rate (float): Set the refresh rate in seconds, how frequently the input queue is checked. plot_dependency_graph (bool): Plot the dependencies of multiple future objects without executing them. For @@ -392,7 +399,27 @@ def __init__( resource_dict.update( {k: v for k, v in default_resource_dict.items() if k not in resource_dict} ) - if not plot_dependency_graph: + check_restart_limit( + restart_limit=restart_limit, block_allocation=block_allocation + ) + if not plot_dependency_graph and block_allocation: + # Mirror the block allocation mode of the SlurmClusterExecutor: long-lived workers which are restarted up + # to restart_limit times, started as local processes rather than as jobs of the queuing system. + super().__init__( + executor=create_single_node_executor( + max_workers=max_workers, + cache_directory=cache_directory, + max_cores=max_cores, + executor_kwargs=resource_dict, + hostname_localhost=hostname_localhost, + block_allocation=block_allocation, + init_function=init_function, + log_obj_size=log_obj_size, + validator=validate_resource_dict_with_optional_keys, + restart_limit=restart_limit, + ) + ) + elif not plot_dependency_graph: from executorlib.task_scheduler.file.spawner_subprocess import ( subprocess_execute, ) @@ -434,6 +461,7 @@ def __init__( block_allocation=block_allocation, init_function=init_function, log_obj_size=log_obj_size, + restart_limit=restart_limit, ), max_cores=max_cores, refresh_rate=refresh_rate, diff --git a/src/executorlib/executor/slurm.py b/src/executorlib/executor/slurm.py index 95bf941c..7b1fb407 100644 --- a/src/executorlib/executor/slurm.py +++ b/src/executorlib/executor/slurm.py @@ -72,6 +72,10 @@ class SlurmClusterExecutor(BaseExecutor): to be defined on the executor, rather than during the submission of the individual function. init_function (None): optional function to preset arguments for functions which are submitted later + restart_limit (int): The maximum number of restarting worker processes. Only available with + block_allocation=True. When a worker job is cancelled by the queuing system, for example + on a preemptible overflow queue, the interrupted task is returned to the queue and a new + worker job is submitted, until the restart limit is reached. Defaults to 0. disable_dependencies (boolean): Disable resolving future objects during the submission. refresh_rate (float): Set the refresh rate in seconds, how frequently the input queue is checked. plot_dependency_graph (bool): Plot the dependencies of multiple future objects without executing them. For @@ -114,6 +118,7 @@ def __init__( hostname_localhost: bool | None = None, block_allocation: bool = False, init_function: Callable | None = None, + restart_limit: int = 0, disable_dependencies: bool = False, refresh_rate: float = 0.01, plot_dependency_graph: bool = False, @@ -169,6 +174,10 @@ def __init__( resources have to be defined on the executor, rather than during the submission of the individual function. init_function (None): optional function to preset arguments for functions which are submitted later + restart_limit (int): The maximum number of restarting worker processes. Only available with + block_allocation=True. When a worker job is cancelled by the queuing system, for + example on a preemptible overflow queue, the interrupted task is returned to the queue + and a new worker job is submitted, until the restart limit is reached. Defaults to 0. disable_dependencies (boolean): Disable resolving future objects during the submission. refresh_rate (float): Set the refresh rate in seconds, how frequently the input queue is checked. plot_dependency_graph (bool): Plot the dependencies of multiple future objects without executing them. For @@ -195,6 +204,9 @@ def __init__( {k: v for k, v in default_resource_dict.items() if k not in resource_dict} ) check_log_obj_size(log_obj_size=log_obj_size) + check_restart_limit( + restart_limit=restart_limit, block_allocation=block_allocation + ) if not plot_dependency_graph: import pysqa # noqa @@ -216,6 +228,7 @@ def __init__( pysqa_config_directory=pysqa_config_directory, backend="slurm", validator=validate_resource_dict_with_optional_keys, + restart_limit=restart_limit, ), ) @@ -256,6 +269,7 @@ def __init__( hostname_localhost=hostname_localhost, block_allocation=block_allocation, init_function=init_function, + restart_limit=restart_limit, ), max_cores=max_cores, refresh_rate=refresh_rate, diff --git a/src/executorlib/standalone/interactive/communication.py b/src/executorlib/standalone/interactive/communication.py index 6e74119c..5ab60bc3 100644 --- a/src/executorlib/standalone/interactive/communication.py +++ b/src/executorlib/standalone/interactive/communication.py @@ -66,6 +66,14 @@ def send_dict(self, input_dict: dict): data = cloudpickle.dumps(input_dict) if self._logger is not None: self._logger.warning("Send dictionary of size: " + str(sys.getsizeof(data))) + # A zmq.PAIR socket blocks on send() while no peer is connected. When the connected client process was + # terminated, for example a worker job cancelled by the queuing system while waiting for the next task, a + # blocking send() would never return. So wait until the socket is ready to send, while checking the client. + while not self._socket.poll(self._time_out_ms, zmq.POLLOUT): + if not self._spawner.poll(): + raise ExecutorlibSocketError( + "SocketInterface crashed during execution." + ) self._socket.send(data) def receive_dict(self) -> dict: @@ -102,7 +110,10 @@ def send_and_receive_dict(self, input_dict: dict) -> dict: Returns: dict: dictionary with response received from the connected client """ - self.send_dict(input_dict=input_dict) + try: + self.send_dict(input_dict=input_dict) + except ExecutorlibSocketError as error: + return {"error": error} return self.receive_dict() def bind_to_random_port(self) -> int: diff --git a/src/executorlib/task_scheduler/interactive/spawner_pysqa.py b/src/executorlib/task_scheduler/interactive/spawner_pysqa.py index cb5984a3..d7f4118b 100644 --- a/src/executorlib/task_scheduler/interactive/spawner_pysqa.py +++ b/src/executorlib/task_scheduler/interactive/spawner_pysqa.py @@ -235,6 +235,7 @@ def create_pysqa_block_allocation_scheduler( pysqa_config_directory: str | None = None, backend: str | None = None, validator: Callable = validate_resource_dict, + restart_limit: int = 0, ): check_init_function_with_cache( init_function=init_function, cache_directory=cache_directory @@ -265,4 +266,5 @@ def create_pysqa_block_allocation_scheduler( executor_kwargs=executor_kwargs, spawner=PysqaSpawner, validator=validator, + restart_limit=restart_limit, ) diff --git a/tests/unit/executor/test_api_block_allocation.py b/tests/unit/executor/test_api_block_allocation.py new file mode 100644 index 00000000..34f12934 --- /dev/null +++ b/tests/unit/executor/test_api_block_allocation.py @@ -0,0 +1,112 @@ +import os +import shutil +import signal +import tempfile +import unittest +from time import sleep + +from executorlib.api import TestClusterExecutor +from executorlib.standalone.interactive.communication import ExecutorlibSocketError +from executorlib.standalone.serialize import cloudpickle_register + + +def get_pid(): + return os.getpid() + + +def add_function(parameter_1, parameter_2): + return parameter_1 + parameter_2 + + +def init_function(): + return {"parameter_2": 3} + + +def kill_worker_on_first_call(marker_file): + """ + Simulate a worker which is cancelled by the queuing system (e.g. preempted on an overflow queue) while it executes + a task: the first call creates the marker file and kills its own worker process, every following call returns the + process id of the worker. + """ + import os + import signal + + if not os.path.exists(marker_file): + open(marker_file, "w").close() + os.kill(os.getpid(), signal.SIGKILL) + return os.getpid() + + +def wait_for_process_to_exit(pid, timeout=10.0): + """The worker is a child of the test process, so poll until it is gone (or reaped).""" + for _ in range(int(timeout / 0.1)): + try: + os.kill(pid, 0) + except ProcessLookupError: + return + try: + finished_pid, _ = os.waitpid(pid, os.WNOHANG) + except ChildProcessError: + return + if finished_pid == pid: + return + sleep(0.1) + + +class TestTestClusterExecutorBlockAllocation(unittest.TestCase): + def setUp(self): + self.working_directory = tempfile.mkdtemp() + self.marker_file = os.path.join(self.working_directory, "killed") + + def tearDown(self): + shutil.rmtree(self.working_directory, ignore_errors=True) + + def test_block_allocation(self): + with TestClusterExecutor(max_workers=2, block_allocation=True) as exe: + cloudpickle_register(ind=1) + future_lst = [exe.submit(add_function, i, parameter_2=1) for i in range(4)] + self.assertEqual([f.result() for f in future_lst], [1, 2, 3, 4]) + + def test_block_allocation_init_function(self): + # The init_function is transferred when the worker boots up, so it has to be registered beforehand. + cloudpickle_register(ind=1) + with TestClusterExecutor( + max_workers=1, block_allocation=True, init_function=init_function + ) as exe: + self.assertEqual(exe.submit(add_function, 1).result(), 4) + + def test_restart_worker_cancelled_during_task(self): + with TestClusterExecutor( + max_workers=1, block_allocation=True, restart_limit=1 + ) as exe: + cloudpickle_register(ind=1) + first_pid = exe.submit(get_pid).result() + restarted_pid = exe.submit( + kill_worker_on_first_call, self.marker_file + ).result() + self.assertTrue(os.path.exists(self.marker_file)) + self.assertNotEqual(first_pid, restarted_pid) + self.assertEqual(exe.submit(get_pid).result(), restarted_pid) + + def test_restart_worker_cancelled_while_idle(self): + with TestClusterExecutor( + max_workers=1, block_allocation=True, restart_limit=1 + ) as exe: + cloudpickle_register(ind=1) + first_pid = exe.submit(get_pid).result() + os.kill(first_pid, signal.SIGKILL) + wait_for_process_to_exit(pid=first_pid) + restarted_pid = exe.submit(get_pid).result(timeout=60) + self.assertNotEqual(first_pid, restarted_pid) + + def test_restart_limit_exhausted(self): + with self.assertRaises(ExecutorlibSocketError): + with TestClusterExecutor( + max_workers=1, block_allocation=True, restart_limit=0 + ) as exe: + cloudpickle_register(ind=1) + exe.submit(kill_worker_on_first_call, self.marker_file).result() + + def test_restart_limit_requires_block_allocation(self): + with self.assertRaises(ValueError): + TestClusterExecutor(block_allocation=False, restart_limit=1) diff --git a/tests/unit/executor/test_slurm_cluster.py b/tests/unit/executor/test_slurm_cluster.py index 32a40c83..0f06a0d8 100644 --- a/tests/unit/executor/test_slurm_cluster.py +++ b/tests/unit/executor/test_slurm_cluster.py @@ -153,5 +153,13 @@ def test_slurm_cluster_block_allocation(self): with self.assertRaises(ValueError): SlurmClusterExecutor(block_allocation=True) + def test_slurm_cluster_block_allocation_restart_limit(self): + with self.assertRaises(ValueError): + SlurmClusterExecutor(block_allocation=True, restart_limit=2) + + def test_slurm_cluster_restart_limit_requires_block_allocation(self): + with self.assertRaises(ValueError): + SlurmClusterExecutor(block_allocation=False, restart_limit=1) + def test_slurm_cluster_file(self): self.assertTrue(SlurmClusterExecutor(block_allocation=False)) \ No newline at end of file