Skip to content
Merged
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- **Several initial steps.** More than one step can set `initial true`. `AshWorkflow.Transformers.AddStateMachine` passes every initial step to the state machine's `initial_states`, and a create action starts a record in one with `change transition_state(:step)`. A create that sets no state starts in the first initial step by declaration order. The reachability check in `AshWorkflow.Verifiers.ValidateWorkflow` starts from every initial step. A step reached only from a second initial step is no longer reported as unreachable. `AshWorkflow.Info.initial_steps/1` and `AshWorkflow.Entities.Step.find_initials/1` list the initial steps, and `AshWorkflow.Info.workflow_graph/1`, the charts and the Clarity overview mark each of them.

### Changed

- The unreachable-step error names the initial step it searched from ("not reachable from the initial step :review") rather than "the first step".
- `AshWorkflow.Verifiers.ValidateWorkflow` no longer raises "Only one step can have initial: true".
- `AshWorkflow.Verifiers.ValidateWorkflow` rejects a create action whose `transition_state` names a step that is not initial. Before, the create failed at runtime.
- `AshWorkflow.Verifiers.ValidateWorkflow` rejects an upserting create action that calls `transition_state`. ash_state_machine only lets an upsert move to a state that a transition declares for that action, and a workflow declares none for creates.
- The unreachable-step error suggests `initial true` for an unreachable step that no other step leads into.

## [0.12.0] - 2026-11-06

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ From the workflow DSL, the extension generates:
| **Calculations** | `:steps`, `:current_step`, `:available_actions`, `:transition_targets`, `:pending_deadlines`, `:workflow_terminated_at` | Workflow introspection |
| **Attributes** | `state_entered_at`, plus one last-fired column per `every` | Added if not already defined |

