Workflows

Definitions, stages, and instances

A definition describes a process. An instance is one run of it, pinned to the definition version it started under and sitting in exactly one stage.

A workflow definition is the authored, deployable description of a process. It combines fields, stages, transitions, activities and actions, conditions, effects, and guards into one versioned contract.

An instance is the stored state of one run. One definition can produce many instances. Each has its own field values, current stage, history, pending effects, and child workflows.

Definition versioning

Use defineWorkflow to author a definition:

const articleReview = defineWorkflow({
  name: 'article-review',
  title: 'Article review',
  initialStage: 'drafting',
  fields: [
    defineField({
      type: 'subject',
      name: 'subject',
      initialValue: {type: 'input'},
      required: true,
    }),
  ],
  stages: [
    defineStage({
      name: 'drafting',
      transitions: [defineTransition({name: 'submit', to: 'review', when: 'true'})],
    }),
    defineStage({name: 'review'}),
  ],
})

The definition is the whole process, written out. defineWorkflow validates it before anything reaches the Content Lake. It reads the shape you authored, expands the shorthand into what actually gets stored, then checks the rules that span more than one field: names must be unique, every transition target must name a declared stage, every stage must be reachable, and no named predicate may reuse the name of a built-in variable. If anything is wrong, one error lists every problem with its path.

defineWorkflow("article-review") failed validation (3 issues):
  - stages[1].transitions[0].to: transition target "ready" is not a declared stage. Known stages: "drafting", "review", "approved"
  - stages[2].name: stage "approved" is unreachable — no transition path leads from initialStage "drafting" to it, so no instance can ever enter it. Add a transition targeting it, or remove the stage
  - predicates.allActivitiesDone: predicate "allActivitiesDone" shadows the built-in $allActivitiesDone — pick another name

Deploying stores a new version, and the version comes from the content itself. The engine turns the definition into a fingerprint and compares it with the latest version already deployed under the same name. If the fingerprint matches, deploying does nothing. If it differs in any way, the engine creates the next version. You never write a version number yourself, and deploying never edits a version that already exists: instances are pinned to those versions and have to keep finding them unchanged. Each version is its own document, with an ID of the form <partition>.<name>.v<version>.

The engine compares against the latest version only, not the whole history. Redeploy content that is identical to an older version and you get a new version, not a match with the old one. Version history only ever moves forward.

Pinned instance versions

An instance is one live run of a definition against content. When startInstance creates it, the engine pins three values onto the instance document and never changes them:

  • pinnedVersion: the definition version number this run started under.
  • pinnedContentHash: the fingerprint of that version, so you can tell when the definition has moved on.
  • definitionSnapshot: a frozen copy of the whole definition as it stood at that moment.

An instance uses its own snapshot for its whole life. Deploy version 4 of a definition while runs are still going on version 3, and nothing happens to those runs. They keep their version 3 stages and conditions, and they finish on version 3. New runs start on the highest deployed version, unless you pass an explicit version to startInstance.

No engine verb moves a running instance onto a newer definition version. If you need runs on the new shape, start new ones and let the old ones finish. Plan definition changes around that: a stage you delete in version 4 still exists for every instance pinned to version 3. Compare pinnedContentHash against the deployed definition to detect a run whose definition has moved on. Like every engine-side check, that is advisory. The Content Lake is the only enforcement point.

Stages, stage visits, and terminal stages

An instance is in exactly one stage at a time. It begins at the definition’s initialStage. The current stage decides which scoped fields, activities, actions, guards, and outgoing transitions are in play.

A stage does not have to contain work. It can receive an instance, wait for something outside the workflow, route on immediately, or stand for an outcome. A stage with no outgoing transitions is terminal, and reaching it completes the instance.

Stage shape

A stage declares:

defineStage({
  name: 'review',
  title: 'Review',
  fields: [
    defineField({type: 'string', name: 'decision'}),
  ],
  activities: [
    defineActivity({
      name: 'editorial-review',
      actions: [
        defineAction({name: 'approve', status: 'done'}),
      ],
    }),
  ],
  transitions: [
    defineTransition({
      name: 'to-published',
      to: 'published',
      when: '$allActivitiesDone',
    }),
  ],
})

A stage combines location-specific state with optional behavior. Fields explains stage scope and Activities and actions explains the work model.

Stage visits

Entering a stage resolves its scoped fields, creates its activities, and registers its guards. Re-entering the same stage creates a new visit, and earlier visits stay in history.

Activities are active from the moment the instance enters the stage, until an action gives them a final status. A stage with no activities is still valid. Finishing the activities never moves the instance on its own: only a transition moves it.

Transitions and routing conditions

A transition is a one-way link to another stage. Its when condition decides when it fires using the transition’s GROQ variables.

defineTransition({
  name: 'to-review',
  to: 'review',
  when: 'defined($fields.reviewer)',
})

If when is omitted, authoring expands it to $allActivitiesDone. Use when: 'true' to route without a condition.

A transition holds no operations and no effects. Actions write the routing decision into fields, and transitions read those fields through conditions. Work that should happen on arrival belongs to a triggered action in the destination stage. Work that must happen before the move belongs to an action in the stage you are leaving.

