Skip to content
GitHub

Variables and Scope

Workflow variables are the data that flows through a Fleans workflow. They carry inputs from POST /Execution/start, are mutated by script tasks and service tasks, get read by gateway conditions and output mappings, and end up persisted alongside the workflow’s event stream.

This guide covers the mental model, how to read and write variables from script tasks, how scopes nest and inherit, and — most importantly — when a child scope’s variables flow back to the parent.

Each workflow instance starts with a single root variable scope. As the workflow executes, the engine opens new child scopes for embedded SubProcesses, event sub-processes (ESPs), multi-instance loop bodies, parallel-fork branches, and compensation handlers. Scopes are organised as a tree rooted at the workflow.

Inside each scope, variables live in an ExpandoObject — a dynamic dictionary-like container. The container is mutated in place by script tasks and serialized via Newtonsoft.Json for persistence.

Types that round-trip cleanly:

  • Numbers (int, long, double, decimal)
  • Strings
  • Booleans
  • Nested objects (you can build a tree by assigning one ExpandoObject’s field to another)
  • Arrays / lists of the above

A field that has never been assigned is null when accessed dynamically — there is no “missing” sentinel distinct from null at the scripting layer.

Inside a <scriptTask scriptFormat="csharp">, the script is split on ; and each expression is compiled on its own with one parameter, _context — the active scope’s ExpandoObject. There are no local variables, so you read a variable by using it on the right-hand side of an assignment to _context:

_context.greeting = "hello, " + _context.userName;
_context.city = _context.user.address.city;
_context.tier = _context.amount > 1000 ? "gold" : "standard"

The rules in short (full list: what a script can contain):

  • Expressions and assignments only — no if, throw, loops, var locals or helper methods. Use cond ? a : b for branching.
  • Not every C# construct parses — notably implicitly-typed array literals (new[] { 1, 2, 3 }) are rejected; use new List<object> { 1, 2, 3 } instead.
  • Scripts are compiled at deploy: one that does not parse rejects the deploy. An exception at run time fails the activity with code 500.

Keep logic linear, and put complex computation behind a custom service-task plugin (see Writing Custom-Task Plugins).

Assignment writes the field on the active scope’s ExpandoObject:

_context.greeting = "hello, " + _context.userName;
_context.total = _context.price * _context.qty

Persistence is event-sourced: at the end of the activity, the engine takes a snapshot of the mutated scope and emits the appropriate domain event. If a script task fails (throws), the partial mutations are not committed — the activity transitions to its error path with the variables it had on entry.

Reads walk up the chain. When a script task in a child scope reads _context.foo, the engine resolves foo by checking the active scope first, then its parent, then its grandparent, up to the root.

Every child scope reads up the chain to the root, but its writes reach the parent only through an explicit merge; multi-instance iterations hand back only their outputElement. Open interactive diagram ↗

Writes are scope-local. _context.foo = ... creates-or-updates foo on the active scope only. It does not mutate any ancestor scope. The only way a child scope’s variables reach an ancestor is via an explicit merge event — see Merge semantics below.

This is the source of the common pitfall “my SubProcess wrote a variable but the parent doesn’t see it” — see Common pitfalls.

Fleans records scope changes with five variable-scope domain events:

  • ChildVariableScopeCreated(ScopeId, ParentScopeId) — a new empty child scope opens that resolves reads via its parent
  • VariableScopeCloned(NewScopeId, SourceScopeId, Detached) — a new scope opens pre-populated with a snapshot of the source scope’s variables (no parent link required for resolution). Detached marks a clone that no join will merge back: a boundary or escalation branch’s
  • VariablesMerged(VariablesId, Variables) — a set of fields is merged into an existing scope (last-write-wins on the merged keys)
  • VariableScopeTrimmed(ScopeId, RemovedNames) — a detached clone keeps only what its branch changed
  • VariableScopesRemoved(ScopeIds) — listed scopes are deleted from the workflow’s scope tree

The engine emits them in the following situations:

  • Embedded SubProcess entry — opens a ChildVariableScopeCreated so the SubProcess body sees enclosing variables but its writes stay local until merge.
  • Event sub-process activation (interrupting + non-interrupting) — handler activation creates a fresh child scope and (when the trigger carries data, e.g. a message payload) merges those fields into the new scope.
  • Multi-instance loop body — each iteration opens a ChildVariableScopeCreated child of the host scope (reads resolve through the host), seeded with loopCounter and the per-iteration item value.
  • Parallel fork branches — every outgoing branch from a parallel fork gets a VariableScopeCloned snapshot of the fork-time variables, giving each branch an isolated copy.
  • Compensation handler activation — each handler gets a fresh child scope that sees the compensable activity’s completion-time snapshot, overlaying the enclosing scope. When the handler completes, only the variables it changed merge back into the enclosing scope; a snapshot value it merely read never overwrites a later one.
  • Non-interrupting boundary events — the branch runs on a detached clone of the host’s variables, so its writes never reach the host.
  • Escalation handler activation — host scope is cloned for the handler as a detached clone; if the escalation throw carries variables they are merged in.
  • Activity input mappings — an activity with <fleans:input> mappings gets its own child scope (ActivityInputScopeOpened) holding the evaluated inputs; it executes against that scope, and the scope is removed when it completes. Inputs never reach the enclosing scope; <fleans:output> mappings, when present, are the only variables that do. See Input/Output Mapping.
  • Branch / scope cleanup — once a join completes (or an interrupting boundary cancels siblings), the consumed child scopes are removed via VariableScopesRemoved.
  • Detached clone cleanup — when a detached clone’s branch ends (nothing active runs on it, no open fork will merge into it, no child scope or conditional watcher reads it), it is reduced via VariableScopeTrimmed to the variables that differ from the scope it was cloned from, or removed via VariableScopesRemoved if none do. A branch’s result therefore stays visible in GET /Instances/{id}/state and on the instance page, while its copy of the host’s other variables goes. A clone used by a failed activity stays whole for diagnosis.