The initial state is the step with `initial true`, or the first non-terminal step by declaration order if none is marked. Declaration order is easy to trip over, so mark the step when the reading order is not the running order:
The initial state is the step with `initial true`, or the first non-terminal step by declaration order if none is marked. Several steps can be marked initial when records start in different places. See [Initial state](documentation/topics/automatic-vs-manual-steps.md#initial-state). Declaration order is easy to trip over, so mark the step when the reading order is not the running order:

```elixir
workflow do
Expand Down
2 changes: 1 addition & 1 deletion documentation/dsls/DSL-AshWorkflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Declares a step in the workflow. Each step becomes a state in the generated stat
| Name | Type | Default | Docs |
|------|------|---------|------|
| [`action`](#workflow-step-action){: #workflow-step-action } | `atom` | | The action to run for automatic steps. Must reference a user-defined update action on the resource. |
| [`initial`](#workflow-step-initial){: #workflow-step-initial } | `boolean` | `false` | If true, this step is the initial state. At most one step can be marked initial. If none are, the first non-terminal step by declaration order is used. |
| [`initial`](#workflow-step-initial){: #workflow-step-initial } | `boolean` | `false` | If true, a create action can start a record in this step. Several steps can be marked initial, and the first by declaration order is the state a create starts in when it sets none. If no step is marked, the first non-terminal step by declaration order is the only initial step. |
| [`terminal`](#workflow-step-terminal){: #workflow-step-terminal } | `boolean` | `false` | Asserts that this is an end state. A step that declares no action, no transitions, no timeouts, no on_success and no on_error is terminal whether or not this is set, so it is only needed to state the intent — the verifier then rejects the step if it grows an outgoing declaration. |
| [`on_error`](#workflow-step-on_error){: #workflow-step-on_error } | `atom` | | The step to transition to on failure. Optional, for automatic steps. |
| [`policy`](#workflow-step-policy){: #workflow-step-policy } | `any` | | An Ash policy check to apply to all transitions in this step. Accepts any {module, opts} tuple implementing Ash.Policy.Check. |
Expand Down
51 changes: 49 additions & 2 deletions documentation/topics/automatic-vs-manual-steps.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,53 @@ workflow do
end
```

At most one step can have `initial true`. If none do, the first non-terminal step is used.
If no step has `initial true`, the first non-terminal step is used.

The extension sets `default_initial_state` and `initial_states` on the generated state machine.
### Several initial steps

A workflow whose records start in different places marks each starting step with `initial true`. A create action that sets no state starts in the first of them by declaration order. Any other create action names its starting step with `transition_state`:

```elixir
workflow do
step :self_service_intake do
initial true
transition :submit, to: :review
end

step :staff_intake do
initial true
transition :submit, to: :review
end

step :review do
transition :approve, to: :done
end

step :done, terminal: true
end

actions do
# Starts in :self_service_intake, the first initial step.
create :open do
accept [:title]
end

create :open_by_staff do
accept [:title]
change transition_state(:staff_intake)
end
end
```

Every step must be reachable from at least one initial step. The compiler also reports:

- A create whose `transition_state` names a step that is not marked initial is a compile error.
- An unreachable step that no other step leads into gets a hint to mark it `initial true`.

Once any step sets `initial true`, the first non-terminal step is no longer initial unless it sets `initial true` too.

#### Upserting creates

An upserting create cannot name its starting step. ash_state_machine only lets an upsert move to a state that a transition declares for that action, and the workflow declares none for creates. A create with `upsert? true` and `transition_state` is a compile error, even for a step marked initial. An upserting create starts a new record in the first initial step. An upsert onto an existing record leaves it in the step it was in, as long as `upsert_fields` does not include the state attribute.

The extension sets `initial_states` to every initial step, and `default_initial_state` to the first, on the generated state machine.
4 changes: 2 additions & 2 deletions documentation/topics/diagrams.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ stateDiagram-v2
| Automatic step | `⚙️ automatic` under the step name |
| Manual step | `✋ manual` under the step name |
| Wait state, where a timeout is the only exit | `⏳ wait state` under the step name |
| Initial step | An edge from the start marker |
| Initial step | An edge from the start marker, one per initial step |
| Terminal step | An edge to the end marker |
| `on_success` | `⚙` and the step's action |
| `on_error` | `✖ on_error` |
Expand Down Expand Up @@ -526,7 +526,7 @@ colours".

#### Layout

`dot` puts the steps in ranks, from the initial step down to the end steps.
`dot` puts the steps in ranks, from the initial steps down to the end steps.
An undo edge points back up to the earlier step, next to the edge that it
undoes. The file writes it from the earlier step, with `dir="back"`, so the
steps keep their forward order. The arrowhead is at the tail, so the `undo`
Expand Down
4 changes: 3 additions & 1 deletion documentation/tutorials/getting-started-with-ash-workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ From that DSL, AshWorkflow generates:
>
> AshWorkflow does not generate one. A workflow record's creation inputs are specific to your application, so the extension leaves `create` to you and only adds the changes that set the initial state and `state_entered_at`. A resource with a `workflow` block and no create action compiles, and then nothing can start a workflow.

`:auto_check` becomes the initial state because it is the first step by declaration order that is not terminal. `AshWorkflow.Entities.Step.find_initial/1` picks it. To name the initial step instead of relying on declaration order, mark it:
`:auto_check` becomes the initial state because it is the first step by declaration order that is not terminal. `AshWorkflow.Entities.Step.find_initials/1` picks it. To name the initial step instead of relying on declaration order, mark it:

```elixir
workflow do
Expand All @@ -127,6 +127,8 @@ end

Without `initial true` that workflow would start in `:review`, because `:review` is declared first. A step that declares transitions has to set `initial` inside its block: `step :intake, initial: true do ... end` does not compile, because the DSL macro takes either options or a block.

Several steps can set `initial true` when records start in different places. See [Several initial steps](../topics/automatic-vs-manual-steps.md#several-initial-steps).

## Use the workflow

```elixir
Expand Down
4 changes: 2 additions & 2 deletions lib/ash_workflow/charts/dot.ex
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ defmodule AshWorkflow.Charts.Dot do
| Manual step | Amber box, `✋ manual` under the name |
| Wait state | Lavender box with a dashed border, `⏳ wait state` under the name |
| Terminal step | Double border. Green, red, amber or grey: see "Terminal steps" |
| Initial step | An edge from a small filled circle |
| Initial step | An edge from a small filled circle, one per initial step |
| `on_success` | Thick blue edge, `⚙` and the action |
| `on_error` | Red edge, `✖ on_error` |
| Timeout | Dashed amber edge, `⏱`, the timeout's name and its deadline |
Expand Down Expand Up @@ -48,7 +48,7 @@ defmodule AshWorkflow.Charts.Dot do

## Layout

`dot` puts the steps in ranks, from the initial step to the end steps. An
`dot` puts the steps in ranks, from the initial steps to the end steps. An
edge that closes a loop, such as a transition back to an earlier step,
goes back up the ranks.

Expand Down
2 changes: 1 addition & 1 deletion lib/ash_workflow/charts/graph/node.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ defmodule AshWorkflow.Charts.Graph.Node do
A timeout is the only way out.
* `:terminal` — an end state.

`initial?` is `true` for the step the workflow starts in. `notes` holds what
`initial?` is `true` for each step a record can be created in. `notes` holds what
the step does without leaving it, so it has no edge: its policy, its retry
policy, the timeouts that run an action, and its `every` entries.
"""
Expand Down
4 changes: 2 additions & 2 deletions lib/ash_workflow/charts/mermaid.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ defmodule AshWorkflow.Charts.Mermaid do
* Each step that is not terminal has a description line with its kind:
`⚙\u{FE0F} automatic`, `✋ manual` or `⏳ wait state`. The gear carries
U+FE0F, so it draws as a colour emoji, the same as the other two.
* The initial step has an edge from `[*]`, and every terminal step has an
edge to `[*]`.
* Every initial step has an edge from `[*]`, and every terminal step has
an edge to `[*]`.
* An edge label starts with a symbol for its kind: `⚙` for `on_success`,
`✖` for `on_error`, `📨` for an `on_signal`, `⏱` for a timeout and `↶`
for undo. A transition has no symbol. A timeout edge gives the timeout's
Expand Down
12 changes: 10 additions & 2 deletions lib/ash_workflow/clarity/content/workflow_overview.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,17 @@ with {:module, _} <- Code.ensure_loaded(Clarity.Content),
]
end

defp initial_label([_]), do: "Initial step"
defp initial_label(_), do: "Initial steps"

defp initial_links(_resource, []), do: "—"

defp initial_links(resource, nodes),
do: nodes |> Enum.map(&step_link(resource, &1.id)) |> Enum.intersperse(", ")

defp summary(resource, graph) do
counts = Enum.frequencies_by(graph.nodes, & &1.kind)
initial = Enum.find(graph.nodes, & &1.initial?)
initial_nodes = Enum.filter(graph.nodes, & &1.initial?)

kinds =
for kind <- [:automatic, :manual, :wait_state, :terminal], count = counts[kind] do
Expand All @@ -63,7 +71,7 @@ with {:module, _} <- Code.ensure_loaded(Clarity.Content),
["Property", "Value"],
[
["State attribute", code(Info.state_attribute(resource))],
["Initial step", if(initial, do: step_link(resource, initial.id), else: "—")],
[initial_label(initial_nodes), initial_links(resource, initial_nodes)],
["Steps", "#{length(graph.nodes)} (#{Enum.join(kinds, ", ")})"],
["Moves", Integer.to_string(Enum.count(graph.edges, &(&1.kind != :undo)))],
["Undo", undo(resource)],
Expand Down
25 changes: 19 additions & 6 deletions lib/ash_workflow/entities/step.ex
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ defmodule AshWorkflow.Entities.Step do
type: :boolean,
default: false,
doc:
"If true, this step is the initial state. At most one step can be marked initial. If none are, the first non-terminal step by declaration order is used."
"If true, a create action can start a record in this step. Several steps can be marked initial, and the first by declaration order is the state a create starts in when it sets none. If no step is marked, the first non-terminal step by declaration order is the only initial step."
],
terminal: [
type: :boolean,
Expand Down Expand Up @@ -167,12 +167,25 @@ defmodule AshWorkflow.Entities.Step do
do: is_nil(List.last(routes).when)

@doc """
Finds the initial step from a list of steps.
Finds the steps a record can be created in.

Returns the step with `initial: true`, or falls back to the first
non-terminal step by declaration order.
Returns every step with `initial: true` in declaration order, or the first
non-terminal step when none is marked.
"""
def find_initial(steps) do
Enum.find(steps, & &1.initial) || steps |> Enum.reject(&terminal?/1) |> List.first()
@spec find_initials([t()]) :: [t()]
def find_initials(steps) do
case Enum.filter(steps, & &1.initial) do
[] -> steps |> Enum.reject(&terminal?/1) |> Enum.take(1)
initial_steps -> initial_steps
end
end

@doc """
Finds the step a record starts in when its create action sets no state.

Returns the first of `find_initials/1`, or `nil` when the workflow has no
non-terminal step.
"""
@spec find_initial([t()]) :: t() | nil
def find_initial(steps), do: steps |> find_initials() |> List.first()
end
22 changes: 15 additions & 7 deletions lib/ash_workflow/info.ex
Original file line number Diff line number Diff line change
Expand Up @@ -270,13 +270,21 @@ defmodule AshWorkflow.Info do
end

@doc """
Returns the initial step for the workflow.
Returns the step a record starts in when its create action sets no state.
"""
@spec initial_step(Ash.Resource.t()) :: Step.t() | nil
def initial_step(resource) do
Step.find_initial(steps(resource))
end

@doc """
Returns every step a record can be created in, in declaration order.
"""
@spec initial_steps(Ash.Resource.t()) :: [Step.t()]
def initial_steps(resource) do
Step.find_initials(steps(resource))
end

@doc """
Returns the workflow's `transition_log` configuration, or `nil` if no
transition log is configured.
Expand Down Expand Up @@ -482,8 +490,8 @@ defmodule AshWorkflow.Info do
* `:action` — the action an automatic step runs, `nil` for every other step
* `:policy` — the step's `policy` check, or `nil`
* `:retry` — the step's `AshWorkflow.Entities.Retry`, or `nil`
* `:initial` — `true` for the step the workflow starts in, as
`AshWorkflow.Entities.Step.find_initial/1` picks it
* `:initial` — `true` for each step a record can be created in, as
`AshWorkflow.Entities.Step.find_initials/1` picks them
* `:terminal` — `true` for an end state
* `:manual` — `true` when nothing runs on entry
* `:wait_state` — `true` when a timeout is the step's only exit
Expand Down Expand Up @@ -547,20 +555,20 @@ defmodule AshWorkflow.Info do
@spec workflow_graph(Ash.Resource.t()) :: %{atom() => map()}
def workflow_graph(resource) do
steps = steps(resource)
initial = Step.find_initial(steps)
initial_steps = Step.find_initials(steps)
undo_enabled? = undo(resource) != nil

Map.new(steps, &step_to_graph_entry(&1, initial, undo_enabled?))
Map.new(steps, &step_to_graph_entry(&1, initial_steps, undo_enabled?))
end

defp step_to_graph_entry(step, initial, undo_enabled?) do
defp step_to_graph_entry(step, initial_steps, undo_enabled?) do
{step.name,
%{
name: step.name,
action: step.action,
policy: step.policy,
retry: step.retry,
initial: step == initial,
initial: step in initial_steps,
terminal: Step.terminal?(step),
manual: Step.manual?(step),
wait_state: Step.wait_state?(step),
Expand Down
20 changes: 12 additions & 8 deletions lib/ash_workflow/transformers/add_state_machine.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ defmodule AshWorkflow.Transformers.AddStateMachine do
Injects the following into the resource's `state_machine` DSL:

- **`state_attribute`** — the workflow's `state_attribute`, when it declares one.
- **`initial_states`** — set to the step with `initial: true`, or the first
- **`initial_states`** — every step with `initial: true`, or the first
non-terminal step by declaration order if none is marked.
- **`default_initial_state`** — same as above
- **`default_initial_state`** — the first of `initial_states`
- **Transitions** for each step type:
- *Automatic steps* — `transition :step_action, from: [:step_name], to: [...]`, where
`to` is every target across the step's `on_success` entries.
Expand Down Expand Up @@ -43,9 +43,9 @@ defmodule AshWorkflow.Transformers.AddStateMachine do
|> Transformer.get_entities([:workflow])
|> Enum.filter(&match?(%Step{}, &1))

case Step.find_initial(steps) do
nil -> raise no_steps_error()
first_step -> add_state_machine(dsl, steps, first_step)
case Step.find_initials(steps) do
[] -> raise no_steps_error()
initial_steps -> add_state_machine(dsl, steps, initial_steps)
end
end

Expand All @@ -63,12 +63,16 @@ defmodule AshWorkflow.Transformers.AddStateMachine do
)
end

defp add_state_machine(dsl, steps, first_step) do
defp add_state_machine(dsl, steps, [default_step | _] = initial_steps) do
dsl =
dsl
|> put_state_attribute()
|> Transformer.set_option([:state_machine], :initial_states, [first_step.name])
|> Transformer.set_option([:state_machine], :default_initial_state, first_step.name)
|> Transformer.set_option(
[:state_machine],
:initial_states,
Enum.map(initial_steps, & &1.name)
)
|> Transformer.set_option([:state_machine], :default_initial_state, default_step.name)

transitions = build_transitions(steps) ++ undo_transitions(dsl)

Expand Down
Loading