Introducing a new way to review your PRs.

Read the announcement

elsa-workflows / elsa-core

The Workflow Engine for .NET

View on GitHub

32 documents · Updated Oct 7, 2026

docs / workflow-execution

Workflow and activity execution

Elsa.Workflows.Core models a workflow as an activity graph and advances it by scheduling activity work. Each activity runs with a context that holds its inputs, outputs, variables, child work, bookmarks, and status. The workflow stops when its scheduled work is exhausted, or it stays resumable when an activity is waiting for an external event. For the wider service view, read Workflow engine, Workflow runtime, and Workflow management.

Execution model

The execution model separates the workflow definition from one run of that definition. A workflow is the top-level composite activity. Its root activity and nested activities form a graph, while a workflow execution context holds the changing state for one workflow instance.

The graph gives each activity a local place and relationship. An activity execution context represents one visit to that place. This distinction allows loops and repeated activity runs to keep separate state while still referring to the same activity node.

ConceptPurpose
ActivityAtomic unit of work with a type, identity, precondition, and execution action.
Composite activityActivity that owns or coordinates child activities.
Activity nodeActivity position in the workflow graph, including parent and child links.
Activity execution contextState for one activity execution, including status, inputs, variables, bookmarks, and child contexts.
Workflow execution contextState for one workflow instance, including the graph, scheduler, workflow inputs and outputs, active contexts, bookmarks, and incidents.
Work itemScheduled request to run an activity with its owner, input, variables, optional existing context, and scheduling lineage.

The structural parent and the scheduling predecessor are different relationships. A container owns an activity structurally, while the activity that completed immediately before scheduling it is recorded as its execution predecessor. This distinction matters in flowcharts and in calls across workflow instances.

References: src/…/Activity.cs• L12-37 src/…/ActivityNode.cs• L3-20 src/…/ActivityExecutionContext.cs• L100-148 src/…/WorkflowExecutionContext.cs• L257-325 src/…/ActivityWorkItem.cs• L5-33 src/…/ActivityWorkItemState.cs• L8-53

Activity graph

The activity graph is the stable map that connects workflow design to execution. The graph builder visits the workflow tree, assigns identities, and exposes both a root node and flat lookups for activity nodes.

An activity has a local Id. An activity node also has a graph-wide NodeId that reflects its place in the activity hierarchy. The execution context uses these node identities to find activities, restore execution state, and schedule only activities that belong to the current workflow graph. Persisted contexts and work items use the node identity as their link back to the definition, so a definition change can leave some saved references unresolved.

References: src/…/WorkflowGraphBuilder.cs• L8-18 src/…/WorkflowGraph.cs• L7-24 src/…/ActivityNode.cs• L23-68 src/…/WorkflowExecutionContextSchedulerStrategy.cs• L10-16 src/…/WorkflowStateExtractor.cs• L139-153

Activity execution contexts

An activity execution context is the working space for an activity visit. It starts in Pending, becomes Running when the activity enters execution, and becomes Completed, Canceled, or Faulted as the visit ends. The context also links to its workflow context and to any child contexts it owns.

The context carries two kinds of activity state. Activity properties and metadata support execution and reporting. Activity state stores evaluated input values for history and restore. Transient properties hold values that only matter during the current run and are not part of durable workflow state.

Activity completion sends an activity-completed signal. The signal lets the owner run its completion callback, then the owner can schedule the next work or complete itself. Completion also clears the activity's bookmarks and callbacks. Child activity variables are removed after completion, while the root context remains available for workflow-level variables.

References: src/…/ActivityExecutionContext.cs• L179-307 src/…/ActivityExecutionContext.Complete.cs• L8-66 src/…/ScheduledChildCallbackBehavior.cs• L7-37

Inputs and outputs

Inputs and outputs connect activity logic to expression memory and to other activities. An Input<T> is a typed value reference that can hold a literal, an expression, a variable, or another activity's output. An Output<T> is a typed destination for a value produced by an activity.

Before an activity runs, the activity pipeline evaluates its auto-evaluated inputs in the current expression context. The evaluated values are placed in activity memory and, when allowed, recorded in activity state. Sensitive inputs are not retained in that state.

