Metadata-Version: 2.4
Name: wofl
Version: 0.4.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 caching, parallel tasks, retries, resource limits, and remote
execution to ordinary Python functions. It is a lightweight alternative to a
workflow DSL: workflow logic stays in Python, and each feature is enabled with
a small, composable decorator.

- Write and test regular Python functions.
- Resumable execution with persistent caching.
- Express task dependencies by passing return values to other tasks.
- Run the same task locally, over SSH, on an HPC scheduler, or in a cloud job.
- Inspect the executions post-mortem with structured logs.
- Use command-line tools without making shell scripts your workflow language.

See the [complete protein-alignment pipeline](examples/align_prots.py), the
[container guide](docs/running_containerized_workloads.md), or the
[Nextflow comparison](docs/comparison_to_nextflow.md) for larger examples.

## Contents

- [Installation](#installation)
- [Quick start](#quick-start)
- [run_cmd](#run_cmd)
- [open_cmd](#open_cmd)
- [@retry](#retry)
- [@cache](#cache)
- [@throttle](#throttle)
- [@task](#task)
- [run_workflow](#run_workflow)
- [Composing decorators](#composing-decorators)
- [Inspecting a run](#inspecting-a-run)
- [Comparisons with other workflow libraries](#comparisons-with-other-workflow-libraries)

## Installation

wofl requires Python 3.11 or newer and a POSIX system. It has no required
Python package dependencies. The `zstd` command-line program is required for
the default `@cache` and `@task` behavior.

Install from PyPI:

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

To use the current GitHub version:

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

wofl is a single public-domain module, so you can also vendor `src/wofl.py`
directly in a project.

## Quick start

Start with the example closest to your use case:

- [Persistent cache demo](examples/persistent_cache_demo.py) adds caching and
  an isolated working directory to ordinary synchronous functions.
- [Async task demo](examples/async_task_demo.py) builds a parallel task graph
  with dependencies, persistent caching, logs, and DAG inspection.

Run either script twice from the repository root to see cached results reused:

```sh
PYTHONPATH=src python3 examples/persistent_cache_demo.py
PYTHONPATH=src python3 examples/async_task_demo.py
```

Use `@cache()` when a function should remain synchronous. Use `@task()` when it
should be scheduled concurrently, run in an isolated process, or dispatched
remotely; enter a task workflow through `run_workflow()`.

## run_cmd

`run_cmd()` runs a command, checks its exit status, and raises
`subprocess.CalledProcessError` on failure. An argument list works on every
supported Python version and does not invoke a shell:

```python
from pathlib import Path

import wofl


def count_lines(input_file: Path) -> None:
    wofl.run_cmd(["wc", "-l", str(input_file)])
```

A string command without `shell=True` is split with `shlex.split`. On Python
3.14 or newer, t-strings keep interpolated values safely quoted as individual
arguments:

```python
wofl.run_cmd(t"seqkit stats {input_file} -o {output_file}")
```

Remaining keyword arguments are forwarded to `subprocess.run`, and `check=True`
is applied by default; an explicit `check` takes priority.

If a command genuinely requires shell syntax, opt into strict Bash explicitly:

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

`strict_bash` runs the command with Bash after prepending this header:

```bash
set -Eeu -o pipefail -o noclobber
shopt -s inherit_errexit 2>/dev/null || true
export LC_ALL=C LANG=C
IFS=$'\n\t'
```

The header enables early failure for command, pipeline, unset-variable, and
overwrite errors; propagates `errexit` into subshells; uses a deterministic
locale; and restricts field splitting to newlines and tabs. Prefer argument
lists, t-strings, or connected `open_cmd()` calls when shell features are not
needed.

## open_cmd

`open_cmd()` opens the stdout of a command as if it were a file. It yields the
`subprocess.Popen` object, pipes stdout by default, decodes text by default,
and is the way to connect processes without `shell=True`:

```python
with (
    wofl.open_cmd(["esearch", "-db", db, "-query", query]) as esearch,
    wofl.open_cmd(
        ["efetch", "-format", "uid"],
        stdin=esearch.stdout,
    ) as efetch,
):
    uids = [int(uid) for uid in efetch.stdout if uid.strip()]
```

`ok_retcodes` lists accepted exit statuses (default `(0,)`) so expected
non-zero exits such as `grep` finding nothing can be tolerated; a command
killed by SIGPIPE is always accepted. If the context body exits while the
command is still running, the command is terminated (SIGTERM, escalating to
SIGKILL) instead of blocking on its output pipes, and no error is raised for
that abort. When the body itself fails, its exception remains primary and the
child failure is attached as a note.

Commands can also read and write each other through bash-style process
substitution. A `/dev/fd/N` path in the command line is passed to the child
and resolves to that pipe end, so a shell-free `diff` of two filtered files
looks like this:

```python
with (
    wofl.open_cmd("grep x file1", ok_retcodes=(0, 1)) as left,
    wofl.open_cmd("grep y file2", ok_retcodes=(0, 1)) as right,
    wofl.open_cmd(
        f"diff -u /dev/fd/{left.stdout.fileno()} /dev/fd/{right.stdout.fileno()}",
        ok_retcodes=(0, 1),
    ) as diff_cmd,
):
    print(diff_cmd.stdout.read())
```

Like `run_cmd`, `open_cmd` recognizes `shell=True, executable="strict_bash"`
and prepends the strict-Bash header.

## @retry

`@retry` retries idempotent work. This example retries connection and timeout
failures three times with exponential backoff:

```python
import wofl


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

The first retry is `_attempt == 1`. The callback may also select payload
arguments by name and inspect the failure through `_error`. Return a
non-negative delay in seconds, `0` to retry immediately, or `None` to stop.
With no arguments, the decorator retries once after one second. Fatal process
exceptions such as `KeyboardInterrupt`, `MemoryError`, `SystemExit`,
`GeneratorExit`, and `RecursionError` are never passed to `delay` or retried;
`OSError` subclasses such as `ConnectionError` and `TimeoutError` are.

## @cache

`@cache` runs a function in a task-specific directory and persists its result
in `{workspace_root}/{module_name}/{task_func_name}/{taskrun_args_hash}/.wofl/cache.pkl.zst`. 

```python
import time
from pathlib import Path

import wofl

@wofl.cache(workspace_root="./work")
def do_useful_work(inp: Path) -> Path:
    time.sleep(5)
    out = Path("./out.txt")
    out.touch()
    return out

```

While the task-dir lock is held, the directory is renamed with a
`.running.{execution_id}` suffix. It is renamed back on success or given a
`.failed` suffix on failure. A temporary `./tmp` directory is created before
execution and removed after success; it is preserved on failure for debugging.

The payload runs with the task directory as cwd only around synchronous calls
(the event loop never chdirs across an await). Relative `Path` arguments and
returned `Path` objects are rebased across that boundary.

Options:

- `workspace_root`: where task directories are stored; the default is
  `./work`.
- `expires_in`: maximum cache age in seconds. Use `0` to always run while
  keeping task-directory isolation.
- `environment_fingerprint`: a stable container digest, lock-file hash,
  module set, or tool version. Change it when external tools change.
- `clear_taskdir=False`: retain existing payload files on an uncached run.
- `ignore_file_meta=True`: always validate file content rather than reusing a
  checksum based on unchanged size and modification time.

Cache validation covers, and invalidates on, changes to the function source,
referenced globals, current captured closure values, transitively referenced
functions, and files referenced as `Path` objects in args, kwargs, and return
values. The args-hash includes bound arguments and defaults, current closure
values, and the caller's current directory when an argument contains a
relative `Path`. Pass an otherwise unused argument to represent external state
that should select a different task directory; function source is validated
separately. Files passed as `Path` arguments are tracked by content, and
directory paths are hashed recursively (ignoring `.wofl/`). External
directories containing more than 1000 objects produce a warning. Arguments
and results must be picklable.

If data in a file is sort-agnostic and the order is non-deterministic, make it
deterministic by sorting it in the upstream task. A `<file>.wofl_checksum`
sidecar written by the producing task takes precedence over hashing the file's
contents, so a task whose outputs carry non-deterministic metadata can
normalize its own checksum. When a result depends on external state, make that
state visible to the cache: pass a version as a normal argument, set
`expires_in`, or provide an `environment_fingerprint`.

The [persistent cache demo](examples/persistent_cache_demo.py) shows cached
scalar and file results, including how input and output paths remain valid
while the function runs in its task directory.

## @throttle

`throttle` creates a reusable concurrency-limiting decorator factory. Calls
decorated through the same factory share its capacity. Both `slots` and
`capacity` default to one, so the simplest form serializes calls:

```python
throttle_database = wofl.throttle()

@throttle_database()
def update_database(record):
    ...
```

Set a larger capacity for bounded parallelism, or use `min_delay` to rate-limit
starts:

```python
throttle_api = wofl.throttle(capacity=10, min_delay=0.1)

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

For weighted resources, each call can acquire more than one slot. `slots` may
also be computed from the function arguments:

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

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

Each call to `wofl.throttle` creates an independent limiter;
reuse its returned factory wherever calls should share capacity or invocation spacing.

## @task

`@task` decorator-factory is used to define asynchronous pipelines
where tasks execute in parallel (similar to Make, Snakemake, Nextflow, etc.)

Calls return eagerly scheduled `asyncio.Task` objects, and the executor defaults to
`"local"`, which runs the payload as an isolated local subprocess. 

`@task`s are implicitly `@cache`d.

Define the workflow in an async function, and invoke it with wofl.run_workflow.

See [async task demo](examples/async_task_demo.py).

### Executors

Set `executor` to a command prefix to select the execution backend:

- local isolated processes: `local` (the default)
- SSH: `ssh user@host`
- Slurm: `srun`, `sbatch`
- SGE: `qrsh`, `qsub`
- LSF, Flux, and HTCondor: `bsub`, `flux`, `condor_submit`
- AWS Batch: `aws batch submit-job`
- AWS ECS: `aws ecs run-task`
- GCP Batch: `gcloud batch jobs submit`
- GCP Cloud Run Jobs: `gcloud run jobs execute`

The workflow itself does not otherwise change:

```python
from pathlib import Path

import wofl


@wofl.task(
    executor="sbatch",
    cpus=8,
    mem_mb=16384,
    queue="compute",
    timeout=1800,
)
def align(input_file: Path, database: Path) -> Path:
    output = Path("alignments.tsv")
    wofl.run_cmd(
        [
            "diamond", "blastp",
            "--query", str(input_file),
            "--db", str(database),
            "--out", str(output),
            "--threads", "8",
        ]
    )
    return output


if __name__ == "__main__":
    result = wofl.run_workflow(lambda: align(Path("input.fa"), Path("db.dmnd")))
```

`executor`, `timeout`, `cpus`, `gpus`, `mem_mb`, `queue`, `remote_cwd`,
`python3`, and `staging_url` use the same interface across schedulers. Each
resource option may be a callable that derives a value from the task's
arguments, evaluated once per attempt before cache lookup. Combined with
`@retry`, `timeout` applies to each attempt and resource callables can escalate
using `_attempt`, which is `0` for the initial execution and increases for each
retry:

```python
@wofl.retry(delay=lambda _attempt: 30 if _attempt <= 3 else None)
@wofl.task(
    executor="qsub -m n -V",
    timeout=300,
    mem_mb=lambda fasta, _attempt: min(
        32768,
        (1024 if fasta.stat().st_size < 1_000_000 else 8192) * 2**_attempt,
    ),
)
def align_batch(fasta: Path, database: Path) -> Path:
    ...
```

`timeout` is a per-attempt payload deadline in seconds; queue waiting time is
outside this deadline. Schedulers with native time limits (SGE, Slurm, LSF,
Flux) receive `timeout` plus 60 seconds for worker startup and error reporting,
rounded up to the scheduler's time resolution. Without a timeout, no native
limit is added. Scheduler-specific flags already present in `executor` are
preserved, and backend-specific keyword arguments are forwarded through
`executor_kwargs`.

`@task` may be reapplied to preserve omitted options; passing `None` explicitly
clears an inherited nullable option. Cache identity uses the resolved backend's
interpreter: retries may change placement and resources, but cannot change this
execution environment.

### Payloads

Task functions must be synchronous, module-level functions in a readable `.py`
file, and their arguments and results must be picklable. Keep workflow startup
behind `if __name__ == "__main__"` so importing the module on a worker does not
start it again. Avoid import-time side effects, and pass data files as `Path`
arguments rather than relying on package data. Prefer built-in Python values
and `Path` objects for results; write large or custom-format results to files
and return their paths.

### Task directories

Eager tasks publish `.wofl/deps.txt` before the payload runs, recording their
direct dependencies, so failed and interrupted runs keep a recoverable
manifest. After a task starts, its handle exposes the absolute directory as
`call.task_dir`. Task-directory layout, lifecycle, and `Path` rebasing are
described in [@cache](#cache).

### Remote execution

By default, HPC jobs use the shared filesystem and the current Python
interpreter. Use `python3` to select a remote interpreter or a containerized
Python command, and `remote_cwd` when the shared working directory differs.
Cloud jobs use a writable S3 or GCS `staging_url` to exchange task files. The
submission host signs short-lived download and upload URLs; cloud worker images
do not need AWS or GCP command-line tools or credentials. The upload must begin
within 12 hours of submission (and possibly sooner when temporary credentials
expire). See
[Running containerized workloads](docs/running_containerized_workloads.md) for
Docker, Singularity, Apptainer, and Conda examples.

Remote hosts need Python 3.11 or newer and `zstd`; staged SSH and cloud hosts
also need Bash and tar, and cloud hosts need curl 7.71 or newer for staged
workdir transfers. wofl itself only needs to be installed on the submission
host. Install application dependencies and command-line tools in the worker
environment.

Remote task source is sent with the job. Remote payloads travel as importable
source modules under `{taskdir}/.wofl/worker/`: module-level functions or
methods in a `.py` source file, plus same-file helpers and referenced local
modules under the task file's tree. Args and kwargs are pickled next to
`wofl.py` and deserialized by the worker.

Remote dispatch is non-blocking: staging subprocesses are offloaded to a thread
pool, and remote-job completion is interrogated without blocking, so many
remote tasks can run concurrently on a single event loop. Cloud submissions
leave a small job receipt beside the task directory after the provider accepts
them. Re-executing the same logical task with the same executor tries to poll
that job and collect its staged result instead of submitting another. This is
only an opportunistic recovery attempt: it does not fingerprint code or
inputs, and a crash before the receipt is written can still leave an
unreconciled job.

## run_workflow

`run_workflow()` runs an awaitable or a zero-argument factory that creates one.
Use a factory to create a root task inside the event loop:

```python
result = wofl.run_workflow(lambda: align(Path("input.fa"), Path("db.dmnd")))
```

Task calls inside the workflow are dispatched from the caller's event loop, as
described in [@task](#task). Tasks nested in the workflow result are
materialized before returning, so workflows may return terminal task graphs
without awaiting each leaf:

```python
@wofl.task()
def produce() -> int:
    return 42


async def workflow():
    call = produce()
    return {"values": [call, (call,)]}


assert wofl.run_workflow(workflow()) == {"values": [42, (42,)]}
```

`run_workflow()` prints task progress to standard error. Pass `log=None` to
silence it or another text stream to redirect it:

```python
result = wofl.run_workflow(workflow(), log=None)
```

By default, the first unrecoverable failure cancels other executing tasks. Use
`termination_policy="finish"` to let already-running work finish before the
error is raised:

```python
result = wofl.run_workflow(workflow(), termination_policy="finish")
```

Ctrl-C cancels executing work under both policies.

## Composing decorators

Decorator order does not change execution. wofl merges the settings from
`@cache`, `@retry`, throttle factories, and `@task` into one task
configuration. This makes reusable stacks straightforward:

```python
throttle_remote_jobs = wofl.throttle(capacity=100)

def remote_task(function):
    function = wofl.task(executor="qsub", mem_mb=4096)(function)
    function = throttle_remote_jobs()(function)
    return function


@remote_task
def analyze_sample(sample: Path) -> Path:
    ...
```

`@cache`, `@retry`, and decorators created by `throttle` can also decorate
ordinary synchronous functions without `@task`.

## Inspecting a run

Each workflow writes a structured log under
`<workspace>/<module>/.wofl_logs/`. It contains task state, cache decisions,
dependencies, retries, remote submissions, exceptions, and captured worker
output.

Every task records its direct dependencies. Recover the graph rooted at a task
directory with:

```sh
python3 -m wofl show-dag ./work/<module>/<function>/<args_hash>
python3 -m wofl show-dag ./work/<module>/<function>/<args_hash> --out-fmt=tsv
python3 -m wofl inspect-pickle ./work/<module>/<function>/<args_hash>/.wofl/worker/inp.pkl.zst
```

The [async task demo](examples/async_task_demo.py) includes representative log
and `show-dag` output for its parallel workflow.

## Comparisons with other workflow libraries

wofl occupies the intersection of four kinds of tool: a Python task-graph
library, a content-aware build cache with an isolated directory for every call,
an HPC and cloud job launcher, and a small collection of independently usable
execution decorators.

- [Comparison with other workflow libraries](docs/comparison_to_other_workflow_libs.md)
  compares programming and execution models with Nextflow, Snakemake, Airflow,
  Dagster, and others.
- [Nextflow facilities wofl intentionally omits](docs/comparison_to_nextflow.md)
  walks through the Nextflow grammar wofl does not ship and shows the
  Python-native equivalent for channel factories and operators, process
  qualifiers, and directives.
