Metadata-Version: 2.4
Name: wofl
Version: 0.5.0
Summary: Composable task graphs for Python workflows with caching and remote execution.
License-Expression: CC0-1.0
Project-URL: Homepage, https://github.com/ast-al/wofl
Project-URL: Source, https://github.com/ast-al/wofl
Project-URL: Issues, https://github.com/ast-al/wofl/issues
Keywords: workflow,pipeline,dag,caching,remote,hpc
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Operating System :: POSIX
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.md
Provides-Extra: format
Requires-Dist: black; extra == "format"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-xdist; extra == "dev"
Dynamic: license-file

# wofl: composable tasks for Python workflows

wofl adds persistent caching, retries, resource limits, and local or remote
execution to Python functions. Build parallel pipelines by passing task results
to other tasks; use ordinary Python loops, conditionals, and `await` to control
the workflow. Each feature is available through a small, composable decorator.

For complete examples, see the [cache demo](examples/persistent_cache_demo.py),
[async task demo](examples/async_task_demo.py), and
[protein-alignment pipeline](examples/align_prots.py).

## Contents

- [Installation](#installation)
- [Command helpers](#command-helpers)
  - [`run_cmd`: run a command or script](#run_cmd-run-a-command-or-script)
  - [`open_cmd`: connect and read commands](#open_cmd-connect-and-read-commands)
- [Decorators](#decorators)
  - [`@retry`: retry transient failures](#retry-retry-transient-failures)
  - [`@cache`: persist results on disk](#cache-persist-results-on-disk)
  - [`@throttle`: limit concurrency and invocation rate](#throttle-limit-concurrency-and-invocation-rate)
- [Asynchronous pipelines](#asynchronous-pipelines)
  - [`@task`: define a pipeline task](#task-define-a-pipeline-task)
  - [`run_workflow`: execute a pipeline](#run_workflow-execute-a-pipeline)
  - [Inspecting a run](#inspecting-a-run)
  - [Rerunning a task out of band](#rerunning-a-task-out-of-band)
  - [Inspecting task inputs and outputs](#inspecting-task-inputs-and-outputs)
  - [Remote execution](#remote-execution)
  - [Containerization](#containerization)
- [Comparison with other libraries](#comparison-with-other-libraries)
- [Comparison with Nextflow](#comparison-with-nextflow)

## Installation

Requires Python 3.11+, a POSIX system, and the `zstd` command-line program for
caching and task execution. There are no required third-party Python packages.

```sh
pip install wofl
# or
uv add wofl
```

To install the GitHub version:

```sh
pip install git+https://github.com/ast-al/wofl.git
```

wofl is a single public-domain module; you can also copy
[`src/wofl.py`](src/wofl.py) into your project.

## Command helpers

### `run_cmd`: run a command or script

`wofl.run_cmd()` runs a command and raises `subprocess.CalledProcessError` on
failure. Pass an argument list to keep filenames and other values intact:

```python
from pathlib import Path
import wofl

input_file = Path("reads.fa")
wofl.run_cmd(["wc", "-l", str(input_file)])
```

A plain string is split with `shlex.split`; no shell runs unless you request
one. On Python 3.14+, t-strings quote interpolated values automatically:

```python
wofl.run_cmd(t"wc -l {input_file}")
```

For shell pipelines or scripts, enable Bash with strict error handling:

```python
wofl.run_cmd(
    "sort input.txt | gzip > output.gz",
    shell=True,
    executable="strict_bash",
)
```

`strict_bash` enables `errexit`, `nounset`, `pipefail`, and `noclobber`, sets
the locale to `C`, and limits field splitting to newlines and tabs. Other
keyword arguments go to `subprocess.run`; `check=True` is the default.
`run_cmd` returns `None`; use `open_cmd` to read command output.

### `open_cmd`: connect and read commands

`wofl.open_cmd()` is a context manager yielding a `subprocess.Popen` object.
It pipes stdout and decodes text by default, so commands can be connected
without a shell:

```python
with (
    wofl.open_cmd(["cat", "input.txt"]) as source,
    wofl.open_cmd("sort -u", stdin=source.stdout) as unique,
):
    lines = [line.rstrip("\n") for line in unique.stdout]
```

It accepts the same command forms and strict-Bash option as `run_cmd`.
Use `text=False` for bytes and `ok_retcodes=(0, 1)` for commands such as `grep`
where a nonzero status can be expected. Other unexpected exit statuses raise
`CalledProcessError`; SIGPIPE is accepted. Read the output inside the context:
exiting early terminates a still-running command.

For process substitution, include a pipe's `/dev/fd/N` path in a command;
`open_cmd` automatically passes the referenced file descriptor to the child.

## Decorators

All decorator factories require parentheses. `@cache()`, `@retry()`, and
decorators created by `throttle()` work on ordinary synchronous functions.
Add `@task()` to schedule calls as asynchronous pipeline tasks.

wofl combines these policies into one configuration, so their order does not
change the execution stages. Cache hits skip execution; on a miss, throttles
are acquired before the payload and held across retries.

### `@retry`: retry transient failures

Use retries for idempotent work: repeating a failed call should be safe.
`@wofl.retry()` retries once after one second. Supply `delay` to control which
errors to retry and how long to wait:

```python
@wofl.retry(
    delay=lambda _attempt, _error: (
        2 ** _attempt
        if _attempt <= 3 and isinstance(_error, (ConnectionError, TimeoutError))
        else None
    ),
)
def fetch_data(url: str) -> bytes:
    ...
```

`_attempt` is `1` for the first retry, and `_error` is the exception just
raised. The callback may also request function arguments by name. Return
seconds to wait, `0` to retry immediately, or `None` to stop. Fatal exceptions
such as `KeyboardInterrupt`, `SystemExit`, and `MemoryError` are never retried.

### `@cache`: persist results on disk

Like `functools.cache`, `@wofl.cache()` reuses a function's result, but persists
it across script runs. The wrapped function retains ordinary Python working-
directory and `Path` semantics:

```python
@wofl.cache()
def normalize(input_file: Path) -> Path:
    output = input_file.with_suffix(".normalized.txt")
    output.write_text(input_file.read_text().lower())
    return output

normalized = normalize(Path("input.txt"))
```

Each call's result is stored in
`./work/<module>/<function>/<args_hash>/.wofl/cache.pkl.zst`, without changing
the function's current working directory. The caller's current working directory
is not implicitly part of cache identity. If the function depends on it, pass
`Path.cwd()` as an argument or represent it in `environment_fingerprint`.
Relative `Path` arguments are associated with the directory that resolves them.
Arguments and results must be picklable.

Pass files as **`Path` objects** to track their contents; strings are ordinary
values. Cache-only functions receive and return paths unchanged. Directory
inputs are tracked recursively, excluding `.wofl/` metadata. Returned files are
tracked by content; returned directories track only their existence and type,
not their contents.

Cache validation automatically includes the workflow process's `sys.version`.
It also tracks function source, directly referenced helper functions, picklable
globals and captured closure values, and input/output files. A code or file
change invalidates the result without necessarily changing the call directory.
Module contents reached through module objects or lazy imports, unpicklable
object state, API data, installed tools, and the payload's runtime environment
need an explicit version argument, an expiry, or an environment fingerprint.

The executor, backend, `python3` command, resources, and executor-specific
options control dispatch and are not cache identity. Use
`environment_fingerprint` to identify a remote interpreter, container image,
Conda environment, loaded modules, or other external runtime. If it is omitted,
changing those settings may reuse an existing result.

| Option | Purpose |
| --- | --- |
| `workspace_root="./work"` | Choose where call directories and cache records live. |
| `expires_in=None` | Limit cache age in seconds; `None` never expires, `0` disables cache lookup and storage. |
| `environment_fingerprint=None` | Declare a stable identity for the payload runtime or external state, such as a tool version, image digest, or lock-file hash. |
| `ignore_file_meta=False` | Set to `True` to recompute file checksums even when size and modification time are unchanged. |

A call directory has a `.running.<id>` suffix during execution and a `.failed`
suffix after failure.

For outputs with irrelevant, nondeterministic metadata, the producing task can
write a `<file>.wofl_checksum` sidecar with a normalized checksum. wofl uses
that checksum in place of hashing the file's bytes.

### `@throttle`: limit concurrency and invocation rate

`wofl.throttle()` creates a reusable decorator factory. Functions decorated
through the **same factory** share its limit:

```python
api_limit = wofl.throttle(capacity=4, min_delay=0.5)

@wofl.task()
@api_limit()
def fetch_page(url: str) -> bytes:
    ...
```

This permits up to four concurrent calls and spaces starts by at least half a
second. Defaults are `capacity=1`, `min_delay=0`, and one slot per call.

For weighted resources, calculate the required slots from arguments:

```python
memory_limit = wofl.throttle(capacity=32768)

@wofl.task()
@memory_limit(slots=lambda requested_mb: requested_mb)
def analyze(input_file: Path, requested_mb: int) -> Path:
    ...
```

Each new `wofl.throttle()` call creates an independent limiter.

## Asynchronous pipelines

### `@task`: define a pipeline task

`@wofl.task()` makes a function call return an eagerly scheduled `asyncio.Task`.
By default, the payload runs in an isolated local process with cache expiry set
to `0`, so results are not reused. Each task runs in its input-addressed call
directory. Relative input paths are adjusted for that working directory;
returned paths must exist and stay within it, and are adjusted back for the
caller. See the [task path-rebasing demo](examples/task_path_rebasing_demo.py)
for a minimal runnable example of both adjustments. Add `@cache()` to reuse
results indefinitely, or `@cache(expires_in=3600)` to set a positive expiry in
seconds.

`clear_taskdir=True` clears old payload files before an uncached execution or
cache miss while preserving `.wofl/`; pass `False` to retain them. A fresh
`tmp/` directory is available to every task attempt, removed on success, and
retained on failure for debugging.

Pass task handles to other tasks to express dependencies, including handles
nested in lists, tuples, or dictionaries. wofl waits for them and passes their
resolved values to the payload. Independent calls can run concurrently.
Use `await` when the workflow itself needs a value to branch or build more work.

Save this example as `pipeline.py` and run it twice to see cache reuse:

```python
from pathlib import Path
import wofl

@wofl.task()
@wofl.cache()
def uppercase(text: str) -> Path:
    output = Path("text.txt")
    output.write_text(text.upper())
    return output

@wofl.task()
@wofl.cache()
def combine(files: list[Path]) -> Path:
    output = Path("combined.txt")
    output.write_text("\n".join(path.read_text() for path in files))
    return output

async def workflow():
    parts = [uppercase(word) for word in ("hello", "world")]
    return combine(parts)

if __name__ == "__main__":
    result = wofl.run_workflow(workflow)
    print(result.read_text())
```

Task payloads must be synchronous, module-level functions in readable `.py`
files. Keep workflow startup behind `if __name__ == "__main__"`, since workers
import the module. Arguments must be picklable; return built-in values and
`Path` objects, as arbitrary custom result classes are not supported. Store
large results in files and return their paths. Dependent tasks must share a
workspace.

#### Task results and dependency provenance

Awaiting a task, or calling `result()` on a completed task, returns a
`TaskResult` wrapper. It carries the originating task so that passing the value
to another task records the dependency in the run graph; wofl unwraps it before
the downstream payload runs. `run_workflow()` also unwraps task results before
returning to synchronous code.

The wrapper delegates common operations to the payload value, so it can usually
be used or passed onward directly. When code needs the exact returned object or
an operation the wrapper does not provide, access `.value` explicitly:

```python
async def workflow():
    result = await uppercase("hello")  # TaskResult carrying provenance
    path = result.value                # the exact Path returned by uppercase
    return result                      # run_workflow() returns that Path
```

Manually unwrapping with `.value` discards provenance from that value. Pass the
wrapper or the original task handle to downstream tasks when the dependency
edge should be retained.

### `run_workflow`: execute a pipeline

`wofl.run_workflow()` is the synchronous entry point. It accepts an awaitable
or a zero-argument function that creates one, and resolves tasks nested in the
returned result:

```python
result = wofl.run_workflow(workflow)        # or workflow()
result = wofl.run_workflow(lambda: uppercase("hello"))
```

Create task calls inside the workflow or a factory, where an event loop is
running. Returning a list or dictionary of terminal tasks is sufficient;
there is no need to await each leaf separately.

Progress goes to standard error; pass `log=None` to silence it or a text stream
to redirect it. By default, an unrecoverable failure cancels other executing
tasks. Set `termination_policy="finish"` to let them finish before raising the
error. Ctrl-C cancels work under either policy.

Structured event logging is controlled separately by `structured_log`. Its
default, `"auto"`, writes a run-specific YAML file under the workspace,
compresses it at the end of the run, and prints the final `.yaml.zst` path as
`Logfile: <path>`. Pass `None` to disable structured logging, or pass a text
stream to write the YAML directly without creating a structured-log file; the
caller retains ownership of that stream.

### Inspecting a run

In the default `structured_log="auto"` mode, structured logs live in
`<workspace>/<module>/.wofl_logs/` and record task states, cache decisions,
retries, exceptions, and worker output. Completed logs are compressed YAML;
read the path printed after the run with `zstd -dc path/to/log.yaml.zst`.

To inspect the dependency graph leading to an output task, use its directory:

```sh
taskdir='work/pipeline/combine/<args_hash>'  # replace with the actual directory
python3 -m wofl show-dag "$taskdir"
python3 -m wofl show-dag "$taskdir" --out-fmt=tsv
```

The default YAML output includes a text timeline, task timings, cache status,
and input/output files. Dependency manifests are written before execution, so
failed runs can also be inspected. Worker stdout, stderr, and host/resource
diagnostics are in `<taskdir>/.wofl/worker/` as compressed files.

### Rerunning a task out of band

Run a previously dispatched task locally with its saved arguments:

```sh
python3 -m wofl run pipeline.py "$taskdir"
```

Use the existing directory, including its `.failed` suffix if present. This
executes the payload in place and writes `.wofl/worker/out.pkl.zst`; it bypasses
caching, retries, throttling, and scheduler submission, and does not refresh
the workflow cache. The local environment must provide the payload's tools.

Failed tasks retain a source snapshot under `.wofl/worker/source/`, which
takes precedence over the supplied pipeline file. Successful tasks remove that
snapshot and use the available source when rerun. For normal resumption of
cached tasks, run the workflow again and let cache validation select the tasks
to execute.

### Inspecting task inputs and outputs

`inspect-pickle` renders saved values as JSON:

```sh
python3 -m wofl inspect-pickle "$taskdir/.wofl/worker/inp.pkl.zst"
python3 -m wofl inspect-pickle "$taskdir/.wofl/worker/out.pkl.zst"
python3 -m wofl inspect-pickle "$taskdir/.wofl/cache.pkl.zst"
```

These contain the saved `(args, kwargs)`, the worker result or exception, and
the cache record respectively. File outputs remain in the task directory.

### Remote execution

Set `executor` to a command prefix; task bodies and dependency wiring stay the
same:

| Execution target | `executor` |
| --- | --- |
| Local process (default) | `"local"` |
| SSH | `"ssh user@host"` |
| Slurm / SGE | `"srun"`, `"sbatch"` / `"qrsh"`, `"qsub"` |
| LSF / Flux / HTCondor | `"bsub"` / `"flux"` / `"condor_submit"` |
| AWS Batch / ECS | `"aws batch submit-job ..."` / `"aws ecs run-task ..."` |
| GCP Batch / Cloud Run Jobs | `"gcloud batch jobs submit ..."` / `"gcloud run jobs execute ..."` |

Executor strings can include scheduler or provider flags. Common resource
options are `cpus`, `gpus`, `mem_mb`, `queue`, and `timeout` (seconds per
attempt, excluding queue wait). Options can be computed from arguments and the
zero-based attempt number:

```python
@wofl.retry(delay=lambda _attempt: 30 if _attempt <= 2 else None)
@wofl.task(
    executor="sbatch",
    cpus=8,
    mem_mb=lambda _attempt: 4096 * 2 ** _attempt,
    timeout=1800,
)
def align(input_file: Path) -> Path:
    ...
```

`executor`, resource options, and backend-specific keyword arguments accept
synchronous callbacks selecting payload arguments by name. They are evaluated
once per attempt before cache lookup. Resource requests go to the scheduler;
configure the tool itself to use the requested CPUs or GPUs.

HPC jobs expect a shared filesystem. SSH also uses shared paths by default;
set `remote_cwd="/scratch"` to stage the task and its input files to that host.
Cloud jobs require a writable `staging_url`, such as `"s3://bucket/wofl/"` or
`"gs://bucket/wofl/"`, and the provider's submission flags and credentials on
the submitting host.

wofl ships its module and a snapshot of the task's Python source. Workers need
Python 3.11+, `zstd`, and the payload's packages and command-line tools;
installing wofl on workers is unnecessary. Staged SSH execution also needs
Bash and tar; cloud images additionally need curl 7.71+. Cloud transfers use
signed URLs, so worker images do not need cloud CLIs or credentials for staging.
Pass data files as `Path` arguments; package data is not shipped automatically.

### Containerization

The `python3` option accepts a full interpreter command, allowing tasks to run
through Docker, Apptainer, Singularity, or Conda:

```python
@wofl.cache(environment_fingerprint="my-image-sha256:...")
@wofl.task(
    executor="sbatch",
    python3="docker run --rm -v $PWD:$PWD my-image python3",
)
def process(input_file: Path) -> Path:
    ...
```

`$PWD` expands to the work root; mount it at the same absolute path and make
input paths outside it accessible too. The environment needs Python, `zstd`,
and the task's dependencies. Pin the environment and set
`environment_fingerprint` to its digest or lock-file hash so changes invalidate
cached results. The `python3` command controls execution only; changing it does
not invalidate the cache by itself. Cloud executors use the image configured
for the cloud job.

See [Running containerized workloads](docs/running_containerized_workloads.md)
for further examples.

## Comparison with other libraries

Related Python libraries include
[redun](https://insitro.github.io/redun/design.html), with lazy task expressions
and database-backed provenance;
[Pydra](https://nipype.github.io/pydra/explanation/hashing-caching.html), with
hashed task directories and file-aware caching; and
[Parsl](https://parsl.readthedocs.io/en/stable/userguide/workflows/workflow.html),
with futures and parallel Python workflows.

wofl combines eager `asyncio` tasks, persistent file-aware caching, and direct
job submission in one vendorable module. State lives in task directories and
logs, with no daemon or metadata database. It provides no web UI, recurring
schedule service, or worker-pool autoscaler. See the
[detailed comparison](docs/comparison_to_other_workflow_libs.md) for differences
in execution, persistence, and scope.

## Comparison with Nextflow

Both support cached, parallel scientific pipelines with cluster and cloud
execution. Nextflow expresses work through
[processes](https://docs.seqera.io/nextflow/process) and
[workflows connected by channels](https://docs.seqera.io/nextflow/workflow).
wofl expresses it through Python functions and task results:

| Concern | Nextflow | wofl |
| --- | --- | --- |
| Task inputs and outputs | Process input/output declarations | Function arguments and return values; `Path` for files |
| Scatter and gather | Channels and operators | Loops, comprehensions, lists of tasks, and `await` |
| Execution policy | Directives and [configuration profiles](https://docs.seqera.io/nextflow/config#config-profiles) | Decorator options and reusable Python decorator functions |
| Workflow composition | Named workflows with `take` / `emit` | Async functions returning task results |

Compare the same protein-alignment pipeline in
[Python](examples/align_prots.py) and [Nextflow](examples/align_prots.nf).
The [feature comparison](docs/comparison_to_nextflow.md) maps further Nextflow
constructs to Python and describes facilities wofl omits.