Activity definitions cross the JSON boundary through JsonActivitySerializer. It uses the activity registry to find the type descriptor and keeps ordinary activity properties on the standard metadata-aware JSON path. When a descriptor declares synthetic inputs or outputs, the serializer adds those descriptor-defined fields and checks that the final activity is a JSON object with no duplicate property names.

Synthetic input data carries its target type, expression, and memory reference. Synthetic output data carries its type and memory reference and can also carry a value converter. A descriptor can adjust the serializer options for its activity, but expressions still need a registered descriptor and only expressions marked as serializable retain their value in JSON.

Input definitions can be serialized as typed expression objects. A plain JSON value is treated as a literal, an empty expression produces an empty input, and an expression with an unknown type is rejected because the runtime cannot resolve its expression descriptor. This keeps workflow definitions portable without claiming that run-time-only expressions can be restored from JSON.

When an activity sets an output, the value is available through expression memory and through the workflow's activity output register. The register keeps values by activity identity and execution instance. A workflow can expose its own outputs through its output definitions and can keep a result in its result variable.

References: src/…/Input.cs• L7-34 src/…/Output.cs• L5-36 src/…/ActivityExecutionContextExtensions.InputEvaluation.cs• L17-31 src/…/ActivityExecutionContext.cs• L678-833 src/…/ActivityOutputRegister.cs• L3-59 src/…/Workflow.cs• L16-47 src/…/JsonActivitySerializer.cs• L11-49 src/…/SyntheticPropertiesWriter.cs• L8-117 src/…/ExpressionJsonConverter.cs• L22-78 src/…/InputJsonConverter.cs• L29-91

Variables and memory

Variables provide named memory that activities can share within a scope. Workflow variables belong to the workflow scope. Container variables belong to a nested scope, and dynamic variables can be added when an activity execution context is created.

Each variable has a name, a value, and an optional storage driver type. Without a storage driver, the value stays in the expression context for the life of that context. A storage driver gives the runtime a way to persist the variable beyond that in-memory lifetime.

The scope of a variable follows the activity tree. A container declares its variables before it schedules children, so child activities can resolve them through the expression context. Scheduled variables are declared in the new activity's own memory before the child runs. This prevents nested loops from overwriting a parent loop's CurrentValue or CurrentIndex. The runtime removes variables owned by a completed child context to prevent that child scope from leaking into later work.

Loop activities use this scope to expose the current item or step to their body. For advances a numeric value from Start toward End, ForEach<T> runs one body visit at a time and exposes the current item, and ParallelForEach<T> gives each scheduled body visit its own item and index variables.

References: src/…/Variable.cs• L7-57 src/…/ActivityExecutionContext.cs• L155-182 src/…/WorkflowExecutionContext.cs• L405-413 src/…/WorkflowExecutionContext.cs• L580-609 src/…/ActivityExecutionContext.Complete.cs• L54-62 src/…/For.cs• L81-123 src/…/ForEachT.cs• L71-112 src/…/ParallelForEachT.cs• L62-114

Activity scheduling

Scheduling is the hand-off between an activity and the workflow execution loop. An activity asks the scheduler to run a child. The scheduler turns that request into a work item and records the callback that will notify the owner when the child completes.

The workflow pipeline takes work items until none remain. A scheduler can use stack order or queue order, but the execution contract stays the same: take the next work item, create or reuse its activity execution context, and run the activity pipeline. A missing child is treated as an immediate completion so containers can finish cleanly when an optional branch is empty.

Each scheduled work item carries the data needed to continue the hand-off after a pause. This includes the activity node, owner context, optional input and variables, an existing context when resuming a visit, a tag, and the scheduling activity or workflow identity. The state extractor saves these values and rebuilds the work item when execution resumes.

The main container patterns use this contract in different ways:

  • Sequence schedules one child at a time and advances its index after each completion. A direct reschedule keeps the sequence as the completion-callback owner.
  • Parallel schedules all children and completes after every child callback arrives.
  • If evaluates a condition and schedules one selected branch.
  • Loop activities either reschedule their body after each completion or schedule all body visits at once. For and ForEach<T> wait for each body visit before advancing. ParallelForEach<T> records a tag for every visit and completes only after every tag reports completion.

