From 0a9755d283a3e60bea37b28e090879165a747455 Mon Sep 17 00:00:00 2001 From: Florent Pollet Date: Tue, 24 Nov 2026 22:16:28 -0500 Subject: [PATCH] Allow SLURM runs from an installed released distribution execution=slurm required a clean committed Git checkout of the algorithm, so an algorithm installed from PyPI (pip/uv install) could only run locally. The plan now also records the installed distribution providing the algorithm (name, version, editable). SLURM accepts either a clean committed checkout (unchanged checks) or a released, non-editable installed distribution; each worker checks that the same name and version are still installed before running its stage. An editable install outside a Git checkout is still refused, as its source can change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJQdbHt5icm1CgFVHsHTNx --- src/meds_algorithm/ORCHESTRATION.md | 8 +-- src/meds_algorithm/orchestration/execution.py | 49 +++++++++++++++--- src/meds_algorithm/orchestration/planning.py | 4 +- src/meds_algorithm/runtime/provenance.py | 18 +++++++ tests/test_orchestration.py | 51 ++++++++++++++++++- 5 files changed, 118 insertions(+), 12 deletions(-) diff --git a/src/meds_algorithm/ORCHESTRATION.md b/src/meds_algorithm/ORCHESTRATION.md index ee5661b..76cb37a 100644 --- a/src/meds_algorithm/ORCHESTRATION.md +++ b/src/meds_algorithm/ORCHESTRATION.md @@ -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. diff --git a/src/meds_algorithm/orchestration/execution.py b/src/meds_algorithm/orchestration/execution.py index a929d69..157c84c 100644 --- a/src/meds_algorithm/orchestration/execution.py +++ b/src/meds_algorithm/orchestration/execution.py @@ -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 @@ -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: @@ -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, @@ -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}) @@ -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, @@ -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"]} diff --git a/src/meds_algorithm/orchestration/planning.py b/src/meds_algorithm/orchestration/planning.py index 6a374c3..e8819f5 100644 --- a/src/meds_algorithm/orchestration/planning.py +++ b/src/meds_algorithm/orchestration/planning.py @@ -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 @@ -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), ) diff --git a/src/meds_algorithm/runtime/provenance.py b/src/meds_algorithm/runtime/provenance.py index 156edb7..403bf0c 100644 --- a/src/meds_algorithm/runtime/provenance.py +++ b/src/meds_algorithm/runtime/provenance.py @@ -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 @@ -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} diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py index 9fbd23b..1b6a720 100644 --- a/tests/test_orchestration.py +++ b/tests/test_orchestration.py @@ -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) @@ -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")))