Skip to content

Latest commit

 

History

History
534 lines (449 loc) · 26.4 KB

workflows.md

File metadata and controls

534 lines (449 loc) · 26.4 KB

Workflow Orchestration Component

Purpose

Executes multi-step workflows with advanced templating, state tracking, and dynamic tool generation. The workflow engine transforms complex, multi-step platform operations into simple, single-command executions.

Key Responsibilities

  • Workflow Definition Management: Parse and validate YAML workflow definitions
  • Dynamic Tool Generation: Generate workflow_<name> execution tools for each defined workflow
  • Step Execution: Execute workflow steps with dependency management and error handling
  • Template Processing: Advanced argument templating with variable substitution
  • Runs: Every run of a workflow is kept in the run store, driven the same way whoever starts it
  • Cross-Tool Integration: Orchestrate core tools, external MCP tools, and services

Component Architecture

Key Files

  • executor.go: The step machine: runs a workflow's top-level steps from a run's state
  • executor_long.go, executor_repeat.go: The steps that make a run wait, loop, start a child or end
  • driver.go, driver_worker.go: Start runs inline, commit each step, resume due runs on any replica
  • driver_long.go, driver_cancel.go, driver_enqueue.go, driver_task.go: Waiting runs, signals, cancelling, child runs and runs of MCP tasks
  • dry_run.go: Which calls of a dry run are writes, and what it keeps of those it holds
  • runstore/: The run store: Postgres for several replicas, memory for one
  • api_adapter.go, api_adapter_runs.go, api_adapter_run_tools.go: API integration and the run tools

Tool Generation Pattern

Each workflow definition automatically generates a corresponding execution tool:

.muster/workflows/connect-monitoring.yaml → workflow_connect-monitoring
.muster/workflows/check-cilium-health.yaml → workflow_check-cilium-health
.muster/workflows/login-management-cluster.yaml → workflow_login-management-cluster

Advanced Features

Template Processing

  • Input Variables: {{ .input.argName }} for workflow arguments
  • Step Results: {{ .results.stepId.fieldName }} for step result chaining — every step's result is referenceable by later steps regardless of any flag
  • One Expression Language: step args, condition templates, and condition jsonPath expectations all use the same Go-template/sprig engine and the same path navigator (dotted paths with array indexing, e.g. items[0].name)
  • Default Values: Built-in support for argument defaults
  • Type Validation: Schema validation for all arguments

Result Shaping

  • output flag: marks the steps whose results are included in the returned document (the deprecated store flag is a backwards-compatible alias)
  • output template: a workflow-level templated object rendered against .input / .results / .vars after all steps complete, returned in place of the default response to produce a small, structured result (JSON types are preserved)

Runs

  • One engine: a workflow_<name> call creates a run in the run store, holds its lease and drives it inline, so a workflow without waits ends inside the call and returns its result, with the run's ID under run_id. See Workflow runs.
  • History: every run, its steps and its events are kept; core_workflow_run_list and core_workflow_run_get read them
  • Cancel and retry: core_workflow_run_cancel stops a run before its next step; core_workflow_run_retry queues a failed run again from the step that failed
  • Long work: wait, repeat, child workflow and end steps, cancelWhen, onCancel and signals let a run wait for days while it holds nothing; see Steps that wait
  • Dry runs: a dry run reads for real and holds every write, recording what it would have sent; see Dry runs

Tool Integration Patterns

Workflows seamlessly orchestrate across tool types:

steps:
  # External MCP tool usage
  - id: "kubernetes-action"
    tool: "x_kubernetes_port_forward"

  # Conditional execution
  - id: "health-check"
    tool: "core_service_status"
    args:
      name: "monitoring-service"

Integration with muster Ecosystem

Service Management Integration

Workflows orchestrate services:

  • Monitor health with core_service_status
  • Manage lifecycle with start/stop/restart operations

MCP Server Coordination

Workflows can coordinate multiple external MCP servers:

  • Infrastructure management (Kubernetes)
  • Monitoring setup (Prometheus, Grafana)
  • GitOps operations (Flux)

Configuration Persistence

All workflow definitions persist in .muster/workflows/ enabling:

  • Version control of operational procedures
  • Team sharing of standardized workflows
  • Consistent execution across environments

This architecture transforms complex, error-prone manual procedures into reliable, repeatable, single-command operations that AI agents can execute consistently.

Workflow runs