This diagram shows how a scheduled activity moves through the workflow and activity pipelines before its completion returns control to its owner.

flowchart TD
    A[Activity schedules child] --> B[Work item enters scheduler]
    B --> C[Workflow scheduler takes work item]
    C --> D[Create or reuse activity context]
    D --> E[Evaluate inputs and check precondition]
    E --> F[Run activity execution pipeline]
    F --> G[Activity completes or waits]
    G --> H[Completion callback or bookmark state]
    H --> A

References: src/…/WorkflowExecutionContextSchedulerStrategy.cs• L8-50 src/…/ActivityExecutionContextSchedulerStrategy.cs• L8-71 src/…/DefaultActivitySchedulerMiddleware.cs• L21-65 src/…/Sequence.cs• L20-73 src/…/Parallel.cs• L13-57 src/…/If.cs• L15-70 src/…/For.cs• L101-126 src/…/ForEachT.cs• L90-112 src/…/ParallelForEachT.cs• L87-114 src/…/ActivityWorkItemState.cs• L8-53

Bookmarks and resumption

A bookmark is a durable waiting point that lets an activity pause until an external stimulus arrives. The bookmark stores a name, a payload, the related activity and activity instance, and rules for callback, automatic burn, and automatic completion.

Creating a bookmark adds it to the workflow context and causes the workflow to suspend after current pending work finishes. On resumption, the runtime finds the bookmarked activity context, schedules that existing context, and selects either the bookmark callback, automatic completion, or a no-op continuation. An automatically burned bookmark is removed after it resumes.

Bookmarks make a workflow resumable without treating the waiting activity as finished. The activity remains the location where the next stimulus continues the workflow.

References: src/…/Bookmark.cs• L5-32 src/…/ActivityExecutionContext.cs• L397-533 src/…/WorkflowExecutionContextExtensions.cs• L74-113 src/…/WorkflowSubStatus.cs• L6-45

Flowchart progression

A flowchart is a container whose activities are connected by named outcomes. When a child completes, the flowchart uses the child's outcomes to select outbound connections and schedule the next reachable activities.

Token-based progression tracks each active path with a token. A token records its source activity, target activity, and outcome. The flowchart consumes tokens when their target activation uses them, blocks tokens when a path must not activate, and clears them when the related activity is canceled or the flowchart completes.

Each target applies a merge mode to decide when its inbound paths can schedule it:

  • Stream proceeds from an available upstream completion and ignores dead paths. None uses this behavior as its default.
  • Merge waits for every forward inbound connection. It ignores backward connections used for loops.
  • Converge waits for every inbound connection, including backward connections.
  • Cascade schedules each arriving token as its own activation.
  • Race schedules the first arriving path and cancels or blocks competing inbound paths.

A terminal activity completes the flowchart at once. Otherwise, the flowchart schedules targets that meet their merge rules and completes when no pending work remains. The execution mode is selected for the workflow run, with a workflow property taking priority over configured defaults and the legacy static fallback.

This diagram shows how a completed activity turns its selected outcomes into path state and how the target's merge rule controls the next activation.

flowchart TD
    A[Child completes with outcomes] --> B[Create active path tokens]
    B --> C{Target merge mode}
    C -->|Stream| D[Proceed from available path]
    C -->|Merge| E[Wait for all forward paths]
    C -->|Converge| F[Wait for all inbound paths]
    C -->|Cascade| G[Activate for each arriving path]
    C -->|Race| H[Activate first path and block others]
    D --> I[Schedule target]
    E --> I
    F --> I
    G --> I
    H --> I
    I --> J[Continue flowchart or complete when work ends]

References: src/…/Flowchart.cs• L12-63 src/…/Flowchart.cs• L90-165 src/…/Flowchart.Tokens.cs• L13-211 src/…/Token.cs• L3-25 src/…/MergeMode.cs• L7-52 src/…/Connection.cs• L5-57 src/…/FlowFork.cs• L10-37 src/…/FlowJoin.cs• L12-45 src/…/Flowchart.Counters.cs• L17-63

State machine progression

A state machine models progression as named states and transitions. The active state is part of the activity context, so a resumed state machine can continue from its current state instead of starting again.

