Skip to main content

orchestral

Orchestrate and execute shell commands, async coroutines, and sync Python functions in dependency-graph waves with pause, resume, and durable checkpointing.

PyPI version License PyPI - Python Version

Package orchestral
Version 0.4.0
Download https://pypi.org/project/orchestral/
Source https://github.com/adalundhe/orchestral
Keywords async, tasks, workflow, runner, graph, shell, jobs

Features

  • Unified task orchestration: Mix shell commands (add_command), async def coroutines, and synchronous Python callables (add_task) in the same workflow.
  • Dependency-graph wave execution: Declare step dependencies by name/alias, callable, or Step reference; orchestral validates the DAG (detecting missing dependencies and cycles upfront) and executes topologically sorted parallel waves.
  • Explicit sequential groups: Organize stages with workflow.group() when you want strict stage barriers, with optional intra-group or cross-group dependencies.
  • Suspension, resumption & durable checkpointing (powered by taskex >= 0.5.0):
    • Live await orch.pause() / await orch.resume() (and per-step pause_step() / resume_step()) across async tasks, thread-pool sync tasks, POSIX shell subprocesses (SIGSTOP/SIGCONT), and repeating schedules—with pause-aware timeouts.
    • Cooperative in-task checkpoint() / pause_point() / last_checkpoint() helpers (async & sync) plus external checkpoint inspection APIs.
    • Workflow-level & cross-process crash recovery with MemoryCheckpointStore, durable SQLiteCheckpointStore (via Env(MERCURY_SYNC_CHECKPOINT_DB_PATH=...) or explicit store), or custom sync/async CheckpointStore backends—skipping already-completed waves and resuming failed/cancelled steps from their latest checkpoint.
  • Streaming wave results: Consume each wave's results as it completes using async for batch in orch:.
  • Fail-fast & branch-aware failure handling: Under fail_fast=True, failures immediately cancel in-flight siblings and halt remaining waves; under fail_fast=False, independent branches continue while steps with failed explicit upstream dependencies are safely skipped (RunStatus.CANCELLED).
  • Timeouts at every level: Enforce deadlines on individual steps or the entire workflow using numbers (seconds) or duration strings ("500ms", "5s", "1m30s").
  • Safe process & resource lifecycle: Automatically terminates and reaps subprocesses (including child process groups on POSIX), shuts down executors cleanly, and supports async with, stop(), shutdown(), and abort().
  • Scheduled / repeating steps: Repeat individual steps on an interval with bounded history retention (COUNT, AGE, or COUNT_AND_AGE).

Installation

Requires Python 3.11+ and taskex >= 0.5.0.

pip install orchestral

Or with uv:

uv add orchestral

Quick Start

Dependency-graph (DAG) workflow

import asyncio
from orchestral import Orchestral


async def build() -> str:
    await asyncio.sleep(0.05)
    return "artifact.whl"


async def unit_tests() -> str:
    await asyncio.sleep(0.05)
    return "unit:ok"


async def integration_tests() -> str:
    await asyncio.sleep(0.05)
    return "integration:ok"


async def main() -> None:
    async with Orchestral() as orch:
        with orch as workflow:
            s_build = workflow.add_task(build)
            s_unit = workflow.add_task(unit_tests, dependencies=[s_build])
            s_int = workflow.add_task(integration_tests, dependencies=["build"])
            workflow.add_command(
                "echo",
                "deploying",
                alias="deploy",
                dependencies=[s_unit, s_int],
            )

        # Inspect planned parallel waves before running:
        # [["build"], ["unit_tests", "integration_tests"], ["deploy"]]
        print("Waves:", orch.execution_order())

        await orch.run(wait=True, fail_fast=True, timeout="30s")
        print("Status:", orch.status, f"({orch.elapsed:.3f}s)")


asyncio.run(main())

Checkpointing, live pause & crash recovery

import asyncio
from orchestral import (
    Env,
    Orchestral,
    SQLiteCheckpointStore,
    checkpoint,
    last_checkpoint,
    pause_point,
)


async def etl(items: list[str]) -> list[str]:
    prev = last_checkpoint()
    start_idx = prev.state["idx"] if prev else 0
    done = list(prev.state["done"]) if prev else []

    for i in range(start_idx, len(items)):
        await pause_point()
        done.append(items[i].upper())
        await checkpoint({"idx": i + 1, "done": done})

    return done


async def main() -> None:
    with SQLiteCheckpointStore("state/workflow.db") as store:
        async with Orchestral(
            config=Env(MERCURY_SYNC_EXECUTOR_TYPE="none"),
            checkpoint_store=store,
            workflow_id="daily-etl",
        ) as orch:
            with orch as wf:
                s1 = wf.add_command("echo", "ready", alias="preflight")
                wf.add_task(etl, ["a", "b", "c"], dependencies=[s1])

            await orch.run(wait=False, fail_fast=True)
            await orch.pause()              # Live suspend active steps & freeze timeout
            await orch.resume(wait=True)    # Live resume (or recover from SQLite after failure)


asyncio.run(main())

