diff --git a/libensemble/executors/mpi_runner.py b/libensemble/executors/mpi_runner.py index 48953cc3c..d44152aff 100644 --- a/libensemble/executors/mpi_runner.py +++ b/libensemble/executors/mpi_runner.py @@ -19,6 +19,7 @@ def get_runner(mpi_runner_type, runner_name=None, platform_info=None): "srun": SRUN_MPIRunner, "jsrun": JSRUN_MPIRunner, "msmpi": MSMPI_MPIRunner, + "flux": FLUX_MPIRunner, "custom": MPIRunner, } runner = None @@ -519,3 +520,75 @@ def __init__(self, run_command="jsrun", platform_info=None): def express_spec(self, task, nprocs, nnodes, ppn, machinefile, hyperthreads, extra_args, resources, workerID): """Returns None, None as jsrun uses neither hostlist or machinefile""" return None, None + + +class FLUX_MPIRunner(MPIRunner): + """MPI Runner for Flux Framework (flux run). + + Flux provides flexible resource management and job scheduling. + See https://flux-framework.org/ for details. + """ + + def __init__(self, run_command="flux", platform_info=None): + self.run_command = run_command + self.subgroup_launch = False # Flux manages job lifecycle + self.mfile_support = False + self.arg_nprocs = ("-n", "--ntasks") + self.arg_nnodes = ("-N", "--nodes") + self.arg_ppn = ("--tasks-per-node",) + self.default_mpi_options = None + self.default_gpu_arg_type = "option_gpus_per_task" + self.default_gpu_args = {"option_gpus_per_task": "-g", "option_gpus_per_node": "--gpus-per-node"} + self.platform_info = platform_info + self.rm_rpn = False + + # Flux's per-resource options are mutually exclusive with -n/--ntasks, + # so express layouts with nodes plus per-task resources. + self.mpi_command = [ + self.run_command, + "run", + "-N {num_nodes}", + "-n {num_procs}", + "{extra_args}", + ] + + def get_mpi_specs( + self, + task, + nprocs, + nnodes, + ppn, + ngpus, + machinefile, + hyperthreads, + extra_args, + auto_assign_gpus, + match_procs_to_gpus, + resources, + workerID, + ): + specs = super().get_mpi_specs( + task, + nprocs, + nnodes, + ppn, + ngpus, + machinefile, + hyperthreads, + extra_args, + auto_assign_gpus, + match_procs_to_gpus, + resources, + workerID, + ) + + ppn = specs["procs_per_node"] + if ppn: + extra_args = self._append_to_extra_args(specs["extra_args"], "-c 1") + specs["extra_args"] = extra_args + specs["procs_per_node"] = None + return specs + + def express_spec(self, task, nprocs, nnodes, ppn, machinefile, hyperthreads, extra_args, resources, workerID): + """Returns None, None as flux manages resources internally""" + return None, None diff --git a/libensemble/resources/env_resources.py b/libensemble/resources/env_resources.py index 47b3d7862..3eb1a611c 100644 --- a/libensemble/resources/env_resources.py +++ b/libensemble/resources/env_resources.py @@ -35,6 +35,7 @@ class EnvResources: default_nodelist_env_pbs = "PBS_NODEFILE" default_nodelist_env_lsf = "LSB_HOSTS" default_nodelist_env_lsf_shortform = "LSB_MCPU_HOSTS" + default_nodelist_env_flux = "FLUX_URI" def __init__( self, @@ -43,6 +44,7 @@ def __init__( nodelist_env_pbs: str | None = None, nodelist_env_lsf: str | None = None, nodelist_env_lsf_shortform: str | None = None, + nodelist_env_flux: str | None = None, ) -> None: """Initializes a new EnvResources instance @@ -71,10 +73,17 @@ def __init__( nodelist_env_lsf_shortform: String, optional The environment variable giving a node list in LSF short-form format (Default: uses LSB_MCPU_HOSTS). Note: This is queried only if a node_list file is not provided. + + nodelist_env_flux: String, optional + The environment variable indicating a Flux instance (Default: uses FLUX_URI). + When present, the nodelist is obtained via `flux resource list`. + Note: This is queried only if a node_list file is not provided. """ self.scheduler = None self.nodelists = {} + # Check Flux first - it may run inside Slurm but should take precedence + self.nodelists["Flux"] = nodelist_env_flux or EnvResources.default_nodelist_env_flux self.nodelists["Slurm"] = nodelist_env_slurm or EnvResources.default_nodelist_env_slurm self.nodelists["Cobalt"] = nodelist_env_cobalt or EnvResources.default_nodelist_env_cobalt self.nodelists["PBS"] = nodelist_env_pbs or EnvResources.default_nodelist_env_pbs @@ -82,6 +91,7 @@ def __init__( self.nodelists["LSF_shortform"] = nodelist_env_lsf_shortform or EnvResources.default_nodelist_env_lsf_shortform self.ndlist_funcs = {} + self.ndlist_funcs["Flux"] = EnvResources.get_flux_nodelist self.ndlist_funcs["Slurm"] = EnvResources.get_slurm_nodelist self.ndlist_funcs["Cobalt"] = EnvResources.get_cobalt_nodelist self.ndlist_funcs["PBS"] = EnvResources.get_pbs_nodelist @@ -105,7 +115,7 @@ def get_nodelist(self) -> list[str | Any]: return [] @staticmethod - def abbrev_nodenames(node_list: list[str], prefix: str = None) -> list[str]: + def abbrev_nodenames(node_list: list[str], prefix: str | None = None) -> list[str]: """Returns nodelist with only string up to first dot""" newlist = [s.split(".", 1)[0] for s in node_list] return newlist @@ -151,6 +161,14 @@ def _noderange_append(prefix: str, nidstr: str, suffix: str) -> list[str]: def get_slurm_nodelist(node_list_env: str) -> list[str | Any]: """Gets global libEnsemble nodelist from the Slurm environment""" fullstr = os.environ[node_list_env] + return EnvResources.get_slurm_nodelist_from_string(fullstr) + + @staticmethod + def get_slurm_nodelist_from_string(fullstr: str) -> list[str | Any]: + """Parses a nodelist string in Slurm format (also used by Flux). + + This is extracted from get_slurm_nodelist to allow reuse with Flux. + """ if not fullstr: return [] # Split at commas outside of square brackets @@ -171,6 +189,47 @@ def get_slurm_nodelist(node_list_env: str) -> list[str | Any]: nidlst.extend(EnvResources._noderange_append(prefix, nidstr, suffix)) return sorted(nidlst) + @staticmethod + def get_flux_nodelist(node_list_env: str) -> list[str | Any]: + """Gets global libEnsemble nodelist from a Flux instance. + + Uses `flux resource list` to obtain the list of available nodes. + The node_list_env parameter (FLUX_URI) is used to detect Flux presence + but the actual nodelist comes from the flux command. + """ + import subprocess + + try: + # flux resource list with format to get just hostnames + # -n: no header, -o: output format + result = subprocess.run( + ["flux", "resource", "list", "-n", "-o", "{nodelist}"], + capture_output=True, + text=True, + timeout=10, + ) + if result.returncode != 0: + logger.warning(f"flux resource list failed: {result.stderr}") + return [] + + nodelist_str = result.stdout.strip() + if not nodelist_str: + return [] + + # Parse the nodelist - Flux uses similar format to Slurm (e.g., "node[1-4]") + # We can reuse the Slurm parser for bracket notation + return EnvResources.get_slurm_nodelist_from_string(nodelist_str) + + except subprocess.TimeoutExpired: + logger.warning("flux resource list timed out") + return [] + except FileNotFoundError: + logger.warning("flux command not found") + return [] + except Exception as e: + logger.warning(f"Error getting Flux nodelist: {e}") + return [] + @staticmethod def get_cobalt_nodelist(node_list_env: str) -> list[str | Any]: """Gets global libEnsemble nodelist from the Cobalt environment""" diff --git a/libensemble/resources/mpi_resources.py b/libensemble/resources/mpi_resources.py index 33b62ce3c..22da26413 100644 --- a/libensemble/resources/mpi_resources.py +++ b/libensemble/resources/mpi_resources.py @@ -29,16 +29,24 @@ def rassert(test: int | bool | None, *args) -> None: # logger.setLevel(logging.DEBUG) -def get_MPI_variant() -> str: +def get_MPI_variant() -> str | None: """Returns MPI base implementation Returns ------- - mpi_variant: str - MPI variant 'aprun' or 'jsrun' or 'msmpi' or 'mpich' or 'openmpi' or 'srun' + mpi_variant: str | None + MPI variant 'aprun' or 'jsrun' or 'msmpi' or 'mpich' or 'openmpi' or 'srun' or 'flux', or None if not found """ + # Check for Flux first via FLUX_URI environment variable (indicates running inside a Flux instance) + if os.environ.get("FLUX_URI"): + try: + subprocess.check_call(["flux", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return "flux" + except Exception: + pass + try: subprocess.check_call(["aprun", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) return "aprun" @@ -85,7 +93,7 @@ def get_MPI_variant() -> str: return None -def get_MPI_runner(mpi_runner=None) -> str: +def get_MPI_runner(mpi_runner: str | None = None) -> str | None: """Return whether ``mpirun`` is openmpi or mpich""" var = mpi_runner or get_MPI_variant() if var in ["mpich", "openmpi"]: @@ -102,29 +110,31 @@ def task_partition( """ # Convert to int if string is provided - num_procs = int(num_procs) if num_procs else None - num_nodes = int(num_nodes) if num_nodes else None - procs_per_node = int(procs_per_node) if procs_per_node else None + num_procs_int: int | None = int(num_procs) if num_procs else None + num_nodes_int: int | None = int(num_nodes) if num_nodes else None + procs_per_node_int: int | None = int(procs_per_node) if procs_per_node else None # If machinefile is provided - ignore everything else if machinefile: - if num_procs or num_nodes or procs_per_node: + if num_procs_int or num_nodes_int or procs_per_node_int: logger.warning("Machinefile provided - overriding " "procs/nodes/procs_per_node") return None, None, None - if not num_procs: - rassert(num_nodes and procs_per_node, "Need num_procs, num_nodes/procs_per_node, or machinefile") - num_procs = num_nodes * procs_per_node + if not num_procs_int: + rassert(num_nodes_int and procs_per_node_int, "Need num_procs, num_nodes/procs_per_node, or machinefile") + assert num_nodes_int is not None and procs_per_node_int is not None # for mypy + num_procs_int = num_nodes_int * procs_per_node_int - elif not num_nodes: - procs_per_node = procs_per_node or num_procs - num_nodes = num_procs // procs_per_node + elif not num_nodes_int: + procs_per_node_int = procs_per_node_int or num_procs_int + num_nodes_int = num_procs_int // procs_per_node_int - elif not procs_per_node: - procs_per_node = num_procs // num_nodes + elif not procs_per_node_int: + procs_per_node_int = num_procs_int // num_nodes_int - rassert(num_procs == num_nodes * procs_per_node, "num_procs does not equal num_nodes*procs_per_node") - return num_procs, num_nodes, procs_per_node + assert num_nodes_int is not None and procs_per_node_int is not None # for mypy + rassert(num_procs_int == num_nodes_int * procs_per_node_int, "num_procs does not equal num_nodes*procs_per_node") + return num_procs_int, num_nodes_int, procs_per_node_int def _max_rsets_per_node(worker_resources: WorkerResources) -> int: @@ -137,9 +147,9 @@ def _max_rsets_per_node(worker_resources: WorkerResources) -> int: def get_resources( resources: Resources, - num_procs: int = None, - num_nodes: int = None, - procs_per_node: int = None, + num_procs: int | None = None, + num_nodes: int | None = None, + procs_per_node: int | None = None, hyperthreads: bool = False, ) -> tuple[int, int, int]: """Reconciles user-supplied options with available worker @@ -153,6 +163,7 @@ def get_resources( raised if these are infeasible. """ wresources = resources.worker_resources + assert wresources is not None # for mypy gresources = resources.glob_resources node_list = wresources.local_nodelist rassert(node_list, "Node list is empty - aborting") @@ -190,7 +201,7 @@ def get_resources( f"Nodes: {num_nodes} procs_per_node {procs_per_node}" ) elif not num_nodes and not procs_per_node: - if num_procs <= cores_avail_per_node_per_worker: + if num_procs is not None and num_procs <= cores_avail_per_node_per_worker: num_nodes = 1 else: num_nodes = local_node_count @@ -198,49 +209,54 @@ def get_resources( num_nodes = local_node_count # Checks config is consistent and sufficient to express - num_procs, num_nodes, procs_per_node = task_partition(num_procs, num_nodes, procs_per_node) + result = task_partition(num_procs, num_nodes, procs_per_node) + if result == (None, None, None): + raise MPIResourcesException("task_partition returned all None unexpectedly") + num_procs_out, num_nodes_out, procs_per_node_out = result + # Type narrowing for mypy + assert num_procs_out is not None and num_nodes_out is not None and procs_per_node_out is not None rassert( - num_nodes <= local_node_count, - "Not enough nodes to honor arguments. " f"Requested {num_nodes}. Only {local_node_count} available", + num_nodes_out <= local_node_count, + "Not enough nodes to honor arguments. " f"Requested {num_nodes_out}. Only {local_node_count} available", ) if gresources.enforce_worker_core_bounds: rassert( - procs_per_node <= cores_avail_per_node, + procs_per_node_out <= cores_avail_per_node, "Not enough processors on a node to honor arguments. " - f"Requested {procs_per_node}. Only {cores_avail_per_node} available", + f"Requested {procs_per_node_out}. Only {cores_avail_per_node} available", ) rassert( - procs_per_node <= cores_avail_per_node_per_worker, + procs_per_node_out <= cores_avail_per_node_per_worker, "Not enough processors per worker to honor arguments. " - f"Requested {procs_per_node}. Only {cores_avail_per_node_per_worker} available", + f"Requested {procs_per_node_out}. Only {cores_avail_per_node_per_worker} available", ) rassert( - num_procs <= (cores_avail_per_node * local_node_count), + num_procs_out <= (cores_avail_per_node * local_node_count), "Not enough procs to honor arguments. " - f"Requested {num_procs}. Only {cores_avail_per_node * local_node_count} available", + f"Requested {num_procs_out}. Only {cores_avail_per_node * local_node_count} available", ) - if num_nodes < local_node_count: + if num_nodes_out < local_node_count: logger.debug( "User constraints mean fewer nodes being used " - f"than available. {num_nodes} nodes used. {local_node_count} nodes available" + f"than available. {num_nodes_out} nodes used. {local_node_count} nodes available" ) - return num_procs, num_nodes, procs_per_node + return num_procs_out, num_nodes_out, procs_per_node_out def create_machinefile( resources: Resources, machinefile: str | None = None, - num_procs: int = None, + num_procs: int | None = None, num_nodes: int | None = None, procs_per_node: int | None = None, hyperthreads: bool = False, -) -> tuple[bool, None, int, int]: +) -> tuple[bool, int | None, int | None, int | None]: """Creates a machinefile based on user-supplied config options, completed by detected machine resources """ @@ -252,12 +268,13 @@ def create_machinefile( except Exception as e: logger.warning(f"Could not remove existing machinefile: {e}") + assert resources.worker_resources is not None # for mypy node_list = resources.worker_resources.local_nodelist logger.debug(f"Creating machinefile with {num_nodes} nodes and {procs_per_node} ranks per node") with open(machinefile, "w") as f: for node in node_list[:num_nodes]: - f.write((node + "\n") * procs_per_node) + f.write((node + "\n") * (procs_per_node or 1)) built_mfile = os.path.isfile(machinefile) and os.path.getsize(machinefile) > 0 return built_mfile, num_procs, num_nodes, procs_per_node @@ -268,6 +285,7 @@ def get_hostlist(resources: Resources, num_nodes=None): completed by detected machine resources """ + assert resources.worker_resources is not None # for mypy node_list = resources.worker_resources.local_nodelist hostlist_str = ",".join([str(x) for x in node_list[:num_nodes]]) return hostlist_str diff --git a/libensemble/resources/platforms.py b/libensemble/resources/platforms.py index 69c36242f..07989cb05 100644 --- a/libensemble/resources/platforms.py +++ b/libensemble/resources/platforms.py @@ -230,6 +230,20 @@ class Polaris(Platform): scheduler_match_slots: bool = True +class FluxAllocation(Platform): + """Platform configuration for running inside a Flux allocation. + + This is a generic Flux configuration. For specific systems using Flux + (e.g., LLNL El Capitan), you may want to create a more specific platform + class with cores_per_node and gpus_per_node set appropriately. + """ + + mpi_runner: str = "flux" + runner_name: str = "flux" + gpu_setting_type: str = "runner_default" + scheduler_match_slots: bool = False + + class Known_platforms(BaseModel): """A list of platforms with known configurations. @@ -271,6 +285,7 @@ class Known_platforms(BaseModel): aurora: Aurora = Aurora() generic_rocm: GenericROCm = GenericROCm() frontier: Frontier = Frontier() + flux: FluxAllocation = FluxAllocation() lumi: Lumi = Lumi() lumi_g: LumiGPU = LumiGPU() perlmutter: Perlmutter = Perlmutter() diff --git a/libensemble/resources/resources.py b/libensemble/resources/resources.py index 19e246fb6..9b68e43f0 100644 --- a/libensemble/resources/resources.py +++ b/libensemble/resources/resources.py @@ -182,12 +182,14 @@ def __init__(self, libE_specs: dict, platform_info: dict = {}, top_level_dir: st nodelist_env_cobalt = resource_info.get("nodelist_env_cobalt", None) nodelist_env_lsf = resource_info.get("nodelist_env_lsf", None) nodelist_env_lsf_shortform = resource_info.get("nodelist_env_lsf_shortform", None) + nodelist_env_flux = resource_info.get("nodelist_env_flux", None) self.env_resources = EnvResources( nodelist_env_slurm=nodelist_env_slurm, nodelist_env_cobalt=nodelist_env_cobalt, nodelist_env_lsf=nodelist_env_lsf, nodelist_env_lsf_shortform=nodelist_env_lsf_shortform, + nodelist_env_flux=nodelist_env_flux, ) if node_file is None: diff --git a/libensemble/tests/unit_tests/test_flux.py b/libensemble/tests/unit_tests/test_flux.py new file mode 100644 index 000000000..b5f7c0e01 --- /dev/null +++ b/libensemble/tests/unit_tests/test_flux.py @@ -0,0 +1,353 @@ +""" +Unit tests for Flux Framework integration in libEnsemble. + +Tests cover: +- FLUX_MPIRunner command generation +- Flux nodelist parsing (via slurm-style bracket notation) +- Flux MPI variant detection +- FluxAllocation platform configuration +""" + +import os +import subprocess +from types import SimpleNamespace +from unittest import mock + +import pytest + +from libensemble.executors.mpi_runner import FLUX_MPIRunner, MPIRunner +from libensemble.resources.env_resources import EnvResources +from libensemble.resources.platforms import FluxAllocation, Known_platforms +from libensemble.utils import launcher +from libensemble.utils.validators import check_mpi_runner_type + +# ======================================================================================== +# Tests for FLUX_MPIRunner +# ======================================================================================== + + +def test_flux_runner_factory_registration(): + """Test that flux runner is registered in the factory""" + runner = MPIRunner.get_runner("flux") + assert runner is not None + assert isinstance(runner, FLUX_MPIRunner) + + +def test_flux_runner_default_command(): + """Test default flux run command""" + runner = FLUX_MPIRunner() + assert runner.run_command == "flux" + assert runner.subgroup_launch is False + assert runner.mfile_support is False + + +def test_flux_runner_mpi_command_template(): + """Test the MPI command template for flux""" + runner = FLUX_MPIRunner() + expected = ["flux", "run", "-N {num_nodes}", "-n {num_procs}", "{extra_args}"] + assert runner.mpi_command == expected + + +def test_flux_runner_forms_valid_runline_without_tasks_per_node(): + """Flux run should avoid mixing per-resource and per-task options""" + runner = FLUX_MPIRunner() + specs = runner.get_mpi_specs( + task=SimpleNamespace(env={}, _add_to_env=lambda *args: None, ngpus_req=0), + nprocs=4, + nnodes=2, + ppn=2, + ngpus=None, + machinefile=None, + hyperthreads=False, + extra_args=None, + auto_assign_gpus=False, + match_procs_to_gpus=False, + resources=None, + workerID=1, + ) + + runline = launcher.form_command(runner.mpi_command, specs) + assert runline == ["flux", "run", "-N", "2", "-n", "4", "-c", "1"] + + +def test_flux_runner_arg_parsing(): + """Test argument parsing configuration""" + runner = FLUX_MPIRunner() + assert "-n" in runner.arg_nprocs + assert "--ntasks" in runner.arg_nprocs + assert "-N" in runner.arg_nnodes + assert "--nodes" in runner.arg_nnodes + assert "--tasks-per-node" in runner.arg_ppn + + +def test_flux_runner_gpu_settings(): + """Test GPU argument configuration""" + runner = FLUX_MPIRunner() + assert runner.default_gpu_arg_type == "option_gpus_per_task" + assert runner.default_gpu_args["option_gpus_per_task"] == "-g" + assert runner.default_gpu_args["option_gpus_per_node"] == "--gpus-per-node" + + +def test_flux_runner_express_spec(): + """Test that express_spec returns None for both hostlist and machinefile""" + runner = FLUX_MPIRunner() + hostlist, machinefile = runner.express_spec( + task=None, + nprocs=4, + nnodes=2, + ppn=2, + machinefile=None, + hyperthreads=False, + extra_args=None, + resources=None, + workerID=1, + ) + assert hostlist is None + assert machinefile is None + + +def test_flux_runner_custom_command(): + """Test custom run command override""" + runner = FLUX_MPIRunner(run_command="/custom/flux") + assert runner.run_command == "/custom/flux" + assert runner.mpi_command[0] == "/custom/flux" + + +# ======================================================================================== +# Tests for Flux nodelist parsing +# ======================================================================================== + + +def test_flux_nodelist_from_string_empty(): + """Test parsing empty nodelist string""" + result = EnvResources.get_slurm_nodelist_from_string("") + assert result == [] + + +def test_flux_nodelist_from_string_single(): + """Test parsing single node""" + result = EnvResources.get_slurm_nodelist_from_string("node001") + assert result == ["node001"] + + +def test_flux_nodelist_from_string_range(): + """Test parsing node range (flux uses slurm-style notation)""" + result = EnvResources.get_slurm_nodelist_from_string("node[001-004]") + assert result == ["node001", "node002", "node003", "node004"] + + +def test_flux_nodelist_from_string_mixed(): + """Test parsing mixed single nodes and ranges""" + result = EnvResources.get_slurm_nodelist_from_string("node[001-002,005],other[010-011]") + assert "node001" in result + assert "node002" in result + assert "node005" in result + assert "other010" in result + assert "other011" in result + + +@mock.patch("subprocess.run") +def test_flux_nodelist_success(mock_run): + """Test getting nodelist from flux resource list""" + mock_run.return_value = mock.Mock(returncode=0, stdout="node[001-004]\n", stderr="") + + result = EnvResources.get_flux_nodelist("FLUX_URI") + + mock_run.assert_called_once() + assert "flux" in mock_run.call_args[0][0] + assert "resource" in mock_run.call_args[0][0] + assert result == ["node001", "node002", "node003", "node004"] + + +@mock.patch("subprocess.run") +def test_flux_nodelist_command_failure(mock_run): + """Test handling flux command failure""" + mock_run.return_value = mock.Mock(returncode=1, stdout="", stderr="error message") + + result = EnvResources.get_flux_nodelist("FLUX_URI") + assert result == [] + + +@mock.patch("subprocess.run") +def test_flux_nodelist_timeout(mock_run): + """Test handling flux command timeout""" + mock_run.side_effect = subprocess.TimeoutExpired(cmd="flux", timeout=10) + + result = EnvResources.get_flux_nodelist("FLUX_URI") + assert result == [] + + +@mock.patch("subprocess.run") +def test_flux_nodelist_not_found(mock_run): + """Test handling flux command not found""" + mock_run.side_effect = FileNotFoundError() + + result = EnvResources.get_flux_nodelist("FLUX_URI") + assert result == [] + + +def test_env_resources_flux_detection(): + """Test that EnvResources detects Flux when FLUX_URI is set""" + # Save current env + old_flux_uri = os.environ.get("FLUX_URI") + old_slurm = os.environ.get("SLURM_NODELIST") + + try: + # Clear conflicting env vars + if "SLURM_NODELIST" in os.environ: + del os.environ["SLURM_NODELIST"] + + # Set FLUX_URI + os.environ["FLUX_URI"] = "local:///tmp/flux-test" + + env_resources = EnvResources() + assert env_resources.scheduler == "Flux" + assert "Flux" in env_resources.nodelists + assert "Flux" in env_resources.ndlist_funcs + + finally: + # Restore env + if old_flux_uri: + os.environ["FLUX_URI"] = old_flux_uri + elif "FLUX_URI" in os.environ: + del os.environ["FLUX_URI"] + + if old_slurm: + os.environ["SLURM_NODELIST"] = old_slurm + + +def test_env_resources_flux_env_variable(): + """Test default Flux environment variable""" + assert EnvResources.default_nodelist_env_flux == "FLUX_URI" + + +# ======================================================================================== +# Tests for Flux MPI variant detection +# ======================================================================================== + + +@mock.patch.dict(os.environ, {"FLUX_URI": "local:///tmp/flux-test"}) +@mock.patch("subprocess.check_call") +def test_get_mpi_variant_flux(mock_check_call): + """Test MPI variant detection returns flux when in Flux instance""" + from libensemble.resources.mpi_resources import get_MPI_variant + + mock_check_call.return_value = 0 # flux --version succeeds + + result = get_MPI_variant() + assert result == "flux" + + # Verify flux --version was called + mock_check_call.assert_called_once() + assert mock_check_call.call_args[0][0] == ["flux", "--version"] + + +@mock.patch.dict(os.environ, {}, clear=True) +@mock.patch("subprocess.check_call") +@mock.patch("subprocess.Popen") +def test_get_mpi_variant_no_flux_uri(mock_popen, mock_check_call): + """Test MPI variant detection skips flux when FLUX_URI not set""" + from libensemble.resources.mpi_resources import get_MPI_variant + + # Make all checks fail + mock_check_call.side_effect = Exception("not found") + mock_popen.side_effect = FileNotFoundError() + + result = get_MPI_variant() + + # Should not be flux since FLUX_URI not set + assert result != "flux" or result is None + + +# ======================================================================================== +# Tests for FluxAllocation platform +# ======================================================================================== + + +def test_flux_allocation_platform(): + """Test FluxAllocation platform configuration""" + platform = FluxAllocation() + assert platform.mpi_runner == "flux" + assert platform.runner_name == "flux" + assert platform.gpu_setting_type == "runner_default" + assert platform.scheduler_match_slots is False + + +def test_flux_in_known_platforms(): + """Test that flux is registered in known platforms""" + platforms = Known_platforms() + assert hasattr(platforms, "flux") + assert isinstance(platforms.flux, FluxAllocation) + + +# ======================================================================================== +# Tests for validator +# ======================================================================================== + + +def test_validator_accepts_flux(): + """Test that flux is accepted by the MPI runner validator""" + + class MockCls: + pass + + result = check_mpi_runner_type(MockCls, "flux") + assert result == "flux" + + +def test_validator_accepts_all_runners(): + """Test all valid runner names are accepted""" + + class MockCls: + pass + + valid_runners = ["mpich", "openmpi", "aprun", "srun", "jsrun", "msmpi", "flux", "custom"] + for runner in valid_runners: + result = check_mpi_runner_type(MockCls, runner) + assert result == runner + + +def test_validator_rejects_invalid(): + """Test invalid runner names are rejected""" + + class MockCls: + pass + + with pytest.raises(AssertionError): + check_mpi_runner_type(MockCls, "invalid_runner") + + +# ======================================================================================== +# Test runner standalone execution +# ======================================================================================== + + +if __name__ == "__main__": + # FLUX_MPIRunner tests + test_flux_runner_factory_registration() + test_flux_runner_default_command() + test_flux_runner_mpi_command_template() + test_flux_runner_forms_valid_runline_without_tasks_per_node() + test_flux_runner_arg_parsing() + test_flux_runner_gpu_settings() + test_flux_runner_express_spec() + test_flux_runner_custom_command() + + # Nodelist parsing tests + test_flux_nodelist_from_string_empty() + test_flux_nodelist_from_string_single() + test_flux_nodelist_from_string_range() + test_flux_nodelist_from_string_mixed() + + # Validator tests + test_validator_accepts_flux() + test_validator_accepts_all_runners() + + # Platform tests + test_flux_allocation_platform() + test_flux_in_known_platforms() + + # EnvResources tests + test_env_resources_flux_env_variable() + + print("All standalone tests passed!") diff --git a/libensemble/utils/validators.py b/libensemble/utils/validators.py index 58cddd4ad..c1fee67ac 100644 --- a/libensemble/utils/validators.py +++ b/libensemble/utils/validators.py @@ -96,7 +96,16 @@ def check_gpu_setting_type(cls, value): def check_mpi_runner_type(cls, value): if value is not None: - assert value in ["mpich", "openmpi", "aprun", "srun", "jsrun", "msmpi", "custom"], "Invalid MPI runner name" + assert value in [ + "mpich", + "openmpi", + "aprun", + "srun", + "jsrun", + "msmpi", + "flux", + "custom", + ], "Invalid MPI runner name" return value diff --git a/pyproject.toml b/pyproject.toml index fbb96f22d..db66bf8fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -216,6 +216,13 @@ extra = [ dev = ["wat>=0.7.0,<0.8"] docs = ["pyenchant", "enchant>=0.0.1,<0.0.2", "sphinx-lfs-content>=1.1.10,<2"] +# Note: For FluxExecutor (native Flux Python API), the flux-core Python bindings +# are required. These are typically installed via: +# - conda: conda install -c conda-forge flux-core +# - spack: spack install flux-core +# - system package manager on supported systems +# The MPIExecutor with mpi_runner="flux" works without Python bindings. + # Various config from here onward [tool.black] line-length = 120