The state machine enters the initial state when no current state exists. It runs the state's entry activity, then checks automatic transitions. Trigger activities wait for external or child-driven events. When a trigger completes, the state machine checks the transition condition, runs the source state's exit activity and transition action, then changes the current state.

Only the transition that wins may continue from a state. Competing trigger visits, queued trigger work, and their completion callbacks are canceled or removed. Automatic cycles are placed back on the scheduler before the next state check, which lets the scheduler advance the cycle without growing the current call stack.

This diagram shows the state machine path from state entry to either a new state or workflow completion.

flowchart TD
    A[Enter current state] --> B[Run entry activity]
    B --> C{Automatic transition?}
    C -->|Yes| D[Check condition]
    D --> E[Run exit and transition actions]
    E --> F[Set next current state]
    F --> A
    C -->|No| G[Wait for trigger activities]
    G --> H[Trigger completes]
    H --> D
    C -->|No outbound transition| I[Complete state machine]

References: src/…/StateMachine.cs• L32-73 src/…/StateMachine.cs• L76-153 src/…/StateMachine.cs• L180-224 src/…/StateMachine.cs• L253-337

Execution state persistence

Workflow state persistence preserves the live execution picture needed to stop and later continue a workflow. The state extractor records workflow status and outputs together with bookmarks, active activity contexts, completion callbacks, and scheduled work.

On restore, the extractor maps saved activity node identities back to the current graph. It rebuilds the activity-context hierarchy and expression-context links before it restores callbacks and schedules work. It also restores activity properties, metadata, activity state, status, dynamic variables, and timing data. Inputs are limited to workflow inputs marked for storage, while existing input values on the live context remain authoritative.

A saved reference may not exist in a newer workflow definition. The extractor skips that reference and logs whether the skip is consistent with definition migration or is unexpected. This allows the rest of the state to load while making the broken link visible to operators.

This diagram shows how an active workflow becomes saved state and how that state becomes runnable execution again.

flowchart LR
    A[Live workflow context] --> B[Extract workflow and activity state]
    B --> C[Persist bookmarks callbacks and work]
    C --> D[Load state for a workflow definition]
    D --> E[Resolve activity node identities]
    E --> F[Rebuild context hierarchy]
    F --> G[Restore callbacks and scheduled work]
    G --> H[Resume workflow pipeline]

References: src/…/WorkflowStateExtractor.cs• L13-43 src/…/WorkflowStateExtractor.cs• L47-75 src/…/WorkflowStateExtractor.cs• L105-175 src/…/WorkflowStateExtractor.cs• L178-270 src/…/WorkflowStateExtractor.cs• L290-347 src/…/ActivityWorkItemState.cs• L8-53

Execution pipelines

Execution pipelines wrap workflow and activity execution with shared runtime behavior. The workflow pipeline controls the run as a whole. The activity pipeline evaluates and invokes each activity while adding logging, notifications, exception handling, and state commit points.

The default path is:

  1. WorkflowRunner builds or receives a workflow graph and creates a workflow execution context.
  2. The runner schedules the workflow or restores scheduled work, an interrupted activity, or a bookmark resumption.
  3. The workflow pipeline drains the scheduler.
  4. The activity pipeline evaluates inputs, checks CanExecuteAsync, marks the activity as running, and invokes ExecuteAsync.
  5. Completion callbacks schedule more work or complete the owning activity.
  6. The runner extracts workflow state, reports a finished run when the workflow reaches a terminal state, and commits the result.

This diagram shows the two pipeline levels and the state that moves between them.

sequenceDiagram
    participant Runner as Workflow runner
    participant W as Workflow pipeline
    participant S as Scheduler
    participant A as Activity pipeline
    participant C as Activity context

    Runner->>W: Start or resume workflow
    W->>S: Take work item
    S->>A: Invoke activity
    A->>C: Evaluate inputs and run activity
    C-->>A: Complete, fault, cancel, or bookmark
    A-->>S: Return after activity visit
    S->>S: Take next scheduled item
    W-->>Runner: Finished or suspended state