This list covers the categories, not every code path.

This is the section everyone gets wrong. The rule is: a child scope’s variables do NOT reach an ancestor until an explicit VariablesMerged event targets the ancestor. The cases below cover when that merge happens.

WorkflowExecution.AdvanceCompensationWalkIfHandlerCompleted emits a VariablesMerged event with the handler’s full variable map targeting the parent scope’s variables ID (root scope’s if the walk is at root).

Parallel fork-join — merge AT JOIN, not as-you-go

Section titled “Parallel fork-join — merge AT JOIN, not as-you-go”

Parallel branches run with isolated scopes (each branch gets a VariableScopeCloned snapshot at fork time). A branch writing _context.shared = "A" does not affect a sibling branch.

When all branches arrive at the join gateway, the engine merges each branch’s variables into the original (pre-fork) scope in token-creation order — last write wins — and then emits VariableScopesRemoved for the now-consumed branch scopes. After the join, exactly one scope remains for the joined token.

This is the behaviour exercised by the parallel-variable-isolation.bpmn fixture: the merged scope contains shared with the last branch’s value, and both branches’ branch-local variables end up in the merged scope.

When an embedded SubProcess completes normally, its child scope’s variables are merged back into the enclosing scope before the SubProcess scope is removed. Variables written inside the SubProcess become visible in the parent after completion. With <fleans:output> mappings on the SubProcess, only the mapped outputs are merged; its input-mapping targets are never merged.

Event sub-processes (interrupting / non-interrupting)

Section titled “Event sub-processes (interrupting / non-interrupting)”

Both flavours run in fresh child scopes seeded from the enclosing scope (and trigger payload, if any). For an event sub-process inside an embedded SubProcess, the enclosing scope is the SubProcess’s own scope, so the handler sees the SubProcess’s local variables. When the handler completes, its scope is removed; its writes do not reach the enclosing scope. Completing a handler never touches other scopes, so a running SubProcess, multi-instance iterations or another handler keep theirs (#840).

Each iteration runs in a child scope of the host’s scope: reads resolve through the host, writes stay on the iteration’s scope, so per-iteration writes stay isolated. After all iterations complete, the multi-instance activity completes; to aggregate results across iterations, use outputCollection / outputElement (see Multi-Instance Activities). Per-iteration scopes are removed at completion; their variables do not auto-merge en masse into the host.

“My script task wrote _context.x = 5 but a downstream task sees null”

The downstream task is probably running in a sibling scope or a parent scope, not a descendant. Writes are scope-local — only descendants and the same scope read your write. If you wrote inside a SubProcess and the reader is after the SubProcess, the write becomes visible only after the SubProcess merges (which happens at SubProcess completion).

“Branch A wrote _context.shared = 'A' but Branch B sees the pre-fork value”

This is correct, by design. Parallel-fork branches are isolated (VariableScopeCloned at fork). Cross-branch communication has to go through a join + the merged post-join scope, not through shared variables mid-fork.

“My script task threw, and the variable I wrote earlier in the same script disappeared”

Correct. Script-task failure rolls back the in-flight scope mutations for that activity. Split work that must persist independently across multiple script tasks.

“What type does a nested JSON value have?”

Variables sent over REST are re-read with Newtonsoft.Json into an ExpandoObject: a nested JSON object becomes a nested ExpandoObject (so _context.user.address.city works), an array becomes a List<object>, and whole numbers arrive as long.

Each operation that passes variables to an instance is capped at Fleans:Variables:MaxSizeBytes (default 1 MiB, measured as JSON). The cap applies to start variables, activity completion variables, user-task completions and message deliveries. The engine rejects a larger document before it changes anything:

  • A REST call (POST /Execution/start, complete-activity, user-task completion, sending a message) returns 400 Bad Request.
  • A script task or custom task whose result is too large fails its activity, so an error boundary event can catch it.
  • A custom task that fails with oversized variables still fails its activity, but the variables are dropped.

A script task hands back its whole scope, so for scripts the cap effectively limits the scope size. Keep large payloads (documents, files) outside the workflow and pass a reference such as a URL or an id. See Configuration.

The canonical fixture for variable-scope behaviour is parallel-variable-isolation.bpmn:

  • A pre-fork script task sets shared to an initial value.
  • A parallel fork creates two branches; each writes a different value to shared.
  • The branches join. The merged scope contains a single shared field — the last branch’s value (in token-creation order) — plus any branch-local fields each branch wrote, all consolidated into one scope.
  • The two transient branch scopes are removed (VariableScopesRemoved). The instance completes with one scope.

For SubProcess merging, see the 07-subprocess fixture. For compensation merging, see 24-compensation-event.

  • BPMN Support — which BPMN elements open new scopes
  • API Reference — POST /Execution/start initial variables, POST /Execution/complete-activity output variables
  • Persistence — how variable state and scope-tree events are serialized
  • User Tasks — output variable mappings on user-task completion