Coverage for collectra/pipelines/base.py: 95.05%
1151 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Core pipeline execution and workflow management for Collectra.
3This module contains the main ``Pipeline`` class.
5It provides the core functionality for defining, excuting and managing
6workflows with task dependencies.
8The module supports:
9 - Workflow definition and configuration management
10 - Task dependency graph construction and execution
11 - Workflow visualization and rendering
12 - Training and inference execution modes
14Classes:
15 Pipeline: Main workflow management class
16"""
18from __future__ import annotations
20__all__ = ["Pipeline"]
22import copy
23import datetime
24import filecmp
25import json
26import shlex
27import shutil
28import stat
29import sys
30import tempfile
31import time
32import warnings
33from collections import defaultdict
34from collections.abc import Callable, Mapping, Sequence
35from contextlib import nullcontext
36from dataclasses import replace
37from pathlib import Path
38from typing import Annotated, Any, ClassVar
40import graphviz
41import networkx as nx
42import yaml
43from cappa import Arg
44from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
45from rich.markup import escape
46from rich.progress import (
47 BarColumn,
48 MofNCompleteColumn,
49 Progress,
50 SpinnerColumn,
51 TextColumn,
52 TimeElapsedColumn,
53 TimeRemainingColumn,
54 track,
55)
57from collectra.cli import command, group, subcommands
58from collectra.utils import change_dir, load_class_from_string, write_yaml
59from utils.get_types import get_param_types, get_return_type, unpack_types
61from ..commons.base import LenientAttributes, TaskContext
62from ..commons.results import Results, pop_header, put_header
63from ..logger import get_logger
64from ..resources.base import Resource
65from ..tasks.base import (
66 Task,
67 TaskNode,
68)
69from ..types.base import (
70 Artefact,
71 ArtefactNode,
72 NodeStatus,
73)
74from ..types.images import Image, ImageCrop
75from ..types.links import Link
76from ..types.texts import Text
77from ..usage import UsageLedger
78from .env import PipelineEnv
79from .importing import ImportReport, destination
80from .node_graph_manager import NodeGraphManager
81from .run_plan import RunPlan, RunReport, TaskOutcome, TaskPlan, plan_tasks
83logger = get_logger(__name__)
86def _never() -> bool:
87 """The default stop check of a run: it never stops."""
88 return False
91class PreviousOutputs:
92 """What a task produced before a forced rerun, kept until the rerun succeeds.
94 Output items are emptied and the node's saved files are moved aside so the
95 rerun starts clean. If the rerun produces nothing, everything is put back.
96 """
98 def __init__(self, snapshots: list, moved: list, backup: Path | None):
99 self.snapshots = snapshots
100 self.moved = moved
101 self.backup = backup
103 def restore(self) -> None:
104 for output, items in self.snapshots:
105 output.items.update(items)
106 for kept, original in self.moved:
107 original.parent.mkdir(parents=True, exist_ok=True)
108 shutil.move(str(kept), str(original))
109 self.discard()
111 def discard(self) -> None:
112 if self.backup is not None:
113 shutil.rmtree(self.backup, ignore_errors=True)
114 self.backup = None
117class RunProgress:
118 """One overall bar for a multi-file run, with the file it is up to."""
120 def __init__(self, progress, label: str, total: int):
121 self.progress = progress
122 self.label = label
123 self.task = progress.add_task(escape(label), total=total)
125 def status(self, text: str) -> None:
126 self.progress.update(
127 self.task, description=f"{escape(self.label)} · {escape(text)}"
128 )
130 def file_done(self) -> None:
131 self.progress.advance(self.task)
134class StageGate:
135 """Holds files back at batchable tasks so a whole chunk can prefetch together."""
137 def __init__(self, batchable: set[str]):
138 self.batchable = batchable
139 self.current: set[str] = set()
140 self.deferred: dict[str, list[TaskNode]] = {}
142 def defer(self, node: TaskNode, value) -> bool:
143 """Hold ``node`` for the file at ``value``; False if it should run now."""
144 if node.name not in self.batchable or node.name in self.current:
145 return False
146 held = self.deferred.setdefault(str(value), [])
147 if node not in held:
148 held.append(node)
149 return True
152class Pipeline(LenientAttributes, BaseModel):
153 """Main workflow management class for Collectra pipelines.
155 This class orchestrates the execution of complex data processing workflows
156 by managing task dependencies, data flow, and execution state.
157 """
159 model_config = ConfigDict(
160 extra="allow", validate_assignment=True, arbitrary_types_allowed=True
161 )
163 # Constants
164 RESULTS_FILE: ClassVar[str] = "results.yaml"
165 METADATA_KEY: ClassVar[str] = "collectra_results_metadata"
166 PIPELINE_FILE: ClassVar[str] = "pipeline.yaml"
167 PIPELINE_METADATA_KEY: ClassVar[str] = "collectra_pipeline_metadata"
169 # Graph visualization colors
170 COLOR_PROCESSING: ClassVar[str] = "orange"
171 COLOR_SUCCESS: ClassVar[str] = "green"
172 COLOR_FAILURE: ClassVar[str] = "red"
173 COLOR_FONT: ClassVar[str] = "black"
175 name: str
176 ext: str
177 version: str
178 path: Path
179 pipeline_metadata: dict = Field(default_factory=dict)
180 node_manager: NodeGraphManager = Field(default_factory=NodeGraphManager, repr=False)
181 # The pipeline definition: every other keyword is a task or artefact entry.
182 data: dict[str, Any] = Field(default_factory=dict, repr=False)
183 # Named helpers declared in the definition (lookups and the like); unlike
184 # tasks and artefacts they are not nodes of the graph.
185 resources: dict[str, Any] = Field(default_factory=dict, repr=False, exclude=True)
187 # Runtime state of a run in progress.
188 _stage_gate: StageGate | None = None
189 _run_progress: RunProgress | None = None
190 # (task, file, error) for each task that failed in the current run.
191 _failures: list[tuple[str, str, str]] = PrivateAttr(default_factory=list)
192 # (status, detail) for each task that ran, was skipped, failed or was
193 # stopped in the current run, by page folder and then task name.
194 _outcomes: dict[str, dict[str, tuple[str, str]]] = PrivateAttr(
195 default_factory=lambda: defaultdict(dict)
196 )
197 # (page folder, error) for errors that stopped a page, or with no folder
198 # the whole run, after being logged.
199 _run_errors: list[tuple[str, str]] = PrivateAttr(default_factory=list)
200 # True when the file used the deprecated ``collectra_pipeline_metadata``
201 # block; saving then keeps that form rather than rewriting the file.
202 _legacy_declaration: bool = PrivateAttr(default=False)
203 # The environment variables the user stores for this pipeline.
204 _env: PipelineEnv | None = PrivateAttr(default=None)
205 _usage: UsageLedger = PrivateAttr(default_factory=UsageLedger)
207 @field_validator("version", mode="before")
208 @classmethod
209 def _version_is_text(cls, value):
210 # YAML reads ``version: 1`` as a number; a version is always text.
211 return str(value) if isinstance(value, (int, float)) else value
213 def __init__(
214 self,
215 name: str,
216 ext: str,
217 version: str,
218 path: str | Path = "",
219 pipeline_metadata: dict | None = None,
220 **kwargs,
221 ):
222 """Initialize the Collectra workflow.
224 Args:
225 name (str): Name of the workflow.
226 ext (str): File extension that the workflow accepts.
227 version (str): Version of the workflow.
228 path (str, optional): Path to the workflow files. Defaults to name.
229 **kwargs: The pipeline definition: task and artefact entries.
230 """
231 super().__init__(
232 name=name,
233 ext=ext,
234 version=version,
235 path=Path(path) if path else Path.cwd() / str(name),
236 pipeline_metadata={
237 **(pipeline_metadata or {}),
238 "name": name,
239 "ext": ext,
240 "version": str(version),
241 },
242 data=kwargs,
243 )
245 # A pipeline is a long-lived object holding its graph: compare by identity.
246 def __eq__(self, other: object) -> bool:
247 return self is other
249 __hash__ = object.__hash__
251 def __call__(self, task_name: str, **kwargs):
252 """Allow instance to be called directly to run workflow."""
253 self.run(task_name, **kwargs)
255 @classmethod
256 def from_file(cls, pipeline_path: str | Path) -> "Pipeline":
257 """Load a pipeline from a directory or a pipeline YAML file.
259 The file declares its pipeline as an entry whose ``type`` is
260 ``collectra.Pipeline`` (or a subclass of it); the entry's name is the
261 pipeline's name and its other keys are the pipeline's attributes.
262 The older ``collectra_pipeline_metadata`` block is still read, with a
263 warning that it is deprecated.
264 """
265 path = Path(pipeline_path).expanduser().resolve()
266 config_path = path / cls.PIPELINE_FILE if path.is_dir() else path
267 with config_path.open() as stream:
268 config = yaml.safe_load(stream) or {}
269 legacy = cls.PIPELINE_METADATA_KEY in config
270 if legacy:
271 attributes = config.pop(cls.PIPELINE_METADATA_KEY)
272 pipeline_class, name = cls, attributes.get("name")
273 warnings.warn(
274 f"{config_path} declares its pipeline with "
275 f"{cls.PIPELINE_METADATA_KEY!r}, which is deprecated. Replace it "
276 f"with an entry named {name!r} that has 'type: collectra.Pipeline' "
277 "and the same attributes (ext, version, ...), as the first item.",
278 FutureWarning,
279 stacklevel=2,
280 )
281 else:
282 name, pipeline_class = cls._find_declaration(config, config_path)
283 attributes = {
284 key: value for key, value in config.pop(name).items() if key != "type"
285 }
286 for required in ("ext", "version"):
287 if required not in attributes:
288 raise ValueError(
289 f"Pipeline {name!r} in {config_path} needs a {required!r}"
290 )
291 # Before any task is imported: some libraries read the environment then.
292 env = PipelineEnv(name)
293 env.load()
294 pipeline = pipeline_class(
295 name,
296 attributes["ext"],
297 attributes["version"],
298 path=config_path.parent,
299 pipeline_metadata=attributes,
300 **config,
301 )
302 pipeline._legacy_declaration = legacy
303 pipeline._env = env
304 return pipeline
306 @classmethod
307 def _find_declaration(cls, config: dict, config_path: Path) -> tuple[str, type]:
308 """The name and class of the entry that declares the pipeline itself."""
309 for name, value in config.items():
310 if not isinstance(value, dict) or not isinstance(value.get("type"), str):
311 continue
312 try:
313 declared = load_class_from_string(value["type"])
314 except (ImportError, AttributeError):
315 continue # a task whose class cannot be loaded is reported on connect
316 if isinstance(declared, type) and issubclass(declared, Pipeline):
317 return name, declared
318 raise ValueError(
319 f"{config_path} does not declare a pipeline. Add an entry such as:\n"
320 "MyPipeline:\n type: collectra.Pipeline\n ext: my\n version: 1.0"
321 )
323 @command(name="run")
324 def cli_run(
325 self,
326 inputs: list[str],
327 task: str = "",
328 output: Path | None = None,
329 single: bool = False,
330 verbose: bool = False,
331 usage: bool = False,
332 render: bool = False,
333 force: Annotated[
334 bool,
335 Arg(
336 help="Rerun tasks whose outputs already exist, replacing those outputs. By default such tasks are skipped."
337 ),
338 ] = False,
339 ) -> None:
340 """Run the complete pipeline or start at a named task."""
341 from collectra.logger import setup_logging
342 from collectra.utils import resolve_files
344 setup_logging(verbose=verbose)
345 files = resolve_files(inputs, self.file_extensions())
346 if not files:
347 logger.warning("No supported input files found for: %s", ", ".join(inputs))
348 return
349 self.run(
350 task,
351 files=files,
352 output=str(output) if output else None,
353 single=single,
354 usage=usage,
355 render=render,
356 force=force,
357 )
358 self.usage.print_summary()
360 @property
361 def usage(self) -> UsageLedger:
362 """The LLM tokens and cost of the latest run, by task."""
363 return self._usage
365 @property
366 def env(self) -> PipelineEnv:
367 """The environment variables the user stores for this pipeline.
369 They are kept in the user's config folder, by the pipeline's name, and
370 ``from_file`` loads them into the environment.
371 """
372 if self._env is None:
373 self._env = PipelineEnv(self.name)
374 return self._env
376 @subcommands(name="env")
377 def cli_env(self) -> PipelineEnv:
378 """Set, show, delete or clear the environment variables stored for this
379 pipeline."""
380 return self.env
382 @command(name="path")
383 def cli_path(self) -> None:
384 """Print the folder this pipeline lives in."""
385 print(self.path.resolve())
387 @command(name="code", available=lambda: shutil.which("code"))
388 def cli_code(self) -> None:
389 """Open this pipeline's folder in VS Code."""
390 import subprocess
392 code = shutil.which("code")
393 if code is None:
394 raise SystemExit("VS Code's `code` command was not found on your PATH")
395 result = subprocess.run([code, str(self.path.resolve())])
396 if result.returncode:
397 raise SystemExit(f"Could not open VS Code (exit code {result.returncode})")
399 @command(name="gui")
400 def launch_gui(
401 self,
402 *inputs: Path,
403 debug: bool = False,
404 max_pixels: Annotated[
405 int,
406 Arg(
407 help="Maximum image and mask preview dimension in pixels (longest edge). Originals remain full resolution."
408 ),
409 ] = 4096,
410 ) -> None:
411 """Open the GUI with optional result folders, results.yaml files, or parent directories."""
412 from collectra.gui.backend import start
414 if max_pixels < 1:
415 raise ValueError("--max-pixels must be positive")
416 self._ensure_workflow_connected()
417 start(pipeline=self, debug=debug, inputs=inputs, max_pixels=max_pixels)
419 @command(name="partition")
420 def cli_partition(
421 self,
422 inputs: Annotated[
423 list[str],
424 Arg(help="Result folders, results.yaml files, or parent directories."),
425 ],
426 train: Annotated[
427 str,
428 Arg(help="Share of results labelled 'train' (e.g. 80%, 0.8, or 100)."),
429 ] = "",
430 validation: Annotated[
431 str,
432 Arg(help="Share of results labelled 'validation' (e.g. 20%, 0.2, or 25)."),
433 ] = "",
434 val: Annotated[
435 str, Arg(help="Share of results labelled 'val' (e.g. 20%, 0.2, or 25).")
436 ] = "",
437 test: Annotated[
438 str, Arg(help="Share of results labelled 'test' (e.g. 10%, 0.1, or 10).")
439 ] = "",
440 seed: Annotated[
441 int, Arg(help="Random seed used to shuffle results before splitting.")
442 ] = 42,
443 partition: Annotated[
444 list[str] | None,
445 Arg(
446 help="Custom partition as NAME=VALUE (e.g. holdout=5%); may be repeated."
447 ),
448 ] = None,
449 force: Annotated[
450 bool,
451 Arg(
452 help="Override existing partitions instead of refusing to change them."
453 ),
454 ] = False,
455 ) -> None:
456 """Assign result partitions using percentages, fractions, or file counts.
458 For example: partition results --train 80% --validation 20%.
459 Use repeated --partition NAME=VALUE options for custom labels.
460 All values must use the same form (percentages, fractions, or counts).
461 Fails if any result already has a partition unless --force is given.
462 Unassigned results retain their existing partition.
463 """
464 from collectra.partition import partition_results
466 partitions = {
467 label: value
468 for label, value in (
469 ("train", train),
470 ("validation", validation),
471 ("val", val),
472 ("test", test),
473 )
474 if value != ""
475 }
476 for specification in partition or []:
477 label, separator, value = specification.partition("=")
478 if not separator or not label.strip() or not value.strip():
479 raise ValueError("Custom partitions must use NAME=VALUE")
480 if label in partitions:
481 raise ValueError(f"Partition {label!r} was specified more than once")
482 partitions[label] = value
483 partition_results(inputs, self.ext, partitions, seed, force=force)
485 @command(name="install")
486 def cli_install(self, name: str, bin_dir: Path | None = None) -> None:
487 """Install this pipeline as a standalone command."""
488 destination = (bin_dir or Path.home() / ".local" / "bin").expanduser()
489 destination.mkdir(parents=True, exist_ok=True)
490 launcher = destination / name
491 pipeline_path = (self.path / self.PIPELINE_FILE).resolve()
492 code = (
493 "from pathlib import Path\n"
494 "from collectra.main import main\n"
495 f"main(pipeline_path=Path({str(pipeline_path)!r}), program_name={name!r})\n"
496 )
497 # Kernel shebang parsing cannot quote an interpreter path containing
498 # spaces. Let the shell invoke the exact interpreter as one argument.
499 launcher.write_text(
500 "#!/bin/sh\n" f'exec {shlex.join([sys.executable, "-c", code])} "$@"\n',
501 encoding="utf-8",
502 )
503 launcher.chmod(
504 launcher.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
505 )
506 print(f"Installed {name!r} at {launcher}")
508 @command(name="install-app")
509 def cli_install_app(
510 self,
511 *inputs: Path,
512 name: str = "Collectra",
513 app_dir: Path | None = None,
514 icon: Path | None = None,
515 force: bool = False,
516 ) -> Path:
517 """Create a macOS Applications launcher for this pipeline's GUI.
519 Optional inputs are result folders or files opened when the app starts.
520 The default destination is ~/Applications; icon accepts an .icns or PNG file. Pipeline metadata supplies the default icon.
521 """
522 from .app_launcher import install_app
524 pipeline_icon = self.pipeline_metadata.get(
525 "icon"
526 ) or self.pipeline_metadata.get("logo")
527 if icon is None and pipeline_icon:
528 icon = Path(pipeline_icon).expanduser()
529 if not icon.is_absolute():
530 icon = self.path / icon
531 bundle = install_app(
532 self.path / self.PIPELINE_FILE,
533 name=name,
534 app_dir=app_dir,
535 icon=icon,
536 inputs=inputs,
537 force=force,
538 )
539 print(f"Installed {name!r} at {bundle}")
540 return bundle
542 @group(name="task")
543 def cli_tasks(self) -> dict[str, Task]:
544 """Operate on one of the tasks in this pipeline."""
545 self._ensure_workflow_connected()
546 return {
547 node.name: node.get_task() for node in self.node_manager.get_task_nodes()
548 }
550 @group(name="artefact")
551 def cli_artefacts(self) -> dict[str, object]:
552 """Operate on one of the artefacts in this pipeline."""
553 self._ensure_workflow_connected()
554 artefacts: dict[str, object] = {}
555 for node in self.node_manager.get_artefact_nodes():
556 artefact_types = [
557 type_ for type_ in node.types if issubclass(type_, Artefact)
558 ]
559 if not artefact_types:
560 continue
561 # IO inference can add a base and a more-specific type to a node.
562 # Prefer the most specific class so its CLI capabilities win.
563 artefact_type = max(
564 artefact_types,
565 key=lambda type_: len(type_.mro()),
566 )
567 artefacts[node.name] = artefact_type.cli_commands(node, self.ext)
568 return artefacts
570 def task(self, task_name: str) -> dict:
571 """Get a task from the workflow by name.
573 Args:
574 task_name (str): Name of the task to retrieve.
576 Returns:
577 dict | None: Task configuration dictionary or None if not found.
578 """
579 data = self.data.get(task_name, None)
580 if not data:
581 raise ValueError(f"Task {task_name} not found in workflow")
582 data["name"] = task_name
583 return data
585 def _check_is_root(self, node_name: str) -> bool:
586 """Check if a node is a root node (no parents or only data parents)."""
587 node = self.node_manager.resolve_node(node_name)
588 parents = self.node_manager.get_parents(node)
589 for parent in parents:
590 grandparents = self.node_manager.get_parents(parent)
591 if len(grandparents) > 0:
592 return False
593 if isinstance(parent, TaskNode):
594 return False
595 return True
597 def run(self, task_name: str = "", **kwargs):
598 """Run the workflow from the specified task or from all root tasks.
600 Args:
601 task_name: Name of the task to start from. If empty, starts from
602 all root tasks in the workflow.
603 **kwargs: Run options including:
604 - single: Run only the starting task without propagating.
605 - files: List of file paths to process.
606 - usage: Whether to track usage metrics.
607 - render: Whether to render workflow visualization.
608 - force: Rerun tasks whose outputs already exist.
609 - output: Output directory for results.
610 """
611 self._outcomes = defaultdict(dict)
612 self._run_errors = []
613 self._usage = UsageLedger()
614 try:
615 self._ensure_workflow_connected()
616 starting_nodes = self._get_starting_nodes(task_name)
617 run_options = self._extract_run_options(kwargs)
618 run_options["usage_ledger"] = self._usage
619 self._process_files(starting_nodes, run_options)
620 except Exception as e:
621 logger.error("Workflow run failed: %s", e, exc_info=True)
622 self._run_errors.append(("", f"{type(e).__name__}: {e}"))
624 def _ensure_workflow_connected(self):
625 """Ensure the workflow graph is connected before execution.
627 If the workflow graph has no nodes, calls connect() to build
628 the graph from the workflow configuration.
629 """
630 if self.node_manager.is_empty():
631 self.connect()
633 def _get_starting_nodes(self, task_name: str) -> list[TaskNode]:
634 """Get the starting nodes for workflow execution.
636 Args:
637 task_name: Specific task to start from, or empty for all root tasks.
639 Returns:
640 List of starting task nodes.
641 """
642 if task_name:
643 return self._get_specific_starting_node(task_name)
644 return self._get_root_starting_nodes()
646 def _get_specific_starting_node(self, task_name: str) -> list[TaskNode]:
647 """Get a specific task node as the starting point."""
648 task_node = self.node_manager.resolve_node(task_name)
649 if not isinstance(task_node, TaskNode):
650 raise TypeError(f"Task {task_name} not found in workflow")
651 return [task_node]
653 def _get_root_starting_nodes(self) -> list[TaskNode]:
654 """Get all root task nodes as starting points."""
655 starting_nodes = []
656 task_nodes = self.node_manager.get_task_nodes()
657 for task_node in task_nodes:
658 if self._check_is_root(task_node.name):
659 starting_nodes.append(task_node)
660 return starting_nodes
662 def _extract_run_options(self, kwargs: dict) -> dict:
663 """Extract and return run options from kwargs."""
664 options = {
665 "single": kwargs.pop("single", False),
666 "files": kwargs.pop("files", []),
667 "usage": kwargs.pop("usage", False),
668 "render": kwargs.pop("render", False),
669 "force": kwargs.pop("force", False),
670 "output": kwargs.pop("output", None),
671 # Tasks to rerun as if forced, and a check made before each task
672 # starts that stops the run when it returns True.
673 "rerun": set(kwargs.pop("rerun", set())),
674 "stop": kwargs.pop("stop", _never),
675 # A page run reads a page's image from its copy in the results
676 # folder when the image its results refer to cannot be read.
677 "page_copy": kwargs.pop("page_copy", False),
678 # Called once a file's tasks are done; raising stops the files after it
679 "page_done": kwargs.pop("page_done", None),
680 }
681 options["task_overrides"] = kwargs.copy()
682 return options
684 def file_extensions(self) -> set[str]:
685 """File extensions this pipeline accepts as input.
687 Its own results-folder extension, plus those of the artefact types its
688 input node reads when it has a single input node.
689 """
690 extensions = {f".{self.ext}"}
691 self._ensure_workflow_connected()
692 roots = [
693 node
694 for node in self.node_manager.get_artefact_nodes()
695 if self._check_is_root(node.name)
696 ]
697 if len(roots) == 1:
698 for artefact_type in roots[0].types:
699 try:
700 extensions |= artefact_type.file_extensions()
701 except NotImplementedError:
702 pass
703 return extensions
705 def _get_root_input(self) -> str:
706 """Get the name of the root input artefact node for the workflow."""
707 for artefact_node in self.node_manager.get_artefact_nodes():
708 if self._check_is_root(artefact_node.name):
709 return artefact_node.name
710 raise ValueError("No root input artefact node found in the workflow")
712 def _process_files(self, starting_nodes: list[TaskNode], options: dict):
713 """Process each file in the workflow.
715 Files are processed in chunks sized to the largest ``batch_size`` of any
716 task that can batch its work, so those tasks see a whole chunk at once.
718 Args:
719 starting_nodes: List of nodes to start execution from.
720 options: Execution options (single, files, usage, render, output).
721 """
722 files = options["files"]
723 self._failures = []
724 downstream = {} if options["single"] else self._batchable_tasks(starting_nodes)
725 batch_size = self._starting_batch_size(starting_nodes)
726 batch_size = max([batch_size, *(t.batch_size for t in downstream.values())])
727 overall = (
728 Progress(
729 SpinnerColumn(),
730 TextColumn("{task.description}"),
731 BarColumn(),
732 MofNCompleteColumn(),
733 TimeElapsedColumn(),
734 TimeRemainingColumn(),
735 )
736 if len(files) > 1
737 else None
738 )
739 with overall if overall is not None else nullcontext():
740 if overall is not None:
741 label = ", ".join(node.name for node in starting_nodes) or self.name
742 self._run_progress = RunProgress(overall, label, len(files))
743 try:
744 for start in range(0, len(files), batch_size):
745 chunk = files[start : start + batch_size]
746 self._process_chunk(starting_nodes, chunk, options, downstream)
747 finally:
748 self._run_progress = None
749 self._report_failures()
751 def _report_failures(self) -> None:
752 """Say at the end of a run which tasks failed, since each was only logged."""
753 if not self._failures:
754 return
755 lines = "\n".join(
756 f" {task} on {file}: {error}" for task, file, error in self._failures
757 )
758 logger.error("%d task failure(s) in this run:\n%s", len(self._failures), lines)
760 def _process_chunk(
761 self,
762 starting_nodes: list[TaskNode],
763 chunk: list,
764 options: dict,
765 downstream: dict[str, Task],
766 ):
767 """Run a chunk of files, pausing each at batchable tasks until all arrive.
769 Every file runs until it reaches a batchable task further down the DAG
770 and is saved there. Once the whole chunk has arrived the task prefetches
771 all of its inputs together, and each file resumes from its saved results.
772 """
773 stage = [(file_path, starting_nodes) for file_path in chunk]
774 stage_options = options
775 prefetch = self._starting_batch_size(starting_nodes) > 1
776 self._stage_gate = StageGate(set(downstream)) if downstream else None
777 try:
778 while stage:
779 if prefetch:
780 self._announce_batch(stage)
781 self._prefetch_stage(stage, stage_options)
782 deferred: list[tuple[str, list[TaskNode]]] = []
783 for file_path, nodes in stage:
784 if self._run_progress:
785 self._run_progress.status(Path(str(file_path)).name)
786 if self._stage_gate:
787 self._stage_gate.current = {node.name for node in nodes}
788 self._stage_gate.deferred = {}
789 try:
790 self._process_single_file(nodes, file_path, stage_options)
791 except Exception as e:
792 logger.error("Error processing file: %s", e, exc_info=True)
793 error = f"{type(e).__name__}: {e}"
794 self._run_errors.append((str(file_path), error))
795 held = self._stage_gate.deferred if self._stage_gate else {}
796 deferred.extend(held.items())
797 if self._run_progress and not held:
798 self._run_progress.file_done()
799 if options.get("page_done") and not held:
800 options["page_done"](file_path)
801 # Later stages resume from each file's saved folder, in place.
802 stage = deferred
803 stage_options = {**options, "output": None}
804 prefetch = True
805 finally:
806 self._stage_gate = None
807 self._clear_prefetch(
808 [*starting_nodes, *self._task_nodes_by_name(downstream)]
809 )
811 def _announce_batch(self, stage: list[tuple[str, list[TaskNode]]]) -> None:
812 """Say on the overall bar that a batch is being prepared with the model."""
813 if not self._run_progress:
814 return
815 names = sorted(
816 {
817 node.name
818 for _, nodes in stage
819 for node in nodes
820 if node.get_task().batch_size > 1
821 }
822 )
823 if names:
824 count = len(stage)
825 self._run_progress.status(
826 f"waiting on batch of {count} file{'s' if count != 1 else ''} "
827 f"({', '.join(names)})"
828 )
830 def _task_nodes_by_name(self, tasks: dict[str, Task]) -> list[TaskNode]:
831 return [self.node_manager.resolve_node(name) for name in tasks]
833 def _starting_batch_size(self, starting_nodes: list[TaskNode]) -> int:
834 """Number of files to run through the starting tasks per batch."""
835 sizes = [
836 int(getattr(node.get_task(), "batch_size", 1) or 1)
837 for node in starting_nodes
838 if isinstance(node, TaskNode)
839 ]
840 return max([1, *sizes])
842 def _batchable_tasks(self, starting_nodes: list[TaskNode]) -> dict[str, Task]:
843 """Tasks below ``starting_nodes`` that batch their work via ``prefetch``."""
844 start_names = {node.name for node in starting_nodes}
845 found: dict[str, Task] = {}
846 seen: set[str] = set()
847 queue = list(starting_nodes)
848 while queue:
849 node = queue.pop()
850 if node.name in seen:
851 continue
852 seen.add(node.name)
853 queue.extend(self.node_manager.get_children(node))
854 if not isinstance(node, TaskNode) or node.name in start_names:
855 continue
856 task = node.get_task()
857 if (
858 isinstance(task, Task)
859 and task.batch_size > 1
860 and type(task).prefetch is not Task.prefetch
861 ):
862 found[node.name] = task
863 return found
865 def _prefetch_stage(self, stage: list[tuple[str, list[TaskNode]]], options: dict):
866 """Let each file's pending tasks batch their model work up front.
868 The files are then processed one at a time as usual, with each task
869 reusing what it cached, so results are saved after every batch.
870 """
871 gathered: dict[str, list] = {}
872 nodes_by_name: dict[str, TaskNode] = {}
873 for file_path, nodes in stage:
874 try:
875 self._setup_file(nodes, file_path, options)
876 for node in nodes:
877 task = node.get_task()
878 if not isinstance(task, Task) or task.batch_size <= 1:
879 continue
880 forced = options["force"] or node.name in options["rerun"]
881 if not forced and self._has_output(node):
882 continue
883 self._apply_task_run_overrides(task, options["task_overrides"])
884 parents = self.node_manager.get_parents_artefact(node)
885 nodes_by_name[node.name] = node
886 gathered.setdefault(node.name, []).extend(
887 list(entry) for entry in task.prepare_inputs(parents)
888 )
889 except Exception as e:
890 logger.warning("Could not prepare %s for batching: %s", file_path, e)
891 for name, node in nodes_by_name.items():
892 try:
893 with change_dir(self.path):
894 node.get_task().prefetch(gathered[name])
895 except Exception as e:
896 logger.warning(
897 "Batched run of %s failed, running files individually: %s",
898 name,
899 e,
900 exc_info=True,
901 )
902 node.get_task().clear_prefetch()
904 def _clear_prefetch(self, starting_nodes: list[TaskNode]):
905 for node in starting_nodes:
906 task = node.get_task()
907 if isinstance(task, Task):
908 task.clear_prefetch()
910 def _setup_file(
911 self, starting_nodes: list[TaskNode], file_path: str, options: dict
912 ) -> tuple[str, str | Path]:
913 """Create the collectra file for ``file_path`` and load it into the graph."""
914 key = (
915 "file"
916 if Path(file_path).suffix == f".{self.ext}"
917 else self._get_root_input()
918 )
919 if options.get("page_copy"):
920 # Never start results in a folder that is not a page
921 self._check_page(Path(file_path))
922 key, value = self._create_collectra_file(key, file_path, options["output"])
924 # Create task context for this file
925 context = TaskContext(
926 usage_file=(
927 Path.cwd() / str(Path(value) / "usage.yaml")
928 if options["usage"]
929 else None
930 ),
931 usage_ledger=options.get("usage_ledger"),
932 render=options["render"],
933 # Absolute: tasks run inside the pipeline's folder, where a path
934 # relative to the caller's folder would point somewhere else.
935 file_path=Path(value).resolve(),
936 single_run=options["single"],
937 )
939 # Set context for all tasks
940 self._set_task_contexts(context)
942 self._init_input_data(starting_nodes, **{key: value})
943 if options.get("page_copy"):
944 self._read_page_copy(Path(value))
945 return key, value
947 def _process_single_file(
948 self, starting_nodes: list[TaskNode], file_path: str, options: dict
949 ):
950 """Process a single file through the workflow.
952 Args:
953 starting_nodes: Nodes to start from.
954 file_path: Path to file to process.
955 options: Execution options.
956 """
957 key, value = self._setup_file(starting_nodes, file_path, options)
958 self.render("workflow_run", file=str(value), render=options["render"])
960 self._run_nodes(
961 starting_nodes,
962 single=options["single"],
963 key=key,
964 value=value,
965 render=options["render"],
966 force=options["force"],
967 rerun=options["rerun"],
968 stop=options["stop"],
969 task_overrides=options["task_overrides"],
970 )
971 self._warn_unready_starting_tasks(starting_nodes, value)
973 def plan_page_run(self, folder: Path, overwrite: bool = False) -> RunPlan:
974 """Which tasks running this results folder would run, re-run or skip.
976 The folder is loaded the way a run loads it, but no task runs.
978 Args:
979 folder: The results folder.
980 overwrite: Re-run every task that has output, replacing it.
982 Raises:
983 FileNotFoundError: The folder has no results, or the image copy
984 its results refer to is missing.
985 ValueError: The results do not match this pipeline's tasks.
986 """
987 folder = Path(folder)
988 differences = self._check_page(folder)
989 options = {
990 "output": None,
991 "usage": False,
992 "render": False,
993 "single": False,
994 "page_copy": True,
995 }
996 self._setup_file(self._get_root_starting_nodes(), str(folder), options)
997 flow = self.node_manager.flow
998 tasks = {node.name: node for node in self.node_manager.get_task_nodes()}
999 order = [name for name in nx.topological_sort(flow) if name in tasks]
1000 children = {
1001 name: {
1002 grandchild.name
1003 for output in self._output_nodes(node)
1004 for grandchild in self.node_manager.get_children(output)
1005 if isinstance(grandchild, TaskNode)
1006 }
1007 for name, node in tasks.items()
1008 }
1009 missing = {name for name, node in tasks.items() if not self._has_output(node)}
1010 if overwrite:
1011 plan = RunPlan(
1012 [
1013 (
1014 TaskPlan(name, "run", "no output yet")
1015 if name in missing
1016 else TaskPlan(name, "rerun", "overwrite")
1017 )
1018 for name in order
1019 ]
1020 )
1021 else:
1022 plan = plan_tasks(missing, children, order)
1023 return replace(plan, warnings=differences)
1025 def _check_page(self, folder: Path) -> tuple[str, ...]:
1026 """Check a results folder holds this pipeline's results and its image.
1028 Nothing is written: a folder a run would treat as a new input, and so
1029 start new results in, is refused.
1031 Returns:
1032 What differs between this pipeline and the one that made the
1033 results, said for the log and the preview; it does not stop a run.
1035 Raises:
1036 FileNotFoundError: The folder has no results, or the image copy
1037 its results refer to is missing.
1038 ValueError: The folder is not named as this pipeline's pages are,
1039 or the results do not match this pipeline's tasks.
1040 """
1041 results_file = folder / self.RESULTS_FILE
1042 if not results_file.exists():
1043 raise FileNotFoundError(f"{results_file} does not exist.")
1044 if not self._is_existing_collectra_folder(folder):
1045 raise ValueError(
1046 f"{folder.name} cannot be run with the {self.name} pipeline: "
1047 f"its pages are folders whose names end in .{self.ext}."
1048 )
1049 self._ensure_workflow_connected()
1050 root = self._get_root_input()
1051 header, entry = self._page_entry(folder, root)
1052 if entry is None:
1053 raise ValueError(
1054 f"The results in {folder.name} do not match this pipeline: "
1055 f"there is no '{root}' entry."
1056 )
1057 name = self._page_image_name(entry)
1058 if name and not (folder / name).exists():
1059 raise FileNotFoundError(
1060 f"{name} is missing from {folder}; the results refer to it."
1061 )
1062 differences = []
1063 if header.workflow and header.workflow != self.name:
1064 differences.append(
1065 f"these results were made by the {header.workflow} pipeline, "
1066 f"not {self.name}"
1067 )
1068 if header.version and self.version and header.version != str(self.version):
1069 differences.append(
1070 f"pipeline version {self.version}, results made with {header.version}"
1071 )
1072 return tuple(differences)
1074 def _page_entry(self, folder: Path, root: str) -> tuple[Results, Any]:
1075 """A page's results header and its root entry (None if it has none)."""
1076 saved = yaml.safe_load((folder / self.RESULTS_FILE).read_text()) or {}
1077 header = pop_header(saved, source=folder)
1078 return header, saved.get(root)
1080 @staticmethod
1081 def _page_image_name(entry: Any) -> str | None:
1082 """The file name of the image a root entry refers to.
1084 A run can record the copy by bare name or by the path it was fed.
1085 """
1086 image = (
1087 entry.get("data", entry.get("path")) if isinstance(entry, dict) else None
1088 )
1089 return Path(str(image)).name if image else None
1091 def _read_page_copy(self, folder: Path) -> None:
1092 """Load a page's image from its copy in ``folder`` if it did not load.
1094 The image the results refer to may have been moved or deleted since
1095 the page was made; the copy in the folder is the same file. The
1096 results are left as they are.
1098 Raises:
1099 ValueError: Neither the image nor its copy could be read.
1100 """
1101 root = self._get_root_input()
1102 node = self.node_manager.resolve_node(root)
1103 if node.items:
1104 return
1105 _, entry = self._page_entry(folder, root)
1106 name = self._page_image_name(entry)
1107 if not name:
1108 raise ValueError(f"The page image of {folder.name} could not be read.")
1109 item = dict(entry)
1110 item.pop("path", None)
1111 item["name"] = root
1112 item["data"] = folder / name
1113 try:
1114 image = load_class_from_string(item.pop("type"))(**item)
1115 except Exception as error:
1116 raise ValueError(
1117 f"The page image {name} could not be read: {error}"
1118 ) from error
1119 image.source_file = folder
1120 node.add_item(image)
1121 self._resolve_links()
1123 def run_page(
1124 self,
1125 folder: Path,
1126 plan: RunPlan,
1127 should_stop: Callable[[], bool] = lambda: False,
1128 ) -> RunReport:
1129 """Run a results folder's planned tasks in place, and say what happened.
1131 Tasks with output are skipped; the plan's re-run tasks replace their
1132 output. ``should_stop`` is checked before each task starts; once it
1133 returns True no further task starts. The page's image is read from
1134 the copy inside the folder.
1136 Raises:
1137 FileNotFoundError: The folder has no results, or the image copy
1138 its results refer to is missing.
1139 ValueError: The results do not match this pipeline's tasks.
1140 """
1141 folder = Path(folder)
1142 self._check_page(folder)
1143 rerun = {task.name for task in plan.tasks if task.action == "rerun"}
1144 return self.run_pages({folder: plan}, rerun, should_stop)[folder]
1146 def run_pages(
1147 self,
1148 plans: Mapping[Path, RunPlan],
1149 rerun: set[str],
1150 should_stop: Callable[[], bool] = lambda: False,
1151 page_done: Callable[[Path], None] | None = None,
1152 ) -> dict[Path, RunReport]:
1153 """Run results folders in place in one pass, and say what happened to each.
1155 Tasks with output are skipped unless named in ``rerun``, which replace
1156 their output on every page. ``should_stop`` is checked before each task
1157 starts; once it returns True no further task starts on any page. One
1158 page failing does not stop the others.
1160 Args:
1161 plans: The plan of each results folder, used for its report.
1162 rerun: Names of the tasks to run again on every page.
1163 should_stop: Checked before each task starts.
1164 page_done: Called with each folder once all its tasks are done.
1165 It must not raise, or the folders after it do not run.
1167 Returns:
1168 The report of each folder, in the order of ``plans``.
1169 """
1170 stopped = False
1172 def stop() -> bool:
1173 nonlocal stopped
1174 stopped = stopped or bool(should_stop())
1175 return stopped
1177 self.run(
1178 files=[str(folder) for folder in plans],
1179 rerun=rerun,
1180 stop=stop,
1181 page_copy=True,
1182 page_done=None if page_done is None else lambda f: page_done(Path(f)),
1183 )
1184 return {
1185 Path(folder): self._page_report(str(Path(folder)), plan, stopped)
1186 for folder, plan in plans.items()
1187 }
1189 def _page_report(self, page: str, plan: RunPlan, stopped: bool) -> RunReport:
1190 """What happened to each of a page's planned tasks in the last run.
1192 Args:
1193 page: The page folder, as the run recorded it.
1194 plan: The page's plan, which gives the tasks, their order and why
1195 each re-runs.
1196 stopped: Whether the run was stopped.
1198 Returns:
1199 The outcome of each planned task, in plan order.
1200 """
1201 errors = "; ".join(e for file, e in self._run_errors if file in ("", page))
1202 statuses: dict[str, str] = {}
1203 outcomes = []
1204 for task in plan.tasks:
1205 status, detail = self._outcomes[page].get(task.name, ("", ""))
1206 if not status and errors:
1207 status, detail = "failed", f"did not run: {errors}"
1208 elif not status:
1209 status = "cancelled"
1210 detail = (
1211 "stopped before it started"
1212 if stopped
1213 else "did not run: its inputs were not produced"
1214 )
1215 if task.action == "rerun" and status != "skipped":
1216 source = task.reason.removeprefix("upstream ").removesuffix(" runs")
1217 upstream = (
1218 f" (upstream {source} ran)"
1219 if task.reason.startswith("upstream ")
1220 else ""
1221 )
1222 if status == "ran":
1223 status = "re-ran"
1224 detail = f"{detail or 'replaced existing output'}{upstream}"
1225 elif not upstream:
1226 detail = f"{detail}; kept previous output"
1227 elif statuses.get(source) in ("ran", "re-ran"):
1228 # Its input was replaced, but its output was not.
1229 detail = (
1230 f"{detail}; kept previous output, which may be out of date"
1231 f"{upstream}"
1232 )
1233 elif status == "ran":
1234 detail = detail or task.reason
1235 statuses[task.name] = status
1236 outcomes.append(TaskOutcome(task.name, status, detail))
1237 return RunReport(outcomes)
1239 def _warn_unready_starting_tasks(self, starting_nodes: list[TaskNode], value):
1240 """Explain why a task the user asked for never ran for this file.
1242 Tasks reached part-way through the DAG may legitimately wait for their
1243 other inputs, so only the tasks the run started from are reported.
1244 """
1245 for node in starting_nodes:
1246 if node.status == NodeStatus.READY:
1247 continue
1248 missing = [
1249 parent.name
1250 for parent in self.node_manager.get_parents_artefact(node)
1251 if parent.status != NodeStatus.READY
1252 ]
1253 lines = [
1254 f" • [bold red]{escape(name)}[/bold red]" for name in missing[:10]
1255 ]
1256 if len(missing) > 10:
1257 lines.append(f" … and {len(missing) - 10} more")
1258 logger.warning(
1259 "Task '%s' did not run for %s. "
1260 "A task only runs once all of its inputs exist.\nMissing input data:\n%s",
1261 node.name,
1262 Path(str(value)).name,
1263 "\n".join(lines) or " • its inputs",
1264 )
1266 def _create_collectra_file(
1267 self, key: str, value: str | Path, output_dir: str | Path | None = None
1268 ) -> tuple[str, str | Path]:
1269 """Create or prepare a collectra file structure for processing.
1271 Handles three cases:
1272 - Existing collectra folder with results.yaml
1273 - Single image file (resuming its results folder if it already has one)
1274 - Directory without results.yaml
1275 """
1276 self._validate_file_inputs(key, value)
1277 savef = Path(value)
1279 # Case A: Existing collectra folder with results.yaml
1280 if self._is_existing_collectra_folder(savef):
1281 return key, self._handle_existing_folder(savef, output_dir)
1283 # Case B: Single image file
1284 if self._is_image_file(savef):
1285 savef = self._handle_image_file(savef, output_dir)
1286 if (savef / self.RESULTS_FILE).exists():
1287 # An earlier run made this folder: keep its results, so that
1288 # rerunning over the images resumes rather than starting again.
1289 return "file", savef
1291 # Case C: Directory without results.yaml - create results file
1292 if savef.is_dir():
1293 self._create_results_file(savef, key, value)
1295 return "file", savef
1297 def _validate_file_inputs(self, key: str, value: str | Path):
1298 """Validate input parameters for file creation."""
1299 if not key or not value:
1300 raise ValueError("Both key and value must be provided for input data.")
1302 savef = Path(value)
1303 if not savef.exists():
1304 raise FileNotFoundError(f"Path {savef} does not exist.")
1306 def _is_existing_collectra_folder(self, path: Path) -> bool:
1307 """Check if path is an existing collectra folder with results."""
1308 return (
1309 path.is_dir()
1310 and path.suffix == f".{self.ext}"
1311 and (path / self.RESULTS_FILE).exists()
1312 )
1314 def _is_image_file(self, path: Path) -> bool:
1315 """Check if path is an image file."""
1316 return path.is_file() and path.suffix.lower() in Image.file_extensions()
1318 def _handle_existing_folder(
1319 self, savef: Path, output_dir: str | Path | None
1320 ) -> Path:
1321 """Handle existing collectra folder, optionally copying to output."""
1322 if output_dir:
1323 output_path = Path(output_dir) / savef.name
1324 output_path.mkdir(parents=True, exist_ok=True)
1325 shutil.copytree(savef, output_path, dirs_exist_ok=True)
1326 savef = output_path
1328 return savef
1330 def _handle_image_file(
1331 self, file_path: Path, output_dir: str | Path | None
1332 ) -> Path:
1333 """Handle single image file by creating collectra folder structure."""
1334 folder_name = file_path.name.replace(file_path.suffix, f".{self.ext}")
1335 savef = (
1336 Path(output_dir) / folder_name
1337 if output_dir
1338 else file_path.parent / folder_name
1339 )
1340 savef.mkdir(parents=True, exist_ok=True)
1341 if (savef / self.RESULTS_FILE).exists():
1342 return savef # already ingested; its results refer to that copy
1344 # Keep the file exactly as supplied, EXIF orientation included: every
1345 # reader in Collectra applies it rather than stripping it.
1346 shutil.copy2(file_path, savef / file_path.name)
1347 return savef
1349 def import_file(self, source: Path) -> Path:
1350 """Make the results folder for one input file and move the file into it.
1352 The folder is made next to the file.
1354 This file's existing page is returned as it is; any other folder of
1355 that name is left alone and the new one is numbered.
1357 Args:
1358 source: The input file.
1360 Returns:
1361 The results folder.
1363 Raises:
1364 ValueError: The pipeline does not accept this kind of file.
1365 OSError: The folder could not be written; what this call created
1366 is removed.
1367 """
1368 source = Path(source)
1369 accepted = self.file_extensions() - {f".{self.ext}"}
1370 if source.suffix.lower() not in accepted:
1371 raise ValueError(
1372 f"{source.name} is not an input the {self.name} pipeline accepts."
1373 )
1374 root = self._get_root_input()
1376 def is_page(folder: Path) -> bool:
1377 try:
1378 name = self._page_image_name(self._page_entry(folder, root)[1])
1379 except (OSError, yaml.YAMLError, AttributeError, TypeError, ValueError):
1380 return False # No results, or unreadable ones
1381 image = folder / source.name
1382 return (
1383 name == source.name
1384 and image.is_file()
1385 and filecmp.cmp(source, image, shallow=False)
1386 )
1388 folder = destination(
1389 source, self.ext, lambda path: path.exists() and not is_page(path)
1390 )
1391 if folder.exists():
1392 return folder
1393 folder.mkdir()
1394 image = folder / source.name
1395 moved = False
1396 try:
1397 shutil.move(source, image)
1398 moved = True
1399 self._create_results_file(folder, root, source)
1400 except BaseException:
1401 restored = True
1402 if moved:
1403 try:
1404 shutil.move(image, source)
1405 except OSError:
1406 restored = False # The folder holds the only copy
1407 if restored:
1408 shutil.rmtree(folder, ignore_errors=True)
1409 raise
1410 logger.info("Imported %s as %s", source, folder)
1411 return folder
1413 def import_inputs(self, inputs: Sequence[Path]) -> ImportReport:
1414 """Turn the inputs a user opens into results folders.
1416 An input is an existing results folder (opened, nothing written), a
1417 ``<x>.<ext>`` folder without results (adopted in place when it holds
1418 exactly one accepted file), an accepted file (moved into a folder next to itself),
1419 or any other folder, whose direct children are handled the same way in
1420 case-insensitive order. Hidden entries are ignored; one input failing
1421 does not stop the others.
1423 Args:
1424 inputs: The files and folders to open.
1426 Returns:
1427 What was created, opened, skipped and failed.
1429 Raises:
1430 FileNotFoundError: An input does not exist.
1431 """
1432 items = [Path(item) for item in inputs]
1433 for item in items:
1434 if not item.exists():
1435 raise FileNotFoundError(f"Path {item} does not exist.")
1436 report = ImportReport()
1437 accepted = self.file_extensions() - {f".{self.ext}"}
1438 known = {} # Each folder's entries before importing
1439 for item in items:
1440 if item.is_dir() and item.suffix != f".{self.ext}":
1441 children = sorted(item.iterdir(), key=lambda path: path.name.lower())
1442 known[item] = set(children)
1443 else:
1444 children = [item]
1445 if not item.is_dir() and item.parent not in known:
1446 known[item.parent] = set(item.parent.iterdir())
1447 for child in children:
1448 if not child.name.startswith("."):
1449 try:
1450 if child.is_dir():
1451 self._open_folder(child, accepted, report)
1452 else:
1453 self._import_one(
1454 child, accepted, known[child.parent], report
1455 )
1456 except OSError as error:
1457 report.failed.append(f"{child.name}: {error}")
1458 return report
1460 def _open_folder(self, path: Path, accepted: set[str], report: ImportReport):
1461 """Open a results folder, or adopt in place one holding a single image."""
1462 if path.suffix != f".{self.ext}":
1463 return # Subfolders are not searched
1464 if self._is_existing_collectra_folder(path):
1465 if path not in report.pages: # Not already opened as a file's page
1466 report.pages.append(path)
1467 report.existing += 1
1468 return
1469 images = [
1470 child
1471 for child in sorted(path.iterdir())
1472 if child.is_file()
1473 and not child.name.startswith(".")
1474 and child.suffix.lower() in accepted
1475 ]
1476 if len(images) != 1:
1477 report.skipped_folders.append(f"{path.name}: {len(images)} images")
1478 return
1479 try:
1480 self._create_results_file(path, self._get_root_input(), images[0])
1481 except BaseException:
1482 (path / self.RESULTS_FILE).unlink(missing_ok=True)
1483 raise
1484 logger.info("Adopted %s", path)
1485 report.pages.append(path)
1486 report.imported += 1
1488 def _import_one(
1489 self, path: Path, accepted: set[str], known: set[Path], report: ImportReport
1490 ):
1491 """Import a file, or open its page when it was imported before."""
1492 if path.suffix.lower() not in accepted:
1493 reason = f"not an input the {self.name} pipeline accepts"
1494 report.skipped.append(f"{path.name}: {reason}")
1495 return
1496 folder = self.import_file(path)
1497 if folder in report.pages:
1498 return # Page already opened by its folder
1499 report.pages.append(folder)
1500 if folder in known:
1501 report.existing += 1
1502 else:
1503 report.imported += 1
1505 def _create_results_file(self, directory: Path, key: str, value: str | Path):
1506 """Create a new results.yaml file in the given directory."""
1507 with change_dir(directory):
1508 results = put_header(
1509 Results(workflow=self.name, version=self.version),
1510 {
1511 key: {
1512 "type": "collectra.Image",
1513 "id": f"{key}",
1514 "data": value.name if isinstance(value, Path) else str(value),
1515 },
1516 },
1517 )
1518 self._write_results_file(results)
1520 def _populate_active_paths(
1521 self,
1522 nodes: list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode],
1523 **kwargs,
1524 ):
1525 """Recursively populate active paths in the workflow with input data.
1527 Traverses the workflow graph from the given nodes, processing artefact nodes
1528 and propagating values to their children.
1530 Args:
1531 nodes: List of nodes to start populating from.
1532 **kwargs: Key-value pairs of input data to populate into matching nodes.
1533 """
1534 for node in nodes:
1535 if isinstance(node, ArtefactNode):
1536 value = kwargs.get(node.name, None)
1537 node.process(node.name, value, **kwargs)
1539 children = self.node_manager.get_children(node)
1540 self._populate_active_paths(children, **kwargs)
1542 def _init_input_data(
1543 self,
1544 starting_nodes: (
1545 list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode]
1546 ),
1547 **kwargs,
1548 ):
1549 """Initialize input data for workflow execution.
1551 Resets all nodes, reconnects the workflow, and populates parent data
1552 nodes with the provided input values.
1554 Args:
1555 starting_nodes: List of nodes that will begin workflow execution.
1556 **kwargs: Key-value pairs of input data to initialize.
1557 """
1558 self._reset_nodes()
1559 self.connect()
1560 for node in starting_nodes:
1561 parents = self.node_manager.get_parents_artefact(node)
1562 for parent in parents:
1563 value = kwargs.get(parent.name, None)
1564 parent.process(parent.name, value, **kwargs)
1565 self._populate_active_paths(starting_nodes, **kwargs)
1566 self._resolve_links()
1568 def _resolve_links(self) -> None:
1569 """Bind loaded links to artefacts in the active pipeline graph."""
1570 artefacts = {
1571 item.id: item
1572 for node in self.node_manager.get_artefact_nodes()
1573 for item in node.items.values()
1574 }
1575 for node in self.node_manager.get_artefact_nodes():
1576 for item in node.items.values():
1577 if type(item) is Link:
1578 item.bind(artefacts)
1580 def _set_task_contexts(self, context: TaskContext):
1581 """Set context for all tasks in the workflow.
1583 Args:
1584 context: TaskContext to apply to all tasks.
1585 """
1586 for task_node in self.node_manager.get_task_nodes():
1587 task = task_node.get_task()
1588 if isinstance(task, Task):
1589 task.context = context
1591 def _reset_nodes(self):
1592 """Reset all nodes in the workflow to their initial state.
1594 Clears items and ensemble items from artefact nodes and sets all node
1595 statuses to NOT_READY.
1596 """
1597 self.node_manager.reset_all_nodes()
1599 def save_run(
1600 self, key: str, value: str | Path, artefact_node: ArtefactNode | None = None
1601 ):
1602 """Save workflow execution results to file.
1604 Args:
1605 key: Key identifier for the data.
1606 value: Path where results should be saved.
1607 artefact_node: Specific artefact node to save, or None for all nodes.
1608 """
1609 if not self._should_save(key, value, artefact_node):
1610 return
1612 savef = Path(value)
1613 if not savef.is_dir():
1614 return
1616 artefact_nodes = self._get_artefact_nodes_to_save(artefact_node)
1617 self._save_results_to_directory(savef, key, value, artefact_nodes)
1618 self._log_save_success(savef, artefact_node)
1620 def _should_save(
1621 self, key: str, value: str | Path, artefact_node: ArtefactNode | None
1622 ) -> bool:
1623 """Check if saving should proceed."""
1624 if not key or not value:
1625 logger.info("No save location specified, skipping save.")
1626 return False
1628 if artefact_node is not None and artefact_node.status != NodeStatus.READY:
1629 logger.info("No new data for %s, skipping save.", artefact_node.name)
1630 return False
1632 return True
1634 def _get_artefact_nodes_to_save(
1635 self, artefact_node: ArtefactNode | None = None
1636 ) -> list[ArtefactNode]:
1637 """Get list of artefact nodes to save."""
1638 if artefact_node is not None:
1639 return [artefact_node]
1641 return self.node_manager.get_artefact_nodes()
1643 def _save_results_to_directory(
1644 self,
1645 directory: Path,
1646 key: str,
1647 value: str | Path,
1648 artefact_nodes: list[ArtefactNode],
1649 ):
1650 """Save results to directory with proper formatting."""
1651 with change_dir(directory):
1652 results = self._load_or_create_results(key, value)
1653 results = self._collect_node_data(results, artefact_nodes)
1654 self._write_results_file(results)
1656 def _load_or_create_results(self, key: str, value: str | Path) -> dict:
1657 """Load existing results file or create new results dictionary."""
1658 resultsf = Path(self.RESULTS_FILE)
1660 if resultsf.exists():
1661 with open(resultsf, "r") as f:
1662 results = yaml.safe_load(f)
1663 # Rewriting the file brings an old-style header up to date, and
1664 # refreshes its timestamp.
1665 results = put_header(
1666 pop_header(results, source=resultsf.resolve()), results
1667 )
1668 else:
1669 results = put_header(
1670 Results(workflow=self.name, version=self.version),
1671 {
1672 key: {
1673 "type": "collectra.Image",
1674 "data": value.name if isinstance(value, Path) else str(value),
1675 },
1676 },
1677 )
1679 return results
1681 def _collect_node_data(
1682 self, results: dict, artefact_nodes: list[ArtefactNode]
1683 ) -> dict:
1684 """Collect data from all ready nodes and add to results."""
1685 for artefact_node in artefact_nodes:
1686 if artefact_node.status != NodeStatus.READY:
1687 continue
1689 name = artefact_node.name
1690 results[name] = self._serialize_node_items(artefact_node)
1692 return results
1694 def _serialize_node_items(self, artefact_node: ArtefactNode) -> dict | list:
1695 """Serialize all items in an artefact node."""
1696 serialized_items = [item.serialize() for item in artefact_node.items.values()]
1697 return serialized_items[0] if len(serialized_items) == 1 else serialized_items
1699 def _write_results_file(self, results: dict):
1700 """Write results dictionary to YAML file."""
1701 write_yaml(results, self.RESULTS_FILE)
1703 def _log_save_success(self, savef: Path, artefact_node: ArtefactNode | None):
1704 """Log successful save operation."""
1705 if artefact_node:
1706 logger.info("Results saved to %s for %s", savef, artefact_node.name)
1707 else:
1708 logger.info("All results saved to %s", savef)
1710 def _run_nodes(
1711 self,
1712 nodes: list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode],
1713 *args,
1714 **kwargs,
1715 ):
1716 """Execute a list of nodes (tasks or artefact nodes) in the workflow.
1718 This method recursively processes nodes, handling both task execution
1719 and artefact node updates. It maintains visualization state and manages
1720 child node execution.
1721 """
1722 single_run = kwargs.get("single", False)
1723 child_tasks = self._run_node_step(nodes, args, kwargs)
1725 if child_tasks and not single_run:
1726 self._run_nodes(child_tasks, *args, **kwargs)
1728 def _run_node_step(
1729 self,
1730 nodes: list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode],
1731 args: tuple,
1732 kwargs: dict,
1733 ) -> list[TaskNode]:
1734 """Execute ``nodes`` themselves, returning the child tasks now ready."""
1735 render = kwargs.get("render", False)
1736 self._mark_nodes_as_processing(nodes)
1737 self.render("workflow_run", file=kwargs.get("value", ""), render=render)
1738 return self._execute_nodes(nodes, args, kwargs, render)
1740 def _mark_nodes_as_processing(
1741 self, nodes: list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode]
1742 ):
1743 """Mark nodes as currently being processed in the graph."""
1744 for node in nodes:
1745 self.node_manager.set_node_attr(
1746 str(node.name), color=self.COLOR_PROCESSING, fontcolor=self.COLOR_FONT
1747 )
1749 def _execute_nodes(
1750 self,
1751 nodes: list[TaskNode | ArtefactNode] | list[TaskNode] | list[ArtefactNode],
1752 args: tuple,
1753 kwargs: dict,
1754 render: bool,
1755 ) -> list[TaskNode]:
1756 """Execute all nodes and collect child tasks.
1758 Returns:
1759 List of child tasks that are ready to execute.
1760 """
1761 child_tasks_of_artefact_nodes = dict()
1763 for node in nodes:
1764 if isinstance(node, TaskNode):
1765 self._execute_task_node(node, args, kwargs, render)
1766 elif isinstance(node, ArtefactNode):
1767 child_tasks = self._execute_artefact_node(node, args, kwargs, render)
1768 child_tasks_of_artefact_nodes.update(child_tasks)
1770 return self._check_tasks_ready(list(child_tasks_of_artefact_nodes.values()))
1772 def _execute_task_node(
1773 self, node: TaskNode, args: tuple, kwargs: dict, render: bool
1774 ):
1775 """Execute a single task node."""
1776 if self._check_task_ready(node) != NodeStatus.READY:
1777 logger.info(f"[yellow]Task {node.name} is not ready, skipping.[/yellow]")
1778 return
1780 children = self._get_node_children(node)
1781 outcomes = self._outcomes[str(kwargs.get("value", ""))]
1782 force = kwargs.get("force") or node.name in kwargs.get("rerun", set())
1783 if not force and self._has_output(node):
1784 existing = [
1785 f"{output.name} ({len(output.items)})"
1786 for output in self._output_nodes(node)
1787 if self._holds_output(output)
1788 ]
1789 logger.warning(
1790 "Skipping task '%s' for %s: output already exists in %s. "
1791 "Use --force to rerun it and replace that output.",
1792 node.name,
1793 Path(str(kwargs.get("value", ""))).name or "this file",
1794 ", ".join(existing),
1795 )
1796 outcomes[node.name] = ("skipped", "kept existing output")
1797 self._update_node_status(node, True)
1798 self._run_nodes(children, **kwargs)
1799 return
1801 if self._stage_gate and self._stage_gate.defer(node, kwargs.get("value", "")):
1802 return
1804 if kwargs.get("stop", _never)():
1805 outcomes[node.name] = ("cancelled", "stopped before it started")
1806 return
1808 previous = self._take_outputs(node, kwargs.get("value")) if force else None
1809 try:
1810 results = self._run_task(node, **kwargs)
1811 except Exception as error:
1812 # Only this task's branch stops: with no output, the tasks that need
1813 # it are never ready, while the rest of the DAG carries on.
1814 if previous is not None:
1815 previous.restore()
1816 self._task_failed(node, kwargs.get("value", ""), error, render)
1817 return
1818 except BaseException:
1819 if previous is not None:
1820 previous.restore()
1821 raise
1822 detail = ""
1823 if previous is not None and not results:
1824 # A failed rerun must not destroy the output it was meant to replace.
1825 previous.restore()
1826 previous = None
1827 detail = "produced nothing, kept existing output"
1828 elif previous is not None and node.name not in kwargs.get("rerun", set()):
1829 # A forced run (the CLI's --force) drops the old output before the
1830 # new one is saved, as it always has. Only a page run's re-runs
1831 # keep it until the new output is saved.
1832 previous.discard()
1833 previous = None
1835 self._update_node_status(node, bool(results))
1836 self.render("workflow_run", file=kwargs.get("value", ""), render=render)
1838 try:
1839 child_tasks = self._run_node_step(children, tuple(results), kwargs)
1840 except BaseException as error:
1841 # Nor must new output that could not be saved.
1842 if previous is not None:
1843 previous.restore()
1844 outcomes[node.name] = (
1845 "failed",
1846 f"could not save its output: {type(error).__name__}: {error}",
1847 )
1848 raise
1849 if previous is not None:
1850 previous.discard()
1851 outcomes[node.name] = ("ran", detail)
1853 if child_tasks and not kwargs.get("single", False):
1854 self._run_nodes(child_tasks, *results, **kwargs)
1856 def _task_failed(
1857 self, node: TaskNode, folder, error: Exception, render: bool = False
1858 ) -> None:
1859 """Log a task's failure and mark it, leaving the rest of the run to go on."""
1860 name = Path(str(folder)).name or "this file"
1861 logger.error(
1862 "Task '%s' failed for %s: %s", node.name, name, error, exc_info=error
1863 )
1864 self._failures.append((node.name, name, f"{type(error).__name__}: {error}"))
1865 self._outcomes[str(folder)][node.name] = (
1866 "failed",
1867 f"{type(error).__name__}: {error}",
1868 )
1869 self._update_node_status(node, False)
1870 self.render("workflow_run", file=folder, render=render)
1872 def _output_nodes(self, node: TaskNode) -> list[ArtefactNode]:
1873 return [
1874 child
1875 for child in self.node_manager.get_children(node)
1876 if isinstance(child, ArtefactNode)
1877 ]
1879 @staticmethod
1880 def _holds_output(output: ArtefactNode) -> bool:
1881 """Whether a node has items, or a saved empty result.
1883 A task that ran and found nothing saves its output as an empty entry,
1884 which loads as a ready node with no items. That is a finished result.
1885 """
1886 return bool(output.items) or output.status == NodeStatus.READY
1888 def _has_output(self, node: TaskNode) -> bool:
1889 """Whether any of a task's output nodes already holds a result."""
1890 return any(self._holds_output(output) for output in self._output_nodes(node))
1892 def _take_outputs(self, node: TaskNode, folder) -> PreviousOutputs:
1893 """Empty a task's output nodes before a forced rerun replaces them.
1895 Each artefact is dropped from its node. If it keeps its content in a
1896 file, that exact file, as the artefact records it, is moved aside until
1897 the rerun succeeds. Nothing is inferred from folder names, so results
1898 written by hand or by older versions are handled the same way.
1899 """
1900 outputs = self._output_nodes(node)
1901 snapshots = [(output, dict(output.items)) for output in outputs]
1902 moved: list[tuple[Path, Path]] = []
1903 backup = None
1904 root = Path(str(folder)).resolve() if folder else None
1905 for output in outputs:
1906 for item in output.items.values():
1907 for file in item.stored_files(root) if root else []:
1908 if not file.resolve().is_relative_to(root):
1909 logger.warning(
1910 "Not deleting %s: it is outside the results folder %s",
1911 file,
1912 root,
1913 )
1914 continue
1915 already = any(file == original for _, original in moved)
1916 if already or not file.is_file():
1917 continue
1918 if backup is None:
1919 backup = Path(tempfile.mkdtemp(prefix="collectra-previous-"))
1920 kept = backup / str(len(moved))
1921 shutil.move(str(file), str(kept))
1922 moved.append((kept, file))
1923 for output, _ in snapshots:
1924 output.items.clear()
1925 return PreviousOutputs(snapshots, moved, backup)
1927 def _execute_artefact_node(
1928 self, node: ArtefactNode, args: tuple, kwargs: dict, render: bool
1929 ) -> dict:
1930 """Execute a single artefact node and return child tasks.
1932 Returns:
1933 Dictionary of child task names to TaskNode objects.
1934 """
1935 # Process incoming data
1936 for arg in args:
1937 if (
1938 isinstance(arg, Artefact)
1939 and node.name == arg.get_name()
1940 and node.check_type(type(arg))
1941 ):
1942 self._check_existing(node, arg)
1943 self._name_new_items(node, args)
1944 folder = kwargs.get("value")
1945 if folder:
1946 for item in node.items.values():
1947 item.finalise(Path(str(folder)), node.name)
1949 # Mark as READY even if no items matched — parent task has completed
1950 if node.status == NodeStatus.NOT_READY:
1951 node.status = NodeStatus.READY
1953 # Save results
1954 self.save_run(
1955 kwargs.get("key", ""), kwargs.get("value", ""), artefact_node=node
1956 )
1958 # Update visualization
1959 self._update_node_status(node, True)
1960 self.render("workflow_run", file=kwargs.get("value", ""), render=render)
1962 # Collect child tasks
1963 children = self._get_node_children(node)
1964 return {child.name: child for child in children if isinstance(child, TaskNode)}
1966 def _get_node_children(
1967 self, node: TaskNode | ArtefactNode
1968 ) -> list[TaskNode | ArtefactNode]:
1969 """Get all children of a node."""
1970 return self.node_manager.get_children(node)
1972 def _update_node_status(self, node: TaskNode | ArtefactNode, success: bool):
1973 """Update node visualization status based on execution result."""
1974 color = self.COLOR_SUCCESS if success else self.COLOR_FAILURE
1975 self.node_manager.set_node_attr(
1976 str(node.name), color=color, fontcolor=self.COLOR_FONT
1977 )
1979 def _check_task_ready(self, task_node: TaskNode) -> NodeStatus:
1980 """Check if a task node is ready to execute.
1982 A task is ready when all its parent artefact nodes have READY status.
1984 Args:
1985 task_node: The task node to check.
1987 Returns:
1988 The updated status of the task node.
1989 """
1990 parents = self.node_manager.get_parents_artefact(task_node)
1991 if all(parent.status == NodeStatus.READY for parent in parents):
1992 task_node.status = NodeStatus.READY
1993 return task_node.status
1995 def _check_tasks_ready(self, task_nodes: list[TaskNode]) -> list[TaskNode]:
1996 """Filter task nodes to return only those that are ready to execute.
1998 Args:
1999 task_nodes: List of task nodes to check.
2001 Returns:
2002 List of task nodes that have READY status.
2003 """
2004 ready_tasks: list[TaskNode] = list()
2005 ready_tasks = [
2006 task_node
2007 for task_node in task_nodes
2008 if self._check_task_ready(task_node) == NodeStatus.READY
2009 ]
2010 return ready_tasks
2012 def _name_new_items(self, node: ArtefactNode, results: tuple) -> None:
2013 """Give automatically identified items in ``node`` their final ids.
2015 A lone item takes the node's name; otherwise items are numbered
2016 ``node-1``, ``node-2``... skipping ids already in use. Ids that were
2017 loaded or chosen explicitly never change, so existing references hold.
2018 ``results`` is everything the task produced, so references to a renamed
2019 item from its siblings are updated too.
2020 """
2021 fresh = [
2022 item for item in node.items.values() if getattr(item, "_auto_id", False)
2023 ]
2024 if not fresh:
2025 return
2026 fresh_objects = {id(item) for item in fresh}
2027 taken = {
2028 item.id for item in node.items.values() if id(item) not in fresh_objects
2029 }
2030 renamed: dict[str, str] = {}
2031 number = 1
2032 for item in fresh:
2033 if len(node.items) == 1:
2034 new_id = node.name
2035 else:
2036 while f"{node.name}-{number}" in taken:
2037 number += 1
2038 new_id = f"{node.name}-{number}"
2039 taken.add(new_id)
2040 renamed[item.id] = new_id
2041 for result in results:
2042 if not isinstance(result, Artefact):
2043 continue
2044 if isinstance(result.parents, str):
2045 result.parents = renamed.get(result.parents, result.parents)
2046 else:
2047 result.parents = [
2048 renamed.get(parent, parent) for parent in result.parents
2049 ]
2050 ordered = list(node.items.values())
2051 for item in fresh:
2052 item.id = renamed[item.id]
2053 item._auto_id = False
2054 node.items.clear()
2055 node.items.update({item.id: item for item in ordered})
2057 def _check_existing(self, node: ArtefactNode, new_item: Artefact) -> None:
2058 """Check if an identical item already exists in the artefact node.
2060 If an identical item is found, update the existing item with the new item's ID.
2061 If no identical item is found, add the new item to the artefact node.
2063 Args:
2064 node: The artefact node to check.
2065 new_item: The new data item to check or add.
2066 """
2067 items = node.items
2068 for existing_id, existing_item in items.items():
2069 if self._is_identical_item(existing_item, new_item):
2070 new_item.id = existing_item.id
2071 # Still provisional if the replaced item had not been named yet.
2072 new_item._auto_id = getattr(existing_item, "_auto_id", False)
2073 items[existing_id] = new_item
2074 return
2076 # No identical item found, add as new
2077 node.add_item(new_item)
2079 def _is_identical_item(self, original_item: Artefact, new_item: Artefact) -> bool:
2080 """Check if two data items are identical.
2082 Compares both parent relationships and serialized data attributes.
2083 """
2084 if set(new_item.parents) != set(original_item.parents):
2085 return False
2087 return self._compare_serialized_data(original_item, new_item)
2089 def _compare_serialized_data(
2090 self, original_item: Artefact, new_item: Artefact
2091 ) -> bool:
2092 """Compare serialized data of two items, ignoring IDs and parents."""
2093 temp_original = self._prepare_for_comparison(copy.deepcopy(original_item))
2094 temp_new = self._prepare_for_comparison(copy.deepcopy(new_item))
2096 return json.dumps(temp_original, sort_keys=True) == json.dumps(
2097 temp_new, sort_keys=True
2098 )
2100 def _prepare_for_comparison(self, item: Artefact) -> dict:
2101 """Prepare data item for comparison by normalizing and removing metadata."""
2102 serialized = item.serialize()
2103 serialized.pop("parents", None)
2104 serialized.pop("id", None)
2106 # Normalize string data for comparison
2107 if isinstance(serialized.get("data"), str):
2108 serialized["data"] = serialized["data"].strip().lower()
2110 return serialized
2112 def _apply_task_run_overrides(self, task: Task, overrides: dict) -> None:
2113 """Apply runtime CLI overrides to a task before execution."""
2114 if not overrides:
2115 return
2116 merged_overrides = self._merge_task_params(task.name, dict(overrides))
2117 for key, value in merged_overrides.items():
2118 setattr(task, key, value)
2120 def _run_task(self, task_node: TaskNode, **kwargs) -> list:
2121 """Execute a task node and return its output results.
2123 Prepares inputs from parent artefact nodes, runs the task, and collects
2124 all output data items.
2126 Args:
2127 task_node: The task node to execute.
2128 **kwargs: Additional execution parameters.
2130 Returns:
2131 List of Artefact objects produced by the task execution.
2133 Raises:
2134 TypeError: If the node does not contain a valid Task.
2135 """
2136 task = task_node.get_task()
2137 if not isinstance(task, Task):
2138 raise TypeError(f"Node {task_node.name} is not a Task")
2139 logger.info("Attempting to run task: %s", task.name)
2140 self._apply_task_run_overrides(task, kwargs.get("task_overrides", {}))
2141 parents = self.node_manager.get_parents_artefact(task_node)
2142 entries = task.prepare_inputs(parents)
2143 results = list()
2144 if len(entries) == 0:
2145 logger.warning("No input data found for task %s, skipping.", task.name)
2146 return results
2147 # Inside an overall bar a per-task bar would only add noise.
2148 listed = (
2149 entries
2150 if self._run_progress
2151 else track(
2152 entries,
2153 total=len(entries),
2154 description=f"Running {task.name}",
2155 )
2156 )
2157 try:
2158 with change_dir(self.path):
2159 for entry in listed:
2160 if not isinstance(entry, list):
2161 entry = list(entry)
2162 entry_result = self._execute_entries(entry, task)
2163 results.extend(entry_result)
2164 finally:
2165 # A task that fails leaves track()'s generator, and its refresh
2166 # thread, open. Closing it now stops the thread at once; left to
2167 # the garbage collector it can deadlock with the bar's own lock.
2168 if listed is not entries:
2169 listed.close()
2170 return results
2172 def _execute_entries(self, entries: list[Artefact], task: Task) -> list[Artefact]:
2173 """Execute a task with the given input entries.
2175 Runs the task with the provided data entries, sets parent relationships
2176 on output items, and handles any execution errors.
2178 Args:
2179 entries: List of input Artefact objects for the task.
2180 task: The task to execute.
2182 Returns:
2183 List of Artefact objects produced by the task, with parent relationships set.
2184 """
2185 output: Artefact | list[Artefact] | None = task.run(*entries)
2186 try:
2187 if output is None:
2188 return list()
2189 if not isinstance(output, list):
2190 output = [output]
2191 for result in output:
2192 result.set_parents(entries)
2193 return output
2194 except Exception as e:
2195 logger.error(
2196 "Error executing entries for task %s: %s (entries: %s)",
2197 task.name,
2198 e,
2199 entries,
2200 exc_info=True,
2201 )
2202 return list()
2204 def _merge_task_params(self, task_name: str, kwargs: dict) -> dict:
2205 """Merge task-specific parameters with provided kwargs."""
2206 task_params = self.data.get(task_name, dict()).get("params", dict())
2207 return task_params | kwargs
2209 def ensemble(self, folder: list[Path], output: str | Path):
2210 """Create ensembled files from source folders.
2212 Delegates to EnsembleProcessor for the actual ensemble logic.
2214 Args:
2215 folder: List of source folders containing collectra results
2216 output: Output folder path for ensembled results
2217 """
2218 from collectra.pipelines.ensemble import EnsembleProcessor
2220 self._ensure_workflow_connected()
2221 processor = EnsembleProcessor(
2222 node_manager=self.node_manager,
2223 ext=self.ext,
2224 name=self.name,
2225 version=self.version,
2226 )
2227 processor.ensemble(folder, Path(output))
2229 @property
2230 def metadata(self) -> dict:
2231 """The pipeline's declaration, as it is written at the top of pipeline.yaml.
2233 Returns:
2234 The pipeline entry (``{name: {type, ext, version, ...}}``), or for a
2235 file that still uses the deprecated form, its metadata block.
2236 """
2237 if self._legacy_declaration:
2238 return {self.PIPELINE_METADATA_KEY: self.pipeline_metadata.copy()}
2239 extras = {
2240 key: value
2241 for key, value in self.pipeline_metadata.items()
2242 if key not in ("name", "ext", "version")
2243 }
2244 cls = type(self)
2245 declared_type = (
2246 "collectra.Pipeline"
2247 if cls is Pipeline
2248 else f"{cls.__module__}.{cls.__qualname__}"
2249 )
2250 return {
2251 self.name: {
2252 "type": declared_type,
2253 "ext": self.ext,
2254 "version": self.version,
2255 **extras,
2256 }
2257 }
2259 def gui_graph(self) -> dict:
2260 """Return the live workflow graph in the shape expected by the GUI."""
2261 self._ensure_workflow_connected()
2262 nodes = []
2263 for name in self.node_manager.get_node_names():
2264 node = self.node_manager.resolve_node(name)
2265 inputs = list(self.node_manager.flow.predecessors(name))
2266 outputs = list(self.node_manager.flow.successors(name))
2267 params = {}
2269 if isinstance(node, TaskNode):
2270 task = node.get_task()
2271 detail = task.get_class_path()
2272 params = getattr(task, "params", {})
2273 node_type = "Task"
2274 types = []
2275 else:
2276 types = sorted(type_.get_class_path() for type_ in node.types)
2277 detail = ", ".join(types)
2278 node_type = "Artefact"
2280 nodes.append(
2281 {
2282 "id": name,
2283 "label": name,
2284 "nodeType": node_type,
2285 "types": types,
2286 "detail": detail,
2287 "inputs": inputs,
2288 "outputs": outputs,
2289 "params": params,
2290 }
2291 )
2293 edges = [
2294 {"source": source, "target": target}
2295 for source, target in self.node_manager.flow.edges
2296 ]
2297 return {"nodes": nodes, "edges": edges, "ext": self.ext}
2299 def save(self, task_name: str | None = None):
2300 """Save the workflow configuration to pipeline.yaml."""
2301 with change_dir(self.path):
2302 # Pull updated data from file if it exists to ensure we don't overwrite changes
2303 data_diff: dict | None = None
2304 if Path(self.PIPELINE_FILE).exists():
2305 with open(self.PIPELINE_FILE, "r") as f:
2306 file_data = yaml.safe_load(f) or dict()
2307 file_data.pop(self.PIPELINE_METADATA_KEY, None)
2308 if self.name not in self.data:
2309 file_data.pop(self.name, None) # the pipeline's own entry
2310 # compare diffs between current data and file data, prioritizing file data for any keys that exist in both
2311 data_diff = dict()
2312 for key, data in file_data.items():
2313 if key != task_name and file_data[key] != self.data.get(key, None):
2314 data_diff[key] = data
2315 data_to_save = (
2316 self.data | data_diff if data_diff and len(data_diff) > 0 else self.data
2317 )
2318 config = self.metadata | data_to_save
2319 self._write_pipeline_config(config)
2321 def _write_pipeline_config(self, config: dict):
2322 """Write pipeline configuration to YAML file."""
2323 write_yaml(config, self.PIPELINE_FILE)
2325 def _get_io_list(self, io: list | str) -> list:
2326 """Convert an IO specification to a list format.
2328 Args:
2329 io: Either a single string or a list of IO identifiers.
2331 Returns:
2332 List containing the IO identifier(s).
2333 """
2334 return [io] if isinstance(io, str) else io
2336 def _check_task_io(self, io_type: str, task: Task, task_config: dict) -> list:
2337 """Extract IO node information from task configuration.
2339 Args:
2340 io_type: Either 'input' or 'output'.
2341 task: The task object.
2342 task_config: Configuration dictionary for the task.
2344 Returns:
2345 List of tuples containing (node_name, types).
2346 """
2347 if io_type not in task_config:
2348 return list()
2350 param_types = list(
2351 unpack_types(
2352 task.run, get_param_types if io_type == "input" else get_return_type
2353 ).items()
2354 )
2355 io = self._get_io_list(task_config.get(io_type, []))
2356 nodes: list = list()
2357 for item in io:
2358 for _, types in param_types:
2359 if not isinstance(types, tuple):
2360 types = (types,)
2361 nodes.append((item, types))
2362 return nodes
2364 def _check_data_assignment(self, collectra_data: dict, data: dict) -> dict:
2365 """Check and resolve data references in configuration.
2367 If a value references another key in collectra_data, replace it with
2368 the actual value.
2370 Args:
2371 collectra_data: The main workflow data dictionary.
2372 data: The dictionary to check for references.
2374 Returns:
2375 Updated data dictionary with resolved references.
2376 """
2377 for key, value in data.items():
2378 if isinstance(value, str) and value in collectra_data:
2379 data[key] = collectra_data[value]
2380 return data
2382 def connect(self):
2383 """Initialise the DAG representing the workflow. Preparing it for execution."""
2384 relations: dict[str, dict] = dict()
2385 with change_dir(self.path):
2386 self._build_nodes_and_relations(relations)
2387 self._create_graph_edges(relations)
2388 for node in self.node_manager.get_task_nodes():
2389 node.get_task().validate_resources(self.resources)
2391 def resource(self, name: str):
2392 """The resource declared under ``name`` (available once connected)."""
2393 try:
2394 return self.resources[name]
2395 except KeyError:
2396 raise KeyError(
2397 f"No resource named {name!r}. Available: "
2398 f"{', '.join(sorted(self.resources)) or 'none'}"
2399 ) from None
2401 def _build_nodes_and_relations(self, relations: dict):
2402 """Build workflow nodes and track their relationships."""
2403 for name, value in self.data.items():
2404 data = copy.deepcopy(value)
2405 if not isinstance(data, dict) or "type" not in data:
2406 continue
2408 cls_ = load_class_from_string(data.pop("type"))
2409 data = self._check_data_assignment(self.data, data)
2410 if issubclass(cls_, Resource):
2411 # Kept by name, reused across connects, and never a graph node.
2412 if type(self.resources.get(name)) is not cls_:
2413 self.resources[name] = cls_(name, **data)
2414 continue
2415 obj = self._create_or_reuse_object(name, cls_, data)
2417 if isinstance(obj, Task):
2418 self._process_task_node(obj, data, relations)
2419 else:
2420 self.node_manager.add_artefact_node(name, obj=obj)
2422 def _create_or_reuse_object(self, name: str, cls_: type, data: dict):
2423 """Create new object or reuse existing task from graph."""
2424 existing_task = self.node_manager.try_resolve_existing_task(name, cls_)
2425 if existing_task is not None:
2426 return existing_task
2427 return cls_(name, **data)
2429 def _process_task_node(self, task: Task, data: dict, relations: dict):
2430 """Process a task node by adding it to the graph and tracking IO."""
2431 task_key = task.name
2432 task.pipeline = self
2433 relations[task_key] = {
2434 "input": self._get_io_list(data.get("input", [])),
2435 "output": self._get_io_list(data.get("output", [])),
2436 }
2437 self.node_manager.add_task_node(task_key, task)
2439 # Add artefact nodes for task inputs and outputs
2440 ios = self._extract_task_io_nodes(task, data)
2441 for io_key, io_types in ios:
2442 self.node_manager.add_artefact_node(io_key, types=list(io_types))
2444 def _extract_task_io_nodes(
2445 self, task: Task, task_config: dict
2446 ) -> list[tuple[str, tuple]]:
2447 """Extract input and output node information from task configuration."""
2448 ios = []
2449 ios.extend(self._check_task_io("input", task, task_config))
2450 ios.extend(self._check_task_io("output", task, task_config))
2451 return ios
2453 def _create_graph_edges(self, relations: dict):
2454 """Create edges in the workflow graph based on task relationships."""
2455 for task_name, io in relations.items():
2456 inputs = io.get("input", [])
2457 outputs = io.get("output", [])
2459 for input_node in inputs:
2460 if self.node_manager.has_node(input_node):
2461 self.node_manager.add_edge(input_node, task_name)
2463 for output_node in self._get_io_list(outputs):
2464 if self.node_manager.has_node(output_node):
2465 self.node_manager.add_edge(task_name, output_node)
2467 def render(self, dest: str | Path = "", file="", render=False) -> None:
2468 """Render the workflow graph as an SVG visualization.
2470 Args:
2471 dest: Destination path for the rendered file.
2472 file: Optional file being processed (shown in title).
2473 render: Whether to actually render (allows conditional rendering).
2474 """
2475 if not render:
2476 return
2478 self._ensure_workflow_connected()
2479 visual_graph = self._prepare_graph_for_visualization()
2480 dot_str = self._generate_dot_string(visual_graph, file)
2482 dest_path = Path(dest) if dest else self.path / "workflow"
2483 graphviz.Source(dot_str).render(filename=dest_path, format="svg", cleanup=True)
2484 time.sleep(0.1) # Brief pause for file system
2486 def _prepare_graph_for_visualization(self) -> nx.DiGraph:
2487 """Prepare a copy of the graph for visualization.
2489 Removes internal node objects that shouldn't be visualized.
2490 """
2491 visual_graph = self.node_manager.copy_graph()
2492 for node_id in visual_graph.nodes:
2493 node_data = visual_graph.nodes[node_id]
2494 if "node" in node_data:
2495 del node_data["node"]
2496 return visual_graph
2498 def _generate_dot_string(self, graph: nx.DiGraph, file: str = "") -> str:
2499 """Generate DOT format string from graph.
2501 Args:
2502 graph: The networkx graph to convert.
2503 file: Optional file name to include in graph title.
2505 Returns:
2506 DOT format string representation of the graph.
2507 """
2508 dot_str = nx.nx_pydot.to_pydot(graph).to_string()
2510 if file:
2511 title = f"{self.name} Workflow - Processing: {file}"
2512 dot_str = dot_str.replace(
2513 "{", f'{{\nlabel="{title}";\nlabelloc="t";\nfontsize=20;\n\n', 1
2514 )
2516 return dot_str
2519# The class was called ``Collectra`` before it became ``Pipeline``; the old name
2520# still works so existing scripts keep running.
2521Collectra = Pipeline