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
4 changes: 2 additions & 2 deletions src/sophios/api/python/_workflow_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
22 changes: 11 additions & 11 deletions src/sophios/api/python/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand All @@ -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
Expand Down Expand Up @@ -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(),
Expand All @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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,
Expand All @@ -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.
Expand All @@ -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,
Expand All @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions src/sophios/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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<job>.+?)\] (?:exited with status: (?P<status>-?\d+)'
r'|was terminated by signal: (?P<signal>\w+)|completed (?P<completed>\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]:
Expand All @@ -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']
Expand Down
25 changes: 8 additions & 17 deletions src/sophios/compiler.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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 "
Expand All @@ -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." \
Expand Down
8 changes: 2 additions & 6 deletions src/sophios/ir/frontdoor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
from dataclasses import dataclass, field
from pathlib import Path

import yaml

from ..lang import (
CWL_VERSION,
CwlRecord,
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions src/sophios/ir/lower.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
36 changes: 27 additions & 9 deletions src/sophios/ir/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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((
Expand Down Expand Up @@ -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}',
Expand Down
Loading
Loading