Every run of a workflow is a row in muster's run store, whatever started it: a workflow_<name> call, a parent's workflow: step, or an MCP event a Workflow subscribes to with subscriptions. Workflows without waits behave as they always did: the run ends inside the workflow_<name> call. What changes is that the run is kept, and that a run can go on without the process that started it. Runs started by events, the Workflows of organizations' namespaces, waits on events and concurrency limits are described in Workflows started by events.

The run store

  • Postgres when postgres.dsn (chart: muster.postgres.existingSecret) is configured. Runs survive a restart and move between replicas. The schema is applied on start by versioned migrations, as the schema owner when a migrate DSN is configured (the runtime role then creates nothing). Steps and run events are partitioned by the month their run was created in.
  • Memory otherwise: one replica only (as for Valkey-less OAuth state), local mode and tests. Runs are lost when the process ends, and they do not move between replicas; the chart does not refuse several replicas without a database, but each runs its own, and polls its own event subscriptions: more than one replica needs Postgres.
  • A configured database is never replaced by memory: muster waits for it at start, and fails its start when it does not answer.
  • When the store cannot keep a run (a database outage), the call fails with the workflow run store failed, and muster_workflow_run_store_errors_total counts it.

A run keeps the Workflow spec it started with (later edits apply to new runs only), its input (with every value passed to a sensitive tool argument redacted), its result or error, who started it, its lease and the state it needs to go on: the position of its next top-level step and what the steps before it produced. Every payload is capped at 256 KiB; a larger one is replaced by a marker and the run is flagged truncated. A completed run drops its state; a failed run keeps it for a retry.

Statuses: queued, running, waiting (open) and completed, failed, cancelled (ended). A step that returns an error result without allowFailure fails its run (the call still returns that error result).

  • queued: no replica drives the run yet -- a child run, a retried run, a run an event started, a run whose tools were missing on resume. A worker claims it when it is due. A run a concurrency limit holds is queued too, and not due until it is admitted (its held says why).
  • running: the replica holding the run's lease runs its steps.
  • waiting: a step made the run wait (Steps that wait). The run holds no lease, no goroutine and no memory: it is a row with a wake time -- its next check, its deadline -- or none while only a signal, the end of the child it waits for or a cancel can wake it. A worker claims it when it is due, as any due run.