References: src/…/WorkflowRunner.cs• L70-97 src/…/WorkflowRunner.cs• L114-203 src/…/WorkflowRunner.cs• L207-257 src/…/WorkflowExecutionPipeline.cs• L6-41 src/…/ActivityExecutionPipeline.cs• L6-41 src/…/DefaultActivityInvokerMiddleware.cs• L23-111

Workflow advancement and completion

Workflow advancement is driven by scheduled work rather than by a fixed call stack. The workflow starts by scheduling its workflow activity. Each activity can add more work through its owner context, so the scheduler becomes empty only when all active paths have completed or the workflow is waiting.

After the scheduler drains, the workflow becomes Finished when all activity contexts are complete or canceled. If active bookmarks or other unfinished activity work remain, the workflow becomes Suspended. A workflow can also become Faulted after an unhandled exception, or Cancelled when cancellation clears bookmarks and completion callbacks.

The Finish activity is an explicit terminal action. It clears pending work and bookmarks, then marks the workflow as finished. Activity completion is narrower: it ends one activity visit, not necessarily the whole workflow. A loop container also remains active until its bounds, item source, or completion tags show that no body work remains.

References: src/…/DefaultActivitySchedulerMiddleware.cs• L27-48 src/…/WorkflowExecutionContextExtensions.cs• L127-130 src/…/Finish.cs• L7-26 src/…/WorkflowSubStatus.cs• L6-45 src/…/WorkflowExecutionContext.cs• L560-578 src/…/WorkflowExecutionContext.Cancel.cs• L11-36 src/…/For.cs• L95-123 src/…/ForEachT.cs• L81-107 src/…/ParallelForEachT.cs• L98-114

Failure handling

Failure handling keeps activity faults local when an enclosing activity can recover them. The activity pipeline catches exceptions, marks the activity as faulted, and offers a fault signal to ancestor activities. If no ancestor handles it, an incident strategy records the fault. Workflow-level exceptions create a workflow incident and move the workflow to Faulted.

Cancellation is separate from fault handling. A cancellation request cancels the workflow and its children, while the runner does not record an operation-cancel exception as the workflow's fault.

References: src/…/ExceptionHandlingMiddleware.cs• L19-47 src/…/ExceptionHandlingMiddleware.cs• L20-62 src/…/WorkflowExecutionContext.Cancel.cs• L11-36

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the activity state shape aligned with the activity context fields used for resume, especially status, parent context, evaluated inputs, dynamic variables, and active execution markers.
  • Keep bookmark creation and bookmark resumption aligned on bookmark identity, activity instance identity, callback selection, and automatic burn or completion rules.
  • Keep container completion callbacks aligned with scheduling ownership. A change to structural ownership must not change the activity that receives the child-completed signal.
  • Keep loop progress state aligned with completion callbacks. Sequential loops must advance the next index or step once per body completion, while parallel loops must retain every scheduled tag until its matching body visit completes.
  • Keep scheduled loop variable IDs distinct across nested loops and keep their declaration in the child context's memory so one loop cannot overwrite another loop's current item.
  • Keep input JSON shape aligned with expression descriptors. Plain values must remain literals, empty expressions must remain empty inputs, and unknown expression types must fail rather than silently change meaning.
  • Keep synthetic activity fields aligned with activity descriptors and serializer options. Their JSON names must not collide with normal activity properties or with each other.
  • Keep flowchart outcome names aligned with connection ports and with the selected join or merge rules.
  • Keep state-machine transition tags and trigger identities aligned with completion callbacks so a completed trigger resolves the intended transition.
  • Keep output recording aligned with output descriptors so activity-level lookup and workflow-level result lookup resolve the same value.
  • Keep workflow status changes aligned with scheduler draining and bookmark persistence so a waiting workflow is not reported as finished.
  • Keep saved node identities, owner context IDs, callback child node IDs, and scheduled work item IDs aligned with the workflow definition used during restore.

Important failure modes

