Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/meds_algorithm/ORCHESTRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,11 @@ local execution does not reserve or isolate those resources. Output streams go d
log files instead of accumulating training logs in the coordinator's memory.

SLURM execution uses Submitit directly to submit one job per stage, chained with `afterok` dependencies.
It returns after submission. A clean committed algorithm checkout is required; workers check that
the commit remains unchanged and the checkout remains clean before starting. Put outputs outside the
checkout or in a Git-ignored directory. Use a shared filesystem and the same installed Python
It returns after submission. The algorithm code must be identifiable: either a clean committed
algorithm checkout (workers check that the commit remains unchanged and the checkout remains clean
before starting; put outputs outside the checkout or in a Git-ignored directory), or a released,
non-editable installed distribution, e.g. `uv pip install my-algorithm==1.2.3` (workers check that the
same name and version are still installed). An editable install outside a Git checkout is refused. Use a shared filesystem and the same installed Python
environment on the submitting and compute hosts. The coordinator does not install environments or
snapshot the source tree. Avoid editing the checkout while jobs are queued/running.

Expand Down
49 changes: 43 additions & 6 deletions src/meds_algorithm/orchestration/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from meds_algorithm.artifacts.manifest import digest_file
from meds_algorithm.runtime.process import run
from meds_algorithm.runtime.provenance import code_provenance
from meds_algorithm.runtime.provenance import code_provenance, distribution_provenance

from .planning import RunPlan, StagePlan

Expand All @@ -21,6 +21,8 @@ class StageJob:
output_dir: Path
config_digest: str
expected_commit: str | None = None
# An installed release instead of a checkout: {"module", "name", "version"} that must still be installed.
expected_release: dict | None = None

def __call__(self):
if digest_file(self.output_dir / "algorithm.json") != self.config_digest:
Expand All @@ -29,6 +31,15 @@ def __call__(self):
provenance = code_provenance(self.repo)
if provenance["git_commit"] != self.expected_commit or provenance["dirty"] is not False:
raise ValueError("Algorithm checkout changed after SLURM submission")
if self.expected_release is not None:
installed = distribution_provenance(self.expected_release["module"])
expected = {key: self.expected_release[key] for key in ("name", "version")}
found = None if installed is None else {key: installed[key] for key in ("name", "version")}
if installed is None or installed["editable"] or found != expected:
raise ValueError(
"Installed algorithm changed after SLURM submission: "
f"expected {expected}, found {installed}"
)
run(
self.stage.argv,
cwd=self.repo,
Expand Down Expand Up @@ -83,7 +94,14 @@ def save():
parameters["slurm_additional_parameters"] = {"dependency": f"afterok:{jobs[-1].job_id}"}
executor.update_parameters(**parameters)
job = executor.submit(
StageJob(stage, plan.repo, plan.output_dir, config_digest, plan.provenance["git_commit"])
StageJob(
stage,
plan.repo,
plan.output_dir,
config_digest,
plan.provenance["git_commit"],
_release(plan),
)
)
jobs.append(job)
receipt["jobs"].append({"stage": stage.name, "job_id": job.job_id})
Expand All @@ -107,11 +125,20 @@ class RunCoordinator:

def execute(self, plan: RunPlan):
if plan.execution == "slurm":
# Refuse unknown or dirty code before creating files or submitting anything.
# Refuse unknown or mutable code before creating files or submitting anything: either a clean
# committed checkout, or a released (non-editable) installed distribution whose version workers
# check again.
current = code_provenance(plan.repo)
if not current["git_commit"] or current["dirty"] is not False or current != plan.provenance:
raise ValueError("SLURM requires an unchanged, clean committed algorithm checkout")
if plan.output_dir.is_relative_to(plan.repo):
planned = {key: plan.provenance.get(key) for key in current}
if current["git_commit"]:
if current["dirty"] is not False or current != planned:
raise ValueError("SLURM requires an unchanged, clean committed algorithm checkout")
elif _release(plan) is None:
raise ValueError(
"SLURM requires an unchanged, clean committed algorithm checkout or an installed "
"released (non-editable) distribution of the algorithm"
)
if current["git_commit"] and plan.output_dir.is_relative_to(plan.repo):
ignored = subprocess.run(
["git", "-C", str(plan.repo), "check-ignore", "--quiet", str(plan.output_dir)],
check=False,
Expand All @@ -126,3 +153,13 @@ def execute(self, plan: RunPlan):
config.write_text(json.dumps(plan.algorithm_configuration, indent=2), encoding="utf-8")
backend = LocalExecution() if plan.execution == "local" else SubmititExecution()
backend.execute(plan, digest_file(config))


def _release(plan: RunPlan) -> dict | None:
"""The planned installed release (``module``, ``name``, ``version``) when no Git commit identifies the
code and the distribution is not editable; ``None`` otherwise."""
distribution = plan.provenance.get("distribution")
if plan.provenance.get("git_commit") or not distribution or distribution["editable"]:
return None
module = plan.algorithm_configuration["type"].rsplit(".", 1)[0]
return {"module": module, "name": distribution["name"], "version": distribution["version"]}
4 changes: 2 additions & 2 deletions src/meds_algorithm/orchestration/planning.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from meds_algorithm import STEP_SPECS, CommandName
from meds_algorithm.algorithms import request_type
from meds_algorithm.runtime.provenance import code_provenance
from meds_algorithm.runtime.provenance import code_provenance, distribution_provenance

from .config import Resources, RunConfig

Expand Down Expand Up @@ -193,6 +193,6 @@ def resolve(self, config: RunConfig) -> RunPlan:
"type": f"{algorithm_type.__module__}.{algorithm_type.__qualname__}",
"values": algorithm.to_dict(),
},
code_provenance(repo),
{**code_provenance(repo), "distribution": distribution_provenance(algorithm_type.__module__)},
tuple(plans),
)
18 changes: 18 additions & 0 deletions src/meds_algorithm/runtime/provenance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Record the caller's algorithm checkout; never infer it from the core package or cwd."""