Selection, cascade, and settling

After each committed operation, the engine checks every outgoing transition on the current stage, in the order you declared them. The first one whose condition holds fires. The instance leaves the current stage, enters the target, and the engine looks at the new state again. Declaration order is your routing priority, so put the specific route above the catch-all: the catch-all wins as soon as it can fire.

A condition the engine cannot decide stops selection. It does not fall through to the next transition. GROQ returns null when a value is missing or cannot be compared, and null is not the same as false. Since the engine cannot tell whether the route applies, it fires nothing rather than pushing the instance past an undecided gate into a later catch-all. Selection runs again on the next commit, once the missing value arrives.

Triggered actions and transitions can make one another eligible, so the engine continues the cascade until the instance settles or reaches a terminal stage. The cascade moves one stage per hop, and each hop is a single commit. Within a hop, triggered actions run until none is left to fire, transition selection reads the state they produced, and then the hop is saved. Each hop is its own commit, so the stage an instance moves into runs its own triggered actions in the next hop, and a multi-stage run is saved stage by stage. Transitions decide movement, and nothing else has the complete edge shape.

The instance settles on the first hop where no transition fires. That is where the run stops and the call returns. A cascade is capped at 100 hops. Beyond that, the engine throws CascadeLimitError rather than looping forever. Hitting the cap almost always means two conditions are contradicting each other and bouncing the instance back and forth.

Nothing in Workflows runs on a timer. The engine is a library, not a service, so a cascade only ever runs inside a call you made: startInstance, fireAction, tick, or completeEffect. A transition that should fire when a deadline passes needs something to call tick after the clock crosses it. If nobody calls, the instance stays where it is.

Starting an instance

Starting an instance creates one stored run from a deployed definition. startInstance pins the definition snapshot, enters the initial stage with every in-scope activity active, and cascades until the instance settles. It checks the caller's initial fields and the definition's start requirements before writing anything, and a caller-supplied instance ID makes a retried start resume instead of creating a second run. Like every engine-side check, the start checks are advisory: anyone holding a write token can create documents in the Content Lake directly, so a start rule that has to hold belongs in a guard or dataset access control.

Start a workflow instance builds the subject reference, pre-flights the start, and handles a refused or interrupted start. Start filters and requirements explains the difference between discovering a workflow and being allowed to start it.

Decide who may abort an instance

Aborting hard-stops a running instance where it stands. Without an abort block, anyone who can write the instance may abort it. Declare abort: {roles: [...]} beside start to limit that to the listed roles. The roles work like an action's roles, including roleAliases:

defineWorkflow({
  name: 'article-review',
  title: 'Article review',
  initialStage: 'draft',
  abort: {roles: ['editor', 'administrator']},
  stages: [defineStage({name: 'draft', title: 'Draft'})],
})

abortInstance refuses a caller outside the roles with AbortDeniedError before writing. Every caller is checked, Administrators included. Evaluations report the same answer as WorkflowEvaluation.abort, so a UI can hide its abort control for that actor. Unlike start.filter, which only controls discovery, the abort roles refuse the call.

Subworkflows stop under their parent's rules. When a parent aborts, or leaves a stage whose spawn uses onExit: 'abort', its children stop without checking their own abort roles. Instances that deleteDefinition aborts with cascade are not checked either.

A definition with an abort block requires reader model 11. Upgrade every runtime sharing the workflow resource, then set the deployment's expectedMinReaderModel to 11 before deploying it. See Upgrade Workflows packages. Like every engine check, this one is advisory: Content Lake permissions still decide who can write the instance.

Stored instance state

An instance is an engine-owned sanity.workflow.instance document. It records the pinned definition, current stage, resolved fields, stage-visit history, effects, child workflows, audit history, and lifecycle timestamps for one run.

To update an instance, use the engine rather than ordinary content patches.

Instance previews

instancePreviewsQuery returns WorkflowInstancePreview rows for list and dashboard surfaces. A preview keeps the current stage, list-relevant fields, open activities, lifecycle timestamps, ancestry, perspective, and any claimed or failed effects. It leaves out the definition snapshot and the audit history, neither of which has a size limit. Parse each row with readInstancePreviewDoc.

Use filter.limit for newest-first pages and pass the previous page’s last {id, startedAt} as filter.before. Paging this way keeps pages from shifting when runs start or finish between reads. Other instance filters, including definition and includeCompleted, work on previews too.

const page = instancePreviewsQuery({
  partition: 'dev',
  filter: {
    includeCompleted: true,
    limit: 500,
    before: previousLastRow,
  },
})

const changes = instanceChangesQuery({partition: 'dev'})

instanceChangesQuery builds one listen filter covering every instance in the partition. Listen once, refetch the preview that changed by ID, and resynchronize after the listener reconnects. A React host does not need to do this itself: useInstancePreviews already provides this paging and refresh behavior.

Next steps

Visiting agent?

Was this page helpful?

Sanity logosanity.ioAll Systems Operational© Sanity 2026
Change site theme