A Python 3.12+ library for defining and executing typed DAG task workflows with Pydantic models, lifecycle hooks, and fail-fast semantics.
For an agent-friendly, runnable YAML example with validation and troubleshooting steps, see the agent quickstart.
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"from pydantic import BaseModel
from taskmaestro import Task, Workflow, Job, Runner, ExecutionContext
class NumberInput(BaseModel):
value: int
class NumberOutput(BaseModel):
value: int
class AddOne(Task[NumberInput, NumberOutput]):
def run(self, input: NumberInput, ctx: ExecutionContext) -> NumberOutput:
return NumberOutput(value=input.value + 1)
class Double(Task[NumberOutput, NumberOutput]):
def run(self, input: NumberOutput, ctx: ExecutionContext) -> NumberOutput:
return NumberOutput(value=input.value * 2)
workflow = Workflow(name="math", tasks=[AddOne, Double])
job = Job(workflow=workflow, config=NumberInput(value=5))
result = Runner().run(job)
print(result.status) # "completed"
print(result.result.value) # 12from pydantic import BaseModel
from taskmaestro import Task, Workflow, Job, Runner, ExecutionContext
class Input(BaseModel):
value: int
class Output(BaseModel):
value: int
class MergedInput(BaseModel):
a: Output
b: Output
class MergedOutput(BaseModel):
total: int
class BranchA(Task[Input, Output]):
def run(self, input: Input, ctx: ExecutionContext) -> Output:
return Output(value=input.value + 1)
class BranchB(Task[Input, Output]):
def run(self, input: Input, ctx: ExecutionContext) -> Output:
return Output(value=input.value * 2)
class Merge(Task[MergedInput, MergedOutput]):
def run(self, input: MergedInput, ctx: ExecutionContext) -> MergedOutput:
return MergedOutput(total=input.a.value + input.b.value)
workflow = (
Workflow.builder(name="fan_in")
.add_task(BranchA)
.add_task(BranchB)
.add_task(Merge, depends_on={"a": BranchA, "b": BranchB})
.build()
)
job = Job(workflow=workflow, config=Input(value=5))
result = Runner().run(job)
print(result.status) # "completed"
print(result.result.total) # 16 (6 + 10)You define Tasks (typed units of work), compose them into a Workflow (linear chain or DAG), bind input data via a Job, and hand it to a Runner for execution. Type safety is enforced at build time — input/output models are validated across the entire graph. Fail-fast semantics stop execution on the first error, and Hooks provide cross-cutting lifecycle observations without coupling to task logic.
| Concept | Description |
|---|---|
| Task | Subclass Task[I, O] with Pydantic models for input and output, then implement run(input, ctx). Each task can declare an optional timeout_seconds. For tasks with multiple named outputs, use inline Inputs/Outputs classes inside the task body. |
| Workflow | Build a linear pipeline with Workflow(tasks=[...]) or a DAG with Workflow.builder(). Prefer builder.task() and task handles for unambiguous dependencies; the fluent add_task() API remains supported. The builder accepts collect() for gathering outputs into collection fields and mapped_over=TaskMap(...) for sequential expansion over configured mappings. Use config_fields to declare which input fields come from JobConfiguration. Workflows are validated at build time for cycles, type compatibility, and input completeness. |
| Job | Binds a Workflow to a typed config (the root task's input). Tracks status (pending → running → completed/failed), the final result, any error, and per-task task_results. Optionally accepts a JobConfiguration for per-task static config values. A job can only be run once. |
| Runner | Executes tasks in topological order, stopping on the first failure (fail-fast). Supports per-task and per-job timeouts via signal.alarm (Unix only). Dispatches lifecycle events to registered hooks. |
| ExecutionContext | Passed to every run() call. Provides a logger, an auto-generated correlation_id (UUID), a scratch_dir (temporary directory), and a service registry (register()/resolve()) for injecting shared resources like DB connections. |
| Hooks | Subclass BaseHook and override methods like on_job_start, on_task_complete, etc. Hook errors are swallowed and reported via warnings.warn(), so they never crash the job. Built-ins: LoggingHook, TimingHook, ResultPersistenceHook. |
| ObjectModel | Generic ObjectModel[T] base model for wrapping arbitrary (non-Pydantic) objects. Enables arbitrary_types_allowed so fields can hold native library objects like database connections or API clients. |
For common cases, run a workflow directly without constructing Job and Runner:
result = workflow.run(
Input(value=5),
task_config={"configured_task": {"option": "value"}},
hooks=[LoggingHook()],
)The explicit Job and Runner API remains available for advanced lifecycle control.
builder.task() adds a task and returns a handle to that specific instance. Handles avoid ambiguous class and string references, especially when the same task class is registered more than once:
builder = Workflow.builder(name="parallel_wells")
model = builder.task(LoadModel)
well_1 = builder.task(LoadWellPath, name="well_1", depends_on=model)
well_2 = builder.task(LoadWellPath, name="well_2", depends_on=model)
builder.task(Process, name="proc_1", depends_on=well_1)
builder.task(Process, name="proc_2", depends_on=well_2)
workflow = builder.build()Use handle.field("field_name") to route one output field. Named input dependencies can be passed directly to task(), while keyword arguments to collect() provide a concise keyed collection:
merged = builder.task(
MergeResults,
primary=producer.field("result"),
checks=collect(tests=tests, lint=lint, types=types),
)
builder.set_result_task(merged)Handles are accepted anywhere dependency references are accepted. A handle from a different builder is rejected. Use the depends_on dictionary form when an input field conflicts with a reserved builder argument such as name or config_fields. The existing fluent add_task() API remains fully supported for backward compatibility.
The same Task class can appear multiple times in a workflow with different names. With the fluent API, use the name= parameter in add_task():
workflow = (
Workflow.builder(name="parallel_wells")
.add_task(LoadModel)
.add_task(LoadWellPath, name="well_1", depends_on=LoadModel)
.add_task(LoadWellPath, name="well_2", depends_on=LoadModel)
.add_task(Process, name="proc_1", depends_on="well_1")
.add_task(Process, name="proc_2", depends_on="well_2")
.build()
)Named instances can be referenced as string dependencies (depends_on="well_1") or in fan-in dicts.
JobConfiguration provides static config values for individual tasks, merged with upstream outputs at runtime. Declare which fields come from config with config_fields:
from taskmaestro import EmptyConfig, Job, JobConfiguration, Workflow
workflow = (
Workflow.builder(name="configured")
.add_task(LoadModel, config_fields=["path"]) # root: all input from config
.add_task(Transform, depends_on=LoadModel, config_fields=["scale_factor"]) # mixed
.build()
)
job_config = JobConfiguration(
{
"load_model": {"path": "/data/model.egrid"},
"transform": {"scale_factor": 2.5},
}
)
job = Job(workflow=workflow, config=EmptyConfig(), job_configuration=job_config)
result = Runner().run(job)Every declared config field, on root, dependent and mapped tasks alike, must have a value in the JobConfiguration; otherwise Job(...) raises WorkflowDefinitionError.
A workflow can be wrapped as a typed task and used inside a larger workflow. Its input type is inferred from its root task and its output type from its result task, so normal workflow type validation still applies at both boundaries:
inner = Workflow(name="normalize", tasks=[CleanText, NormalizeText])
Normalize = inner.as_task(name="normalize_text")
outer = (
Workflow.builder("document_pipeline")
.add_task(LoadDocument)
.add_task(Normalize, depends_on=LoadDocument)
.add_task(IndexDocument, depends_on=Normalize)
.build()
)workflow_task(inner, name="normalize_text") is the equivalent factory-style API.
The inner workflow must have exactly one root that receives input from the outer
workflow. Roots supplied entirely by JobConfiguration are excluded; if every root is
configured, pass that configuration to as_task() and the wrapper accepts
EmptyConfig:
ConfiguredPipeline = inner.as_task(
name="configured_pipeline",
job_configuration=inner_config,
)The inner tasks share the outer ExecutionContext, including services, scratch directory,
and correlation ID. The wrapper is an opaque lifecycle boundary: outer runner hooks and
Job.task_results see one wrapper task, while an inner failure is reported with the inner
workflow and failed task names. Mermaid visualization expands wrappers as subgraphs.
Route a specific field from an upstream task's output (rather than the whole output) using (Task, "field") tuples:
class ExtractKeywords(Task):
class Inputs(BaseModel):
content: TextContent
class Outputs(BaseModel):
keywords: KeywordsOutput
num_words_removed: int
def run(self, input: Inputs, ctx: ExecutionContext) -> Outputs: ...
workflow = (
Workflow.builder(name="analysis")
.add_task(ExtractKeywords, depends_on=PrepareText)
.add_task(
BuildReport,
depends_on={
"keywords": (ExtractKeywords, "keywords"), # routes .keywords field
"num_words_removed": (
ExtractKeywords,
"num_words_removed",
), # routes .num_words_removed
"stats": ComputeWordStats, # whole output
},
)
.build()
)Use collect() when several task outputs should populate one list[T] or
dict[str, T] field. Positional members preserve declaration order:
from taskmaestro import collect
class GridInput(BaseModel):
surfaces: list[Surface]
workflow = (
Workflow.builder("create_grid")
.add_task(LoadSurface, name="top")
.add_task(GenerateSurface, name="middle")
.add_task(LoadSurface, name="base")
.add_task(
CreateGrid,
depends_on={"surfaces": collect("top", "middle", "base")},
)
.build()
)Use a mapping to preserve aliases in a dict[str, T], and use (task, "field")
to collect a specific output field:
depends_on={
"surfaces": collect({
"top": ("top_loader", "surface"),
"base": ("base_loader", "surface"),
})
}The equivalent YAML forms are:
depends_on:
surfaces:
collect:
- top
- [middle, generated_surface]
- basedepends_on:
surfaces:
collect:
top: [top_loader, surface]
base: [base_loader, surface]Every member is checked against the field's element type when the workflow is
built. Subtypes are accepted. collect() and collect({}) explicitly create
empty list and dictionary inputs, respectively.
A member that produces a list[T] or dict[str, T] (for example a mapped
task's output) is flattened into a list collection of T, in declaration
order. A dictionary contributes its values in insertion order and its keys
are dropped. A whole mapped-task output is flattened through its root
dictionary, so no [task, root] reference is needed:
depends_on:
perforations:
collect:
- add_perf_1 # PerforationOutput -> one item
- [batch_perforations, perforations] # dict[str, PerforationOutput] -> values
- mapped_perforation # mapped task -> one item per map keyIn a keyed collection (dict[str, T] field), a dict[str, T] member is merged
in with its own keys; its alias is not used as a key. If two members supply the
same key, the task fails with CollectionKeyConflictError. List members are
rejected in keyed collections.
A member whose value already matches the element type is always added as one
item. So a list[dict[str, T]] field still receives each dictionary whole.
Only one level is flattened.
A mapped task invokes one task declaration for every entry in a configured
mapping. Mapped items execute sequentially in mapping declaration order.
Each item gets a fresh task instance and child ExecutionContext.
builder = Workflow.builder("create_grid")
connection = builder.task(ConnectToResInsight)
surfaces = builder.map_task(
LoadRegularSurface,
name="load_surfaces",
depends_on={"resinsight": connection},
config_fields=["unit"],
over="surfaces",
key_as="surface_name",
value_as="path",
error_mode="fail_fast",
)
builder.task(CreateGrid, depends_on={"surfaces": surfaces})
workflow = builder.build()The mapped task's input model contains the injected key and value fields, not the source mapping:
class LoadSurfaceInput(BaseModel):
resinsight: RipsInstance
unit: str
surface_name: str # key_as
path: str # value_asConfigure the source through JobConfiguration:
job_configuration = JobConfiguration({
"load_surfaces": {
"unit": "meters",
"surfaces": {
"top": "/data/top.irap",
"base": "/data/base.irap",
},
},
})The logical output is a MappedOutput[O] Pydantic root model containing an
insertion-ordered dict[str, O], where O is the task's declared output type.
When a mapped task is connected to a named dict[str, O] input field, its
root value is unwrapped automatically:
class CreateGridInput(BaseModel):
surfaces: dict[str, RegularSurface]The equivalent YAML task declaration is:
- task: resinsight.load_regular_surface
name: load_surfaces
map:
over: surfaces
key_as: surface_name
value_as: path
error_mode: fail_fast
depends_on:
resinsight: resinsight.connect
config_fields: [unit]Input YAML:
load_surfaces:
unit: meters
surfaces:
top: /data/top.irap
base: /data/base.irapfail_fast stops at the first failed item. collect_all attempts every item
and reports an aggregate MappedTaskExecutionError. An empty mapping succeeds
with MappedOutput(root={}). Per-item records are available in
job.mapped_item_results, and
built-in logging, timing, and persistence hooks observe individual items.
Concurrent mapped execution is intentionally deferred.
A workflow can choose between branches at run time. A switch task returns a
branch label; downstream tasks are guarded with when= and run only when their
guard matches. Tasks whose guard does not match are skipped, not failed.
from typing import Literal
from taskmaestro import ConditionTask, SwitchTask, Workflow, first_of
class ChooseShipping(SwitchTask[Parcel, Literal["express", "freight", "standard"]]):
def decide(self, input: Parcel, ctx: ExecutionContext) -> Literal["express", "freight", "standard"]:
return "freight" if input.weight_kg > 100 else "standard"
builder = Workflow.builder("shipping")
parcel = builder.task(LoadParcel)
method = builder.task(ChooseShipping, depends_on=parcel)
express = builder.task(ExpressShipping, depends_on=parcel, when=method.on("express"))
freight = builder.task(FreightShipping, depends_on=parcel, when=method.on("freight"))
standard = builder.task(StandardShipping, depends_on=parcel, when=method.otherwise())
builder.task(PrintLabel, parcel=parcel, shipment=first_of(express, freight, standard))-
SwitchTask[I, L]: implementdecide()and return a label of typeL, aLiteral[...]or anEnum. The task output is aBranchmodel with abranchfield. -
ConditionTask[I]is a switch with the labelsTrue/False; guard withhandle.if_true()andhandle.if_false(). -
handle.on(*labels)runs a task for any of the labels.handle.otherwise()runs it for every label that noon()guard claims. -
Any output field can be a guard too:
when(handle.field("kind"), equals=...),in_=[...]ortruthy=True|False(truthy/falsy needs aboolor optional field; a non-bool value counts as truthy when it is notNone, so0or""still count as set). Guard values are validated strictly against the field type:"no"or1is not accepted for aboolfield, while the string value of an enum member is. Shorthands:handle.field("kind").equals(...),.is_in(...),.truthy(),.falsy(). -
first_of(a, b, ...)joins branches: the input gets the output of the first listed member that ran. -
ContextFlagis a ready-made condition on the execution context: it isTruewhen the context value registered under its configuredkeyis truthy.Runner.runraisesContextValueMissingError(aWorkflowDefinitionError) before any task runs if a configured key is not registered. Flags in nested workflows (workflow_task) and in branches that may be skipped are checked as well. ThetaskmaestroCLI does not register context values, so it reports such workflows as a configuration error.dry = builder.task(ContextFlag, name="dry_run", config_fields=["key"]) builder.task(Deploy, depends_on=data, when=dry.if_false()) # job configuration: {"dry_run": {"key": "dry_run"}} ctx.register("dry_run", True)
-
Ready-made conditions, registered as task plugins so they show up in
taskmaestro tasks listand workflow editors (taskmaestro.condition_tasks):Task id Class Truewhencondition.compareComparevalue <op> threshold;opis one of<,<=,==,!=,>=(default),>condition.is_trueIsTruevalueis truthycondition.path_existsPathExistspathexists;kindmay require afileordirectory- task: condition.compare name: is_large depends_on: value: [pipeline.LoadOrder, amount] config_fields: [op, threshold] - task: pipeline.ManualReview depends_on: pipeline.LoadOrder when: {switch: is_large, case: true}
Validation happens at build time. Labels must belong to the switch's label
type, so typos are caught. Every label needs a guarded task or an
otherwise(). An otherwise() that can never match is an error. A switch with
no guarded tasks is an ordinary task.
At run time:
- A task is skipped when its guard does not match, when the guard's source was
skipped, when any plain dependency was skipped, or when every
first_ofmember was skipped. Skips propagate downstream. collect()leaves out skipped members.- Skipped tasks get a
TaskResultwithstatus=TaskStatus.SKIPPEDand askip_reason, and are listed injob.skipped_tasks. Hooks receiveon_task_skip(job, task_name, reason);on_task_startis not called for them. - If the result task is skipped, the job fails with
ResultTaskSkippedError.
In YAML:
- task: pipeline.ExpressShipping
depends_on: pipeline.LoadParcel
when: {switch: pipeline.ChooseShipping, case: express} # case may be a list
- task: pipeline.StandardShipping
depends_on: pipeline.LoadParcel
when: {switch: pipeline.ChooseShipping, otherwise: true}
- task: pipeline.Audit
depends_on: pipeline.LoadParcel
when: {ref: [pipeline.LoadParcel, priority], truthy: true} # or equals: / in: [...]
- task: pipeline.PrintLabel
depends_on:
parcel: pipeline.LoadParcel
shipment:
first_of: [pipeline.ExpressShipping, pipeline.StandardShipping]In Mermaid diagrams, switch tasks are diamonds and guards are dashed edges
labeled with their case (express, otherwise, true, .kind = a, ...).
first_of joins are drawn as rounded nodes.
ObjectModel[T] wraps arbitrary (non-Pydantic) objects so they can flow through workflows. Use it as a type alias for simple wrappers, or subclass it to add extra fields:
from taskmaestro import ObjectModel
# Type alias — no extra fields needed
GridCase = ObjectModel[rips.EclipseCase]
WellPath = ObjectModel[rips.WellPath]
# Subclass — adds fields alongside the wrapped object
class AddPerforationInput(ObjectModel[rips.WellPath]):
start_md: float
end_md: float
# Access the wrapped object via .value
grid = GridCase(value=eclipse_case)
print(grid.value.name)Installed packages can publish tasks and workflows using standard Python entry points:
[project.entry-points."taskmaestro.tasks"]
"acme.prepare" = "acme_tasks.prepare:Prepare"
[project.entry-points."taskmaestro.workflows"]
"acme.analysis" = "acme_tasks.workflows:analysis_workflow"A task entry point must resolve to a Task subclass and a workflow entry point must
resolve to a Workflow instance. Prefix names with the provider name to avoid clashes.
Consumers can discover plugins without scanning package directories:
from taskmaestro import registered_tasks, registered_workflows
tasks = registered_tasks() # dict[str, type[Task]]
workflows = registered_workflows() # dict[str, Workflow]Use registered_task_names() and registered_workflow_names() to inspect identifiers
without importing plugin modules, or get_registered_task(name) and
get_registered_workflow(name) to load one plugin. Duplicate names and invalid plugin
types raise PluginLoadError.
Agents can inspect installed task plugins from the CLI without loading every plugin:
taskmaestro tasks list --json
taskmaestro tasks describe acme.prepare --jsonlist --json emits {"tasks": ["acme.prepare", ...]} in sorted order; an empty list
means no task plugins are installed. describe --json loads only the named plugin
and emits its registered identifier, task name, timeout_seconds, and Pydantic
input_schema / output_schema (JSON Schema objects). These commands inspect
installed entry points, not task classes local to a workflow YAML file. Without
--json, list prints one identifier per line and describe prints indented JSON.
For runtime-only Python objects (such as ObjectModel[rips.EclipseCase]), schema
fields include "not": {}, "x-taskmaestro-opaque": true, and
"x-taskmaestro-python-type". They cannot be supplied as JSON; wire them from
upstream tasks or a Python context instead. Other unsupported schema constructs,
unknown identifiers, and invalid plugins report an error on stderr and exit with status 2.
Workflows can be defined entirely in YAML instead of Python. A task: value may be
either a registered task identifier or a dotted Python class path. The loader resolves
registered identifiers first and validates the full configuration:
# workflow.yaml
workflow:
name: text_analysis
tasks:
- task: pipeline.PrepareText
- task: pipeline.GenerateStopWords
- task: pipeline.ComputeWordStats
depends_on:
content: pipeline.PrepareText
stop_words: pipeline.GenerateStopWords
- task: pipeline.ExtractKeywords
depends_on:
content: pipeline.PrepareText
stop_words: pipeline.GenerateStopWords
- task: pipeline.ScoreReadability
depends_on: pipeline.PrepareText
- task: pipeline.BuildReport
depends_on:
stats: pipeline.ComputeWordStats
keywords: [pipeline.ExtractKeywords, keywords] # output field routing
readability: pipeline.ScoreReadability
num_words_removed: [pipeline.ExtractKeywords, num_words_removed] # output field routing
runner:
hooks:
- hook: taskmaestro.hooks.logging.LoggingHook
- hook: taskmaestro.hooks.timing.TimingHook
context:
services:
title: "Python Overview"# input.yaml
prepare_text:
text: "Python is a high-level programming language..."
title: "Python Overview"Load and run:
from taskmaestro import load_workflow_from_yaml, run_workflow_from_yaml
# Load for inspection, then run
loaded = load_workflow_from_yaml("workflow.yaml", "input.yaml")
result = loaded.run()
# Or run directly
result = run_workflow_from_yaml("workflow.yaml", "input.yaml")YAML input always uses per-task configuration: every top-level key in input.yaml must be a registered task instance name, and its value must be a mapping or null. Unknown task names and scalar task values are rejected. Fields are validated against the task's input model and can configure root tasks, downstream tasks, and mapped tasks.
YAML also supports named task instances (name:), fan-in dictionaries, and output field routing via [task, field] lists. Named instances use their instance name as the input key:
load_well_path_1:
path: first.dev
load_well_path_2:
path: second.devWhen the same task class (or the same inner YAML file) appears more than once under different name:s, depends_on and result_task must use the instance name — referencing the class path is rejected as ambiguous.
Use workflow: instead of task: to compose another YAML workflow. Paths are resolved
relative to the containing workflow file, and workflow_input: optionally supplies the
inner workflow's per-task configuration:
workflow:
name: document_pipeline
tasks:
- task: pipeline.LoadDocument
- workflow: normalize/workflow.yaml
workflow_input: normalize/input.yaml
name: normalize_text
depends_on: pipeline.LoadDocument
- task: pipeline.IndexDocument
depends_on: normalize_textThe same root/result type inference and single-unconfigured-root requirement apply as for
Workflow.as_task().
Two built-in tasks run user code without a Task class. Both run a subprocess and return
ScriptOutput (result, returncode, stdout, stderr):
| Task id | Runs | Main settings |
|---|---|---|
taskmaestro.python |
<current python> <script> <args...> |
script, args |
taskmaestro.command |
A string through the shell, or a list as an executable with arguments (no shell) | command |
Shared settings: inputs (upstream data), env (extra environment variables), cwd,
timeout (seconds; the process is killed) and check (default true: a nonzero exit
code fails the task with ScriptError, including the last lines of stderr). Absolute paths
are used as given; relative script and cwd paths resolve against the current directory
of the process running the workflow.
Data is exchanged through JSON files in a fresh directory under the scratch directory, deleted when the task finishes:
TASKMAESTRO_INPUT: path to a JSON object holdinginputs(set wheninputsis not empty).TASKMAESTRO_OUTPUT: path where the process may write a JSON value; it becomesresult.
inputs is a dict[str, Any], connected with a keyed collect so scripts always receive a
JSON object. Runtime-only objects (such as ObjectModel[rips.EclipseCase]) cannot be sent to a
process and fail the task; use a regular Task for those.
Their settings are ordinary input fields, given per task in input.yaml:
# workflow.yaml (tasks)
- task: taskmaestro.python
name: word_count
- task: taskmaestro.command
name: save_report
depends_on:
inputs:
collect: {counts: [word_count, result]}# input.yaml
word_count:
script: scripts/word_count.py
args: [data/sample.txt]
save_report:
command: sh scripts/save_report.sh
env: {REPORT_DIR: /tmp/reports}Downstream tasks can use a single field, e.g. depends_on: {path: [save_report, result]};
the downstream input model validates the value at run time. See
docs/script-tasks.md and examples/scripts/.
Generate Mermaid diagrams of workflow topology:
print(workflow.to_mermaid())
# or with config nodes:
print(workflow.to_mermaid(job_configuration=job_config))Output:
---
title: text_analysis
---
graph TD
_start_(("start"))
_end_(("end"))
prepare_text["prepare_text"]
generate_stop_words["generate_stop_words"]
compute_word_stats["compute_word_stats"]
build_report["build_report"]
_start_ -->|TextInput| prepare_text
_start_ -->|TextInput| generate_stop_words
prepare_text -->|content: TextContent| compute_word_stats
compute_word_stats -->|WordStatsOutput| build_report
build_report -->|AnalysisReport| _end_
Edges are labeled with data types. Fan-in edges show field names, and field routing edges show .field: Type. When a JobConfiguration is provided, configured tasks get dashed edges from a JobConfiguration node. Switch tasks are drawn as diamonds with dashed, labeled guard edges (see Conditional Branches).
WorkflowRunnerError (base)
├── WorkflowDefinitionError # Invalid workflow definition
│ ├── CycleDetectedError # Dependency cycle
│ └── IncompleteInputError # Missing fan-in field mappings
├── JobStateError # e.g., re-running a completed job
├── ConfigLoadError # YAML config loading failure
│ └── WorkflowLookupError # Unknown or broken registered workflow name
└── TaskExecutionError # Runtime task failure
├── MappedTaskExecutionError # One or more mapped items failed
├── ResultTaskSkippedError # The result task was skipped by a condition
├── ScriptError # A script/command task failed (returncode, stdout, stderr)
├── TaskOutputTypeError # Output type mismatch
└── TaskTimeoutError # Task exceeded timeout
Installed packages provide a taskmaestro command for YAML and registered workflows:
taskmaestro validate workflow.yaml --input input.yaml
taskmaestro graph workflow.yaml --input input.yaml
taskmaestro run workflow.yaml --input input.yaml --log-level INFO
taskmaestro workflow describe workflow.yaml --json
taskmaestro workflow list --jsonWherever a workflow path is accepted, you can also give the name of a workflow
registered in the taskmaestro.workflows entry-point group (see
Plugin discovery):
taskmaestro workflow describe resinsight.completions --input input.yaml --json
taskmaestro run resinsight.completions --input input.yaml --jsonThe argument is a YAML path if it ends in .yaml/.yml or names an existing
file; otherwise it is looked up as a registered name. An unknown or broken name
is a configuration error whose message lists the registered workflows. Input
files work the same for both kinds, but registered workflows always run with a
default Runner and ExecutionContext; their root tasks take input values only
for declared config_fields. workflow list prints the registered names (one
per line, or {"workflows": [...]} with --json) without importing the
plugins, so one broken plugin does not break the list. In Python, use
load_registered_workflow(name, input_path).
By default, run prints the final output as JSON and reports errors on stderr;
validate prints a human-readable confirmation. graph prints Mermaid markup.
For automation, use --json with validate or run:
taskmaestro validate workflow.yaml --input input.yaml --json
taskmaestro run workflow.yaml --input input.yaml --jsonSuccessful validation emits {"status":"valid","workflow":"..."}. A successful
run emits {"status":"completed","workflow":"...","result":{...}}. A failure
emits one JSON object on stdout, for example:
{"status":"failed","workflow":"example","failed_task":"prepare","error":{"code":"task_failed","type":"ValueError","message":"Task failed","task":"prepare","field":null,"issues":[]}}Errors contain code, exception type, a safe message, nullable task and
field, and issues (field paths and error codes, without input values).
Loading failures have status invalid and code: "configuration_error"; task
failures have status failed and code: "task_failed". If a completed result
cannot be encoded as JSON (e.g. a Python-only object), run --json returns
code: "serialization_error". Missing configuration fields produce issues
with code missing; when no structured field metadata is available, field
is null. Use text mode when you need the original exception message. The
exception is an unknown or broken registered workflow name: its message
names the registered workflows.
Exit codes: 0 success, 1 task or result-serialization failure, 2 workflow
configuration failure. In JSON mode logs and ordinary Python print() output
from imports/tasks go to stderr, reserving stdout for the result document.
Application code can still write directly to file descriptor 1; JSON mode is
not a sandbox. Error objects intentionally omit raw exception messages, but
application-generated stderr may contain sensitive data.
Inspect a workflow before its input file is complete with
taskmaestro workflow describe workflow.yaml --json. The JSON contains the
workflow name and result task plus topologically ordered task instances. Each
instance includes its name, python_type, depends_on references (task /
field), config_fields, required_input_fields, optional map configuration,
and Pydantic input/output schemas. Collection dependencies include their kind
(positional or keyed) and member references; flattened members add
"spread": "list" or "spread": "dict". python_type identifies the
loaded class; it may differ from the plugin entry-point identifier used in YAML.
source tells where the workflow came from: {"kind": "yaml", "path": "/abs/workflow.yaml"}
or {"kind": "entry_point", "name": "resinsight.completions"}.
Pass --input input.yaml to check the input against the workflow. The input
may be incomplete (for example a template whose runtime-picker fields a UI
fills in): provided_config_fields lists the field names set for each task,
missing_config_fields lists declared config_fields the input does not set,
and config_values maps exactly the provided names to their values; without
--input, all three are null. Other problems, such as unknown task keys or a
missing or invalid map source, still fail. validate and run reject missing
configuration fields. Values are what input.yaml contains for
the task, before Pydantic validation, so opaque markers (for example
{"__resinsight_ref__": "EclipseCase", "case_id": 0}) come through unchanged.
Dates and datetimes become ISO 8601 strings, paths become strings, sets become
sorted lists and non-string mapping keys become JSON key strings; binary values,
NaN/infinity and keys that collide after conversion are rejected as invalid.
Fields without a value fall back to input_schema.properties.<field>.default.
The output contains the input values, including any secrets. This check
does not run tasks or hooks and does not validate every configured value's
runtime type. Loading YAML still imports
Python modules (and nested workflows); do not inspect untrusted YAML or plugins
under a privileged account. In JSON mode inspection failures have status
invalid, an error object, and exit code 2. Without --json, inspection
prints indented JSON.
python -m taskmaestro ... is equivalent, which is useful when the scripts directory is not on PATH.
Seven full example pipelines are included in the examples/ directory:
| Example | Features |
|---|---|
examples/text_analysis/ |
DAG with fan-out/fan-in, output field routing, inline Inputs/Outputs classes, YAML config, Mermaid visualization |
examples/resinsight/ |
ObjectModel[T] for gRPC objects, JobConfiguration with per-task config, named task instances, config_fields, YAML config |
examples/image_processing/ |
Nested workflows through Workflow.as_task() and YAML workflow:, typed boundaries, expanded Mermaid subgraph |
examples/release_pipeline/ |
Keyed collect() dependencies, mapped tasks, mapped output routing, per-task YAML config |
examples/conditional_if/ |
If/else with ConditionTask, if_true()/if_false() guards, first_of join, YAML when: |
examples/conditional_switch/ |
Multi-way SwitchTask with on(...) and otherwise(), first_of join, YAML when: |
examples/scripts/ |
taskmaestro.python and taskmaestro.command tasks, keyed collect into a script (YAML only; run from the repository root) |
Run an example:
python examples/text_analysis/pipeline.py # Python API
python examples/text_analysis/pipeline.py --yaml # YAML configsource .venv/bin/activate
pytest -v # run tests
ruff check . # lint
ruff format . # format
mypy taskmaestro # type check (strict)