From be30527243d5ec68e1a3eb85c9d9c705bd7ddb12 Mon Sep 17 00:00:00 2001 From: wakonig_k Date: Tue, 10 Nov 2026 14:45:18 +0100 Subject: [PATCH] feat: add typed Slurm cluster configuration --- .gitignore | 1 + README.md | 26 +++-- examples/submit_job.py | 17 +-- pyproject.toml | 1 + slurm_manager/clusters/__init__.py | 11 ++ slurm_manager/clusters/cluster_info.py | 15 +++ slurm_manager/{ => clusters}/job_options.py | 23 +--- slurm_manager/clusters/ra.py | 26 +++++ slurm_manager/clusters/sfonline.py | 17 +++ slurm_manager/clusters/slsonline.py | 17 +++ slurm_manager/event_messages.py | 1 - slurm_manager/job_future.py | 8 +- slurm_manager/job_tracker.py | 34 +++--- slurm_manager/redis_sub_client.py | 4 +- slurm_manager/slurm_manager.py | 115 +++++++++++++++++++- slurm_manager/slurm_rest_client.py | 29 ++++- test/fixtures/curl_stub.py | 10 +- test/integration/test_ra.py | 46 +++++--- test/test_job_options.py | 13 ++- test/test_job_tracker.py | 17 +-- test/test_slurm_manager.py | 107 ++++++++++++++++-- test/test_slurm_rest_client.py | 31 +++++- 22 files changed, 450 insertions(+), 119 deletions(-) create mode 100644 slurm_manager/clusters/__init__.py create mode 100644 slurm_manager/clusters/cluster_info.py rename slurm_manager/{ => clusters}/job_options.py (75%) create mode 100644 slurm_manager/clusters/ra.py create mode 100644 slurm_manager/clusters/sfonline.py create mode 100644 slurm_manager/clusters/slsonline.py diff --git a/.gitignore b/.gitignore index 579509f..f0fa00d 100644 --- a/.gitignore +++ b/.gitignore @@ -137,6 +137,7 @@ celerybeat.pid # Environments .env +*.env .envrc .venv env/ diff --git a/README.md b/README.md index 1524c2b..a74fe98 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,9 @@ pip install bec-slurm-manager cp .env.example .env ``` -Set `SLURM_JWT` in your local `.env` file. The example contains the RA REST URL -and API version. This credential file is ignored by Git and never uploaded. +Set `SLURM_JWT` and, if needed, `SLURM_USER` in your local `.env` file. +`SlurmManager.for_cluster()` uses the named cluster’s REST and Redis settings. +Pass a cluster name or a `Cluster` enum member from `slurm_manager.clusters`. The credential file is ignored by Git and stays local. The submitter needs access to slurmrestd and Redis. For development from a checkout, install with `pip install -e '.[dev]'`. @@ -22,9 +23,9 @@ For development from a checkout, install with `pip install -e '.[dev]'`. Redis connections use TLS by default, including the worker on compute nodes. Certificates and hostnames are verified against each machine's system trust store. -Set `redis_port` to the server's TLS listener port if it differs from 6379. -Clients do not need their own certificate or a certificate path. -For a local plaintext Redis server, explicitly pass `redis_tls=False`. +For built-in clusters, `ClusterInfo` defines the Redis host, port, and TLS setting. +When constructing a manager directly, pass `redis_port` for a non-default +listener port or `redis_tls=False` for a local plaintext Redis server. The standalone worker likewise defaults to TLS; use `--redis-tls=false` for plaintext. ## Simple job @@ -32,9 +33,10 @@ The standalone worker likewise defaults to TLS; use `--redis-tls=false` for plai Run the included ten-second Bash script using the cluster's default resources: ```python +from slurm_manager.clusters import Cluster from slurm_manager.slurm_manager import SlurmManager -manager = SlurmManager(redis_host="bec-slurm.psi.ch") +manager = SlurmManager.for_cluster(Cluster.RA, env_file=".env") try: job = manager.submit_job( script_path="examples/print_for_10s.sh", working_directory="/das/home/your_username" @@ -54,15 +56,16 @@ Replace `working_directory` with an existing directory accessible on the compute Choose resources and log files, and receive live output and status updates: ```python -from slurm_manager.job_options import JobOptions +from slurm_manager.clusters import Cluster +from slurm_manager.clusters.ra import RAJobOptions from slurm_manager.slurm_manager import SlurmManager -manager = SlurmManager(redis_host="bec-slurm.psi.ch") +manager = SlurmManager.for_cluster(Cluster.RA, env_file=".env") try: job = manager.submit_job( script_path="examples/print_for_10s.sh", working_directory="/das/home/your_username", - job_options=JobOptions( + job_options=RAJobOptions( name="my-analysis", partition="day", tasks=1, @@ -88,8 +91,9 @@ The log directory must already exist on the compute node; `%j` expands to the Sl job ID. Output is also forwarded through Redis. Workloads must flush their output buffers for live feedback. -Supported partitions are `hour`, `day`, `week`, and `gpu`. Omit `job_options` to use -one task and the cluster's default partition and time limit. `JobOptions` also +`RAJobOptions` validates the partition against `hour`, `day`, `week`, and `gpu`. +Omit `job_options` to use one task and the cluster's default partition and time +limit. `RAJobOptions` also accepts `account` and `qos`. Requesting tasks reserves a Slurm allocation; the workload script runs once and must launch any parallel processes itself. diff --git a/examples/submit_job.py b/examples/submit_job.py index f546b47..1a6d99d 100644 --- a/examples/submit_job.py +++ b/examples/submit_job.py @@ -10,8 +10,8 @@ there are no automatic submission retries. from pathlib import Path -from slurm_manager.event_messages import LogMessage -from slurm_manager.job_options import JobOptions +from slurm_manager.clusters.ra import RAJobOptions +from slurm_manager.event_messages import LogMessage, SlurmMessage from slurm_manager.slurm_manager import SlurmManager @@ -32,22 +32,23 @@ def main( """ lines = [] - def log(message: LogMessage) -> None: + def log(message: SlurmMessage) -> None: """Record and print a message delivered through the job's Redis log channel. Args: - message (LogMessage): Parsed worker stdout or stderr message. + message (SlurmMessage): Parsed worker stdout or stderr message. """ - lines.append(message.log) - print(message.log, flush=True) + if isinstance(message, LogMessage): + lines.append(message.log) + print(message.log, flush=True) - manager = SlurmManager(redis_host="bec-slurm.psi.ch", worker_path=worker_path) + manager = SlurmManager.for_cluster("ra", env_file=".env", worker_path=worker_path) try: job = manager.submit_job( script_path=script_path, working_directory=working_directory, callbacks={"log": log}, - job_options=JobOptions( + job_options=RAJobOptions( name="slurm-manager-redis-stdout-smoke", tasks=1, time_limit_minutes=1, diff --git a/pyproject.toml b/pyproject.toml index 580a0fd..06ec079 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ dependencies = [ "pydantic~=2.12.0", "redis[hiredis]>=6.2, <9.0", "python-dotenv~=1.2", + "typing-extensions>=4.12", ] [project.optional-dependencies] diff --git a/slurm_manager/clusters/__init__.py b/slurm_manager/clusters/__init__.py new file mode 100644 index 0000000..872edc7 --- /dev/null +++ b/slurm_manager/clusters/__init__.py @@ -0,0 +1,11 @@ +"""Built-in Slurm cluster definitions.""" + +from enum import StrEnum + + +class Cluster(StrEnum): + """Built-in clusters accepted by the Slurm manager factory.""" + + RA = "ra" + SFONLINE = "sfonline" + SLSONLINE = "slsonline" diff --git a/slurm_manager/clusters/cluster_info.py b/slurm_manager/clusters/cluster_info.py new file mode 100644 index 0000000..3f6c14b --- /dev/null +++ b/slurm_manager/clusters/cluster_info.py @@ -0,0 +1,15 @@ +"""Non-secret connection settings for a Slurm cluster.""" + +from pydantic import BaseModel, ConfigDict + + +class ClusterInfo(BaseModel): + """REST and Redis connection settings for a cluster.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + url: str + api_version: str + redis_host: str = "bec-slurm.psi.ch" + redis_port: int = 6379 + redis_tls: bool = True diff --git a/slurm_manager/job_options.py b/slurm_manager/clusters/job_options.py similarity index 75% rename from slurm_manager/job_options.py rename to slurm_manager/clusters/job_options.py index 0e10531..9c0c2bb 100644 --- a/slurm_manager/job_options.py +++ b/slurm_manager/clusters/job_options.py @@ -1,6 +1,6 @@ """Validated user-facing Slurm job options.""" -from typing import Annotated, Any, Literal +from typing import Annotated, Any from pydantic import BaseModel, ConfigDict, Field, StringConstraints @@ -21,21 +21,14 @@ class JobOptions(BaseModel): name: NonEmptyString | None = Field( default=None, description="Job name shown in Slurm. Omit to use the scheduler default." ) - partition: Literal["hour", "day", "week", "gpu"] | None = Field( - default=None, - description=( - "RA partition: hour (default/max 1 hour), day (default 4 hours, max 24 hours), " - "week (default 2 days, max 8 days), or gpu (default 1 hour, max 7 days). " - "Omit to use the cluster default, currently hour." - ), + partition: NonEmptyString | None = Field( + default=None, description="Slurm partition name. Omit to use the scheduler default." ) account: NonEmptyString | None = Field( default=None, description=( "Slurm accounting/project account; omit to use your default account association. " - "The account must also be allowed by the selected partition: hour/day allow " - "user and proprietary; gpu allows user and gpu-csaxs; week denies gpu-csaxs " - "and tomcat. These partition rules do not establish your account membership." + "The account must also be allowed by the selected partition." ), ) qos: NonEmptyString | None = Field( @@ -43,9 +36,7 @@ class JobOptions(BaseModel): description=( "Quality of Service controlling scheduling priority and resource limits. " "Must be allowed by both your association and the selected partition. " - "Omit to use your association's default job QoS. The gpu partition allows " - "gpu-default, gpu-day, gpu-hour, and gpu-csaxs, and additionally applies " - "partition QoS gpu-default. Partition QoS is separate from requested job QoS." + "Omit to use your association's default job QoS." ), ) tasks: int = Field( @@ -64,9 +55,7 @@ class JobOptions(BaseModel): strict=True, description=( "Maximum job wall-clock runtime in minutes. Slurm terminates the job at this limit. " - "Omit to use the selected partition's default: hour 60, day 240, week 2880, " - "gpu 60 minutes. Partition maxima are respectively 60, 1440, 11520, and " - "10080 minutes; account/QoS limits may impose additional restrictions. " + "Omit to use the selected partition's default. " "Separate from JobFuture.wait(timeout), which is measured in seconds." ), ) diff --git a/slurm_manager/clusters/ra.py b/slurm_manager/clusters/ra.py new file mode 100644 index 0000000..1fc930b --- /dev/null +++ b/slurm_manager/clusters/ra.py @@ -0,0 +1,26 @@ +"""RA connection settings and typed job options.""" + +from typing import Literal + +from pydantic import Field + +from slurm_manager.clusters.cluster_info import ClusterInfo +from slurm_manager.clusters.job_options import JobOptions + +CLUSTER_INFO: ClusterInfo = ClusterInfo(url="https://ra-slurmapi-001.psi.ch", api_version="v0.0.44") + + +RAPartition = Literal["hour", "day", "week", "gpu"] | None + + +class RAJobOptions(JobOptions): + """Job options for the RA cluster, including its typed partition choices.""" + + partition: RAPartition = Field( # pyright: ignore[reportIncompatibleVariableOverride] + default=None, + description=( + "RA partition: hour (default/max 1 hour), day (default 4 hours, max 24 hours), " + "week (default 2 days, max 8 days), or gpu (default 1 hour, max 7 days). " + "Omit to use the cluster default, currently hour." + ), + ) diff --git a/slurm_manager/clusters/sfonline.py b/slurm_manager/clusters/sfonline.py new file mode 100644 index 0000000..51b061a --- /dev/null +++ b/slurm_manager/clusters/sfonline.py @@ -0,0 +1,17 @@ +"""SFOnline connection settings and typed job options.""" + +from typing import Literal + +from slurm_manager.clusters.cluster_info import ClusterInfo +from slurm_manager.clusters.job_options import JobOptions + +CLUSTER_INFO: ClusterInfo = ClusterInfo(url="https://sf-slurmrest.psi.ch", api_version="v0.0.44") + + +SFOnlinePartition = Literal["prod", "prod-aramis", "prod-athos", "prod-gpu"] + + +class SFOnlineJobOptions(JobOptions): + """Job options for the SFOnline cluster.""" + + partition: SFOnlinePartition = "prod" # pyright: ignore[reportIncompatibleVariableOverride] diff --git a/slurm_manager/clusters/slsonline.py b/slurm_manager/clusters/slsonline.py new file mode 100644 index 0000000..c5eec6e --- /dev/null +++ b/slurm_manager/clusters/slsonline.py @@ -0,0 +1,17 @@ +"""SLSOnline connection settings and typed job options.""" + +from typing import Literal + +from slurm_manager.clusters.cluster_info import ClusterInfo +from slurm_manager.clusters.job_options import JobOptions + +CLUSTER_INFO: ClusterInfo = ClusterInfo(url="https://sls-slurm-001.psi.ch", api_version="v0.0.44") + + +SLSOnlinePartition = Literal["hour", "day", "week"] + + +class SLSOnlineJobOptions(JobOptions): + """Job options for the SLSOnline cluster.""" + + partition: SLSOnlinePartition = "hour" # pyright: ignore[reportIncompatibleVariableOverride] diff --git a/slurm_manager/event_messages.py b/slurm_manager/event_messages.py index 150cb6d..22576bf 100644 --- a/slurm_manager/event_messages.py +++ b/slurm_manager/event_messages.py @@ -11,7 +11,6 @@ from pydantic import BaseModel, Field, TypeAdapter class SlurmBaseMessage(BaseModel): """Base class for all messages sent by the job wrapper. It defines the common structure of the messages.""" - msg_type: str = Field(description="Discriminator used to parse incoming job messages.") metadata: dict[str, str] = Field( default_factory=dict, description="Metadata dictionary that contains additional information about the message, e.g. msg_received, slurm_job_id, job_id.", diff --git a/slurm_manager/job_future.py b/slurm_manager/job_future.py index 1b97215..15b224a 100644 --- a/slurm_manager/job_future.py +++ b/slurm_manager/job_future.py @@ -12,7 +12,7 @@ import threading from concurrent.futures import Future from dataclasses import dataclass from enum import StrEnum -from typing import TYPE_CHECKING, Callable, Literal +from typing import TYPE_CHECKING, Any, Callable, Literal from slurm_manager.event_messages import SlurmMessage @@ -48,7 +48,7 @@ class JobFuture: """ def __init__( - self, job_id: str, manager: SlurmManager, slurm_job_id: str, name: str | None = None + self, job_id: str, manager: SlurmManager[Any], slurm_job_id: str, name: str | None = None ) -> None: """Create a future for one job tracked by its submitting manager. @@ -113,11 +113,11 @@ class JobFuture: """ return self._future.done() and self._future.exception() is None - def exception(self) -> Exception | None: + def exception(self) -> BaseException | None: """Return the recorded terminal exception without waiting. Returns: - Exception | None: Failure or cancellation exception, or None if pending or + BaseException | None: Failure or cancellation exception, or None if pending or successful. """ if self._future.done(): diff --git a/slurm_manager/job_tracker.py b/slurm_manager/job_tracker.py index 0fe4cad..10272b1 100644 --- a/slurm_manager/job_tracker.py +++ b/slurm_manager/job_tracker.py @@ -584,21 +584,16 @@ class JobTracker: ) topic = topic_info.heartbeat - def wrapped_callback(message: HeartBeatMessage, sub_info: SubscriptionInfo) -> None: - """Enrich a parsed worker message and dispatch its registered handler. - - Args: - message (HeartBeatMessage): Raw Redis payload or parsed worker message, - as specified by the annotation. - sub_info (SubscriptionInfo): Subscription ownership and heartbeat - bookkeeping. - """ + def wrapped_callback(message: SlurmMessage) -> None: + if not isinstance(message, HeartBeatMessage): + logger.warning("Unexpected message type %s on topic %s", message.msg_type, topic) + return try: message.metadata.update( { "msg_received": datetime.now().isoformat(), "job_id": sub_info.job_id, - "slurm_job_id": sub_info.slurm_job_id, + "slurm_job_id": future.slurm_job_id, } ) self._heartbeat_callback(message, sub_info) @@ -607,7 +602,7 @@ class JobTracker: "Error in callback for topic %s: %s", message.msg_type, message.timestamp ) - cb_id = self._sub_client.subscribe(topic, partial(wrapped_callback, sub_info=sub_info)) + cb_id = self._sub_client.subscribe(topic, wrapped_callback) sub_info.callback_id = cb_id sub_info.last_heartbeat = time.time() self._register_subscription_for_job(sub_info=sub_info) @@ -631,15 +626,12 @@ class JobTracker: ) event_topic = topic_info.event - def wrapped_callback(message: StatusMessage, future: JobFuture) -> None: - """Enrich a parsed worker message and dispatch its registered handler. - - Args: - message (StatusMessage): Raw Redis payload or parsed worker message, as - specified by the annotation. - future (JobFuture): Tracked future whose lifecycle or subscriptions are - being managed. - """ + def wrapped_callback(message: SlurmMessage) -> None: + if not isinstance(message, StatusMessage): + logger.warning( + "Unexpected message type %s on topic %s", message.msg_type, event_topic + ) + return try: message.metadata.update( { @@ -652,7 +644,7 @@ class JobTracker: except Exception: logger.error("Error in callback for topic %s: %s", message.msg_type, message.status) - cb_id = self._sub_client.subscribe(event_topic, partial(wrapped_callback, future=future)) + cb_id = self._sub_client.subscribe(event_topic, wrapped_callback) sub_info.callback_id = cb_id self._register_subscription_for_job(sub_info=sub_info) diff --git a/slurm_manager/redis_sub_client.py b/slurm_manager/redis_sub_client.py index 0ab2345..687be1d 100644 --- a/slurm_manager/redis_sub_client.py +++ b/slurm_manager/redis_sub_client.py @@ -49,7 +49,7 @@ class RedisSubClient: def __init__( self, bootstrap: str | list[str] = "localhost:6379", - redis_cls: type[Redis] = Redis, + redis_cls: Callable[..., Redis] = Redis, **redis_kwargs: Any, ) -> None: """Create Redis resources without starting the listener until subscribed. @@ -57,7 +57,7 @@ class RedisSubClient: Args: bootstrap (str | list[str]): Redis host:port or a nonempty address list; only the first entry is used. - redis_cls (type[Redis]): Redis client implementation, injectable for tests. + redis_cls (Callable[..., Redis]): Redis client factory, injectable for tests. **redis_kwargs (Any): Additional Redis constructor options such as socket timeouts. diff --git a/slurm_manager/slurm_manager.py b/slurm_manager/slurm_manager.py index 9cf4a2a..22263fd 100644 --- a/slurm_manager/slurm_manager.py +++ b/slurm_manager/slurm_manager.py @@ -9,18 +9,23 @@ from collections.abc import Callable from datetime import datetime from logging import getLogger from pathlib import Path -from typing import Any, Literal +from typing import Any, Generic, Literal, overload from uuid import uuid4 +from typing_extensions import TypeVar + +from slurm_manager.clusters import Cluster, ra, sfonline, slsonline +from slurm_manager.clusters.job_options import JobOptions from slurm_manager.event_messages import SlurmMessage, StatusMessage from slurm_manager.job_future import JobFuture, JobStatus -from slurm_manager.job_options import JobOptions from slurm_manager.job_tracker import JobTracker, SubscriptionInfo from slurm_manager.redis_sub_client import RedisSubClient from slurm_manager.slurm_rest_client import SlurmRestClient, SlurmRestError logger = getLogger(__name__) +_JobOptionsT = TypeVar("_JobOptionsT", bound=JobOptions, default=JobOptions) + def _job_exit_code(exit_code: Any) -> int | str | None: """Decode a v0.0.44 process exit status without treating unset codes as success. @@ -43,9 +48,35 @@ def _job_exit_code(exit_code: Any) -> int | str | None: return code if not signal else f"signal {signal}" -class SlurmManager: +class SlurmManager(Generic[_JobOptionsT]): """Submit Slurm jobs and coordinate tracking and scheduler monitoring.""" + @overload + def __init__( + self: SlurmManager[JobOptions], + redis_host: str = "localhost", + redis_port: int = 6379, + *, + redis_tls: bool = True, + env_file: str | Path = ".env", + rest_client: SlurmRestClient | None = None, + worker_path: str = "/usr/bin/bec-slurm-worker", + job_options_type: None = None, + ) -> None: ... + + @overload + def __init__( + self, + redis_host: str = "localhost", + redis_port: int = 6379, + *, + redis_tls: bool = True, + env_file: str | Path = ".env", + rest_client: SlurmRestClient | None = None, + worker_path: str = "/usr/bin/bec-slurm-worker", + job_options_type: type[_JobOptionsT], + ) -> None: ... + def __init__( # noqa: PLR0913 - connection and worker configuration self, redis_host: str = "localhost", @@ -55,6 +86,7 @@ class SlurmManager: env_file: str | Path = ".env", rest_client: SlurmRestClient | None = None, worker_path: str = "/usr/bin/bec-slurm-worker", + job_options_type: type[_JobOptionsT] | None = None, ) -> None: """Create REST/Redis clients and start background job monitoring. @@ -68,12 +100,14 @@ class SlurmManager: rest_client (SlurmRestClient | None): Optional preconfigured REST client; None creates one from env_file. worker_path (str): Absolute path to the Go executable on compute nodes. + job_options_type: Model used to validate submissions for this manager. Raises: ValueError: The worker path or REST connection settings are invalid. """ if not worker_path.startswith("/"): raise ValueError("Worker path must be an absolute compute-node path") + self._job_options_type = JobOptions if job_options_type is None else job_options_type self._redis_tls = redis_tls self.worker_path = worker_path self._redis_address = f"{redis_host}:{redis_port}" @@ -90,6 +124,74 @@ class SlurmManager: ) self._start_threads() + @overload + @staticmethod + def for_cluster( + cluster: Literal["ra", Cluster.RA], + *, + env_file: str | Path, + worker_path: str = "/usr/bin/bec-slurm-worker", + ) -> SlurmManager[ra.RAJobOptions]: ... + + @overload + @staticmethod + def for_cluster( + *, env_file: str | Path, worker_path: str = "/usr/bin/bec-slurm-worker" + ) -> SlurmManager[ra.RAJobOptions]: ... + + @overload + @staticmethod + def for_cluster( + cluster: Literal["sfonline", "SFOnline", Cluster.SFONLINE], + *, + env_file: str | Path, + worker_path: str = "/usr/bin/bec-slurm-worker", + ) -> SlurmManager[sfonline.SFOnlineJobOptions]: ... + + @overload + @staticmethod + def for_cluster( + cluster: Literal["slsonline", "SLSOnline", Cluster.SLSONLINE], + *, + env_file: str | Path, + worker_path: str = "/usr/bin/bec-slurm-worker", + ) -> SlurmManager[slsonline.SLSOnlineJobOptions]: ... + + @staticmethod + def for_cluster( + cluster: str = Cluster.RA, + *, + env_file: str | Path, + worker_path: str = "/usr/bin/bec-slurm-worker", + ) -> SlurmManager[Any]: + """Create a manager bound to a built-in cluster using a local credential file.""" + options_type: type[JobOptions] + match cluster: + case Cluster.RA: + info = ra.CLUSTER_INFO + options_type = ra.RAJobOptions + case Cluster.SFONLINE | "SFOnline": + info = sfonline.CLUSTER_INFO + options_type = sfonline.SFOnlineJobOptions + case Cluster.SLSONLINE | "SLSOnline": + info = slsonline.CLUSTER_INFO + options_type = slsonline.SLSOnlineJobOptions + case _: + raise ValueError( + f"Unknown Slurm cluster {cluster!r}; supported clusters: ra, sfonline, slsonline" + ) + rest_client = SlurmRestClient( + env_file, rest_url=info.url, api_version=info.api_version, use_environment=False + ) + return SlurmManager( + info.redis_host, + info.redis_port, + redis_tls=info.redis_tls, + worker_path=worker_path, + rest_client=rest_client, + job_options_type=options_type, + ) + ################################################ # Public Job Management # ################################################ @@ -100,7 +202,7 @@ class SlurmManager: env_path: str | Path | None = None, *, working_directory: str, - job_options: JobOptions | None = None, + job_options: _JobOptionsT | None = None, callbacks: dict[Literal["log", "status", "heartbeat"], Callable[[SlurmMessage], None]] | None = None, ) -> JobFuture: @@ -138,8 +240,10 @@ class SlurmManager: """ if not working_directory.startswith("/"): raise ValueError("Working directory must be an absolute compute-node path") - if callbacks and set(callbacks) - {"log", "status", "heartbeat"}: + if callbacks and set(callbacks).difference({"log", "status", "heartbeat"}): raise ValueError("Callbacks must use log, status, or heartbeat keys") + options = job_options.model_dump() if isinstance(job_options, JobOptions) else job_options + job = self._job_options_type.model_validate({} if options is None else options).to_rest() job_id = str(uuid4()) script = self._build_job_script( script_path, @@ -149,7 +253,6 @@ class SlurmManager: redis_address=self._redis_address, redis_tls=self._redis_tls, ) - job = JobOptions.model_validate(job_options or {}).to_rest() job.update( { "current_working_directory": working_directory, diff --git a/slurm_manager/slurm_rest_client.py b/slurm_manager/slurm_rest_client.py index de542ca..d0dba73 100644 --- a/slurm_manager/slurm_rest_client.py +++ b/slurm_manager/slurm_rest_client.py @@ -64,13 +64,24 @@ class SlurmRestClient: request so replacing an expired token does not require restarting a manager. """ - def __init__(self, env_file: str | Path = ".env", timeout: float = 30) -> None: + def __init__( + self, + env_file: str | Path = ".env", + timeout: float = 30, + *, + rest_url: str | None = None, + api_version: str | None = None, + use_environment: bool = True, + ) -> None: """Load and validate slurmrestd connection settings. Args: env_file (str | Path): Local credential dotenv path. Environment variables take precedence. timeout (float): Positive HTTP request timeout in seconds. + rest_url: Explicit endpoint, overriding connection settings from dotenv or environment. + api_version: Explicit REST version. + use_environment: Allow process-wide environment overrides for dotenv values. Raises: ValueError: The URL, API version, token, or timeout is invalid. @@ -79,14 +90,19 @@ class SlurmRestClient: if timeout <= 0: raise ValueError("REST timeout must be positive") self.timeout = timeout + self._use_environment = use_environment settings = self._settings() - self.url = settings.get("SLURM_REST_URL", "").rstrip("/") + self.url = (settings["SLURM_REST_URL"] if rest_url is None else rest_url).rstrip("/") parsed = urlsplit(self.url) if parsed.scheme not in {"http", "https"} or not parsed.hostname: raise ValueError("Set SLURM_REST_URL to the slurmrestd HTTP(S) URL") if parsed.username or parsed.password or parsed.query or parsed.fragment: raise ValueError("SLURM_REST_URL must not contain credentials, query, or fragment") - self.api_version = settings.get("SLURM_REST_API_VERSION") or "v0.0.44" + self.api_version = ( + (settings["SLURM_REST_API_VERSION"] or "v0.0.44") + if api_version is None + else api_version + ) if not re.fullmatch(r"v\d+\.\d+\.\d+", self.api_version): raise ValueError("SLURM_REST_API_VERSION must look like v0.0.44") self._headers(settings) @@ -249,7 +265,10 @@ class SlurmRestClient: """ values = dotenv_values(self.env_file, interpolate=False) keys = ("SLURM_REST_URL", "SLURM_REST_API_VERSION", "SLURM_JWT", "SLURM_USER") - return {key: os.environ.get(key, values.get(key) or "") for key in keys} + settings = {key: values.get(key) or "" for key in keys} + if self._use_environment: + return {key: os.environ.get(key, value) for key, value in settings.items()} + return settings @staticmethod def _headers(settings: dict[str, str]) -> dict[str, str]: @@ -267,7 +286,7 @@ class SlurmRestClient: """ token = settings.get("SLURM_JWT", "") if not token: - raise ValueError("Set SLURM_JWT in the local .env file or environment") + raise ValueError("Set SLURM_JWT in the credential file or enabled environment") headers = {"X-SLURM-USER-TOKEN": token, "Accept": "application/json"} if settings.get("SLURM_USER"): headers["X-SLURM-USER-NAME"] = settings["SLURM_USER"] diff --git a/test/fixtures/curl_stub.py b/test/fixtures/curl_stub.py index d700e5d..6a63acb 100644 --- a/test/fixtures/curl_stub.py +++ b/test/fixtures/curl_stub.py @@ -2,6 +2,12 @@ import json import os import sys from pathlib import Path +from typing import NotRequired, TypedDict + + +class RegistryState(TypedDict): + files: dict[str, str] + failed: NotRequired[bool] def main() -> None: @@ -13,7 +19,9 @@ def main() -> None: if os.environ.get("MOCK_CURL_EXIT"): sys.exit(int(os.environ["MOCK_CURL_EXIT"])) state_path = Path(os.environ["MOCK_CURL_STATE"]) - state = json.loads(state_path.read_text()) if state_path.exists() else {"files": {}} + state: RegistryState = ( + json.loads(state_path.read_text()) if state_path.exists() else {"files": {}} + ) url = args[-1] body = b"" if "--upload-file" in args: diff --git a/test/integration/test_ra.py b/test/integration/test_ra.py index b928bd4..d02390f 100644 --- a/test/integration/test_ra.py +++ b/test/integration/test_ra.py @@ -14,15 +14,17 @@ import threading import time from collections.abc import Callable from pathlib import Path -from typing import Literal +from typing import Literal, TypeVar import pytest -from slurm_manager.event_messages import SlurmMessage +from slurm_manager.clusters.job_options import JobOptions +from slurm_manager.event_messages import HeartBeatMessage, LogMessage, SlurmMessage, StatusMessage from slurm_manager.job_future import JobFuture -from slurm_manager.job_options import JobOptions from slurm_manager.slurm_manager import SlurmManager +_MessageT = TypeVar("_MessageT", bound=SlurmMessage) + pytestmark = pytest.mark.skipif( not os.environ.get("SLURM_RA_HOME"), reason="Explicit SLURM_RA_HOME required for live jobs" ) @@ -63,7 +65,11 @@ def test_ra_modules(tmp_path: Path) -> None: script_path=workload, env_path=activation, working_directory=remote_home, - callbacks={"log": lambda message: lines.append(message.log)}, + callbacks={ + "log": lambda message: ( + lines.append(message.log) if isinstance(message, LogMessage) else None + ) + }, job_options=JobOptions( name="smoke-modules", partition="hour", @@ -113,22 +119,22 @@ def test_ra_job_lifecycle(tmp_path: Path) -> None: with lock: events.append(message) - def received(job: JobFuture, kind: str) -> list[SlurmMessage]: + def received(job: JobFuture, message_type: type[_MessageT]) -> list[_MessageT]: """Return a snapshot of messages for the scheduler job. Args: job (JobFuture): Job whose feedback is selected. - kind (str): Message discriminator to select. + message_type: Message model to select. Returns: - list[SlurmMessage]: Matching feedback collected so far. + Matching feedback collected so far. """ with lock: return [ message for message in events if message.metadata.get("slurm_job_id") == job.slurm_job_id - and message.msg_type == kind + and isinstance(message, message_type) ] def submit( @@ -214,7 +220,11 @@ def test_ra_job_lifecycle(tmp_path: Path) -> None: detached = submit( "unlisten", "echo local-only\nsleep 2\n", - {"log": lambda message: local_lines.append(message.log)}, + { + "log": lambda message: ( + local_lines.append(message.log) if isinstance(message, LogMessage) else None + ) + }, ) detached.wait(timeout=90) finally: @@ -225,15 +235,15 @@ def test_ra_job_lifecycle(tmp_path: Path) -> None: finally: manager.shutdown(timeout=65) - assert sorted(message.log for message in received(live, "log")) == sorted( + assert sorted(message.log for message in received(live, LogMessage)) == sorted( [f"stdout-{index}" for index in range(1, 11)] + ["stderr-ok"] ) - assert received(live, "heartbeat") - assert any(message.status == "finished" for message in received(live, "status")) - assert [message.log for message in received(failed, "log")] == ["failure-visible"] - assert any(message.status.startswith("error") for message in received(failed, "status")) - assert received(cancelled, "heartbeat") - assert any(message.status == "cancelled" for message in received(cancelled, "status")) - assert not received(detached, "log") - assert not received(detached, "status") + assert received(live, HeartBeatMessage) + assert any(message.status == "finished" for message in received(live, StatusMessage)) + assert [message.log for message in received(failed, LogMessage)] == ["failure-visible"] + assert any(message.status.startswith("error") for message in received(failed, StatusMessage)) + assert received(cancelled, HeartBeatMessage) + assert any(message.status == "cancelled" for message in received(cancelled, StatusMessage)) + assert not received(detached, LogMessage) + assert not received(detached, StatusMessage) assert local_lines == ["local-only"] diff --git a/test/test_job_options.py b/test/test_job_options.py index 549d414..ea40dd5 100644 --- a/test/test_job_options.py +++ b/test/test_job_options.py @@ -3,7 +3,8 @@ import pytest from pydantic import ValidationError -from slurm_manager.job_options import JobOptions +from slurm_manager.clusters.job_options import JobOptions +from slurm_manager.clusters.ra import RAJobOptions @pytest.mark.parametrize( @@ -42,10 +43,14 @@ def test_runtime_uses_minutes_and_slurm_optional_number_shape(): @pytest.mark.parametrize("partition", ["hour", "day", "week", "gpu"]) def test_supported_ra_partitions(partition): - assert JobOptions(partition=partition).to_rest()["partition"] == partition + assert RAJobOptions(partition=partition).to_rest()["partition"] == partition @pytest.mark.parametrize("partition", ["admin", "jupyter", "gpu-large", "unknown"]) -def test_unsupported_partitions_are_rejected(partition): +def test_unsupported_ra_partitions_are_rejected(partition): with pytest.raises(ValidationError): - JobOptions(partition=partition) + RAJobOptions.model_validate({"partition": partition}) + + +def test_generic_job_options_accept_a_custom_partition(): + assert JobOptions(partition="batch").to_rest()["partition"] == "batch" diff --git a/test/test_job_tracker.py b/test/test_job_tracker.py index 322feda..11f3314 100644 --- a/test/test_job_tracker.py +++ b/test/test_job_tracker.py @@ -10,6 +10,7 @@ from slurm_manager.event_messages import StatusMessage from slurm_manager.job_future import JobFuture from slurm_manager.job_tracker import JobTracker, TopicInfo from slurm_manager.redis_sub_client import RedisSubClient +from slurm_manager.slurm_manager import SlurmManager @pytest.fixture @@ -23,7 +24,7 @@ def tracker(): def test_heartbeat_snapshots_cannot_mutate_tracking_state(tracker): - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") with mock.patch("slurm_manager.job_tracker.time.time", return_value=80): tracker.track(future) @@ -36,8 +37,8 @@ def test_heartbeat_snapshots_cannot_mutate_tracking_state(tracker): def test_completion_preserves_other_jobs_and_their_redis_subscriptions(tracker): - first = JobFuture("first", manager=None, slurm_job_id="123") - second = JobFuture("second", manager=None, slurm_job_id="124") + first = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") + second = JobFuture("second", manager=mock.Mock(spec=SlurmManager), slurm_job_id="124") tracker.track(first) tracker.track(second) tracker.wait_until_ready("second") @@ -61,7 +62,7 @@ def test_completion_preserves_other_jobs_and_their_redis_subscriptions(tracker): def test_scheduler_check_skips_a_job_removed_after_snapshot(tracker): - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) tracker.apply_status(StatusMessage(status="finished"), future) @@ -71,7 +72,7 @@ def test_scheduler_check_skips_a_job_removed_after_snapshot(tracker): @pytest.mark.parametrize("status", ["finished", "cancelled", "error:workload failed", "unknown"]) def test_synthesized_terminal_status_notifies_listeners_once(tracker, status): - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) received = [] tracker.add_subscription("first", "status", received.append) @@ -93,7 +94,7 @@ def test_synthesized_terminal_status_notifies_listeners_once(tracker, status): def test_redis_status_is_dispatched_once_and_shutdown_drains_it(tracker): - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) received = [] tracker.add_subscription("first", "status", received.append) @@ -108,7 +109,7 @@ def test_redis_status_is_dispatched_once_and_shutdown_drains_it(tracker): def test_removing_tracking_reports_failure_to_status_listeners(tracker): - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) received = [] tracker.add_subscription("first", "status", received.append) @@ -125,7 +126,7 @@ def test_removing_tracking_reports_failure_to_status_listeners(tracker): def test_callback_errors_are_logged_without_stopping_other_callbacks(tracker, caplog): import threading - future = JobFuture("first", manager=None, slurm_job_id="123") + future = JobFuture("first", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") tracker.track(future) received = threading.Event() diff --git a/test/test_slurm_manager.py b/test/test_slurm_manager.py index 4498ca0..c6edb93 100644 --- a/test/test_slurm_manager.py +++ b/test/test_slurm_manager.py @@ -10,10 +10,15 @@ from unittest import mock import fakeredis import pytest +from pydantic import ValidationError +from slurm_manager.clusters import Cluster, ra +from slurm_manager.clusters.job_options import JobOptions +from slurm_manager.clusters.ra import RAJobOptions +from slurm_manager.clusters.sfonline import SFOnlineJobOptions +from slurm_manager.clusters.slsonline import SLSOnlineJobOptions from slurm_manager.event_messages import HeartBeatMessage, StatusMessage from slurm_manager.job_future import JobFuture -from slurm_manager.job_options import JobOptions from slurm_manager.job_tracker import TopicInfo from slurm_manager.redis_sub_client import RedisSubClient from slurm_manager.slurm_manager import SlurmManager @@ -56,7 +61,7 @@ def heartbeat_info(manager, future): def test_wait_propagates_failure_arriving_during_wait(): - future = JobFuture("job", manager=None, slurm_job_id="123") + future = JobFuture("job", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") timer = threading.Timer(0.05, lambda: future._update_status("error", "exit code 7")) timer.start() try: @@ -67,7 +72,7 @@ def test_wait_propagates_failure_arriving_during_wait(): def test_wait_timeout_does_not_complete_future(): - future = JobFuture("job", manager=None, slurm_job_id="123") + future = JobFuture("job", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") with pytest.raises(TimeoutError): future.wait(timeout=0) assert not future.done() @@ -77,7 +82,7 @@ def test_wait_timeout_does_not_complete_future(): def test_terminal_state_ignores_late_status_updates(): - future = JobFuture("job", manager=None, slurm_job_id="123") + future = JobFuture("job", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123") future._update_status("finished") future._update_status("running") assert future.status == "finished" @@ -600,22 +605,30 @@ def test_shutdown_clears_manager_wide_registrations(manager): @pytest.mark.parametrize("tls", [True, False]) -def test_redis_transport_reaches_subscriber_and_worker(tmp_path, tls): +def test_cluster_redis_transport_reaches_subscriber_and_worker(tmp_path, monkeypatch, tls): + info = ra.CLUSTER_INFO.model_copy( + update={"redis_host": "redis.example", "redis_port": 6380, "redis_tls": tls} + ) + monkeypatch.setattr(ra, "CLUSTER_INFO", info) workload = tmp_path / "job.sh" workload.write_text("true\n") client = RedisSubClient(redis_cls=fakeredis.FakeRedis) rest = mock.Mock(spec=SlurmRestClient) rest.submit.return_value = {"job_id": 123} - with mock.patch("slurm_manager.slurm_manager.RedisSubClient", return_value=client) as ctor: - manager = SlurmManager(redis_host="redis.example", rest_client=rest, redis_tls=tls) + with ( + mock.patch("slurm_manager.slurm_manager.RedisSubClient", return_value=client) as ctor, + mock.patch("slurm_manager.slurm_manager.SlurmRestClient", return_value=rest), + ): + manager = SlurmManager.for_cluster("ra", env_file=tmp_path / "ra.env") try: - expected = {"bootstrap": "redis.example:6379"} + expected: dict[str, str | bool] = {"bootstrap": "redis.example:6380"} if tls: expected.update(ssl=True, ssl_cert_reqs="required", ssl_check_hostname=True) ctor.assert_called_once_with(**expected) with mock.patch.object(manager._job_tracker, "wait_until_ready"): manager.submit_job(workload, working_directory="/remote/work") script = rest.submit.call_args.args[0] + assert "--redis-address redis.example:6380" in script assert f"--redis-tls={str(tls).lower()}" in script finally: manager.shutdown(timeout=3) @@ -633,3 +646,81 @@ def test_tls_uses_system_trust_by_default(): ) finally: manager.shutdown(timeout=3) + + +@pytest.mark.parametrize("use_enum", [False, True], ids=["name", "enum"]) +@pytest.mark.parametrize( + ("cluster", "url", "invalid_options"), + [ + ("ra", "https://ra-slurmapi-001.psi.ch", RAJobOptions.model_construct(partition="prod")), + ( + "sfonline", + "https://sf-slurmrest.psi.ch", + SFOnlineJobOptions.model_construct(partition="hour"), + ), + ( + "slsonline", + "https://sls-slurm-001.psi.ch", + SLSOnlineJobOptions.model_construct(partition="gpu"), + ), + ], +) +def test_factory_binds_endpoint_credentials_and_partition_validation( + tmp_path, monkeypatch, cluster, url, invalid_options, use_enum +): + credentials = tmp_path / f"{cluster}.env" + credentials.write_text("SLURM_JWT=ra-token\n") + monkeypatch.setenv("SLURM_JWT", "other-token") + monkeypatch.setenv("SLURM_REST_URL", "https://other.example") + monkeypatch.setenv("SLURM_REST_API_VERSION", "v0.0.99") + + redis = RedisSubClient(redis_cls=fakeredis.FakeRedis) + with mock.patch("slurm_manager.slurm_manager.RedisSubClient", return_value=redis) as ctor: + manager = SlurmManager.for_cluster( + Cluster(cluster) if use_enum else cluster, env_file=credentials + ) + try: + ctor.assert_called_once_with( + bootstrap="bec-slurm.psi.ch:6379", + ssl=True, + ssl_cert_reqs="required", + ssl_check_hostname=True, + ) + client = manager.rest_client + assert client.url == url + assert client.api_version == "v0.0.44" + assert client._headers(client._settings())["X-SLURM-USER-TOKEN"] == "ra-token" + with mock.patch.object(client, "submit") as submit_rest: + with pytest.raises(ValidationError, match="partition"): + manager.submit_job( + "examples/print_for_10s.sh", + working_directory="/remote/work", + job_options=invalid_options, + ) + submit_rest.assert_not_called() + finally: + manager.shutdown(timeout=3) + + +@pytest.mark.parametrize( + ("options_type", "partition"), + [ + (SFOnlineJobOptions, "prod"), + (SFOnlineJobOptions, "prod-aramis"), + (SFOnlineJobOptions, "prod-athos"), + (SFOnlineJobOptions, "prod-gpu"), + (SLSOnlineJobOptions, "hour"), + (SLSOnlineJobOptions, "day"), + (SLSOnlineJobOptions, "week"), + ], +) +def test_online_job_options_accept_allowed_partitions(options_type, partition): + assert options_type(partition=partition).to_rest()["partition"] == partition + + +@pytest.mark.parametrize( + ("options_type", "default_partition"), + [(SFOnlineJobOptions, "prod"), (SLSOnlineJobOptions, "hour")], +) +def test_online_job_options_send_cluster_default_partition(options_type, default_partition): + assert options_type().to_rest()["partition"] == default_partition diff --git a/test/test_slurm_rest_client.py b/test/test_slurm_rest_client.py index f8bf761..daf78e9 100644 --- a/test/test_slurm_rest_client.py +++ b/test/test_slurm_rest_client.py @@ -5,6 +5,7 @@ from __future__ import annotations import json import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace import pytest @@ -42,7 +43,7 @@ def endpoint(tmp_path, monkeypatch): payload if isinstance(payload, bytes) else json.dumps(payload).encode() ) - def log_message(self, *_args): + def log_message(self, format, *args): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) @@ -81,8 +82,10 @@ def test_submit_release_cancel_and_accounting_wire_format(endpoint): } assert client.submit("#!/bin/bash\necho hello", job)["job_id"] == 123 client.release("123") - assert client.get_job("123")["job_state"] == ["RUNNING"] - assert client.get_job("123", accounting=True)["state"]["current"] == ["COMPLETED"] + running = client.get_job("123") + completed = client.get_job("123", accounting=True) + assert running is not None and running["job_state"] == ["RUNNING"] + assert completed is not None and completed["state"]["current"] == ["COMPLETED"] client.cancel("123") assert [(method, path) for method, path, _, _ in calls] == [ ("POST", "/slurm/v0.0.44/job/submit"), @@ -111,6 +114,23 @@ def test_token_rotation_and_environment_override(endpoint, monkeypatch): assert calls[1][2]["X-Slurm-User-Name"] == "alice" +def test_removed_environment_override_falls_back_to_credential_file(tmp_path, monkeypatch): + class StaleEnvironment(dict[str, str]): + def __contains__(self, key: object) -> bool: + # Simulate SLURM_JWT disappearing just after a membership check. + return key == "SLURM_JWT" or super().__contains__(key) + + monkeypatch.delenv("SLURM_JWT", raising=False) + env_file = tmp_path / ".env" + env_file.write_text("SLURM_JWT=file-token\n") + client = SlurmRestClient(env_file, rest_url="https://slurm.example") + monkeypatch.setattr( + "slurm_manager.slurm_rest_client.os", SimpleNamespace(environ=StaleEnvironment()) + ) + + assert client._settings()["SLURM_JWT"] == "file-token" + + @pytest.mark.parametrize( "status,payload", [ @@ -189,11 +209,12 @@ def test_manager_submission_and_completion_over_http(endpoint): finally: manager.shutdown(timeout=3) assert not manager._heartbeat_monitoring_thread.is_alive() - assert not redis._listener_thread.is_alive() + assert redis._listener_thread is not None and not redis._listener_thread.is_alive() @pytest.mark.parametrize("error_response", [False, True]) def test_truncated_responses_raise_a_transport_error(endpoint, error_response): + from email.message import Message from http.client import IncompleteRead from unittest import mock from urllib.error import HTTPError @@ -203,7 +224,7 @@ def test_truncated_responses_raise_a_transport_error(endpoint, error_response): response = mock.MagicMock() response.read.side_effect = IncompleteRead(b"partial", 100) if error_response: - error = HTTPError("http://local/job", 500, "Server error", {}, response) + error = HTTPError("http://local/job", 500, "Server error", Message(), response) patch = mock.patch.object(client._opener, "open", side_effect=error) else: opened = mock.MagicMock()