Driving runs

  • The replica that receives a workflow_<name> call creates the run with a lease and runs it inline, as the caller. After every top-level step it commits the step's rows and the run's state, with the next step marked in flight, before that step starts.
  • A worker on every replica claims the runs that are due: queued runs, waiting runs whose wake time passed, and running runs whose lease expired because their replica stopped. Postgres hands them out with FOR UPDATE SKIP LOCKED; there is no leader. A replica renews the lease of a run it drives every 10 s (the lease lasts 30 s) and polls for due runs about every second.
  • A resumed run acts as whoever started it: an organization principal from its own credentials, a person from their muster session (with their login's ID token when muster signs people in). When muster cannot act as them any more -- the person's sign-in is gone -- the run fails with that reason; it never acts as anyone else. A run whose tools are missing on resume (a server still connecting after a restart) is put back for 10 s at a time, for up to 5 minutes.

Crashes and idempotency

A step a crash interrupted (the run's state marks it in flight) is repeated only when every tool it calls -- its own, its condition's and its sub-steps' -- declares readOnlyHint or idempotentHint, or when the run is dry and so made no write. Otherwise the run fails as interrupted, naming the step and the tools, after its onFailure steps ran. A forEach or parallel step counts as one step.

Every tool call a run makes carries _meta["giantswarm.io/idempotency-key"] = "<run>/<step>/<attempt>". <step> is the step's ID with _<index> per forEach iteration (as in its result key), _<check> per check of a wait or of cancelWhen, _<round> per round of a repeat, .condition for a condition's tool, .page<n> for later pages of a paginated step and an onFailure., onCancel. or cancelWhen. prefix for those steps. A child run's ID is derived from the key of its workflow step, so a step repeated after a crash finds the child it started instead of starting another. A repeat after a crash sends the same key, so a tool that honours keys makes its effect once. A retry is a new attempt and sends a new key.

A run whose input held a value for a sensitive tool argument keeps no such value, so it cannot resume after a crash or be retried.

Run tools

Tool Does
core_workflow_run_list Runs, newest first, filtered by workflow_name, status, subject and dry_run; pages of limit (default 50, at most 1000) follow each other by cursor (the previous page's next_cursor)
core_workflow_run_get A run with its steps (include_steps, default true), or the steps of one step_id; a dry run counts the writes it held (held_writes)
core_workflow_run_cancel Cancels a run and its open children: a queued or waiting run at once (once its onCancel steps ran), a running run before its next step; no onFailure steps run
core_workflow_run_retry Queues a failed run again from the step that failed, as that step's next attempt; it acts as its starter, and a person retrying their own run lends it their current session
core_workflow_run_signal Sends a signal to an open run (run_id, name, data): the run sees it as .signals.<name>, and a waiting run wakes at once

Who sees a run: the caller who started it, and every caller who sees the Workflows of its namespace. Every caller sees the Workflows of muster's namespace, so every caller sees the runs there; the runs of an organization's namespace are seen by whoever sees its MCPServers. Who sees a run can cancel and retry it, as who sees a Workflow can run it. List and get are read-only (on the governance safe list); cancel and retry are writes.

Retention

Ended runs and their history are kept for workflowRuns.retention (default 720h, 30 days); open runs are never deleted. Each replica deletes ended runs past retention in batches once an hour and drops the monthly partitions whose runs are all gone. The memory store also keeps at most 10,000 ended runs.

Metrics and events

muster_workflow_runs_total and muster_workflow_run_duration_seconds (by workflow, status and dry_run), muster_workflow_run_store_errors_total and the gauge muster_workflow_runs_open (open runs by workflow, status and dry_run). The counters muster_workflow_run_wait_timeouts_total (waits that reached their timeout), muster_workflow_run_signals_total (signals sent) and muster_workflow_run_children_total (child runs workflow steps started, by the child's workflow) count the work of long runs, and muster_workflow_run_held_writes_total (by workflow) the writes dry runs held; the metrics of subscriptions and concurrency are in Workflows started by events. The Kubernetes events are WorkflowRunStarted, WorkflowRunCompleted, WorkflowRunFailed and WorkflowRunCancelled. The run store also keeps run events (started, waiting, resumed, completed, failed, cancelled, held for a run a concurrency limit holds, and signalled for a signal, delivered for an MCP event occurrence a run received) with a store-wide sequence number and the transaction that appended them. Clients follow them as the MCP event type core_workflow_run: by poll or stream, narrowed by workflow, namespace, subject and type, for the runs core_workflow_run_list shows them, from a cursor that never passes an event still being committed; a run's signals and deliveries are its own and are not followed. See muster's own events.

Steps that wait

A step is exactly one of tool, forEach, parallel, wait, repeat, workflow or end. The last four let one run carry work that takes days -- waiting on CI, on a person's decision, on a child run -- while it holds nothing: whenever one of them has to wait, the run is kept as waiting and gives up its lease, and a worker on any replica goes on with it when it is due. A workflow without them behaves exactly as before; there is no mode. id, condition, allowFailure, output and description apply to them as to tool steps. Durations are Go durations (90s, 30m, 720h).

Templates in these steps (and in every other step) see .input, .results, .vars, .signals and, in a repeat body, .repeat; a wait or cancelWhen on an MCP event sees the occurrence as .event (waits on events). Templates fail on a missing key, so test for a signal that may not have come yet with hasKey .signals "decision" or index .signals "decision".

wait

- id: ci
  wait:
    steps:                         # read steps, run on every check
      - id: checks
        tool: x_github_pr_checks
        args: { pr: "{{ .input.pr }}" }
    until: "{{ eq .results.checks.state \"success\" }}"
    every: 5m                      # default 1m with steps, at least 10s
    signal: proof                  # also check at once when it arrives
    timeout: 72h                   # required
  allowFailure: true               # go on when it times out

A wait checks at once, then whenever a check is due: its interval passed, a signal arrived, or its deadline came. A check runs its read steps one after another (their results are .results.<id>, as for other steps) and renders until. Without until, a wait with a signal is over once a signal of that name arrives that no earlier wait took. At the deadline it checks once more and then fails as timed out; allowFailure lets the run go on. A read step that fails without allowFailure fails the wait. Between checks the run waits until the next check or the deadline, whichever comes first. Only the check that ended the wait keeps its read steps' rows in the run's history. The wait's result is {satisfied, timedOut, checks, since}.

repeat

- id: implementing
  repeat:
    steps:                         # tool, wait, workflow and end steps
      - id: change
        workflow: sdlc-change
        args: { item: "{{ .input.item }}", round: "{{ .repeat.round }}" }
      - id: review
        wait: { signal: decision, timeout: 168h }
    until: "{{ eq .signals.decision.data.verdict \"approved\" }}"
    max: 3                         # 1-1000; the step fails after the last round

A repeat runs its body, then renders until, round after round until it holds, at most max rounds; then the step fails (allowFailure applies). .repeat.round counts from 1. Each round starts with the body's results cleared, and its calls are named <step>_<round>. A body holds tool, wait, workflow and end steps (no forEach, parallel or nested repeat: the CRD's schema cannot recurse); a wait or workflow step in it makes the run wait where it is. An end in the body ends the whole run. The repeat's result is {rounds, satisfied}.

workflow

- id: change
  workflow: sdlc-change
  subject: "{{ .input.pr_url }}"   # what the child run is about
  args: { pr: "{{ .input.pr }}" }

A workflow step starts a run of another workflow as its child: in the same namespace, acting as whoever started this run, with args as its input and parent_run_id naming this run. The child is queued and a worker runs it; this run waits (no wake time) until the child ended, which wakes it. The step's result is {runId, status, output, error}, output being what the child returned; a child that failed or was cancelled fails the step (allowFailure applies). Children nest at most 8 deep, so a workflow that starts itself stops there. A child always runs on a worker, and muster keeps no value passed to a sensitive tool argument (see Crashes and idempotency): a child whose input holds one fails. Call workflow_<name> as a tool step instead to run such a workflow inside the step, as before.

end

- id: nothing-to-do
  end: true
  condition: { template: "{{ .results.item.closed }}" }

An end step ends the run here as completed when its condition holds (always without one); the workflow's output renders as at the end of its steps.

cancelWhen and onCancel

cancelWhen:
  steps:
    - { id: issue, tool: x_github_issue, args: { url: "{{ .input.issue }}" } }
  until: "{{ eq .results.issue.state \"closed\" }}"
  every: 15m
onCancel:
  - { id: unclaim, tool: x_board_unclaim, args: { item: "{{ .input.item }}" } }

cancelWhen is checked when a run starts or wakes, and between steps once every passed since its last check (at every step without steps or every); every also bounds how long a waiting run sleeps. When until holds, the run is cancelled. A read step of cancelWhen that fails counts as not holding.

Cancelling a run -- by cancelWhen or core_workflow_run_cancel -- cancels its open children, then runs its onCancel steps (tool calls, best effort, as whoever started the run), before the run ends as cancelled. A waiting or queued run with onCancel steps is woken for a worker to run them. A cancelled run runs no onFailure steps.

Signals

core_workflow_run_signal {run_id, name, data} sends a signal to an open run. The run keeps each signal as a signalled run event, never lost to a replica that drives the run as it arrives, and sees the latest of each name as .signals.<name> ({data, at}). A signal wakes a waiting run at once, whatever it waits for: a wait checks again, cancelWhen is checked again. A wait on a signal takes the signal that ended it, so a later wait on the same name -- the next round of a repeat -- needs a newer one. A signal to a run that ended is refused.

Calls that wait

A workflow_<name> call drives its run inline until the run ends -- a workflow without these steps always does -- or until a step makes it wait. Then the call returns a normal result and the run goes on without the caller:

{"run_id": "0b5c...", "status": "waiting",
 "waiting": {"step": "ci", "for": "its until condition or signal proof",
             "signal": "proof", "next_check": "2026-12-01T09:05:00Z", "deadline": "2026-12-04T09:00:00Z"}}

core_workflow_run_get shows the same waiting while the run waits, and the run's result once it ended.

MCP tasks

call_tool and every workflow tool declare execution.taskSupport: optional. A task-augmented call_tool of a workflow tool (MCP tasks, revision 2025-11-25) is answered at once with a task whose taskId is the run's ID, and the run goes on without the caller. mcp-go keeps the tasks it serves in its own process, so muster serves the tasks of runs itself, from the run store, in front of the Streamable HTTP transport: they work on any replica and after a restart.

  • The call goes on as a plain call -- through the toolset, approval and principal gates of any call -- carrying the task; the workflow starts its run in the background and the call's answer is replaced by the task. A call whose arguments do not validate is answered as a plain call.
  • tasks/get maps the run's status: queued, running and waiting are working (the status message says what a waiting run waits for), completed, failed and cancelled map to themselves.
  • tasks/result blocks until the run ended and answers what the call would have returned: the run's result with its run_id, or an error result naming the run and why it failed or was cancelled.
  • tasks/cancel cancels the run (as core_workflow_run_cancel); a run that ended cannot be cancelled.
  • tasks/list lists the runs the caller started.

A task for any other tool is answered as a plain call. The stdio and SSE transports do not serve the tasks of runs: there mcp-go keeps a task in its own process.

Dry runs

A process such as an SDLC first runs against the real world without changing it: a dry run makes its reads for real and holds every write, recording what it would have sent. It is the same run as a live one, on the same engine and run store; only its writes are held. Going live is a reviewed change to the Workflow.

Marking a run dry

spec:
  dryRun: true                     # every run of this Workflow is dry
  steps:
    - id: issue
      tool: x_github_issue_get     # read-only: called
      args: { url: "{{ .input.issue }}" }
    - id: pr
      tool: x_github_pr_open       # a write: held
      args: { repo: "{{ .results.issue.repo }}", title: "{{ .results.issue.title }}" }
      dryRun: { number: 42, url: "https://github.com/{{ .results.issue.repo }}/pull/42" }
    - id: checks
      tool: x_github_pr_checks     # read-only: called with number 42
      args: { pr: "{{ .results.pr.number }}" }
  • spec.dryRun: true makes every run of the Workflow dry, whoever or whatever starts it: a workflow_<name> call, an event its subscriptions name, a parent.
  • A workflow_<name> call may pass the reserved argument _dryRun: true for one dry run of a live Workflow (like _debug, it is no input of the run). No argument makes a run of a dry Workflow live.
  • A child of a dry run is dry: the run a workflow: step starts, and the run of a workflow_<name> tool a step calls.
  • A run keeps whether it is dry: core_workflow_run_list shows dry_run and filters on it, a workflow_<name> call's answer carries "dry_run": true, and a retried dry run stays dry.

What is a write

A write is a call of a tool whose readOnlyHint is not true as the run's starter sees the tool: the person who called, or the organization's principal, in the tool listing muster serves them. A missing hint is a write (the MCP default), and so is a tool the starter does not see. A server's tools carry the hints it declares; muster's own tools carry theirs (core_workflow_run_list is read-only, core_workflow_run_signal is not); a workflow_<name> tool is read-only only when every tool its steps call is. A Workflow cannot declare a write to be a read.

The decision covers every call a run makes: tool steps, wherever they are (forEach and parallel sub-steps, repeat bodies), a condition's tool, the read steps of wait and cancelWhen, and the onFailure and onCancel steps.

What runs for real:

  • reads: read-only tool calls, a wait's re-reads, event subscriptions (subscriptions, waits on events) and cancelWhen checks;
  • muster's own writes for the run: the run itself, its children, admission (dry runs count against concurrency limits), the signals it receives and its history. A step that calls one of muster's tools that writes -- core_workflow_run_signal to another run, say -- is held like any write.

Held writes

A write is not called. Its step is kept with status held, and core_workflow_run_get shows it with:

  • input: the evaluated arguments the call would have carried;
  • held: the idempotency_key the call would have sent, the tool's destructive_hint and idempotent_hint (the MCP defaults, destructive and not idempotent, when it declares none), the position of the run's top-level step and whether an answer stood in for the result (answered);
  • result: the step's dryRun answer.

A tool step's dryRun is any JSON, its strings templated like args. It is the step's result: later steps see it as .results.<id>, as they would see the tool's (paginate and jq do not apply to it). In a forEach or parallel step each held call is kept the same way, the answer rendered per iteration (.vars.<as>).

Without an answer, the run ends right there as completed -- no allowFailure lets it go on, and no onFailure steps run -- its result the default response with dry_run_stopped_at (the step) and message ("dry run stopped at : a write without a dry-run answer"). A parent whose child ended so ends the same way, naming its workflow: step and the child. A condition whose tool is a write has no answer: the run stops there too. In onFailure and onCancel an unanswered write is held and the cleanup goes on: the run ends as failed or cancelled anyway.

A crash never makes a dry run fail as interrupted: it made no write a repeat could make twice. core_workflow_run_get counts a dry run's held writes in held_writes, and muster_workflow_run_held_writes_total counts them by workflow.

Going live

Going live is removing spec.dryRun. Runs that are open stay dry. The Workflow's subscriptions subscribe afresh with cursors of their own: a source such as core_tool_changed with includeExisting fires again for every item there is and starts live runs for them, though dry runs of the same subjects may still be open (see Workflows started by events).