import json
import subprocess
from importlib import metadata
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -29,3 +31,19 @@ def git(*args):
except (OSError, subprocess.CalledProcessError):
return unknown
return {"repository": str(root), "git_commit": commit, "dirty": bool(status)}


def distribution_provenance(module: str) -> dict[str, Any] | None:
"""The installed distribution providing ``module``'s top-level package.

Returns ``{"name", "version", "editable"}``, or ``None`` when no installed distribution provides it (e.g.
code run from a source tree without installing). An editable install points at mutable source, so its
version does not identify the code that runs.
"""
names = metadata.packages_distributions().get(module.split(".")[0])
if not names:
return None
distribution = metadata.distribution(sorted(names)[0])
direct_url = distribution.read_text("direct_url.json")
editable = bool(direct_url and json.loads(direct_url).get("dir_info", {}).get("editable"))
return {"name": distribution.metadata["Name"], "version": distribution.version, "editable": editable}
51 changes: 50 additions & 1 deletion tests/test_orchestration.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,16 @@ def submit(self, callable):
)


def test_slurm_refuses_dirty_or_unknown_checkout(setup):
def _installed(monkeypatch, release):
"""Pretend the example algorithm comes from ``release`` (``None``: no installed distribution)."""
from meds_algorithm.orchestration import execution, planning

monkeypatch.setattr(planning, "distribution_provenance", lambda module: release)
monkeypatch.setattr(execution, "distribution_provenance", lambda module: release)


def test_slurm_refuses_dirty_or_unknown_checkout(setup, monkeypatch):
_installed(monkeypatch, None)
plan = setup.planner.resolve(replace(setup.config, execution="slurm"))
with pytest.raises(ValueError, match="clean committed"):
RunCoordinator().execute(plan)
Expand All @@ -273,6 +282,46 @@ def test_slurm_refuses_dirty_or_unknown_checkout(setup):
RunCoordinator().execute(plan)


def test_slurm_submits_an_installed_release_and_workers_check_its_version(setup, monkeypatch):
"""Without a Git checkout, a released (non-editable) installed distribution identifies the code."""
import submitit

release = {"name": "my-algorithm", "version": "1.2.3", "editable": False}
_installed(monkeypatch, release)
plan = setup.planner.resolve(replace(setup.config, execution="slurm", stages=["preprocess_data"]))
assert plan.provenance["git_commit"] is None and plan.provenance["distribution"] == release
submitted = []

class Executor:
def __init__(self, **kwargs):
pass

def update_parameters(self, **kwargs):
pass

def submit(self, callable):
submitted.append(callable)
return SimpleNamespace(job_id="1", cancel=lambda: None)

monkeypatch.setattr(submitit, "AutoExecutor", Executor)
RunCoordinator().execute(plan)
job = submitted[0]
assert job.expected_commit is None and job.expected_release["version"] == "1.2.3"
assert job() == "preprocess_data" # the same release is still installed: the stage runs
_installed(monkeypatch, {**release, "version": "1.2.4"})
with pytest.raises(ValueError, match="Installed algorithm changed"):
job()

# An editable install points at mutable source: refused before any file is written.
_installed(monkeypatch, {**release, "editable": True})
editable = setup.planner.resolve(
replace(setup.config, execution="slurm", output_dir=str(setup.repo.parent / "editable"))
)
with pytest.raises(ValueError, match="installed released"):
RunCoordinator().execute(editable)
assert not editable.output_dir.exists()


def test_slurm_rejects_output_that_would_dirty_checkout(setup):
commit_repo(setup.repo)
plan = setup.planner.resolve(replace(setup.config, execution="slurm", output_dir=str(setup.repo / "run")))
Expand Down
Loading