Explicit sequential groups

import asyncio
from orchestral import Env, Orchestral


async def fetch_greeting(name: str) -> str:
    await asyncio.sleep(0.05)
    return f"Hello, {name}!"


def compute_checksum(text: str) -> int:
    return sum(ord(ch) for ch in text)


async def main() -> None:
    config = Env(MERCURY_SYNC_EXECUTOR_TYPE="thread")

    async with Orchestral(config=config) as orch:
        with orch as workflow:
            # Group 1: runs concurrently
            prepare = workflow.group()
            prepare.add_command("echo", "starting pipeline", alias="banner")
            prepare.add_task(fetch_greeting, "orchestral", alias="greet")

            # Group 2: starts only after Group 1 finishes
            analyze = workflow.group()
            analyze.add_task(compute_checksum, "orchestral", alias="checksum")

        await orch.run(wait=True, fail_fast=True, timeout="30s")

        print("Status:", orch.status)
        for task_name, runs in orch.results.items():
            for run_id, result in runs.items():
                print(task_name, run_id, result.status, result.result)


asyncio.run(main())

Common Patterns

Non-blocking runs & streaming wave results

async with Orchestral() as orch:
    with orch as workflow:
        workflow.add_command("ls", alias="list_files")
        workflow.add_command("pwd", alias="working_dir")
        workflow.add_command(
            "echo",
            "done",
            alias="finish",
            dependencies=["list_files", "working_dir"],
        )

    await orch.run(wait=False)

    async for batch in orch:
        print("Completed wave:", [(r.task_name, r.status.value) for r in batch])

Explicit lifecycle management

If you prefer not to use async with, always call await orch.shutdown() (or synchronous orch.abort() in emergency teardown) when finished:

orch = Orchestral()
try:
    with orch as workflow:
        workflow.add_command("echo", "hello")
    await orch.run(wait=True)
finally:
    await orch.shutdown()

Error handling & fail_fast

  • Graph validation errors: Missing dependencies, forward references to later groups, and dependency cycles raise OrchestralGraphError / OrchestralCycleError before any step runs.
  • fail_fast=False (default): Individual failures are recorded on their TaskRun / ShellProcess entries in orch.results with status == RunStatus.FAILED. Steps that explicitly depend on a failed upstream step are skipped (RunStatus.CANCELLED), while independent branches continue to run.
  • fail_fast=True: The first failed step immediately cancels remaining in-flight siblings in the current wave, skips subsequent waves, records the completed results from the failing wave, sets orch.status = WorkflowStatus.FAILED, and populates orch.error with an OrchestralTaskFailure (and orch.trace with the traceback).

Executor configuration

Synchronous functions passed to add_task() run in either a ProcessPoolExecutor (default), a ThreadPoolExecutor, or the default loop executor ("none"), configured via taskex.Env:

from orchestral import Env, Orchestral

# Use threads for closures, lambdas, bound methods, or sync checkpointing/pause
orch = Orchestral(
    config=Env(
        MERCURY_SYNC_EXECUTOR_TYPE="thread",
        MERCURY_SYNC_TASK_RUNNER_MAX_THREADS=4,
        MERCURY_SYNC_CHECKPOINT_DB_PATH="./state/checkpoints.db",
    )
)

Note: When using "process" mode, sync callables and arguments must be picklable, and in-task ContextVar checkpoint/pause helpers require "thread" or "none" mode. Pure shell and async workflows never spawn a sync executor when config is omitted.

Documentation

Detailed guides and API reference live in docs/:

Runnable examples are available in examples/:

Development & Testing

uv venv --python 3.13
uv pip install -r requirements.txt pytest pytest-asyncio
PYTHONPATH=. .venv/bin/pytest -v tests/

License

MIT — see LICENSE.

Metadata

Release files for orchestral 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for orchestral 0.4.0
File Size Uploaded Provenance Actions
orchestral-0.4.0.tar.gz 43.0 kB Without provenance Details for orchestral-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for orchestral 0.4.0
File Interpreter ABI Platform Actions
orchestral-0.4.0-py3-none-any.whl Python 3 none any Details for orchestral-0.4.0-py3-none-any.whl

Total release size: 71.9 kB

Release files / orchestral-0.4.0.tar.gz

Download URL orchestral-0.4.0.tar.gz
Size 43.0 kB
Tags Source
SHA-256 checksum
How to use checksums
24dac2694285bc0348d17d31cb36e8753cbb750452cf81bf956855b29d8178ce
BLAKE2b-256 checksum
How to use checksums
9234d6f2b27875c5d53ecf89177c5c09f61d58b639cff07d8f198b6d9d0c76d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / orchestral-0.4.0-py3-none-any.whl

Download URL orchestral-0.4.0-py3-none-any.whl
Size 28.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cf333208b7306b0f3dd657746fc92654665ede0e33cf2ac9ee70ad9f8842f17b
BLAKE2b-256 checksum
How to use checksums
9f4f7c73d74c819b0ee260f1279c2e357e4114e98063121371a8b6746780f28f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for orchestral 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page