From 93ed1cc9e332ecac2b5c2856ab3c5248d3d62ae2 Mon Sep 17 00:00:00 2001 From: Vasu Jaganath Date: Tue, 17 Nov 2026 13:14:18 -0500 Subject: [PATCH] fix(toil): give Toil output directories it keeps Toil drops the empty listing of a CWL Directory literal in a step's job, then fails reading it (DataBiosphere/toil#5692). A Toil run's job now names each output directory in Toil's own empty-directory form. --- src/sophios/backends.py | 15 ++++++++-- src/sophios/input_output.py | 9 +++--- src/sophios/run_setup.py | 23 +++++++++------ src/sophios/runtime_inputs.py | 39 +++++++++++++++++--------- tests/core/test_ci_coverage.py | 3 ++ tests/core/test_python_api_workflow.py | 10 +++++++ 6 files changed, 70 insertions(+), 29 deletions(-) diff --git a/src/sophios/backends.py b/src/sophios/backends.py index cd7950dd0..64d870c8c 100644 --- a/src/sophios/backends.py +++ b/src/sophios/backends.py @@ -30,7 +30,7 @@ from .nf_reader import read_nextflow from .nf_types import ExecutableNextflowWorkflow from .runners import RunSettings -from .runtime_inputs import output_target_inputs +from .runtime_inputs import directory_literal, output_target_inputs from .utils_nf import nextflow_names from .wic_types import Json @@ -204,13 +204,17 @@ def _log_lines(log: Path) -> list[str]: class _Cwl: # pylint: disable=too-few-public-methods """What every CWL runner shares: the pre-flight checks the machine, `run_setup` writes the files.""" + #: An empty output directory, as this runner takes one in its job. + empty_directory = staticmethod(directory_literal) + def prepare(self, lowered: run_setup.Lowered[CompilationArtifact], analyses: tuple[realtime.Analysis, ...], basepath: Path, settings: run_setup.Settings) -> run_setup.Prepared: """The workflow and its job under `basepath`, its analyses beside it, and its images pulled. The artifact written is the model, as the front door rewrote it. """ - return run_setup.prepare(lowered.model, analyses, basepath, settings, output_target_inputs(lowered.view)) + return run_setup.prepare(lowered.model, analyses, basepath, settings, output_target_inputs(lowered.view), + empty_directory=self.empty_directory) class CwltoolBackend(_Cwl): @@ -261,6 +265,13 @@ def command(cwl: Path, job: Path, outdir: Path, cachedir: Path) -> list[str]: class ToilBackend(_Cwl): """Toil's CWL runner, `toil-cwl-runner`.""" + @staticmethod + def empty_directory(name: str) -> Json: + """An empty directory named `name` in Toil's own form. Toil drops the empty listing of a CWL Directory + literal in a step's job, then fails reading it (DataBiosphere/toil#5692).""" + from toil.lib.directory import encode_directory # pylint: disable=import-outside-toplevel + return {'class': 'Directory', 'basename': name, 'location': encode_directory({})} + def launch(self, request: RunRequest) -> Launch: """`toil-cwl-runner` with a job store per workflow under the base path, then the documents.""" basepath = str(request.basepath.absolute().resolve()) diff --git a/src/sophios/input_output.py b/src/sophios/input_output.py index e897ca10f..858bb517a 100644 --- a/src/sophios/input_output.py +++ b/src/sophios/input_output.py @@ -10,7 +10,7 @@ from ruamel.yaml.nodes import ScalarNode as _RuamelScalarNode from . import auto_gen_header -from .runtime_inputs import runner_job_inputs +from .runtime_inputs import EmptyDirectory, directory_literal, runner_job_inputs from .ir.artifacts import CompilationArtifact from .ir.locations import absolute_paths from .lang.diagnostics import SophiosError @@ -88,19 +88,20 @@ def read_inputs_file(path: str) -> Yaml: def write_artifacts_to_disk(artifact: CompilationArtifact, path: Path, inputs_file: str = '', - *, output_targets: Collection[str]) -> None: + *, output_targets: Collection[str], + empty_directory: EmptyDirectory = directory_literal) -> None: """Write a graph-derived artifact tree in `path`, each document under its own name, and the root's job. Only the root has a job: a runner reads no other. A relative `location` or `path` of a File or Directory in `inputs_file`, at any depth, is resolved against the inputs file's own directory (CWL v1.2 section 5.1.5: the base IRI of the document) and written absolute. Each of `output_targets` (`runtime_inputs.output_target_inputs`) is a name for the run to create, so it is read as one first and - written as the Directory literal the runner creates. + written as the empty directory the runner creates, in the form `empty_directory` gives. """ inputs = absolute_paths(runner_job_inputs(read_inputs_file(inputs_file), output_targets), Path(inputs_file).absolute().parent) if inputs_file else {} path.mkdir(parents=True, exist_ok=True) - job = runner_job_inputs({**artifact.job_inputs, **inputs}, output_targets) + job = runner_job_inputs({**artifact.job_inputs, **inputs}, output_targets, empty_directory) (path / f'{artifact.name}_inputs.yml').write_text( f'{auto_gen_header}{dump_wic_yaml(job)}', encoding='utf-8') _write_documents(artifact, path) diff --git a/src/sophios/run_setup.py b/src/sophios/run_setup.py index d22930e51..a430bd1d0 100644 --- a/src/sophios/run_setup.py +++ b/src/sophios/run_setup.py @@ -16,7 +16,7 @@ from sophios.ir.resolved import ResolvedWorkflow from sophios.lang.diagnostics import Diagnostic from sophios.runners import RunSettings -from sophios.runtime_inputs import runner_job_inputs +from sophios.runtime_inputs import EmptyDirectory, directory_literal, runner_job_inputs from sophios.wic_types import Yaml ModelT = TypeVar('ModelT') @@ -65,14 +65,17 @@ class Prepared: documents: tuple[Path, ...] +# pylint: disable-next=too-many-arguments def prepare(artifact: CompilationArtifact, analyses: tuple[realtime.Analysis, ...], basepath: Path, - settings: Settings, output_targets: Collection[str]) -> Prepared: + settings: Settings, output_targets: Collection[str], *, + empty_directory: EmptyDirectory = directory_literal) -> Prepared: """Write `artifact` and `analyses` under `basepath` as they are given, and make the machine ready to run them. `artifact` is written as it is: a tree from the command line, one document under `--cwl_inline_runtag` and from Python. Its job is the values bound in the workflow, as `targets.for_run` made - them for the runner, under the inputs file's. The pre-flight reads `settings.bound`, the same values as written. Each of `output_targets` (`runtime_inputs.output_target_inputs`) - is a name for the run to create. + them for the runner, under the inputs file's. The pre-flight reads `settings.bound`, the same values as written. + Each of `output_targets` (`runtime_inputs.output_target_inputs`) is a name for the run to create, written in the + job as `empty_directory` gives the runner an empty directory. A check (`settings.check`) writes them into a temporary directory instead, removed when the check ends, so it leaves `basepath` as it found it. @@ -81,9 +84,9 @@ def prepare(artifact: CompilationArtifact, analyses: tuple[realtime.Analysis, .. SophiosError: What the pre-flight found in the way, before anything is pulled. """ if not settings.check: - return _prepare(artifact, analyses, basepath, settings, output_targets) + return _prepare(artifact, analyses, basepath, settings, output_targets, empty_directory=empty_directory) with tempfile.TemporaryDirectory(prefix='sophios-check-') as scratch: - return _prepare(artifact, analyses, Path(scratch), settings, output_targets) + return _prepare(artifact, analyses, Path(scratch), settings, output_targets, empty_directory=empty_directory) def inputs_job(inputs_file: str, named: str, output_targets: Collection[str] = ()) -> preflight.Job | None: @@ -95,10 +98,12 @@ def inputs_job(inputs_file: str, named: str, output_targets: Collection[str] = ( Path(inputs_file).parent.absolute(), named) +# pylint: disable-next=too-many-arguments def _prepare(artifact: CompilationArtifact, analyses: tuple[realtime.Analysis, ...], basepath: Path, - settings: Settings, output_targets: Collection[str]) -> Prepared: + settings: Settings, output_targets: Collection[str], *, empty_directory: EmptyDirectory) -> Prepared: """`prepare`, writing under `basepath`.""" - input_output.write_artifacts_to_disk(artifact, basepath, settings.run.inputs_file, output_targets=output_targets) + input_output.write_artifacts_to_disk(artifact, basepath, settings.run.inputs_file, output_targets=output_targets, + empty_directory=empty_directory) plans = realtime.write(analyses, basepath, artifact.name, settings.root_dir) # The pre-flight reads the CWL the runner will get, so it runs after the write. documents = (basepath / f'{artifact.name}.cwl', *realtime.documents(analyses, basepath)) @@ -116,7 +121,7 @@ def _prepare(artifact: CompilationArtifact, analyses: tuple[realtime.Analysis, . artifact = plugins.dockerPull_append_noentrypoint_artifact(artifact) # The images are built from the ones the pre-flight pulled, so the rewrite is written over the first write. input_output.write_artifacts_to_disk(artifact, basepath, settings.run.inputs_file, - output_targets=output_targets) + output_targets=output_targets, empty_directory=empty_directory) analyses = tuple(replace(a, artifact=plugins.dockerPull_append_noentrypoint_artifact(a.artifact)) for a in analyses) plans = realtime.write(analyses, basepath, artifact.name, settings.root_dir) diff --git a/src/sophios/runtime_inputs.py b/src/sophios/runtime_inputs.py index f298ab96c..be7dab984 100644 --- a/src/sophios/runtime_inputs.py +++ b/src/sophios/runtime_inputs.py @@ -3,10 +3,10 @@ from __future__ import annotations import copy -from collections.abc import Collection, Mapping +from collections.abc import Callable, Collection, Mapping from pathlib import PurePath, PurePosixPath, PureWindowsPath import re -from typing import Any +from typing import Any, TypeAlias from cwl_utils.parser.cwl_v1_2 import Dirent, InitialWorkDirRequirement @@ -18,20 +18,31 @@ _INPUT_REFERENCE = re.compile(r"\binputs\.([A-Za-z_][A-Za-z0-9_-]*)") +#: An empty directory of a given name, as a runner takes one in a job. +EmptyDirectory: TypeAlias = Callable[[str], Json] -def runner_job_inputs(job_inputs: Mapping[str, Any], output_targets: Collection[str]) -> Json: + +def directory_literal(name: str) -> Json: + """An empty directory named `name` as CWL writes one: a Directory literal the runner creates.""" + return {"class": "Directory", "basename": name, "listing": []} + + +def runner_job_inputs(job_inputs: Mapping[str, Any], output_targets: Collection[str], + empty_directory: EmptyDirectory = directory_literal) -> Json: """`job_inputs` as a runner gets them: each File's format resolved, and each of `output_targets` (the root - job keys `output_target_inputs` names) a Directory literal the runner creates, empty, under the name it gave.""" - return name_output_targets(resolve_file_formats(job_inputs), output_targets) + job keys `output_target_inputs` names) an empty directory the runner creates under the name it gave.""" + return name_output_targets(resolve_file_formats(job_inputs), output_targets, empty_directory) -def name_output_targets(job_inputs: Mapping[str, Any], output_targets: Collection[str]) -> Json: - """A copy of `job_inputs` in which each of `output_targets` is a Directory literal the runner creates, empty, - under the name it gave: a runner given an absolute path for a Directory would never create it.""" +def name_output_targets(job_inputs: Mapping[str, Any], output_targets: Collection[str], + empty_directory: EmptyDirectory = directory_literal) -> Json: + """A copy of `job_inputs` in which each of `output_targets` is an empty directory the runner creates under the + name it gave, as `empty_directory` writes one: a runner given an absolute path for a Directory would never + create it.""" job = dict(job_inputs) for name in output_targets: if name in job: - job[name] = _output_target_directory(job[name], name) + job[name] = _output_target_directory(job[name], name, empty_directory) return job @@ -104,10 +115,10 @@ def _is_directory(cwl_type: Any) -> bool: return inner == "Directory" or isinstance(inner, list) and "Directory" in inner -def _output_target_directory(value: Any, source_key: str) -> Any: - """The literal for a name, or for a Directory read as one: its `location`, `path` or `basename`. An absolute path - or a URL is left as written: it is a Directory as CWL reads any, and where a tool may write is the runner's to - say (`InplaceUpdateRequirement`).""" +def _output_target_directory(value: Any, source_key: str, empty_directory: EmptyDirectory) -> Any: + """The empty directory for a name, or for a Directory read as one: its `location`, `path` or `basename`. An + absolute path or a URL is left as written: it is a Directory as CWL reads any, and where a tool may write is the + runner's to say (`InplaceUpdateRequirement`).""" match value: case str() as name: pass @@ -121,7 +132,7 @@ def _output_target_directory(value: Any, source_key: str) -> Any: return value if "://" in name or PurePosixPath(name).is_absolute() or PureWindowsPath(name).is_absolute(): return value - return {"class": "Directory", "basename": _output_target_basename(name, source_key), "listing": []} + return empty_directory(_output_target_basename(name, source_key)) def _output_target_basename(location: str, source_key: str) -> str: diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index 63de6d426..a8c782c4d 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -363,6 +363,9 @@ def _tests_importing(module: str, path: Path) -> set[str]: # The failure pins the wording of cwltool's job-failure record, which the summary # reads; the other tests of the summary use a stand-in for cwltool and run on every leg. 'tests/core/test_python_api_workflow.py::test_a_real_run_prints_its_output_or_names_the_step_that_failed', + # One `Workflow.run()` by Toil of a step that writes into the output directory it is given, in about seven + # seconds. What the job names for each runner is Toil's to read; only Toil shows that it creates the directory. + 'tests/core/test_python_api_workflow.py::test_toil_fills_the_output_directory_a_step_is_given', # A workflow run by cwltool through --run_local, with two real-time analyses # run by cwltool beside it, one of them failing, in one run of about eight # seconds. The watcher's own tests use a stand-in for cwltool and run on diff --git a/tests/core/test_python_api_workflow.py b/tests/core/test_python_api_workflow.py index f9565e9e3..64628cc2e 100644 --- a/tests/core/test_python_api_workflow.py +++ b/tests/core/test_python_api_workflow.py @@ -590,3 +590,13 @@ def test_a_real_run_prints_its_output_or_names_the_step_that_failed(monkeypatch: Workflow([step], 'exits').run(basepath=str(tmp_path / 'autogenerated')) err = capfd.readouterr().err assert "Failure! step 'exits_3" in err and 'exited with status 3.' in err + + +@pytest.mark.needs_cwltool +def test_toil_fills_the_output_directory_a_step_is_given(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """A real run by Toil: the step writes into the directory it is given by name, and the run returns it filled.""" + step = Step(clt_path=PYTHON_API / 'write_dir.cwl') + step.inputs.outDir = Path('result.outDir') + monkeypatch.chdir(tmp_path) + result = Workflow([step], 'wf').run(basepath=str(tmp_path / 'autogenerated'), runner=Toil()) + assert result is not None and (result.outdir / 'result.outDir' / 'done.txt').is_file()