diff --git a/src/sophios/api/python/_workflow_runtime.py b/src/sophios/api/python/_workflow_runtime.py index ca1852453..b849453d7 100644 --- a/src/sophios/api/python/_workflow_runtime.py +++ b/src/sophios/api/python/_workflow_runtime.py @@ -43,7 +43,7 @@ # Re-exported by `workflow`, which reaches the run settings only through this adapter. from sophios.runners import Cwltool, Nextflow, Runner, RunSettings, Toil # pylint: disable=unused-import from sophios.runtime_inputs import output_target_inputs, resolve_file_formats, runner_job_inputs -from sophios.utils_cwl import tool_process +from sophios.lang.cwl import read_tool, tool_process from sophios.wic_types import DEFAULT_BASEPATH, GraphSettings, Json, StepId, Tool, Tools, Yaml from ._inference import Inference @@ -147,7 +147,7 @@ def load_clt(clt_path: Path, tool_registry: Tools) -> tuple[CWLCommandLineTool, if clt_path.exists(): try: # The process first: a packed document with no `main` is refused by name, not as "invalid". - yaml_file = tool_process(_load_yaml(clt_path), str(clt_path)) + yaml_file = read_tool(str(clt_path)) clt = load_document_by_uri(clt_path) except SophiosError: raise diff --git a/src/sophios/api/python/workflow.py b/src/sophios/api/python/workflow.py index c262b55d8..a7c0f70f7 100644 --- a/src/sophios/api/python/workflow.py +++ b/src/sophios/api/python/workflow.py @@ -21,7 +21,7 @@ from sophios.lang.names import check_written_name from sophios.lang.spans import SourceSpan from sophios.run_status import RunResult, RunState, RunStatus, StepStatus, WorkflowRunError -from sophios.wic_types import DEFAULT_BASEPATH, Tools +from sophios.wic_types import DEFAULT_BASEPATH, TargetName, Tools from ._compiled import CompiledNextflowWorkflow, CompiledWorkflow from ._inference import Inference @@ -989,7 +989,7 @@ def compile( def compile( # pylint: disable=too-many-arguments self, *, - target: Literal["cwl", "nextflow"] = "cwl", + target: TargetName = "cwl", tool_registry: Tools | None = None, lang_version: str | None = None, inference: Inference = Inference(), @@ -998,7 +998,7 @@ def compile( # pylint: disable=too-many-arguments """Compile this workflow into the selected target representation. Args: - target (Literal["cwl", "nextflow"]): Compilation target. + target (TargetName): Compilation target. tool_registry (Tools | None): Optional tool registry override. lang_version (str | None): Pin the Sophios language version for this compilation; None (the default) infers it. An explicit @@ -1037,7 +1037,7 @@ def check( # pylint: disable=too-many-arguments tool_registry: Tools | None = None, *, workflow_paths: Mapping[str, Mapping[str, Path]] | None = None, - target: Literal["cwl", "nextflow"] = "cwl", + target: TargetName = "cwl", lang_version: str | None = None, inference: Inference = Inference(), policy: RunPolicy = RunPolicy(), @@ -1063,7 +1063,7 @@ def check( # pylint: disable=too-many-arguments basepath (str): As :meth:`run` takes it: the directory the run would write into. tool_registry (Tools | None): As :meth:`compile` takes it. workflow_paths (Mapping[str, Mapping[str, Path]] | None): As :meth:`run` takes it. - target (Literal["cwl", "nextflow"]): The target to check for. + target (TargetName): The target to check for. lang_version (str | None): As :meth:`compile` takes it. inference (Inference): As :meth:`compile` takes it. policy (RunPolicy): As :meth:`compile` takes it. @@ -1158,7 +1158,7 @@ def run( # pylint: disable=too-many-arguments workflow_paths: Mapping[str, Mapping[str, Path]] | None = None, inference: Inference = Inference(), policy: RunPolicy = RunPolicy(), - target: Literal["cwl", "nextflow"] = "cwl", + target: TargetName = "cwl", runner: Runner | None = None, outdir: str = _RUN.outdir, inputs_file: str = _RUN.inputs_file, @@ -1192,7 +1192,7 @@ def run( # pylint: disable=too-many-arguments infers the same edges ``compile(inference=...)`` does. policy (RunPolicy): As :meth:`compile` takes it: the run writes the CWL ``compile(policy=...)`` returns. - target (Literal["cwl", "nextflow"]): What the workflow is run as: CWL, or the pipeline + target (TargetName): What the workflow is run as: CWL, or the pipeline the Nextflow target lowers it to. runner (Runner | None): The program that runs it, with the flags it is given as they are and its own settings: ``Toil('--batchSystem', 'slurm', @@ -1232,7 +1232,7 @@ def start( # pylint: disable=too-many-arguments workflow_paths: Mapping[str, Mapping[str, Path]] | None = None, inference: Inference = Inference(), policy: RunPolicy = RunPolicy(), - target: Literal["cwl", "nextflow"] = "cwl", + target: TargetName = "cwl", runner: Runner | None = None, outdir: str = _RUN.outdir, inputs_file: str = _RUN.inputs_file, @@ -1259,7 +1259,7 @@ def start( # pylint: disable=too-many-arguments ``.wic`` files a real-time analysis may be. inference (Inference): How an unbound input is connected. policy (RunPolicy): As :meth:`run` takes it. - target (Literal["cwl", "nextflow"]): As :meth:`run` takes it. + target (TargetName): As :meth:`run` takes it. runner (Runner | None): As :meth:`run` takes it. outdir (str): As :meth:`run` takes it. inputs_file (str): As :meth:`run` takes it. @@ -1286,7 +1286,7 @@ async def run_async( # pylint: disable=too-many-arguments workflow_paths: Mapping[str, Mapping[str, Path]] | None = None, inference: Inference = Inference(), policy: RunPolicy = RunPolicy(), - target: Literal["cwl", "nextflow"] = "cwl", + target: TargetName = "cwl", runner: Runner | None = None, outdir: str = _RUN.outdir, inputs_file: str = _RUN.inputs_file, @@ -1313,7 +1313,7 @@ async def run_async( # pylint: disable=too-many-arguments name real-time analyses, which are refused. inference (Inference): How an unbound input is connected. policy (RunPolicy): As :meth:`run` takes it. - target (Literal["cwl", "nextflow"]): As :meth:`run` takes it. + target (TargetName): As :meth:`run` takes it. runner (Runner | None): As :meth:`run` takes it. outdir (str): As :meth:`run` takes it. inputs_file (str): As :meth:`run` takes it. diff --git a/src/sophios/backends.py b/src/sophios/backends.py index 64d870c8c..7406b403d 100644 --- a/src/sophios/backends.py +++ b/src/sophios/backends.py @@ -31,6 +31,7 @@ from .nf_types import ExecutableNextflowWorkflow from .runners import RunSettings from .runtime_inputs import directory_literal, output_target_inputs +from .utils import strip_terminal_codes from .utils_nf import nextflow_names from .wic_types import Json @@ -167,8 +168,6 @@ def _environment(request: RunRequest) -> dict[str, str]: #: cwltool's messages for a job that did not succeed (cwltool/job.py), as its log prints them. _JOB_ENDED: Final = re.compile(r'\[job (?P.+?)\] (?:exited with status: (?P-?\d+)' r'|was terminated by signal: (?P\w+)|completed (?P\w+))\s*$') -#: A terminal colour code: cwltool colours its log. -_COLOUR: Final = re.compile(r'\x1b\[[0-9;]*m') def failed_steps(lines: Iterable[str]) -> dict[str, int | str | None]: @@ -181,7 +180,7 @@ def failed_steps(lines: Iterable[str]) -> dict[str, int | str | None]: ended: dict[str, int | str] = {} failed: dict[str, int | str | None] = {} for line in lines: - found = _JOB_ENDED.search(_COLOUR.sub('', line)) + found = _JOB_ENDED.search(strip_terminal_codes(line)) if found is None: continue job = found['job'] diff --git a/src/sophios/compiler.py b/src/sophios/compiler.py index a1b8a8bf4..59037e49e 100644 --- a/src/sophios/compiler.py +++ b/src/sophios/compiler.py @@ -1,11 +1,9 @@ """The typed compiler boundary over the phase pipeline.""" -import re import sys from collections.abc import Iterator from copy import deepcopy from dataclasses import dataclass from pathlib import Path -from typing import Final from . import utils_cwl @@ -27,7 +25,8 @@ from .lang import versions from .lang.diagnostics import Diagnostic, Diagnostics, Locator, Severity, SophiosError from .lang.nodes import CwlRecord, UnresolvedName -from .lang.parser import Grammar +from .lang.cwl import inputs_read +from .lang.parser import step_key from .lang.error_codes import SophiosErrorCode from .wic_types import Cwl, Tool @@ -74,7 +73,9 @@ def compile_source(bundle: SourceBundle, linked = link(prepared) if linked.graph is None: raise SophiosError(linked.diagnostics) - inferred = infer(linked.graph, settings.inference, InsertionCatalog.from_registry(bundle.registry)) + inferred = infer(linked.graph, settings.inference, + InsertionCatalog.from_registry(bundle.registry) if settings.inference.insert_steps_automatically + else InsertionCatalog()) if inferred.graph is None: raise SophiosError(inferred.diagnostics) graph = declare_namespaces(inferred.graph, bundle.registry) @@ -134,17 +135,6 @@ def _tools(graph: WorkflowGraph, descriptions: '_Descriptions') -> Iterator[tupl yield from _tools(called, descriptions) -#: `inputs.name` and `inputs["name"]` inside a `when:` expression. -_EXPRESSION_INPUT: Final = re.compile(r'inputs(?:\.([A-Za-z_]\w*)|\[\s*["\']([^"\']+)["\']\s*\])') - - -def _expression_inputs(expression: object) -> tuple[str, ...]: - """Every step input a CWL expression reads, in order of first mention.""" - if not isinstance(expression, str): - return () - return tuple(dict.fromkeys(a or b for a, b in _EXPRESSION_INPUT.findall(expression))) - - def _authored_spelling_notes(graph: WorkflowGraph) -> list[str]: """One plain line for each `outputSource` that names a step by an id more than one step has: it means the first. @@ -161,7 +151,8 @@ def _authored_spelling_notes(graph: WorkflowGraph) -> list[str]: ids = [step.id.name for step in graph.steps] for name, source in graph.output_mapping: written = str(sources[name]).rsplit('/', 1)[0] - if Grammar.WIC_STEP_KEY.match(written) or ids.count(source.step.name) == 1: + key = step_key(written) + if key is not None and key.index is not None or ids.count(source.step.name) == 1: continue position = [step.id for step in graph.steps].index(source.step) + 1 notes.append(f"Warning! {file}: output {str(name)!r} has outputSource '{sources[name]}', but " @@ -185,7 +176,7 @@ def _when_notes(graph: WorkflowGraph, names: Names) -> list[Diagnostic]: return [note for child in graph.children for note in _when_notes(child, names)] for step in graph.steps: declared = [names.port(port.id.port) for port in step.inputs] - for read in _expression_inputs(dict(step.interpreted).get('when')): + for read in inputs_read(dict(step.interpreted).get('when')): if read not in declared: made = [name for name in declared if name.startswith(f'{read}{NAMESPACE_SEPARATOR}')] hint = f" Write {' or '.join(f'inputs[{name!r}]' for name in made)} to read one it declares." \ diff --git a/src/sophios/ir/frontdoor.py b/src/sophios/ir/frontdoor.py index df533cee3..9d5f868ad 100644 --- a/src/sophios/ir/frontdoor.py +++ b/src/sophios/ir/frontdoor.py @@ -10,8 +10,6 @@ from dataclasses import dataclass, field from pathlib import Path -import yaml - from ..lang import ( CWL_VERSION, CwlRecord, @@ -25,8 +23,8 @@ UnresolvedName, parse, ) +from ..lang.cwl import read_tool from ..python_cwl_adapter import generate_CWL_CommandLineTool, get_module -from ..utils_cwl import tool_process from ..wic_types import StepId, Tool, Tools from .resolve import (RegistrySnapshot, generated_process_id, inline_run_name, namespace_of, path_from_root, run_path_name, step_sidecar, version_pins) @@ -200,9 +198,7 @@ def _register_run(step: Step, namespace: str, document_dir: Path, reading: _Read name = run_path_name(run, path_from_root(target, reading.root_directory)) reading.run_names[(document_dir, run)] = name if run.endswith('.cwl'): - with open(target, mode='r', encoding='utf-8') as handle: - reading.generated[StepId(name, namespace)] = Tool( - str(target), tool_process(yaml.safe_load(handle.read()), str(target)), from_file=True) + reading.generated[StepId(name, namespace)] = Tool(str(target), read_tool(str(target)), from_file=True) else: _register_workflow((namespace, name), target, reading) return True diff --git a/src/sophios/ir/lower.py b/src/sophios/ir/lower.py index d9378e5ba..df37583c5 100644 --- a/src/sophios/ir/lower.py +++ b/src/sophios/ir/lower.py @@ -21,7 +21,7 @@ from ..lang.error_codes import SophiosErrorCode from ..lang.names import check_written_name from ..lang.nodes import CwlRecord, Document, EdgeRef, InputValue, OpaqueCwl, Step, UnresolvedName, WicSidecar -from ..lang.parser import Grammar +from ..lang.parser import step_key from ..lang.spans import SourceSpan from .declarations import port_declaration from .locations import absolute_paths @@ -304,9 +304,9 @@ def output_step(step_ids: Sequence[str], step_text: str) -> tuple[int, str | Non checks the name; an id names its first occurrence. None when `step_text` names no step. """ - key = Grammar.WIC_STEP_KEY.match(step_text) - if key is not None: - return int(key.group(1)), key.group(2) + key = step_key(step_text) + if key is not None and key.index is not None: + return key.index, key.name if step_text in step_ids: return step_ids.index(step_text) + 1, None return None diff --git a/src/sophios/ir/resolve.py b/src/sophios/ir/resolve.py index 91d768b36..cfc53cbce 100644 --- a/src/sophios/ir/resolve.py +++ b/src/sophios/ir/resolve.py @@ -10,6 +10,7 @@ from collections.abc import Callable, Sequence from copy import deepcopy from dataclasses import dataclass, replace +from functools import cached_property from hashlib import sha256 import json import os @@ -34,21 +35,34 @@ UnresolvedName, WicSidecar, ) -from ..lang.diagnostics import Diagnostic, Diagnostics, Locator +from ..lang.diagnostics import Diagnostic, Diagnostics, Locator, SophiosError from ..lang.nodes import GraphvizEntry, InputValue, OpaqueCwl, Step -from ..wic_types import Cwl, Tools +from ..wic_types import Cwl, Tool, Tools from .declarations import port_declaration from .types import PortDeclaration, RegistryKey -@dataclass(frozen=True, slots=True) +@dataclass(frozen=True) class ToolDefinition: """An owned snapshot of one runnable process definition.""" key: RegistryKey - run_path: str - cwl: Cwl - from_file: bool = False + source: Tool + + @property + def run_path(self) -> str: + """Where the tool is, or is named as.""" + return self.source.run_path + + @property + def from_file(self) -> bool: + """Whether `run_path` is the tool's own file.""" + return self.source.from_file + + @cached_property + def cwl(self) -> Cwl: + """The tool's process, copied when first asked: the snapshot's own, read only for a tool a step runs.""" + return deepcopy(self.source.cwl) #: Why a tool is not a valid CWL process, or None when it is: what `resolve` asks of each tool a step runs, before it @@ -91,8 +105,7 @@ def from_tools(cls, tools: Tools, *, root_directory: Path | None = None) -> 'RegistrySnapshot': """Own a deterministic snapshot of the legacy public registry.""" definitions = tuple(sorted(( - ToolDefinition(RegistryKey(step_id.plugin_ns, step_id.stem), - tool.run_path, deepcopy(tool.cwl), tool.from_file) + ToolDefinition(RegistryKey(step_id.plugin_ns, step_id.stem), tool) for step_id, tool in tools.items() ), key=lambda item: item.key)) sources = tuple(sorted(( @@ -235,7 +248,12 @@ def _resolve_process(step: Step, index: int, sidecar: WicSidecar | None, registr f'process {namespace}/{name} is absent from the supplied registry', step.span) return None - cwl = tool.cwl + try: + cwl = tool.cwl + except SophiosError as error: # a tool file is read here, when a step runs it + for diagnostic in error.diagnostics: + diagnostics.error(diagnostic.code, diagnostic.message, step.span, Locator(step=step.id, index=index)) + return None if check is not None and (refusal := check(tool)) is not None: diagnostics.error(SophiosErrorCode.TOOL_REFUSED, f'step {step.id!r} runs {tool.run_path}, which cwltool refuses:\n{refusal}', diff --git a/src/sophios/lang/cwl.py b/src/sophios/lang/cwl.py index 7dae34833..e20a503e2 100644 --- a/src/sophios/lang/cwl.py +++ b/src/sophios/lang/cwl.py @@ -7,9 +7,11 @@ from collections.abc import Mapping, Sequence from enum import Enum, StrEnum from pathlib import Path, PurePosixPath +import re from typing import Any, Final, TypeAlias, TypeGuard, TypeVar from cwl_utils.parser import cwl_v1_2 as _standard +import yaml from .diagnostics import SophiosError from .error_codes import SophiosErrorCode @@ -246,6 +248,23 @@ def requirement(process: Process, cls: type[_Requirement]) -> _Requirement | Non None) +#: An input a CWL expression reads, `inputs.name` or `inputs["name"]`: `inputs.name-1` is `inputs.name` minus 1. +_INPUT_READ: Final = re.compile(r'\binputs(?:\.([A-Za-z_]\w*)|\[\s*["\']([^"\']+)["\']\s*\])') + + +def inputs_read(value: Any) -> tuple[str, ...]: + """Every input the CWL expressions in `value` (a string, or the strings at any depth of a list or mapping) read, + in order of first mention.""" + match value: + case str(): + return tuple(dict.fromkeys(a or b for a, b in _INPUT_READ.findall(value))) + case list(): + return tuple(dict.fromkeys(name for item in value for name in inputs_read(item))) + case Mapping(): + return inputs_read(list(value.values())) + return () + + def fields_set(value: Any) -> list[str]: """The fields of a loaded object that were written, spelled as the standard spells them, then a vendor's as its document spelled them.""" @@ -256,3 +275,76 @@ def fields_set(value: Any) -> list[str]: namespaces = value.loadingOptions.namespaces or {} return [*standard, *(next((f'{prefix}:{name.removeprefix(uri)}' for prefix, uri in namespaces.items() if name.startswith(uri)), name) for name in value.extension_fields)] + + +def read_tool(path: str) -> dict[str, Any]: + """The process the tool file at `path` defines, read when a step first needs it. + + Raises: + SophiosError: `wic001` for a file that is not YAML or cannot be read; see `tool_process` for the others. + """ + try: + with open(path, mode='r', encoding='utf-8') as stream: + document = yaml.safe_load(stream.read()) + except yaml.YAMLError as error: + raise SophiosError.error(SophiosErrorCode.INVALID_YAML, + f'The tool {path} is not valid YAML: {" ".join(str(error).split())}') from error + except (OSError, UnicodeDecodeError) as error: + raise SophiosError.error(SophiosErrorCode.INVALID_YAML, + f'The tool {path} cannot be read as UTF-8 text: {error}') from error + return tool_process(document, path) + + +def tool_process(cwl: dict[str, Any], source: str) -> dict[str, Any]: + """The process a tool document defines: the document itself, or its ``main`` if it is packed. + + A CWL runner runs a packed document through its ``main`` process and + refuses one without; Sophios reads a tool the same way, once, where the + document is loaded, so every reader of a tool's CWL sees one process. + ``main`` is the ``$graph`` entry of that id, or the whole document when + ``cwltool --pack`` packs a single tool (no ``$graph``, ``id: '#main'``). + It is written out as a file of its own, so it takes the ``cwlVersion``, + ``$namespaces`` and ``$schemas`` the packed document declares once at its + top, and drops the ``id`` that placed it in the graph. A packer writes + ``main``'s ports as ``#main/``; they lose that prefix, so each port + keeps the name it is bound by. + + Args: + cwl (dict[str, Any]): A loaded CWL document. + source (str): Where it came from, for the diagnostic. + + Raises: + SophiosError: ``SUBWORKFLOW_INVALID`` for a ``$graph`` with no ``main``. + """ + if not isinstance(cwl, dict): + return cwl # not a CWL document: cwltool refuses it at the step that runs it + graph = cwl.get('$graph') + if not isinstance(graph, list): + return _as_main(cwl) if cwl.get('id') in ('main', '#main') else cwl + processes = [entry for entry in graph if isinstance(entry, dict)] + main = next((entry for entry in processes if entry.get('id') in ('main', '#main')), None) + if main is None: + ids = ', '.join(str(entry.get('id')) for entry in processes) + raise SophiosError.error( + SophiosErrorCode.SUBWORKFLOW_INVALID, + f'{source} is a packed CWL document ($graph) with no main process; it holds: {ids}. ' + 'CWL runs a packed document through its main, so name the process to run main, ' + 'or unpack it into a file of its own') + shared: dict[str, Any] = {key: cwl[key] for key in ('cwlVersion', '$namespaces', '$schemas') if key in cwl} + return _as_main({**shared, **main}) + + +def _as_main(process: dict[str, Any]) -> dict[str, Any]: + """A packed ``main`` as a file of its own: without its ``id``, and its ports named as they are bound.""" + process = {key: value for key, value in process.items() if key != 'id'} + for ports in ('inputs', 'outputs'): + if isinstance(process.get(ports), list): + process[ports] = [_without_main_prefix(port) for port in process[ports]] + return process + + +def _without_main_prefix(port: Any) -> Any: + """A port of a packed ``main`` with its ``id`` as ````, not ``#main/`` or ``main/``.""" + if isinstance(port, dict) and isinstance(port.get('id'), str): + return {**port, 'id': port['id'].removeprefix('#').removeprefix('main/')} + return port diff --git a/src/sophios/plugins.py b/src/sophios/plugins.py index 8c566c337..0eeb20e9a 100644 --- a/src/sophios/plugins.py +++ b/src/sophios/plugins.py @@ -4,12 +4,10 @@ import glob import os from pathlib import Path -import re import sys import tempfile from typing import Any, Iterable, Iterator, TypeAlias -import yaml import podman import docker @@ -32,8 +30,8 @@ def filter(self, record: logging.LogRecord) -> bool: class NoResolvedFilter(logging.Filter): # pylint:disable=too-few-public-methods def filter(self, record: logging.LogRecord) -> bool: - m = re.match(r"Resolved '.*' to '.*'", record.getMessage()) - return not bool(m) # (True if m else False) + message = record.getMessage() + return not (message.startswith("Resolved '") and "' to '" in message) def logging_filters() -> None: @@ -121,12 +119,14 @@ def get_tools_cwl(config: Json, validate_plugins: bool = False, basepath: str | Path = DEFAULT_BASEPATH) -> Tools: """Uses glob() to find all of the CWL CommandLineTool definition files within the configured search paths + Only names and paths are indexed: a tool file is read, and refused if it is not a tool, when a step runs it. + A stem found more than once in a namespace prints a warning, and the later definition wins: search paths in the order the config lists them, then files in sorted path order. Args: config (Json): The user specified (or default generated) config json object - validate_plugins (bool, optional): Performs validation on all CWL CommandLineTools. Defaults to False. + validate_plugins (bool, optional): Reads and validates every CWL CommandLineTool now. Defaults to False. basepath (str | Path, optional): The directory Sophios writes generated files into: `--basepath`, or `Workflow.run(basepath=)`. Nothing under it is a tool. Defaults to `autogenerated`. @@ -134,7 +134,7 @@ def get_tools_cwl(config: Json, validate_plugins: bool = False, Tools: The CWL CommandLineTool definitions found using glob() """ cwl_dirs_tag = config['search_paths_cwl'] - # Load ALL of the tools. + # Index all of the tools; each is read when a step uses it. tools_cwl: Tools = {} definitions: _Definitions = {} for plugin_ns in cwl_dirs_tag: @@ -151,8 +151,6 @@ def get_tools_cwl(config: Json, validate_plugins: bool = False, for cwl_path_str in cwl_paths: if 'biobb_md' in cwl_path_str: continue # biobb_md is deprecated (in favor of biobb_gromacs) - with open(cwl_path_str, mode='r', encoding='utf-8') as f: - tool: Cwl = utils_cwl.tool_process(yaml.safe_load(f.read()), cwl_path_str) stem = Path(cwl_path_str).stem if validate_plugins: @@ -160,7 +158,7 @@ def get_tools_cwl(config: Json, validate_plugins: bool = False, cwl_path_abs = os.path.abspath(cwl_path_str) _record(definitions, StepId(stem, plugin_ns), cwl_path_abs) - tools_cwl[StepId(stem, plugin_ns)] = Tool(cwl_path_abs, tool, from_file=True) + tools_cwl[StepId(stem, plugin_ns)] = Tool(cwl_path_abs, from_file=True) _warn_duplicates('tool', definitions) return tools_cwl diff --git a/src/sophios/preflight.py b/src/sophios/preflight.py index db0c6dce5..e802ebde7 100644 --- a/src/sophios/preflight.py +++ b/src/sophios/preflight.py @@ -32,6 +32,7 @@ from .lang.diagnostics import Diagnostic, Severity, SophiosError from .lang.error_codes import SophiosErrorCode from .runners import RunSettings +from .utils import strip_terminal_codes from .wic_types import Yaml #: Engines ` info` reaches: it needs the engine's daemon or machine, and no container or network. @@ -339,10 +340,6 @@ def _program_problems(found: Needs, run: RunSettings) -> list[Diagnostic]: return problems -#: A terminal control sequence: the nextflow launcher colours what it prints. -_CONTROL: Final = re.compile(r'\x1b(?:\[[0-9;]*[A-Za-z]|\([A-Z0-9])') - - def nextflow_problems(run: RunSettings) -> list[Diagnostic]: """A `wic029` when a run cannot start `nextflow`: it is not here, or `nextflow -version` fails, as it does without a Java it can run, or Sophios cannot run it on this platform. The first line it printed is quoted. @@ -364,7 +361,7 @@ def nextflow_problems(run: RunSettings) -> list[Diagnostic]: proc = sub.run([program, '-version'], check=False, stdout=sub.PIPE, stderr=sub.STDOUT, text=True, errors='replace') if proc.returncode == 0: return [] - said = next((line.strip() for line in _CONTROL.sub('', proc.stdout).splitlines() if line.strip()), + said = next((line.strip() for line in strip_terminal_codes(proc.stdout).splitlines() if line.strip()), 'it said nothing') return [_missing(f'nextflow -version exited with status {proc.returncode} ({said}): Nextflow needs a Java it ' 'can run; install one and point JAVA_HOME at it')] diff --git a/src/sophios/runtime_inputs.py b/src/sophios/runtime_inputs.py index be7dab984..5ad854418 100644 --- a/src/sophios/runtime_inputs.py +++ b/src/sophios/runtime_inputs.py @@ -5,19 +5,16 @@ import copy from collections.abc import Callable, Collection, Mapping from pathlib import PurePath, PurePosixPath, PureWindowsPath -import re from typing import Any, TypeAlias from cwl_utils.parser.cwl_v1_2 import Dirent, InitialWorkDirRequirement from sophios.edam import resolve_file_format from sophios.ir.resolved import InputRef, ResolvedWorkflow, Through, tool_steps -from sophios.lang.cwl import Process, ports_named, required, requirement +from sophios.lang.cwl import Process, inputs_read, ports_named, required, requirement from sophios.wic_types import Json, Tool -_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] @@ -98,7 +95,7 @@ def _output_target_inputs(run: Tool) -> set[str]: target_inputs: set[str] = set() for output in process.outputs: if _is_directory(output.type_) and (binding := getattr(output, "outputBinding", None)) is not None: - for input_name in _referenced_inputs(binding.glob): + for input_name in inputs_read(binding.glob): if input_name in writable_inputs and input_name in inputs and _is_directory(inputs[input_name].type_): target_inputs.add(input_name) return target_inputs @@ -107,7 +104,7 @@ def _output_target_inputs(run: Tool) -> set[str]: def _writable_initial_workdir_inputs(process: Process) -> set[str]: listing = getattr(requirement(process, InitialWorkDirRequirement), "listing", None) return {name for entry in listing if isinstance(entry, Dirent) and entry.writable is True - for name in _referenced_inputs(entry.entry)} if isinstance(listing, list) else set() + for name in inputs_read(entry.entry)} if isinstance(listing, list) else set() def _is_directory(cwl_type: Any) -> bool: @@ -142,15 +139,3 @@ def _output_target_basename(location: str, source_key: str) -> str: f"output-target Directory input {source_key!r} must be a simple directory name, got {location!r}" ) return basename - - -def _referenced_inputs(value: Any) -> set[str]: - match value: - case str() as text: - return set(_INPUT_REFERENCE.findall(text)) - case list() as items: - return set().union(*(_referenced_inputs(item) for item in items)) - case Mapping() as mapping: - return set().union(*(_referenced_inputs(item) for item in mapping.values())) - case _: - return set() diff --git a/src/sophios/utils.py b/src/sophios/utils.py index 612a19547..1128e8a34 100644 --- a/src/sophios/utils.py +++ b/src/sophios/utils.py @@ -1,4 +1,13 @@ -from typing import Any +import re +from typing import Any, Final + +#: A terminal control sequence: a colour or cursor code, or a character-set switch, as cwltool and Nextflow print. +_TERMINAL_CODE: Final = re.compile(r'\x1b(?:\[[0-9;]*[A-Za-z]|\([A-Z0-9])') + + +def strip_terminal_codes(text: str) -> str: + """`text` without the terminal's control sequences.""" + return _TERMINAL_CODE.sub('', text) def recursively_delete_dict_key(key: str, obj: Any) -> Any: diff --git a/src/sophios/utils_cwl.py b/src/sophios/utils_cwl.py index 0419d8284..111297616 100644 --- a/src/sophios/utils_cwl.py +++ b/src/sophios/utils_cwl.py @@ -14,66 +14,11 @@ from schema_salad.fetcher import DefaultFetcher from .input_output import dump_wic_yaml -from .lang.diagnostics import SophiosError -from .lang.error_codes import SophiosErrorCode +from .lang.cwl import tool_process +from .utils import strip_terminal_codes from .wic_types import Cwl, Yaml -def tool_process(cwl: Yaml, source: str) -> Yaml: - """The process a tool document defines: the document itself, or its ``main`` if it is packed. - - A CWL runner runs a packed document through its ``main`` process and - refuses one without; Sophios reads a tool the same way, once, where the - document is loaded, so every reader of a tool's CWL sees one process. - ``main`` is the ``$graph`` entry of that id, or the whole document when - ``cwltool --pack`` packs a single tool (no ``$graph``, ``id: '#main'``). - It is written out as a file of its own, so it takes the ``cwlVersion``, - ``$namespaces`` and ``$schemas`` the packed document declares once at its - top, and drops the ``id`` that placed it in the graph. A packer writes - ``main``'s ports as ``#main/``; they lose that prefix, so each port - keeps the name it is bound by. - - Args: - cwl (Yaml): A loaded CWL document. - source (str): Where it came from, for the diagnostic. - - Raises: - SophiosError: ``SUBWORKFLOW_INVALID`` for a ``$graph`` with no ``main``. - """ - if not isinstance(cwl, dict): - return cwl # not a CWL document: cwltool refuses it at the step that runs it - graph = cwl.get('$graph') - if not isinstance(graph, list): - return _as_main(cwl) if cwl.get('id') in ('main', '#main') else cwl - processes = [entry for entry in graph if isinstance(entry, dict)] - main = next((entry for entry in processes if entry.get('id') in ('main', '#main')), None) - if main is None: - ids = ', '.join(str(entry.get('id')) for entry in processes) - raise SophiosError.error( - SophiosErrorCode.SUBWORKFLOW_INVALID, - f'{source} is a packed CWL document ($graph) with no main process; it holds: {ids}. ' - 'CWL runs a packed document through its main, so name the process to run main, ' - 'or unpack it into a file of its own') - shared: Yaml = {key: cwl[key] for key in ('cwlVersion', '$namespaces', '$schemas') if key in cwl} - return _as_main({**shared, **main}) - - -def _as_main(process: Yaml) -> Yaml: - """A packed ``main`` as a file of its own: without its ``id``, and its ports named as they are bound.""" - process = {key: value for key, value in process.items() if key != 'id'} - for ports in ('inputs', 'outputs'): - if isinstance(process.get(ports), list): - process[ports] = [_without_main_prefix(port) for port in process[ports]] - return process - - -def _without_main_prefix(port: Any) -> Any: - """A port of a packed ``main`` with its ``id`` as ````, not ``#main/`` or ``main/``.""" - if isinstance(port, dict) and isinstance(port.get('id'), str): - return {**port, 'id': port['id'].removeprefix('#').removeprefix('main/')} - return port - - #: The keys schema-salad resolves against the document that writes them. _REFERENCE_KEYS: Final = ('$include', '$import', '$mixin') #: A URI scheme of two letters or more, so a Windows drive (`C:`) is not one. @@ -135,7 +80,6 @@ class InvalidTool(Exception): #: The position cwltool's message line starts with, `:::`, and the nesting after it. _POSITION: Final = re.compile(r'^\S+?:(\d+):(\d+):( *)') -_COLOUR: Final = re.compile(r'\x1b\[[0-9;]*m') #: What schema-salad heads a nested resolution error with: the loader's object id, and the document's URI. _IDENTIFIED: Final = re.compile(r'\(\d+\) (?:\([^)\s]*\) )?') _ATTEMPT: Final = re.compile(r"tried (?:array of <[^>]*>|\S+) but\b\s*|,? tried \S+$") @@ -151,7 +95,7 @@ def _plain(error: Exception, name: str, *, positions: bool) -> str: document no file holds. """ places: list[list[str]] = [] - for line in _COLOUR.sub('', str(error)).splitlines(): + for line in strip_terminal_codes(str(error)).splitlines(): if found := _POSITION.match(line): places.append([f"{found[1]}:{found[2]}" if positions else '', found[3] + line[found.end():].strip()]) elif _IDENTIFIED.match(line.lstrip()): diff --git a/src/sophios/wic_types.py b/src/sophios/wic_types.py index df3af2d8a..217fa9899 100644 --- a/src/sophios/wic_types.py +++ b/src/sophios/wic_types.py @@ -2,7 +2,7 @@ from functools import cached_property from typing import Any, Final, Literal, NamedTuple, TypeAlias, TypedDict, get_args -from .lang.cwl import Process, Written, load_process +from .lang.cwl import Process, Written, load_process, read_tool # See https://mypy.readthedocs.io/en/stable/kinds_of_types.html#type-aliases @@ -28,10 +28,23 @@ @dataclass(frozen=True) class Tool: run_path: str - cwl: Cwl + #: The tool's process; None for a tool file, which `cwl` reads when first asked, so only a tool a step runs + #: has to be readable. + _cwl: Cwl | None = None #: Whether the file at `run_path` is the tool, read from it, and not a path a tool written elsewhere is named by. from_file: bool = False + @cached_property + def cwl(self) -> Cwl: + """The tool's process. + + Raises: + SophiosError: `wic001` for a tool file that is not YAML. + """ + if self._cwl is None: + return read_tool(self.run_path) + return self._cwl + @cached_property def loaded(self) -> tuple[Process, Written]: """The tool read once into the standard's classes, shared by every reader of it and edited by none (a reader diff --git a/tests/core/budgets.py b/tests/core/budgets.py index 1ba7c8fcb..6a4de9aeb 100644 --- a/tests/core/budgets.py +++ b/tests/core/budgets.py @@ -29,3 +29,8 @@ def budget(max_examples: int) -> settings: property in this suite relaxes: generated workflows are slow to compile.""" return settings(max_examples=max_examples * SCALE, suppress_health_check=[HealthCheck.too_slow], deadline=None, print_blob=True) + + +#: The budget of a property that only parses or renders; one that compiles takes `COMPILED`. +FAST: Final = budget(200) +COMPILED: Final = budget(100) diff --git a/tests/core/compile_harness.py b/tests/core/compile_harness.py index cc83a30af..33c5ce791 100644 --- a/tests/core/compile_harness.py +++ b/tests/core/compile_harness.py @@ -3,14 +3,9 @@ from sophios.ir.artifacts import CompilationResult from sophios.wic_types import Yaml -from .budgets import budget from .hermetic import bundle from .test_setup import load_test_registry -#: Shared Hypothesis budgets; compiled properties are far slower than parse-only ones, so COMPILED gets a smaller count. -FAST = budget(200) -COMPILED = budget(100) - def compile_info(yml: Yaml, name: str = 'harness') -> CompilationResult: """Compile one in-memory workflow against the discovered registry.""" diff --git a/tests/core/data/output_directory/write_dir_listed.cwl b/tests/core/data/output_directory/write_dir_listed.cwl index be12a3b2b..fac7a59c9 100644 --- a/tests/core/data/output_directory/write_dir_listed.cwl +++ b/tests/core/data/output_directory/write_dir_listed.cwl @@ -1,11 +1,11 @@ cwlVersion: v1.2 class: CommandLineTool # The same tool as write_dir.cwl with its requirements, inputs and outputs written as lists, as the Python -# API's tool builder writes them. +# API's tool builder writes them, and its input read as inputs["outDir"]. requirements: - class: InitialWorkDirRequirement listing: - - entry: $(inputs.outDir) + - entry: $(inputs["outDir"]) writable: true baseCommand: touch arguments: @@ -17,4 +17,4 @@ outputs: - id: outDir type: Directory outputBinding: - glob: $(inputs.outDir.basename) + glob: $(inputs["outDir"].basename) diff --git a/tests/core/nextflow/test_public_api.py b/tests/core/nextflow/test_public_api.py index 66c0d7876..b3bf359ef 100644 --- a/tests/core/nextflow/test_public_api.py +++ b/tests/core/nextflow/test_public_api.py @@ -157,21 +157,25 @@ def test_a_target_takes_its_own_options_and_no_other(capsys: pytest.CaptureFixtu if owner in {"every target", target}: cli.validate_target_args(args) continue - with pytest.raises(SystemExit, match="2"): + with pytest.raises(SystemExit) as caught: cli.validate_target_args(args) + assert caught.value.code == 2 assert f"{action.option_strings[0]} (--target {owner})" in capsys.readouterr().err - with pytest.raises(SystemExit, match="2"): + with pytest.raises(SystemExit) as caught: sophios_main._main(cli.get_args("workflow.wic", ["--target", target]), ["--bogus"]) + assert caught.value.code == 2 assert "--passthrough_flags" in capsys.readouterr().err.splitlines()[-1] for flags in (["--run_local"], ["--check"], ["--generate_run_script"], ["--passthrough_flags", "yes"]): assert cli.get_args("workflow.wic", ["--target", "nextflow", *flags]).target == "nextflow" for flags in (["--generate_cwl_workflow"], ["--quiet"], ["--cwl_runner", "toil-cwl-runner"], ["--container_engine", "podman"], ["--cachedir", "cache"], ["--outdir", "out"], ["--inputs_file", "inputs.yml"]): - with pytest.raises(SystemExit, match="2"): + with pytest.raises(SystemExit) as caught: cli.get_args("workflow.wic", ["--target", "nextflow", *flags]) - with pytest.raises(SystemExit, match="2"): + assert caught.value.code == 2 + with pytest.raises(SystemExit) as caught: cli.get_args("workflow.wic", ["--run_local", "--generate_cwl_workflow"]) + assert caught.value.code == 2 @pytest.mark.fast @@ -182,8 +186,9 @@ def test_a_plain_cwl_workflow_under_allow_raw_cwl_is_lowered_under_nextflow( written.""" raw = str(DATA / "nextflow" / "cli" / "raw.cwl") monkeypatch.chdir(tmp_path) - with pytest.raises(SystemExit, match="1"): + with pytest.raises(SystemExit) as caught: sophios_main._main(cli.get_args(raw, ["--allow_raw_cwl", "--homedir", str(tmp_path)]), []) + assert caught.value.code == 1 assert "--generate_cwl_workflow" in capsys.readouterr().out sophios_main._main(cli.get_args(raw, [ "--allow_raw_cwl", "--homedir", str(tmp_path), "--target", "nextflow", "--basepath", "out"]), []) diff --git a/tests/core/test_ci_coverage.py b/tests/core/test_ci_coverage.py index b5a727843..1d61f632b 100644 --- a/tests/core/test_ci_coverage.py +++ b/tests/core/test_ci_coverage.py @@ -15,7 +15,6 @@ """ import ast import json -import re import shlex import subprocess import sys @@ -69,7 +68,7 @@ def _invocations(workflow: Path) -> list[list[str]]: for job in (script.get('jobs') or {}).values(): for step in (job.get('steps') or []): for line in (step.get('run') or '').splitlines(): - if not re.search(r'\bpytest\b', line): + if 'pytest' not in line: continue tokens = shlex.split(line, comments=True) if 'pytest' in tokens: diff --git a/tests/core/test_cookbook.py b/tests/core/test_cookbook.py index 4b4de9f1c..aaf72f035 100644 --- a/tests/core/test_cookbook.py +++ b/tests/core/test_cookbook.py @@ -77,7 +77,7 @@ def _compile_wic(root: Path, settings: sophios.compiler.CompileSettings) -> Comp def _bodies(diagnostics: Any) -> list[str]: """Each diagnostic as it is printed, but for the place it points at, which is the surface's own.""" - return [re.sub(r'^.+?:\d+:\d+: ', '', str(item)) for item in diagnostics] + return [str(replace(item, span=None)) for item in diagnostics] def _refusal(error: SophiosError) -> list[dict[str, Any]]: diff --git a/tests/core/test_diagnostics.py b/tests/core/test_diagnostics.py index 7cefbddd9..10d18c132 100644 --- a/tests/core/test_diagnostics.py +++ b/tests/core/test_diagnostics.py @@ -24,13 +24,12 @@ from sophios.lang.error_codes import EXPLANATIONS, Kind, SophiosErrorCode from sophios.lang.spans import SourceSpan -from .budgets import budget +from .budgets import FAST, budget from .cases import case_dirs, match, printed from .helpers import run_cli from .hermetic import compile_hermetic, compile_hermetic_source, cwl_tree from .strategies import author_names, pinned from .synthetic_tools import clt, registered -from .test_lang_parser import FAST _TYPES: Final = {'int': int, 'long': int, 'float': float, 'double': float, 'boolean': bool, 'string': str} _TEXTS = st.text('07.e+-:axy', max_size=4) diff --git a/tests/core/test_emit.py b/tests/core/test_emit.py index 76857a448..6353accce 100644 --- a/tests/core/test_emit.py +++ b/tests/core/test_emit.py @@ -302,8 +302,16 @@ def test_a_string_job_value_is_a_string_to_cwltool(texts: list[str]) -> None: lambda inner: st.lists(inner, max_size=2), max_leaves=4) +#: Values their types take: without them, a coercer that refused every value would pass the property. +_TAKEN: Final[tuple[tuple[str, Yaml, Any], ...]] = ( + ('string', {}, 'a'), ('int', {}, 1), ('File', {'format': 'edam:format_1'}, {'class': 'File', 'location': 'a'})) + + @pytest.mark.skip_pypi_ci @given(_TYPES, st.sampled_from([{}, {'format': 'edam:format_1'}]), _VALUES) +@example(*_TAKEN[0]) +@example(*_TAKEN[1]) +@example(*_TAKEN[2]) @COVERAGE def test_a_job_value_is_its_own_normal_form(raw: Any, fmt: Yaml, value: Any) -> None: """Coercing a coerced job value changes nothing, which is what lets a @@ -313,6 +321,7 @@ def test_a_job_value_is_its_own_normal_form(raw: Any, fmt: Yaml, value: Any) -> try: once = coerce_job_value(name, declaration, value) except SophiosError: + assert (raw, fmt, value) not in _TAKEN, 'a value its type takes was refused' return assert coerce_job_value(name, declaration, once) == once diff --git a/tests/core/test_graph_features.py b/tests/core/test_graph_features.py index 34f849be1..1c35ff47b 100644 --- a/tests/core/test_graph_features.py +++ b/tests/core/test_graph_features.py @@ -76,4 +76,4 @@ def test_the_drawing_is_what_its_example_states(monkeypatch: pytest.MonkeyPatch, ranks = [[len(indent), [_unquoted(name) for name in names.split('; ')]] for indent, names in re.findall(r'^(\t*)\{rank=same; (.*)\}$', dot, re.MULTILINE)] assert 'ranks' not in drawn or ranks == drawn['ranks'] - assert match({'contains': drawn['said']} if 'said' in drawn else {'re': ''}, capsys.readouterr().err) + assert 'said' not in drawn or match({'contains': drawn['said']}, capsys.readouterr().err) diff --git a/tests/core/test_lang_parser.py b/tests/core/test_lang_parser.py index c4cf6ac4e..824789e38 100644 --- a/tests/core/test_lang_parser.py +++ b/tests/core/test_lang_parser.py @@ -37,14 +37,12 @@ from sophios.utils_yaml import Key from . import provocations -from .budgets import budget +from .budgets import FAST, budget from .cases import DATA, case_dirs, diagnostic as as_written from .test_setup import workflow_paths from .strategies import documents, identifiers, input_lines, pinned, scalar_spellings from .wic_reading import YamlWithSophiosTagsOpaque -FAST = budget(200) - #: The exported schema, as an editor validates a document's JSON projection with it. SCHEMA_VALIDATOR: Final = jsonschema.Draft202012Validator(wic_schema()) diff --git a/tests/core/test_lang_render.py b/tests/core/test_lang_render.py index 5b7fe6dbb..c5e9ef69e 100644 --- a/tests/core/test_lang_render.py +++ b/tests/core/test_lang_render.py @@ -12,14 +12,12 @@ from sophios.lang.render import render from sophios.lang.spans import SourceSpan -from .budgets import budget +from .budgets import FAST, budget from .cases import DATA from .strategies import documents, identifiers, pinned from .test_lang_parser import reading from .wic_reading import YamlWithSophiosTagsOpaque -FAST = budget(200) - # Literals are drawn as YAML source text rather than converted from Python values: writing the spelling out keeps # the awkward cases visible, and leaves the test no quoting logic of its own to agree with the renderer's. Included on # purpose: the falsy values a naive `x or ''` would destroy, and the characters that force the renderer off plain style. diff --git a/tests/core/test_lang_version.py b/tests/core/test_lang_version.py index 49acd0d7c..3aba29050 100644 --- a/tests/core/test_lang_version.py +++ b/tests/core/test_lang_version.py @@ -13,8 +13,8 @@ import sophios.cli import sophios.main +from .budgets import FAST from .cases import DATA -from .compile_harness import FAST from .test_setup import load_test_registry #: The key earlier Sophios versions annotated compiled CWL with. diff --git a/tests/core/test_leak_boundary.py b/tests/core/test_leak_boundary.py index 84c1b9338..9503513ff 100644 --- a/tests/core/test_leak_boundary.py +++ b/tests/core/test_leak_boundary.py @@ -17,7 +17,8 @@ from . import ast_strategies as strat from .ast_strategies import hints_values, passthrough_keys, passthrough_values -from .compile_harness import COMPILED, compile_info +from .budgets import COMPILED +from .compile_harness import compile_info from .cwl_validation import validate_cwl from .hermetic import compile_hermetic, cwl_tree diff --git a/tests/core/test_plugins.py b/tests/core/test_plugins.py index 229feae0e..689ba830e 100644 --- a/tests/core/test_plugins.py +++ b/tests/core/test_plugins.py @@ -19,14 +19,18 @@ import sophios.plugins import sophios.preflight +from sophios.compiler import CompileSettings, compile_source +from sophios.ir.frontdoor import bundle_from_disk from sophios.ir.types import PortType from sophios.ir.policy import RunPolicy, tolerant_tool from sophios.lang.cwl import CWL_VERSION from sophios.lang.diagnostics import SophiosError +from sophios.lang.error_codes import SophiosErrorCode from sophios.wic_types import Yaml from .budgets import budget from .cases import DATA, cases, match +from .hermetic import cwl_tree from .helpers import ADAPTERS, run_cli, search_config @@ -371,3 +375,33 @@ def test_validate_plugins_accepts_the_shipped_tools_and_names_the_file_of_one_cw refusing = {'search_paths_cwl': {'global': [str(DATA / 'compiler' / 'refused')]}} with pytest.raises(SophiosError, match=r"(?s)wic057.*refused.\w+\.cwl is a tool cwltool refuses:"): sophios.plugins.get_tools_cwl(refusing, validate_plugins=True) + + +@pytest.mark.fast +def test_a_tool_file_that_is_not_yaml_stops_only_the_workflow_that_runs_it(tmp_path: Path) -> None: + """Discovery indexes tools by name and path; a tool file is read when a step runs it, so one that cannot be read + leaves a workflow that does not use it alone, and refuses the step that does with its file named.""" + shutil.copy(ADAPTERS / 'echo.cwl', tmp_path) + (tmp_path / 'unreadable.cwl').write_text('this: is: not: yaml: [\n', encoding='utf-8') + (tmp_path / 'binary.cwl').write_bytes(b'\xff\xfe\x00bad') + (tmp_path / 'insert_steps_automatically_x.cwl').write_text('this: is: not: yaml: [\n', encoding='utf-8') + (tmp_path / 'unused.wic').write_text('steps:\n- id: echo\n in:\n message: !ii hi\n', encoding='utf-8') + (tmp_path / 'used.wic').write_text('steps:\n- id: unreadable\n', encoding='utf-8') + (tmp_path / 'binary.wic').write_text('steps:\n- id: binary\n', encoding='utf-8') + tools = sophios.plugins.get_tools_cwl({'search_paths_cwl': {'global': [str(tmp_path)]}}) + + def compiled(workflow: str) -> Any: + return cwl_tree(compile_source(bundle_from_disk(tmp_path / workflow, {}, tools), CompileSettings(), quiet=True)) + + assert [child.namespace for child in compiled('unused.wic').children] == [('echo',)] + with pytest.raises(SophiosError) as raised: + compiled('used.wic') + diagnostic, = raised.value.diagnostics + assert diagnostic.code is SophiosErrorCode.INVALID_YAML + assert diagnostic.locator is not None and diagnostic.locator.step == 'unreadable' + assert str(tmp_path / 'unreadable.cwl') in diagnostic.message + with pytest.raises(SophiosError) as raised: + compiled('binary.wic') + diagnostic, = raised.value.diagnostics + assert diagnostic.code is SophiosErrorCode.INVALID_YAML and diagnostic.locator is not None + assert diagnostic.locator.step == 'binary' diff --git a/tests/core/test_python_api_workflow.py b/tests/core/test_python_api_workflow.py index 64628cc2e..ccbde46a9 100644 --- a/tests/core/test_python_api_workflow.py +++ b/tests/core/test_python_api_workflow.py @@ -425,10 +425,8 @@ def test_run_writes_what_compile_returns_and_hands_the_runner_its_own_flags(monk lambda documents, settings, jobs=(), **_: prepared.append((documents, settings))) monkeypatch.setattr(sophios.plugins.docker, 'from_env', lambda: SimpleNamespace(images=SimpleNamespace(build=lambda **_: None))) - for quiet in (True, False): - workflow.run(basepath='base', runner=Cwltool(remove_entrypoints=True), generate_run_script=True, quiet=quiet) - command = (tmp_path / 'run.sh').read_text(encoding='utf-8').splitlines()[-1].split() - assert ('--quiet' in command) is quiet + workflow.run(basepath='base', runner=Cwltool(remove_entrypoints=True), generate_run_script=True) + assert '--quiet' in (tmp_path / 'run.sh').read_text(encoding='utf-8').splitlines()[-1].split() compiled = workflow.compile() assert sorted(path.name for path in (tmp_path / 'base').iterdir()) == ['exact.cwl', 'exact_inputs.yml'] diff --git a/tests/core/test_runtime_inputs.py b/tests/core/test_runtime_inputs.py index f857fa851..fff6b0020 100644 --- a/tests/core/test_runtime_inputs.py +++ b/tests/core/test_runtime_inputs.py @@ -116,8 +116,8 @@ def test_an_output_target_directory_given_an_absolute_path_is_left_as_written(gi ('listed.wic', 'write_dir_listed~outDir')], ids=['one', 'two', 'listed']) def test_an_output_target_directory_below_calls_is_a_directory_literal_at_its_root_key( tmp_path: Path, source: str, key: str) -> None: - """The job key is the step's qualified input, however many calls deep, and whether the tool writes its - requirements as a mapping or as a list.""" + """The job key is the step's qualified input, however many calls deep, whether the tool writes its + requirements as a mapping or as a list, and whether it reads the input as inputs.outDir or inputs["outDir"].""" out = _written(tmp_path, source, f'{key}: {{class: Directory, location: result.outDir}}\n') assert _job(out, source.removesuffix('.wic')) == { key: {'class': 'Directory', 'basename': 'result.outDir', 'listing': []}} diff --git a/tests/core/test_scattering_scaling.py b/tests/core/test_scattering_scaling.py index d0b25caa5..7b256de2e 100644 --- a/tests/core/test_scattering_scaling.py +++ b/tests/core/test_scattering_scaling.py @@ -3,6 +3,7 @@ import subprocess as sub import time +import numpy import yaml from .helpers import REPO_ROOT @@ -30,35 +31,7 @@ def _run_command(cmd: list[str]) -> str: def _quadratic_coefficient(samples: dict[int, float]) -> float: """Return the x^2 coefficient from a least-squares quadratic timing fit.""" - rows = [[float(size * size), float(size), 1.0] for size in samples] - values = list(samples.values()) - normal_matrix = [ - [sum(row[i] * row[j] for row in rows) for j in range(3)] - for i in range(3) - ] - normal_vector = [sum(row[i] * value for row, value in zip(rows, values)) for i in range(3)] - augmented = [ - [*matrix_row, vector_value] - for matrix_row, vector_value in zip(normal_matrix, normal_vector) - ] - - for pivot in range(3): - pivot_row = max(range(pivot, 3), key=lambda row: abs(augmented[row][pivot])) - assert abs(augmented[pivot_row][pivot]) > 1e-12 - augmented[pivot], augmented[pivot_row] = augmented[pivot_row], augmented[pivot] - - pivot_value = augmented[pivot][pivot] - augmented[pivot] = [value / pivot_value for value in augmented[pivot]] - for row_index in range(3): - if row_index == pivot: - continue - factor = augmented[row_index][pivot] - augmented[row_index] = [ - current - factor * pivot_value - for current, pivot_value in zip(augmented[row_index], augmented[pivot]) - ] - - return augmented[0][3] + return float(numpy.polyfit(list(samples), list(samples.values()), 2)[0]) def test_scattering_scaling(tmp_path: Path) -> None: diff --git a/tests/core/test_targets.py b/tests/core/test_targets.py index d8e7ded31..c4d8042eb 100644 --- a/tests/core/test_targets.py +++ b/tests/core/test_targets.py @@ -1,20 +1,11 @@ """One table of targets, which every entry point reads.""" -import importlib -from typing import get_args, get_type_hints - import pytest -from sophios import cli -from sophios.api.python.workflow import Workflow +from sophios.targets import TARGETS +from sophios.wic_types import TARGET_NAMES @pytest.mark.fast -def test_the_table_the_command_line_and_the_python_api_name_the_same_targets() -> None: - """A target the table holds is one `--target` and every `target=` accept, and nothing else is.""" - targets = set(importlib.import_module("sophios.targets").TARGETS) - choices = next(action.choices for action in cli.parser._actions # pylint: disable=protected-access - if action.dest == "target") - named = {method: set(get_args(get_type_hints(getattr(Workflow, method))["target"])) - for method in ("compile", "check", "run", "start", "run_async")} - assert set(choices or ()) == targets - assert named == {method: targets for method in named} +def test_the_table_holds_the_targets_the_entry_points_name() -> None: + """`--target` and every `target=` take `wic_types.TargetName`; the table holds exactly those targets.""" + assert set(TARGETS) == set(TARGET_NAMES)