feat: add Slurm resource and dependency options

This commit is contained in:
wakonig_k authored and Klaus Wakonig committed 2026-11-11 19:59:51 +01:00
1 parent be30527243
commit cf40bc2cac
7 files changed
+380 -28

No files matched your search

+29 -2
View File
@@ -69,7 +69,9 @@ try:
name="my-analysis",
partition="day",
tasks=1,
time_limit_minutes=120,
cpus_per_task=4,
memory_per_node=8192,
time_limit=120,
standard_output="/das/home/your_username/slurm_logs/%j.out",
standard_error="/das/home/your_username/slurm_logs/%j.err",
),
@@ -97,7 +99,32 @@ 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.
`time_limit_minutes` limits job runtime in minutes. `job.wait(timeout=...)` limits
Use `reservation` to name an existing Slurm reservation and `cpus_per_task` to
request CPUs per task. Choose either `memory_per_cpu` or
`memory_per_node`, both measured in MiB. A per-node value of `0` requests all
memory on each node. Use `exclusive=True` to request exclusive nodes or
`shared` to set a Slurm sharing mode explicitly. Slurm still applies the
requested memory amount or its default.
Use `nodes` for a node count or range such as `"2-4"`, and `tasks_per_node` for
task placement. With `tasks_per_node` set, omit `tasks` to let Slurm infer the
total. Otherwise, omitted `tasks` defaults to one. Use `tasks_per_core` to
limit tasks per CPU core, or set it to `65535` for no per-core limit. Use
`tres_per_node` or `tres_per_task` to request resources such as GPUs,
`constraints` to select nodes by feature, and `dependency` to wait for other
jobs, for example `"afterok:12345"`.
To submit a job that runs after earlier jobs succeed, pass their returned
futures to `submit_job(..., after_ok=prepare)` or
`submit_job(..., after_ok=[prepare, calibrate])`. Use `after_any` to wait until
all of those jobs finish, regardless of outcome. You can combine `after_ok`
and `after_any` to require both conditions. Use futures returned by the
same manager, including completed jobs. For external jobs or other dependency
types, supply a raw expression in `JobOptions.dependency` by itself. The
manager asks Slurm to cancel a dependent job if its dependency can never
be satisfied.
`time_limit` limits job runtime in minutes. `job.wait(timeout=...)` limits
how long the client waits, in seconds; it raises on failure or timeout. A timeout
does not cancel the job automatically, so the example explicitly calls
`job.cancel()`. `manager.shutdown()` disconnects without cancelling jobs.
+1 -1
View File
@@ -51,7 +51,7 @@ def main(
job_options=RAJobOptions(
name="slurm-manager-redis-stdout-smoke",
tasks=1,
time_limit_minutes=1,
time_limit=1,
standard_output=f"{log_directory}/redis-stdout-%j.out",
standard_error=f"{log_directory}/redis-stdout-%j.err",
),
+81 -11
View File
@@ -1,8 +1,8 @@
"""Validated user-facing Slurm job options."""
from typing import Annotated, Any
from typing import Annotated, Any, Literal, Self
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, model_validator
NonEmptyString = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
@@ -39,17 +39,74 @@ class JobOptions(BaseModel):
"Omit to use your association's default job QoS."
),
)
reservation: NonEmptyString | None = Field(
default=None, description="Name of an existing Slurm reservation to use."
)
constraints: NonEmptyString | None = Field(
default=None, description="Required scheduler-defined node features."
)
dependency: NonEmptyString | None = Field(
default=None, description="Slurm dependency expression, such as afterok:12345."
)
nodes: NonEmptyString | None = Field(
default=None, description='Slurm node count or range, such as "2" or "2-4".'
)
tasks: int = Field(
default=1,
ge=1,
strict=True,
description=(
"Number of Slurm tasks requested for the allocation; defaults to one. "
"The worker executes the workload script once, without launching MPI ranks. "
"This does not specify CPUs per task."
"Total Slurm tasks. Defaults to one unless tasks_per_node is supplied. "
"The worker executes the workload script once, without launching MPI ranks."
),
)
time_limit_minutes: int | None = Field(
tasks_per_node: int | None = Field(
default=None,
ge=1,
le=65533,
strict=True,
description="Number of tasks to request per node.",
)
tasks_per_core: int | None = Field(
default=None,
ge=1,
le=65535,
strict=True,
description="Maximum tasks per core. Use 65535 for no per-core task limit.",
)
cpus_per_task: int | None = Field(
default=None,
ge=1,
le=65533,
strict=True,
description="Number of CPUs requested per task. Omit to use Slurm's default.",
)
memory_per_cpu: int | None = Field(
default=None, ge=1, lt=2**63, strict=True, description="Memory in MiB per allocated CPU."
)
memory_per_node: int | None = Field(
default=None,
ge=0,
lt=2**63,
strict=True,
description="Memory in MiB per node. Use 0 to request all memory on each node.",
)
tres_per_node: NonEmptyString | None = Field(
default=None, description="Slurm trackable resource requests per node, such as GPUs."
)
tres_per_task: NonEmptyString | None = Field(
default=None, description="Slurm trackable resource requests per task, such as GPUs."
)
exclusive: bool = Field(
default=False, strict=True, description="Request exclusive access to the allocated nodes."
)
shared: list[Literal["none", "oversubscribe", "user", "mcs", "topo"]] | None = Field(
default=None,
min_length=1,
max_length=1,
description='Job resource sharing mode. Use ["none"] to request exclusive nodes.',
)
time_limit: int | None = Field(
default=None,
ge=1,
strict=True,
@@ -76,6 +133,14 @@ class JobOptions(BaseModel):
),
)
@model_validator(mode="after")
def _validate_resource_options(self) -> Self:
if self.memory_per_cpu is not None and self.memory_per_node is not None:
raise ValueError("Specify either memory_per_cpu or memory_per_node")
if self.exclusive and self.shared is not None:
raise ValueError("Specify either exclusive=True or shared")
return self
################################################
# Public Serialization #
################################################
@@ -84,10 +149,15 @@ class JobOptions(BaseModel):
"""Serialize validated options into slurmrestd job-description fields.
Returns:
dict[str, Any]: REST options with unset values omitted and runtime expressed
as an optional integer.
dict[str, Any]: REST options with unset values omitted and memory and runtime
encoded as Slurm optional integers.
"""
options = self.model_dump(exclude={"time_limit_minutes"}, exclude_none=True)
if self.time_limit_minutes is not None:
options["time_limit"] = {"set": True, "number": self.time_limit_minutes}
options = self.model_dump(exclude={"exclusive"}, exclude_none=True)
if self.tasks_per_node is not None and "tasks" not in self.model_fields_set:
options.pop("tasks", None)
for field in ("time_limit", "memory_per_cpu", "memory_per_node"):
if field in options:
options[field] = {"set": True, "number": options[field]}
if self.exclusive:
options["shared"] = ["none"]
return options
+60 -5
View File
@@ -5,12 +5,13 @@ from __future__ import annotations
import json
import shlex
import threading
from collections.abc import Callable
from collections.abc import Callable, Sequence
from datetime import datetime
from logging import getLogger
from pathlib import Path
from typing import Any, Generic, Literal, overload
from uuid import uuid4
from weakref import WeakValueDictionary
from typing_extensions import TypeVar
@@ -117,6 +118,8 @@ class SlurmManager(Generic[_JobOptionsT]):
redis_options = {"ssl": True, "ssl_cert_reqs": "required", "ssl_check_hostname": True}
self.sub_client = RedisSubClient(bootstrap=self._redis_address, **redis_options)
self._job_tracker = JobTracker(self.sub_client)
self._submitted_futures: WeakValueDictionary[str, JobFuture] = WeakValueDictionary()
self._submitted_futures_lock = threading.Lock()
self._stop_heartbeat_thread = threading.Event()
# Heartbeat monitoring thread
self._heartbeat_monitoring_thread = threading.Thread(
@@ -196,13 +199,15 @@ class SlurmManager(Generic[_JobOptionsT]):
# Public Job Management #
################################################
def submit_job(
def submit_job( # noqa: PLR0913 - submission options
self,
script_path: str | Path,
env_path: str | Path | None = None,
*,
working_directory: str,
job_options: _JobOptionsT | None = None,
after_ok: JobFuture | Sequence[JobFuture] | None = None,
after_any: JobFuture | Sequence[JobFuture] | None = None,
callbacks: dict[Literal["log", "status", "heartbeat"], Callable[[SlurmMessage], None]]
| None = None,
) -> JobFuture:
@@ -217,6 +222,11 @@ class SlurmManager(Generic[_JobOptionsT]):
the job runs.
job_options (JobOptions | None): Validated resources and Slurm output
settings; None uses JobOptions defaults.
after_ok: One or more jobs from this manager that must succeed before the
new job starts.
after_any: One or more jobs from this manager that must finish before the
new job starts, regardless of outcome. Both after_ok and after_any
may be supplied. Use job_options.dependency for a raw expression.
callbacks (dict[str, Callable] | None): Callbacks keyed by log, status, or
heartbeat, acknowledged before job release.
@@ -226,8 +236,8 @@ class SlurmManager(Generic[_JobOptionsT]):
Raises:
FileNotFoundError: A local workload or activation file does not exist.
ValueError: The remote working directory or callback event names are
invalid.
ValueError: The working directory, callback event names, or dependencies
are invalid.
ValidationError: Resource or output options fail JobOptions validation.
SlurmRestError: Submission or release fails. A known held job is cancelled
on setup failure.
@@ -242,8 +252,18 @@ class SlurmManager(Generic[_JobOptionsT]):
raise ValueError("Working directory must be an absolute compute-node path")
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
options = job_options
if isinstance(job_options, JobOptions):
exclude = {"tasks"} if job_options.tasks_per_node is not None else set()
options = job_options.model_dump(exclude=exclude - job_options.model_fields_set)
job = self._job_options_type.model_validate({} if options is None else options).to_rest()
dependency = self._build_job_dependency(
after_ok=after_ok, after_any=after_any, has_raw_dependency="dependency" in job
)
if dependency is not None:
job["dependency"] = dependency
if "dependency" in job:
job["flags"] = [*job.get("flags", ()), "KILL_INVALID_DEPENDENCY"]
job_id = str(uuid4())
script = self._build_job_script(
script_path,
@@ -283,6 +303,8 @@ class SlurmManager(Generic[_JobOptionsT]):
StatusMessage(status=f"error:Submission setup failed: {exc}"), job_future
)
raise
with self._submitted_futures_lock:
self._submitted_futures[job_id] = job_future
return job_future
def cancel_job(self, slurm_job_id: str, job_id: str) -> None:
@@ -448,6 +470,39 @@ class SlurmManager(Generic[_JobOptionsT]):
# Internal Script Packaging #
################################################
def _build_job_dependency(
self,
*,
after_ok: JobFuture | Sequence[JobFuture] | None,
after_any: JobFuture | Sequence[JobFuture] | None,
has_raw_dependency: bool,
) -> str | None:
"""Validate issued futures and return their Slurm dependency expression."""
dependencies = []
for argument, kind, dependency_jobs in (
("after_ok", "afterok", after_ok),
("after_any", "afterany", after_any),
):
if dependency_jobs is None:
continue
if has_raw_dependency:
raise ValueError(f"Specify either {argument} or job_options.dependency")
upstream = (
(dependency_jobs,)
if isinstance(dependency_jobs, JobFuture)
else tuple(dependency_jobs)
)
with self._submitted_futures_lock:
if not upstream or any(
not isinstance(future, JobFuture)
or self._submitted_futures.get(future._job_id) is not future
for future in upstream
):
raise ValueError(f"{argument} must contain futures returned by this manager")
ids = ":".join(future.slurm_job_id for future in upstream)
dependencies.append(f"{kind}:{ids}")
return ",".join(dependencies) if dependencies else None
@staticmethod
def _build_job_script( # noqa: PLR0913 - worker command and TLS configuration
script_path: str | Path,
+2 -2
View File
@@ -74,7 +74,7 @@ def test_ra_modules(tmp_path: Path) -> None:
name="smoke-modules",
partition="hour",
tasks=1,
time_limit_minutes=1,
time_limit=1,
standard_output=f"{remote_home}/slurm_logs/smoke-modules-%j.out",
standard_error=f"{remote_home}/slurm_logs/smoke-modules-%j.err",
),
@@ -163,7 +163,7 @@ def test_ra_job_lifecycle(tmp_path: Path) -> None:
name=f"smoke-{name}",
partition="hour",
tasks=1,
time_limit_minutes=1,
time_limit=1,
standard_output=f"{remote_home}/slurm_logs/smoke-{name}-%j.out",
standard_error=f"{remote_home}/slurm_logs/smoke-{name}-%j.err",
),
+98 -5
View File
@@ -14,10 +14,34 @@ from slurm_manager.clusters.ra import RAJobOptions
("tasks", -1),
("tasks", True),
("tasks", 1.5),
("time_limit_minutes", 0),
("time_limit_minutes", -1),
("time_limit_minutes", "60"),
("time_limit", 0),
("time_limit", -1),
("time_limit", "60"),
("partition", " "),
("reservation", " "),
("constraints", " "),
("dependency", " "),
("nodes", " "),
("nodes", 2),
("tasks_per_node", 0),
("tasks_per_node", True),
("tasks_per_node", 65534),
("tasks_per_core", 0),
("tasks_per_core", True),
("tasks_per_core", 65536),
("tres_per_node", " "),
("tres_per_task", " "),
("cpus_per_task", 0),
("cpus_per_task", True),
("cpus_per_task", 65534),
("memory_per_cpu", 0),
("memory_per_node", -1),
("memory_per_node", "4096"),
("exclusive", 1),
("shared", "none"),
("shared", []),
("shared", ["none", "oversubscribe"]),
("shared", ["exclusive"]),
("hold", False),
("time_limit", {"set": True, "number": 1}),
],
@@ -31,14 +55,83 @@ def test_unset_options_preserve_slurm_defaults():
assert JobOptions().to_rest() == {"tasks": 1}
def test_per_node_layout_omits_an_implicit_total_task_count():
assert JobOptions(nodes="2", tasks_per_node=4).to_rest() == {"nodes": "2", "tasks_per_node": 4}
@pytest.mark.parametrize("tasks_per_core", [1, 2, 65535])
def test_tasks_per_core_is_sent_as_a_rest_integer(tasks_per_core):
assert RAJobOptions(tasks_per_core=tasks_per_core).to_rest() == {
"tasks": 1,
"tasks_per_core": tasks_per_core,
}
def test_runtime_uses_minutes_and_slurm_optional_number_shape():
options = JobOptions(partition="hour", tasks=2, time_limit_minutes=60)
options = JobOptions(partition="hour", tasks=2, time_limit=60)
assert options.to_rest() == {
"partition": "hour",
"tasks": 2,
"time_limit": {"set": True, "number": 60},
}
assert options.time_limit_minutes == 60
assert options.time_limit == 60
def test_cluster_job_options_serialize_reservation_cpus_memory_and_exclusive():
options = RAJobOptions(
reservation=" beamtime ", cpus_per_task=4, memory_per_cpu=2048, shared=["none"]
)
assert options.to_rest() == {
"tasks": 1,
"reservation": "beamtime",
"cpus_per_task": 4,
"memory_per_cpu": {"set": True, "number": 2048},
"shared": ["none"],
}
def test_exclusive_uses_slurm_sharing_mode():
assert RAJobOptions(exclusive=True).to_rest() == {"tasks": 1, "shared": ["none"]}
assert RAJobOptions(exclusive=False).to_rest() == {"tasks": 1}
def test_exclusive_cannot_be_combined_with_explicit_sharing():
with pytest.raises(ValidationError, match="either exclusive=True or shared"):
JobOptions(exclusive=True, shared=["oversubscribe"])
def test_job_options_forward_node_layout_resources_and_dependencies():
options = RAJobOptions(
nodes="2-4",
tasks=4,
tasks_per_node=2,
constraints="a100",
dependency="afterok:12345",
tres_per_node="gres/gpu=2",
tres_per_task="gres/gpu=1",
)
assert options.to_rest() == {
"nodes": "2-4",
"tasks": 4,
"tasks_per_node": 2,
"constraints": "a100",
"dependency": "afterok:12345",
"tres_per_node": "gres/gpu=2",
"tres_per_task": "gres/gpu=1",
}
@pytest.mark.parametrize("memory_mib", [0, 4096])
def test_memory_per_node_serializes_zero_and_explicit_amounts(memory_mib):
assert JobOptions(memory_per_node=memory_mib).to_rest() == {
"tasks": 1,
"memory_per_node": {"set": True, "number": memory_mib},
}
def test_memory_options_are_mutually_exclusive():
with pytest.raises(ValidationError, match="either memory_per_cpu or memory_per_node"):
JobOptions(memory_per_cpu=1024, memory_per_node=0)
@pytest.mark.parametrize("partition", ["hour", "day", "week", "gpu"])
+109 -2
View File
@@ -399,18 +399,125 @@ def test_local_files_are_uploaded_without_mutating_options(manager, tmp_path):
activation = tmp_path / "it's my activation.sh"
workload.write_text("#!/bin/bash\nprintf 'hello'\n")
activation.write_text("module load redis\n")
options = JobOptions(partition="hour", tasks=2, time_limit_minutes=5)
options = JobOptions(partition="hour", tasks=2, time_limit=5)
manager.submit_job(workload, activation, working_directory="/remote/work", job_options=options)
script, job = manager.rest_client.submit.call_args.args
assert "hello" in script
assert "module load redis" in script
assert str(tmp_path) not in script
assert job["hold"] is True
assert options == JobOptions(partition="hour", tasks=2, time_limit_minutes=5)
assert "flags" not in job
assert options == JobOptions(partition="hour", tasks=2, time_limit=5)
assert job["tasks"] == 2
assert job["time_limit"] == {"set": True, "number": 5}
@pytest.mark.parametrize("tasks", [None, 1, 8])
def test_submission_preserves_explicit_tasks_for_per_node_layout(manager, tasks):
options = (
JobOptions(nodes="2", tasks_per_node=4)
if tasks is None
else JobOptions(nodes="2", tasks_per_node=4, tasks=tasks)
)
manager.submit_job(
"examples/print_for_10s.sh", working_directory="/remote/work", job_options=options
)
_, job = manager.rest_client.submit.call_args.args
assert job["nodes"] == "2"
assert job["tasks_per_node"] == 4
if tasks is None:
assert "tasks" not in job
else:
assert job["tasks"] == tasks
@pytest.mark.parametrize(("argument", "kind"), [("after_ok", "afterok"), ("after_any", "afterany")])
@pytest.mark.parametrize("multiple", [False, True], ids=["single", "multiple"])
def test_dependency_futures_use_scheduler_job_ids(manager, argument, kind, multiple):
manager.rest_client.submit.side_effect = [{"job_id": number} for number in (123, 456, 789)]
first = submit(manager)
upstream = [first, submit(manager)] if multiple else first
manager.submit_job(
"examples/print_for_10s.sh", working_directory="/remote/work", **{argument: upstream}
)
_, job = manager.rest_client.submit.call_args.args
assert job["dependency"] == (f"{kind}:123:456" if multiple else f"{kind}:123")
assert job["flags"] == ["KILL_INVALID_DEPENDENCY"]
def test_raw_dependency_requests_cancellation_if_it_can_never_be_satisfied(manager):
manager.submit_job(
"examples/print_for_10s.sh",
working_directory="/remote/work",
job_options=JobOptions(dependency="afterok:123,afterany:456"),
)
_, job = manager.rest_client.submit.call_args.args
assert job["dependency"] == "afterok:123,afterany:456"
assert job["flags"] == ["KILL_INVALID_DEPENDENCY"]
@pytest.mark.parametrize("argument", ["after_ok", "after_any"])
def test_dependency_futures_reject_a_raw_dependency(manager, argument):
upstream = submit(manager)
manager.rest_client.submit.reset_mock()
with pytest.raises(ValueError, match=f"either {argument} or job_options.dependency"):
manager.submit_job(
"examples/print_for_10s.sh",
working_directory="/remote/work",
job_options=JobOptions(dependency="afterany:123"),
**{argument: upstream},
)
manager.rest_client.submit.assert_not_called()
@pytest.mark.parametrize("argument", ["after_ok", "after_any"])
def test_dependencies_require_futures_from_this_manager(manager, argument):
issued = submit(manager)
foreign_job = JobFuture("foreign", manager=mock.Mock(spec=SlurmManager), slurm_job_id="123")
copied_job = JobFuture(issued._job_id, manager=manager, slurm_job_id=issued.slurm_job_id)
manager.rest_client.submit.reset_mock()
for upstream in (foreign_job, [issued, copied_job], []):
with pytest.raises(ValueError, match="futures returned by this manager"):
manager.submit_job(
"examples/print_for_10s.sh",
working_directory="/remote/work",
**{argument: upstream},
)
manager.rest_client.submit.assert_not_called()
def test_dependencies_accept_completed_futures_from_this_manager(manager):
upstream = submit(manager)
manager._job_tracker.apply_status(StatusMessage(status="finished"), upstream)
assert upstream.done()
assert manager._job_tracker.get_future(upstream._job_id) is None
manager.submit_job(
"examples/print_for_10s.sh", working_directory="/remote/work", after_ok=upstream
)
_, job = manager.rest_client.submit.call_args.args
assert job["dependency"] == "afterok:123"
def test_combines_after_ok_and_after_any(manager):
manager.rest_client.submit.side_effect = [
{"job_id": number} for number in (123, 456, 789, 1011)
]
prepare, calibrate, monitor = (submit(manager) for _ in range(3))
manager.submit_job(
"examples/print_for_10s.sh",
working_directory="/remote/work",
after_ok=[prepare, calibrate],
after_any=monitor,
)
_, job = manager.rest_client.submit.call_args.args
assert job["dependency"] == "afterok:123:456,afterany:789"
def test_submission_failure_does_not_register_job(manager):
manager.rest_client.submit.side_effect = SlurmRestError("submission failed")
with pytest.raises(SlurmRestError, match="submission failed"):