Metadata-Version: 2.4
Name: wofl
Version: 0.3.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 is a lightweight, Python-native alternative to heavyweight workflow engines
such as Nextflow or Snakemake. The goal is to express entire pipelines in
regular Python while keeping caching, task isolation, retries, and remote
execution primitives close at hand, and keep the API minimal-and-sufficient.

[Full pipeline example](examples/align_prots.py)

## Table of Contents

- [Why use wofl?](#why-use-wofl)
- [Running shell pipelines safely from Python](#running-shell-pipelines-safely-from-python)
  - [Process substitution without a shell](#process-substitution-without-a-shell)
- [Network failures and transient errors](#network-failures-and-transient-errors)
- [Persistent caching/memoization](#persistent-cachingmemoization)
- [Execution graph recovery](#execution-graph-recovery)
- [Parallel task execution with dependencies](#parallel-task-execution-with-dependencies)
  - [`@task`: caching in an isolated task directory](#task-caching-in-an-isolated-task-directory)
- [Scatter-gather workloads](#scatter-gather-workloads)
- [Running tasks on HPC clusters or remote servers](#running-tasks-on-hpc-clusters-or-remote-servers)
- [Throttled execution (resource limits)](#throttled-execution-resource-limits)
- [Wall-time resource requirements](#wall-time-resource-requirements)
- [Running containerized workloads (Docker / Singularity / Apptainer / Conda)](docs/running_containerized_workloads.md)
- [Decorator composition](#decorator-composition)
- [Full pipeline example](examples/align_prots.py)
- [Nextflow facilities wofl omits (facility-by-facility mapping)](docs/comparison_to_nextflow.md)
- [Installation](#installation)

## Why use wofl?

- **Plain Python instead of a framework DSL.** `wofl` decorates functions rather
  than taking over your pipeline, so your debugger, type checker, tests, and IDE
  still see ordinary code. Adopt it one function at a time, with no migration
  project.
- **No business logic buried in bash strings.** Task bodies stay Python, while
  command-line tools still compose into UNIX pipelines. You keep shell power
  without making the shell your workflow language.
- **Safer by construction.** Common pipelines do not need a shell; when one is
  unavoidable, quoting and strict execution stay explicit.
- **Errors you can actually debug.** Failures surface as ordinary Python
  exceptions, locally or remotely, and remote jobs return the context needed to
  diagnose them. You debug your code, not an opaque workflow runtime.
- **Caching that understands your inputs.** Finished work survives reruns.
  Changes to task code or tracked file inputs invalidate affected results
  automatically.
- **Parallelism without a new mental model.** Build static and dynamic
  scatter-gather workflows from awaitable task calls and ordinary async helpers instead
  of learning a channel grammar.
- **One decorator takes you remote.** Develop and debug a function locally, then
  run the same task body on a cluster or cloud job.
- **Zero required Python package dependencies.** Install or vendor one
  public-domain module built on the Python standard library wherever your
  pipeline runs.
- **A tiny API you can hold in your head.** A few composable decorators add
  caching, task isolation, retries, resource limits, or remote execution to
  existing functions, so you adopt only what you need.

## Running shell pipelines safely from Python
**Use-case:** pipe commands together (e.g., `cmd1 | cmd2`) but avoid subprocess with `shell=True`.

**Solution:** Use the `wofl.open_cmd()` context manager to compose command
pipelines.

For one command, use `wofl.run_cmd()`. It checks the exit status and accepts
the same string or argv command forms as `open_cmd()`; Python 3.14+ t-strings
also quote interpolated values automatically.

```python
wofl.run_cmd(t"seqkit split --force -s {batch_size} -O ./out {fasta}")
```

With ordinary strings and f-strings, quote each interpolated value with `qw()`
so that it remains one command argument.

```python
import wofl
from wofl import qw

def eutils_fetch_uids(db: str, query: str) -> list[int]:
    """Pipe esearch output to efetch, returning UIDs."""
    with (
        wofl.open_cmd(f"esearch -db {qw(db)} -query {qw(query)}") as esearch,
        wofl.open_cmd("efetch -format uid", stdin=esearch.stdout) as efetch,
    ):
        return [int(uid) for uid in efetch.stdout if uid.strip()]
```

### Process substitution without a shell
Bash process-substitutions `<(cmd)` and `>(cmd)` can be expressed by referencing
the sub-processes `stdin` or `stdout` as `/dev/fd/{my_proc.stdout.fileno()}`.
Note: Unlike the silent process-substitution failures in bash, if a subprocess fails,
the `CalledProcessError` exception is raised.

```python
# Equivalent of: diff -u <(grep x file1) <(grep y file2)
with (
    wofl.open_cmd(f"grep x {qw(file1)}", ok_retcodes=(0, 1)) as sub1,
    wofl.open_cmd(f"grep y {qw(file2)}", ok_retcodes=(0, 1)) as sub2,
    wofl.open_cmd(
        f"diff -u /dev/fd/{sub1.stdout.fileno()} /dev/fd/{sub2.stdout.fileno()}",
        ok_retcodes=(0, 1),
    ) as diff,
):
    print(diff.stdout.read())

# Equivalent of: seq 1000 | tee >(gzip > out.gz) | wc -l
import subprocess

with (
    open("out.gz", "wb") as out_gz,
    wofl.open_cmd("gzip", stdin=subprocess.PIPE, stdout=out_gz) as gz,
    wofl.open_cmd("seq 1000") as producer,
    wofl.open_cmd(
        ["tee", f"/dev/fd/{gz.stdin.fileno()}"],
        stdin=producer.stdout,
    ) as tee,
    wofl.open_cmd("wc -l", stdin=tee.stdout) as wc,
):
    print(wc.stdout.read())
```

**Strict-bash mode**

If you ever do need a shell for something `open_cmd` can't express, pass
`shell=True, executable="strict_bash"` to `open_cmd` or `from_cmd`
to execute with the following bash header prepended.
```bash
set -Eeu -o pipefail -o noclobber             # strict errors: ERR trap, exit on error, unset vars, pipe failures, no-overwrite with '>'
shopt -s inherit_errexit 2>/dev/null || true  # propagate -e into subshells and pipelines
export LC_ALL=C LANG=C                        # deterministic locale
IFS=$'\n\t'                                   # safe field splitting
```

```python
import wofl
from wofl import qw

def eutils_fetch_uids(db: str, query: str) -> list[int]:
    out = wofl.from_cmd(
        f"esearch -db {qw(db)} -query {qw(query)} | efetch -format uid",
        shell=True,
        executable="strict_bash",
    )
    return [int(uid) for uid in out.splitlines() if uid.strip()]
```
---

## Network failures and transient errors
**Use-case:** function non-deterministically fails due to network issues, API rate limits, or temporary service unavailability.

**Solution:** Use `@retry_on_exception` decorator.
```python
import asyncio

from wofl import retry_on_exception

@retry_on_exception(
    delay=lambda attempt: 2 ** attempt if attempt < 5 else None,
    condition=lambda e: isinstance(e, (ConnectionError, TimeoutError))
)
def fetch_remote_data(url: str) -> str:
    return requests.get(url, timeout=5).text

data = asyncio.run(fetch_remote_data("https://example.com/data"))
```

The retry policy is governed entirely by two arguments:

- `delay: (attempt) -> seconds`: sleep before attempt `attempt` (1 = first
  retry). Return `None`/`False` to stop retrying; `0` means no delay.
  **Default: retry exactly once, after 5 seconds.**
- `condition: (exception) -> bool`: which exceptions are retryable (default:
  all). `KeyboardInterrupt`, `MemoryError`, `SystemExit`, `GeneratorExit`,
  `RecursionError` are never retried; `OSError` subclasses (`ConnectionError`,
  `TimeoutError`) are retried when `condition` permits.
- `remote_options`: resource-escalation ladder for `@remote` jobs. The first
  attempt uses the resources on `@remote`; retry `k` overlays
  `remote_options[k-1]` (repeating the last entry once the list is exhausted):
  ```python
  @retry_on_exception(
      delay=lambda n: 30 if n <= 3 else None,
      remote_options=[{"mem_mb": 8192}, {"mem_mb": 32768}],
  )
  @remote("qsub -m n -V", mem_mb=1024)
  def align_batch(fasta: Path, db: Path) -> Path:
      ...
  ```

---

## Persistent caching/memoization
**Use-case:** `@functools.cache`-like functionality, but for the cache to be persistent across script re-runs.

**Solution:** Use `@workspace` and `@cached` to cache results with automatic invalidation:
```python
import asyncio

from wofl import cached, workspace
from pathlib import Path

@workspace(root="./work")
@cached
def uppercase_file(input_file: Path) -> Path:
    output = Path("result.txt")
    output.write_text(input_file.read_text().upper())
    return output

output = asyncio.run(uppercase_file(Path("input.txt")))
```
`@workspace`
- Creates a directory `task_dir = {workspace}/{module}/{function}/{args_hash}/` and runs synchronous payload code from it. Async workflow and decorator code uses the task directory without holding a process-global CWD across an await.
- `clear_dir=True` removes payload files before uncached calls and cache misses; cache hits preserve them. Set it to `False` to keep existing payload files.
- A task call publishes `.wofl/deps.txt` before the payload runs, so failed
  and interrupted runs keep a recoverable dependency manifest.
- It also creates `./tmp` in the taskdir and deletes it afterward. Transient work files should go there.
- An inter-process lock prevents identical task runs from using the same task directory concurrently.
- Any relative `Path`s in the input args are rebased to be valid within the taskdir.
- Upon return, any relative `Path`s in the return-value are rebased relative to the original CWD.

Equivalent calls share a task directory regardless of positional/keyword
syntax, explicit defaults, or set ordering.

`@cached` memoizes the function-call in `{task_dir}/.wofl/cache.pkl.zst`, containing
- function source and wofl version hash
- execution identity: Python command/version and an optional environment fingerprint
- metadata and content-hashes of input files passed as `Path` in function's args
- invocation's start and stop timestamps
- serialized function's return value

The cache is automatically invalidated by:
- source code changes, detected via code digest (including the source of
  referenced top-level functions, current closure values, and referenced
  globals, transitively)
- a changed wofl version
- a changed Python command/version or `environment_fingerprint`
- input file(s) modifications, detected via mtime and content hash. Directory
  Paths are hashed recursively (ignoring `.wofl/`), but only task-directories
  and directories inside them are accepted. External directories are
  deliberately rejected, so a stray `Path("/")` cannot trigger hashing an
  entire filesystem. Use `ignore_file_meta=True` for strict content checks.
- cache expiration, if specified with `@cached(expires_in=...)` (e.g. if the function access a remote file or makes a db query)

When hashing an input file, a producer-provided checksum sidecar takes
precedence over hashing the file's contents: if `<file>.wofl_checksum` exists,
its first whitespace-separated token is used as the file's checksum. A task
whose outputs carry non-deterministic metadata (e.g. timestamps a tool embeds
in the file) should write such a sidecar next to each such output, so that
downstream tasks fingerprint the normalized checksum instead of the raw bytes.
The sidecar is trusted unconditionally, so producers must keep it in sync with
the file.

External tools, containers, Conda environments, and module sets are not
inspected automatically. Declare them with one stable cache identity on
`@cached` or `@remote`:

```python
@wofl.cached(environment_fingerprint="container-sha256:...")
@wofl.task
def analyze():
    ...
```

Use a container digest, lock-file hash, loaded-module set, or tool fingerprint.
Queue names, memory requests, and other submission settings do not affect this
identity. Pass external directory or remote-data identities as ordinary task
arguments. Closure values are hashed when each call starts, so changes made
between calls invalidate the previous cache identity.

## Execution graph recovery

Each task writes its direct dependencies to
`{task_dir}/.wofl/deps.txt`. A task call nested in an argument creates an edge
automatically. During recovery, an input `Path` inside another task directory
also creates an edge to that task.

Use `show-dag` to recover the graph rooted at a published task directory:

```sh
python -m wofl show-dag ./work/<module>/<function>/<args_hash>
python -m wofl show-dag ./work/<module>/<function>/<args_hash> --out-fmt=tsv
```

After a call starts, `call.task_dir` contains its absolute task-directory path.
The default YAML output contains the dependency forest and task metadata,
including cached input and output files, timestamps, and cache-hit status. The
TSV output contains one `task`/`parent-task` edge per line.

## Parallel task execution with dependencies
**Use-case:** multiple tasks with dependencies that you want to execute in parallel, like with `make -j4`

**Solution:** Build an async workflow from eagerly scheduled task calls. Calls
nested in a downstream argument are resolved before the downstream payload.

```python
import asyncio
import time

import wofl

@wofl.cached(expires_in=0)
@wofl.task
def t_process_chunk(data: str) -> str:
    time.sleep(1)  # stand-in for synchronous work
    return data.upper()

@wofl.cached(expires_in=0)
@wofl.task
def t_join_results(chunks: list[str]) -> str:
    return " | ".join(chunks)

async def workflow() -> asyncio.Task[str]:
    chunks = [
        t_process_chunk("hello"),
        t_process_chunk("world"),
    ]
    return t_join_results(chunks)

output = wofl.run_workflow(workflow())
print(output)  # "HELLO | WORLD" (both chunks processed in parallel)
```


### `@task`: caching in an isolated task directory

`@task`-decorated function calls return eagerly scheduled `asyncio.Task`
objects. Calls must therefore be made inside a running event loop. `@task`
automatically composes `@cached`, `@workspace`, and
`@remote(submit_cmd="local")`; a shared task can be awaited more than once.

At a synchronous program boundary, `wofl.run_workflow(awaitable)` awaits a workflow
call and materializes task objects nested in its result. Pass a zero-argument
factory to create a root task inside the event loop. Every task runs as an
isolated local subprocess
(`wofl.py run`) dispatched from the caller's event loop, so any number of
tasks can run concurrently - bound their concurrency with `@throttled`.
Because payloads execute as shipped subprocesses, they must be module-level
functions defined in readable `.py` source files, and their args and results
must be picklable.

Await a task inside a workflow when Python needs its value for control flow,
such as iteration. Otherwise, return terminal task handles and let `wofl.run_workflow()`
materialize them.

```python
from pathlib import Path

import wofl
from wofl import task

@task
def t_getfasta(ids: list[int]) -> Path:
    prots_fa = Path("prots.fa")
    ids_txt = "\n".join(map(str, ids))
    prots_fa.write_text(ids_txt)
    return prots_fa

ids = [1, 2, 3]
path_to_fasta = wofl.run_workflow(lambda: t_getfasta(ids))

```
This creates the output file in `{work_root}/{module}/{function}/{args_hash}/prots.fa`.
As mentioned above `@workspace` context-manager rebases the return-path to be relative
to the original directory upon return.

---

## Scatter-gather workloads
**Use-case:** A large input that's more efficient to split into chunks, process in parallel, then combine.

**Solution:** Keep scatter logic in a plain async workflow helper. Paths returned
by the split task identify that dependency after its batch list is materialized.

```python
import asyncio
import os
from pathlib import Path

import wofl
from wofl import qw

@wofl.task  # aligns single batch, producing a .hits file.
def t_align_prots(fasta: Path, db: Path) -> Path:
    hits_path = Path(fasta.stem).with_suffix(".hits")
    wofl.run_cmd(
        f"time diamond blastp --query {qw(fasta)} --db {qw(db)} --out {qw(hits_path)} "
        "--fast --threads 32 --header simple --quiet "
        "--outfmt 6 qseqid qlen qcovhsp sseqid slen scovhsp pident"
    )
    return hits_path

@wofl.task  # splits input fasta into batches of specified size
def t_split_fasta(fasta: Path, batch_size=10000) -> list[Path]:
    wofl.run_cmd(f"seqkit split --force -s {qw(batch_size)} -O ./out {qw(fasta)}")
    return [
        Path(f"./out/{fa}")
        for fa in os.listdir("out")
        if str(fa).endswith(".fa")
    ]

@wofl.task  # combines the results from all batches into one file.
def t_gather_results(paths: list[Path]) -> Path:
    combined_path = Path("combined.hits")
    combined_path.write_bytes(b"".join(path.read_bytes() for path in paths))
    return combined_path

async def workflow() -> asyncio.Task[Path]:
    batches = await t_split_fasta(fasta=fasta_path)
    hits = [
        t_align_prots(batch, db_path)
        for batch in batches
    ]
    return t_gather_results(hits)

combined_hits_result: Path = wofl.run_workflow(workflow())
```

---

## Running tasks on HPC clusters or remote servers
**Use-case:** orchestrate and dispatch long-running tasks to an HPC cluster (Slurm, SGE) or remote server, or on the cloud.

**Solution:** Use `@remote` to have the wrapped function execute on HPC schedulers or SSH:

```python
import wofl

run_on_sge_1gig = wofl.remote(
    submit_cmd="qrsh -m n -V -l mem_free=1G",
    python3="/opt/python-all/bin/python3"  # or e.g. "singularity exec ... /path/in/container/bin/python3"
)                                          # to execute with docker/singularity/apptainer, etc.

@wofl.task
@run_on_sge_1gig
def foo(i: int) -> str:
    import socket
    print(f"Hello from {socket.gethostname()}!")
    open("out_file.txt", "w").write("hello\n")
    return str(i)

assert wofl.run_workflow(lambda: foo(42)) == "42"
```

```sh
>>time python3 remote_example.py
Hello from sge12345!

real 0m3.377s
user 0m0.086s
sys  0m0.050s
```

The second execution returns quickly, prints the structured log path, and
returns the cached value.
```sh
>>time python3 remote_example.py
real 0m0.129s
user 0m0.071s
sys  0m0.019s
```

```
>>tree -a ./work
./work
`-- remote_example
    `-- foo
        `-- 9afe8dd7da54e50ae64c26798a5ed5d4551476ef
            |-- .wofl
            |   |-- cache.pkl.zst
            |   |-- deps.txt
            |   `-- worker_node
            |       |-- host.info.json
            |       |-- host.meminfo.txt
            |       |-- host.rusage.json
            |       |-- host.ps.txt
            |       |-- inp.pkl.zst
            |       |-- out.pkl.zst
            |       |-- stderr.zst
            |       |-- stdout.zst
            |       |-- task.json
            |       |-- wofl.py
            |       `-- _task_payload.py
            `-- out_file.txt
```

`@remote` ships the task to the remote host as an importable source module:
the function's own `.py` source file is copied into the worker directory as
`_task_payload.py`, the arguments are pickled to `inp.pkl.zst`, and a `task.json`
records the module, qualified name, sys.path, interpreter command, and payload
time budget. The
remote host starts `wofl.py run-supervised`, which re-executes the payload
under the recorded interpreter as `wofl.py run`; the local backend (`submit_cmd="local"`)
spawns that same `wofl.py run` directly, without the `run-supervised`
supervisor process, so tasks run as isolated, individually debuggable local
processes. The worker imports the module,
resolves the function, runs it, and pickles the return value (or the raised
exception, with a remote-host traceback) back into `out.pkl.zst`. The approach
is similar to Nextflow's `.command.run` and `.command.sh`; `out.pkl.zst` is the
equivalent of Nextflow's `.exitcode`, and the exception is re-raised locally
with the full remote backtrace.

Nextflow decouples the cluster configuration from the pipeline definition.
Equivalently, the `@remote` parameters need not be hardcoded, and instead
come from some config-dictionary backed by some yaml-file, or however you desire.
```py
remote_smallhost = wofl.remote(
    submit_cmd=remote_config["sge"]["small"],
    python3=remote_config["apptainer-run-command"] + " python3 -B",
)

@wofl.task
@remote_smallhost
def my_task(i: int) -> str:
    ...
```

Dispatch is coordinated on the caller's event loop. SSH and blocking HPC
launchers are awaited asynchronously; detached HPC and cloud completion are
interval-polled, with blocking status and file operations run in threads. A
Many `@task @remote` calls can be in flight concurrently from one event loop.

Resource requirements and backend `submit_kwargs`, such as
`container_overrides_json`, may be callables taking the payload's own
arguments. They are evaluated per call at dispatch, so requirements can depend on the inputs -
Nextflow's `memory { ... }` / `queue { ... }` closures and Snakemake's
`resources: mem_mb=lambda wildcards: ...`:

```python
@wofl.task
@wofl.remote(
    "qsub",
    mem_mb=lambda reads: 1024 if len(reads) < 1e6 else 8192,
)
def align(reads, db):
    ...
```

The callable receives the payload's arguments by name - only the ones it
declares (`def sub(**kw)` receives everything; defaults are applied) - with
dependencies already resolved; see `examples/dynamic_resources.py`.

`@remote` maps `cpus`, `gpus`, `mem_mb`, `queue`, and `timeout` to the native
requirements of its selected backend. Switching schedulers changes
`submit_cmd`, not the resource interface. Existing arguments in `submit_cmd`
are preserved; do not also spell the same resource as a manual scheduler flag.
For SGE, `-pe PE_NAME 1` is the exception: Wofl replaces `1` with `cpus`.
Without that placeholder, Wofl selects a common PE name reported by `qconf`,
or asks for an explicit PE when none is available.
GCP Cloud Run CPU and memory resources are properties of the deployed job and
cannot change for each execution.

Task payloads must be module-level functions (or methods) defined in a `.py`
source file; nested functions, lambdas, and decorated functions are rejected
before submission, and the source file must import without unwanted side
effects (guard a script's entry point with `if __name__ == "__main__"`).
Payload functions must use `def`; `async def` payloads are rejected before
submission. The whole source file ships, so same-file module-level helpers,
classes, and constants are available on the worker. Local helper modules the
task references (functions, classes, and modules whose source lives under the
task file's directory tree) are also shipped, preserving their relative layout,
so sibling modules and subpackages import on the worker too. Imports from
outside that directory tree must be importable on the remote host. Arguments
are pickled to `inp.pkl.zst` and deserialized on the worker, so any picklable
argument works (scalars, `Path`s, containers, numpy arrays, custom classes,
etc.); heavy-weight inputs should still be passed as files.

The return value is unpickled on the submitting host with a restricted
unpickler, so results must be Python-native too (arguments' types, plus
`datetime`/`Decimal`/`UUID`/`os.stat_result` and built-in exceptions).
Custom classes - dataclasses, numpy arrays, enums - can't be returned;
convert them to native types (e.g. `tuple(x.tolist())`) at the end of the
remote function, or serialize to file(s) and return as `Path`.

To run on the cloud, `remote()` takes the path to the writable S3 or GCS bucket,
which is used as intermediate storage to exchange the input and output files between
the local and remote environments, which happens behind the scenes.

For containerized workloads on HPC, provide the containerized python3 interpreter.

Supported remote backends:
```
- Local          : local (no scheduler or supervisor process: `wofl.py run` is spawned directly)
- SSH           : ssh user@host
- HPC schedulers: srun, sbatch, qrsh, qsub, bsub, flux, condor_submit
- AWS Batch     : aws batch submit-job --job-queue Q --job-definition D
- AWS ECS       : aws ecs run-task --cluster C --task-definition T
- GCP Batch     : gcloud batch jobs submit --location L
- GCP Cloud Run : gcloud run jobs execute JOB --region R
```

For Cloud Run, configure Bash as the deployed job's container command. Wofl
passes the remote script to that command as `-c <script>`.

---

## Throttled execution (resource limits)

`@throttled` bounds how many tasks consuming a shared resource run concurrently -
GPUs, memory, remote job slots, etc. It also limits `@remote` tasks, which run
on the event loop.

Specify the resource capacity when you first use `@throttled`:

```python
import wofl

@wofl.task
@wofl.throttled(resource="gpu", slots=2, capacity=4)
def train_model(config):
    ...
```

`slots` units are acquired atomically for the duration of the call and released on
return, so at most `capacity // slots` such tasks run at once. Later decorators for
the same resource can omit `capacity`. Repeating the same capacity has no effect;
a different capacity raises an error during decoration.

---

## Wall-time resource requirements

Use `@task(timeout=...)` for the per-attempt payload deadline. The local
launcher enforces it directly; SSH, HPC, and cloud workers enforce it in
supervised mode. A `TimeoutError` can therefore participate in the normal
retry policy.

Use `@remote(timeout=...)` for the outer native scheduler allocation limit.
Both values are seconds. When both are present, the remote limit must be
greater so the worker has time to publish the payload's structured timeout.

```python
import wofl

@wofl.task(timeout=300)
@wofl.retry_on_exception(
    delay=lambda n: 60 if n <= 2 else None,  # up to 3 attempts, 60s apart
)
@wofl.remote("sbatch", timeout=360)
def long_running():
    ...
```

SGE (`qsub`/`qrsh`), Slurm (`srun`/`sbatch`), LSF (`bsub`), and Flux support
the native `@remote` limit. Local, SSH, cloud, and HTCondor do not accept a
remote limit; use `@task(timeout=...)`, which the local launcher or worker
supervisor enforces. Each retry gets a fresh task deadline and scheduler
allocation.

---

## Decorator composition

The execution decorators merge their options into one option set per function,
so their application order is irrelevant: decorating an already-decorated
function updates the matching options in place. Every call runs one fixed
pipeline - `@workspace`, `@cached`, `@throttled`, `@retry_on_exception`,
`@remote` (or the inline payload) - no matter how the decorators are written.

```python
import sys
from pathlib import Path

from wofl import (
    cached,
    compose,
    workspace,
    remote,
    retry_on_exception,
    task,
    throttled,
)

@workspace(root="./task-work", clear_dir=False)
@cached(expires_in=3600)
@task
@throttled(
    resource="banana",  # block until at least two bananas are available,
    slots=2,            # and atomically acquire for the duration of the
    capacity=4,         # function execution; at most four are shared.
)
@retry_on_exception(
    delay=lambda attempt: min(30, 2 ** attempt) if attempt < 5 else None,
    condition=lambda exc: isinstance(exc, (ConnectionError, TimeoutError)),
    remote_options=[{"mem_mb": 8192}, {"mem_mb": 32768}],
)
@remote(
    "qsub -m n -V",
    mem_mb=1024,
    python3=sys.executable,
)
def align_batch(fasta: Path, db: Path) -> Path:
    ...
```

Repeated applications update the specified keyword arguments in place, so
re-applying a decorator outside `@task` configures its constituent layer:

```python
@cached
@task
def select_nonrepresentative_ids(hits_paths: list[Path]) -> list[str]:
    ...
```

A task producing files with non-deterministic metadata can normalize their
checksums for downstream tasks by writing a sidecar next to each output:

```python
@remote_task
def t_align_prots(fasta: Path, db: Path) -> Path:
    hits = Path(fasta.stem).with_suffix(".hits")
    wofl.run_cmd(f"diamond blastp --query {qw(fasta)} --db {qw(db)} --out {qw(hits)} ...")

    with hits.open("a", encoding="utf-8") as output:
        output.write(f"#{datetime.datetime.now()}")  # nondeterministic metadata

    # Downstream fingerprinting uses this sidecar instead of hashing the bytes.
    Path(f"{hits}.wofl_checksum").write_text(
        wofl.from_cmd(
            f"grep -Pv '^#' {qw(hits)} | sha1sum",
            shell=True,
            executable="strict_bash",
        ),
        encoding="utf-8",
    )
    return hits
```

Repeated `@throttled` decorators with the same `resource` update that
resource's entry, while distinct resources coexist.

Use `compose` to define a reusable decorator stack:

```python
remote_task = compose(
    task,
    throttled(resource="remote_jobs", capacity=100),
    remote(submit_cmd="qsub -m n -V -l mem_free=1G"),
)
```

Each use creates fresh decorator options.

`@cached`, `@workspace`, `@remote`, `@retry_on_exception`, and `@throttled`
create async functions. `@task` eagerly creates an `asyncio.Task`; await it or
pass it as an argument to another task. At a synchronous boundary,
`wofl.run_workflow(awaitable)` awaits a workflow call or a zero-argument awaitable
factory in a new event loop, then materializes wofl tasks nested in the result.

`wofl.run_workflow(..., termination_policy=...)` selects what a failing task does to the
rest of the run: `"cancel"` (default) cancels all executing work; `"finish"`
lets executing work finish without starting new tasks. The run raises the
failure under both policies; it also raises failures from eager tasks whose
outcomes were not observed. Ctrl-C cancels executing work under both policies.

---

## Nextflow facilities wofl omits

Coming from Nextflow? [docs/comparison_to_nextflow.md](docs/comparison_to_nextflow.md)
maps the channel grammar, operators, and process directives onto plain Python
and wofl decorators, facility by facility.

---

## Installation

wofl has no required Python package dependencies. It requires Python 3.11 or
newer and a POSIX host.

Install the `zstd` command-line executable before you use the default
`@cached` or `@task` behavior. Staged SSH and cloud runs also require Bash and
tar on the submission and remote hosts.

wofl writes one structured execution log per run to
`{work_dir}/{module}/.wofl_logs/{timestamp}.yaml`. The path is printed to stdout
when the first task is created, so the YAML list can be watched while the task runs. On
completion it is atomically compressed to `{timestamp}.yaml.zst`. Records include
host metadata, per-task execution identities, task creation and dependency
edges, cache decisions, lifecycle state, retry and remote-submission details,
exceptions, and captured worker stdout/stderr as YAML block literals.

`enable_logging()` remains available for human-readable progress on stderr (pass
`file=` to write elsewhere), or configure the `"wofl"` logger yourself:

```python
import wofl
wofl.enable_logging()  # optional; shows task lifecycle and cache-hit progress on stderr
```

Install from PyPI:

```sh
pip install wofl
```

Or, if you use uv:
```sh
uv add wofl
```

Install directly from GitHub:

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

Or, if you use uv:
```sh
uv add git+https://github.com/ast-al/wofl.git
```

Or with the following shebang in your `pipeline.py`
```python
#!/usr/bin/env -S uv run --with git+https://github.com/ast-al/wofl.git
```

Note: for `@remote` runs, wofl only needs to be installed on the
submission host (where you launch the workflow). Remote hosts need Python 3.11
or newer and `zstd`; staged SSH and cloud hosts also need Bash and tar. wofl
ships `wofl.py` (with `run-supervised` and `run` worker commands) alongside the
payload source file,
so nothing needs to be installed on the remote host.

Alternatively, since the library is a single module and public-domain licensed
(CC0-1.0), you can copy `src/wofl.py` directly into your project and vendor it,
if you prefer to avoid a dependency.