TriggerConsequenceGuard
An activity schedules an object that is not in the workflow graphScheduling fails and the workflow cannot advance along that pathValidate graph membership before scheduling the activity.
An input expression cannot be evaluatedThe activity does not run and the input error is surfaced as an input evaluation failureTreat input evaluation as a required step before activity execution.
Serialized input names an expression type with no registered descriptorDeserialization throws a JSON error and the workflow definition cannot loadRegister the expression descriptor or use a supported literal or expression type.
An activity has synthetic fields with duplicate JSON namesSerialization throws a JSON error and the activity definition cannot be writtenKeep descriptor names distinct from normal property names and from other synthetic fields.
A custom activity serializer produces a non-object valueSerialization throws because an activity must have an object representationKeep custom activity representations compatible with the activity JSON contract.
A synthetic input expression has no registered descriptorSerialization fails before the synthetic field can be writtenRegister the expression descriptor used by the activity input.
An activity creates a bookmark and does not completeThe workflow remains resumable instead of finishingResume the saved activity context through the matching bookmark.
A sequential loop body never reports completionThe loop does not advance to its next item or stepPreserve the body completion callback when scheduling the next iteration.
A parallel loop loses a scheduled or completed tagThe loop may never complete even after body work endsKeep tag creation and completion recording paired for every scheduled body visit.
A flowchart target receives no valid active outcomeThe target path is skipped or the flowchart can remain with no pending workMatch outcome names to source connection ports.
A state machine reuses a trigger activity or trigger ID across transitionsThe state machine rejects the trigger identities before it can run reliablyGive each transition its own trigger activity with a unique ID.
A saved activity node or callback reference is absent from the target definitionThe extractor skips that state reference and the workflow may lose a pending path or callbackPreserve node identities across definition changes or handle migration explicitly.
An unhandled activity exception reaches workflow middlewareThe workflow records an incident and becomes faultedHandle the fault in an ancestor only when recovery is complete.
Completion is called while an activity is not runningThe call has no effect and the activity remains in its prior stateComplete only from an active activity execution path.

Key files

FileWhy to read it
src/…/Activity.csDefines the activity contract and the base behavior for execution, preconditions, completion, and signals.
src/…/Workflow.csShows how the top-level workflow acts as a composite activity with inputs, outputs, variables, and a root activity.
src/…/WorkflowExecutionContext.csDescribes the state and relationships held for one workflow run.
src/…/ActivityExecutionContext.csDescribes one activity visit and its memory, scheduling, bookmark, and output boundaries.
src/…/WorkflowRunner.csShows how a workflow starts, resumes, advances, extracts state, and returns a result.
src/…/WorkflowStateExtractor.csShows how active contexts, callbacks, inputs, bookmarks, and scheduled work become restorable workflow state.
src/…/ActivityWorkItemState.csDefines the saved shape of a scheduled activity hand-off and its resume links.
src/…/DefaultActivitySchedulerMiddleware.csShows how scheduled work drives the workflow until it finishes or suspends.
src/…/DefaultActivityInvokerMiddleware.csShows the activity-level execution order and the points where inputs, completion, bookmarks, and commits interact.
src/…/Sequence.csIllustrates callback-driven sequential progression and preserved completion ownership during direct rescheduling.
src/…/Parallel.csIllustrates fan-out and completion after all child work returns.
src/…/For.csIllustrates bounded numeric iteration with a persistent current step and one body visit at a time.
src/…/ForEachT.csIllustrates typed sequential collection iteration and scoped current-item variables.
src/…/ParallelForEachT.csIllustrates parallel collection iteration and completion tracking for all body visits.
src/…/StateMachine.csIllustrates state entry, trigger-driven transitions, competing-trigger cancellation, and automatic-cycle scheduling.
src/…/Flowchart.csDefines the flowchart container and its start and completion boundary.
src/…/Flowchart.Tokens.csIllustrates outcome-driven path tracking, token cleanup, and merge-mode scheduling for flowchart execution.
src/…/Bookmark.csDefines the persisted waiting point used to resume an activity.
src/…/Variable.csDefines scoped workflow memory and its optional persistence boundary.
src/…/JsonActivitySerializer.csDefines the activity JSON boundary and the rules for ordinary and synthetic activity properties.
src/…/SyntheticPropertiesWriter.csShows how descriptor-defined inputs and outputs are added to an activity representation.
src/…/InputJsonConverter.csShows how typed inputs, literals, empty expressions, and expression descriptors cross the JSON boundary.
src/…/ExpressionJsonConverter.csShows how expression types are resolved and how non-serializable expression values are handled.