From 8f0619e2a2d0675f92deedc758266af1bc0e143e Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Sun, 18 Oct 2026 21:16:03 +0200 Subject: [PATCH 01/15] fix: log no transition when a create upserts onto an existing row --- lib/ash_workflow/changes/record_event.ex | 5 +++ test/ash_workflow/upsert_test.exs | 40 +++++++++++++++++ test/support/domain.ex | 2 + test/support/workflows/upsert_log.ex | 30 +++++++++++++ test/support/workflows/upsert_workflow.ex | 52 +++++++++++++++++++++++ 5 files changed, 129 insertions(+) create mode 100644 test/ash_workflow/upsert_test.exs create mode 100644 test/support/workflows/upsert_log.ex create mode 100644 test/support/workflows/upsert_workflow.ex diff --git a/lib/ash_workflow/changes/record_event.ex b/lib/ash_workflow/changes/record_event.ex index 2e9cb74b..7ba1cdc8 100644 --- a/lib/ash_workflow/changes/record_event.ex +++ b/lib/ash_workflow/changes/record_event.ex @@ -289,6 +289,11 @@ defmodule AshWorkflow.Changes.RecordEvent do nil -> record + # A create that upserts onto an existing row leaves it in the step it + # was in, so there is no event to log. + _log when changeset.action_type == :create and record.__metadata__.upsert_action == :update -> + record + log -> attrs = build_log_attrs(changeset, record, log, opts, context) diff --git a/test/ash_workflow/upsert_test.exs b/test/ash_workflow/upsert_test.exs new file mode 100644 index 00000000..933fc55e --- /dev/null +++ b/test/ash_workflow/upsert_test.exs @@ -0,0 +1,40 @@ +defmodule AshWorkflow.UpsertTest do + @moduledoc """ + A create action that upserts onto an existing row enters no step, so it + writes no transition log row. + """ + use ExUnit.Case, async: true + + alias AshWorkflowTest.UpsertLog + alias AshWorkflowTest.UpsertWorkflow, as: Workflow + + defp open(code) do + Workflow + |> Ash.Changeset.for_create(:open, %{code: code}) + |> Ash.create!() + end + + defp log_states(record) do + UpsertLog + |> Ash.read!() + |> Enum.filter(&(&1.workflow_id == record.id)) + |> Enum.map(& &1.to_state) + |> Enum.sort() + end + + test "an upsert onto an existing row keeps its state and logs nothing" do + first = open("a") + {:ok, closed} = first |> Ash.Changeset.for_update(:close, %{}) |> Ash.update() + + again = open("a") + + assert again.id == first.id + assert again.state == :closed + assert again.state_entered_at == closed.state_entered_at + assert log_states(first) == [:closed, :open] + end + + test "an upsert that inserts a row logs its initial step" do + assert open("b") |> log_states() == [:open] + end +end diff --git a/test/support/domain.ex b/test/support/domain.ex index 275500d0..9582dd70 100644 --- a/test/support/domain.ex +++ b/test/support/domain.ex @@ -31,6 +31,8 @@ defmodule AshWorkflowTest.Domain do resource AshWorkflowTest.OneMinuteWorkflow resource AshWorkflowTest.FireAtWorkflow resource AshWorkflowTest.PreCheckedIdentityWorkflow + resource AshWorkflowTest.UpsertWorkflow + resource AshWorkflowTest.UpsertLog resource AshWorkflowTest.PreciseTimeoutWorkflow resource AshWorkflowTest.PreciseDeadlineWorkflow resource AshWorkflowTest.PreciseStatusWorkflow diff --git a/test/support/workflows/upsert_log.ex b/test/support/workflows/upsert_log.ex new file mode 100644 index 00000000..afd050cd --- /dev/null +++ b/test/support/workflows/upsert_log.ex @@ -0,0 +1,30 @@ +defmodule AshWorkflowTest.UpsertLog do + @moduledoc """ + The transition log for `AshWorkflowTest.UpsertWorkflow`. + """ + + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets + + ets do + private? true + end + + actions do + defaults [:read, create: :*] + end + + attributes do + uuid_v7_primary_key :id + attribute :from_state, :atom, public?: true + attribute :to_state, :atom, allow_nil?: false, public?: true + attribute :transition_name, :atom, allow_nil?: false, public?: true + attribute :occurred_at, :utc_datetime_usec, allow_nil?: false, public?: true + attribute :triggered_by, :atom, allow_nil?: false, public?: true + end + + relationships do + belongs_to :workflow, AshWorkflowTest.UpsertWorkflow, allow_nil?: false, public?: true + end +end diff --git a/test/support/workflows/upsert_workflow.ex b/test/support/workflows/upsert_workflow.ex new file mode 100644 index 00000000..d2144ee0 --- /dev/null +++ b/test/support/workflows/upsert_workflow.ex @@ -0,0 +1,52 @@ +defmodule AshWorkflowTest.UpsertWorkflow do + @moduledoc """ + A logged workflow whose create action upserts on an identity, so a second + create for the same code returns the existing row. + """ + + use Ash.Resource, + domain: AshWorkflowTest.Domain, + data_layer: Ash.DataLayer.Ets, + extensions: [AshWorkflow] + + ets do + private? true + end + + workflow do + scheduler AshWorkflow.Scheduler.Precise + transition_log AshWorkflowTest.UpsertLog + + step :open do + transition :close, to: :closed + end + + step :closed, terminal: true + end + + actions do + defaults [:read] + + create :open do + accept [:code] + upsert? true + upsert_identity :unique_code + upsert_fields [] + end + + # The identity's `pre_check_with` adds a `before_action` hook, which an + # atomic update cannot run. + update :close do + require_atomic? false + end + end + + attributes do + uuid_v7_primary_key :id + attribute :code, :string, allow_nil?: false, public?: true + end + + identities do + identity :unique_code, [:code], pre_check_with: AshWorkflowTest.Domain + end +end From d4914436ea7268a3d3450830282e9c0cce2007bc Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 13:24:52 +0200 Subject: [PATCH 02/15] fix: leave the scheduler alone when a create upserts onto an existing row `AshWorkflow.Changes.RecordEvent` no longer calls `AshWorkflow.Scheduler.notify_state_change/1` for a create whose record carries `upsert_action: :update` metadata. The row stays in the step it was in, so its deadlines are unchanged. The `[:ash_workflow, :transition]` span still emits `:stop` on that path. Its `:start` event fires in `change/3`, before the data layer reports whether the row was inserted, and skipping `:stop` would leave the span open. --- lib/ash_workflow/changes/record_event.ex | 34 ++++++++---- test/ash_workflow/upsert_test.exs | 65 ++++++++++++++++++++++- test/support/notifying_scheduler.ex | 18 +++++++ test/support/workflows/upsert_workflow.ex | 2 +- 4 files changed, 107 insertions(+), 12 deletions(-) create mode 100644 test/support/notifying_scheduler.ex diff --git a/lib/ash_workflow/changes/record_event.ex b/lib/ash_workflow/changes/record_event.ex index 7ba1cdc8..c9f7a5cf 100644 --- a/lib/ash_workflow/changes/record_event.ex +++ b/lib/ash_workflow/changes/record_event.ex @@ -73,6 +73,14 @@ defmodule AshWorkflow.Changes.RecordEvent do A timer armed before the commit could fire against a record still holding the old state. + ## Upserts + + A create action that upserts onto an existing row leaves that row in the + step it was in. This change writes no log row for it and does not call + `AshWorkflow.Scheduler.notify_state_change/1`. The telemetry span still opens + and closes, because its `:start` event fires before the data layer reports + whether the row was inserted. + ## Atomicity This change implements `atomic/3` rather than falling back to @@ -183,15 +191,28 @@ defmodule AshWorkflow.Changes.RecordEvent do defp every_field(opts), do: Keyword.get(opts, :every_field) + # The `:start` event fired before the data layer reported whether the create + # inserted, so the span still closes on an upsert that entered no step. defp finish(changeset, record, opts, context) do - record = append_log(changeset, record, opts, context) - - emit_stop(changeset, record) - Scheduler.notify_state_change(record) + if upserted_onto_existing_row?(changeset, record) do + emit_stop(changeset, record) + else + append_log(changeset, record, opts, context) + emit_stop(changeset, record) + Scheduler.notify_state_change(record) + end record end + # A create that upserts onto an existing row leaves it in the step it was in. + defp upserted_onto_existing_row?(%{action_type: :create}, %{ + __metadata__: %{upsert_action: :update} + }), + do: true + + defp upserted_onto_existing_row?(_changeset, _record), do: false + # The span opens here rather than in the after_action hook because this is # where the action begins: `change/3` and `atomic/3` both run while the # changeset is being built, before the data layer is touched. @@ -289,11 +310,6 @@ defmodule AshWorkflow.Changes.RecordEvent do nil -> record - # A create that upserts onto an existing row leaves it in the step it - # was in, so there is no event to log. - _log when changeset.action_type == :create and record.__metadata__.upsert_action == :update -> - record - log -> attrs = build_log_attrs(changeset, record, log, opts, context) diff --git a/test/ash_workflow/upsert_test.exs b/test/ash_workflow/upsert_test.exs index 933fc55e..bd324c3e 100644 --- a/test/ash_workflow/upsert_test.exs +++ b/test/ash_workflow/upsert_test.exs @@ -1,19 +1,26 @@ defmodule AshWorkflow.UpsertTest do @moduledoc """ A create action that upserts onto an existing row enters no step, so it - writes no transition log row. + writes no transition log row and does not tell the scheduler. """ use ExUnit.Case, async: true alias AshWorkflowTest.UpsertLog alias AshWorkflowTest.UpsertWorkflow, as: Workflow + @start [:ash_workflow, :transition, :start] + @stop [:ash_workflow, :transition, :stop] + defp open(code) do Workflow |> Ash.Changeset.for_create(:open, %{code: code}) |> Ash.create!() end + defp close(record) do + record |> Ash.Changeset.for_update(:close, %{}) |> Ash.update!() + end + defp log_states(record) do UpsertLog |> Ash.read!() @@ -22,9 +29,35 @@ defmodule AshWorkflow.UpsertTest do |> Enum.sort() end + # Handlers run in the emitting process, so matching on self() keeps out + # events from tests running concurrently. + defp attach_span_handler do + handler_id = "upsert-test-#{inspect(make_ref())}" + pid = self() + + :telemetry.attach_many( + handler_id, + [@start, @stop], + fn event, _measurements, metadata, _config -> + if self() == pid, do: send(pid, {:span, event, metadata}) + end, + nil + ) + + on_exit(fn -> :telemetry.detach(handler_id) end) + end + + defp flush_notifications(id) do + receive do + {:state_change_notified, ^id} -> flush_notifications(id) + after + 0 -> :ok + end + end + test "an upsert onto an existing row keeps its state and logs nothing" do first = open("a") - {:ok, closed} = first |> Ash.Changeset.for_update(:close, %{}) |> Ash.update() + closed = close(first) again = open("a") @@ -37,4 +70,32 @@ defmodule AshWorkflow.UpsertTest do test "an upsert that inserts a row logs its initial step" do assert open("b") |> log_states() == [:open] end + + test "an upsert onto an existing row does not tell the scheduler" do + first = "c" |> open() |> close() + flush_notifications(first.id) + + open("c") + + refute_received {:state_change_notified, _id} + end + + test "an upsert that inserts a row tells the scheduler" do + record = open("d") + + assert_received {:state_change_notified, id} + assert id == record.id + end + + test "an upsert onto an existing row still closes the span it opened" do + first = "e" |> open() |> close() + attach_span_handler() + + open("e") + + assert_received {:span, @start, %{from_state: nil}} + assert_received {:span, @stop, %{workflow_id: id, to_state: :closed}} + assert id == first.id + refute_received {:span, _event, _metadata} + end end diff --git a/test/support/notifying_scheduler.ex b/test/support/notifying_scheduler.ex new file mode 100644 index 00000000..b9c0ae25 --- /dev/null +++ b/test/support/notifying_scheduler.ex @@ -0,0 +1,18 @@ +defmodule AshWorkflowTest.NotifyingScheduler do + @moduledoc """ + A scheduler that sends the calling process `{:state_change_notified, id}` + each time `AshWorkflow.Scheduler.notify_state_change/1` reaches it. + """ + use AshWorkflow.Scheduler + + @impl AshWorkflow.Scheduler + def deadline_changed(record, _works), do: notify(record) + + @impl AshWorkflow.Scheduler + def cancel(record, _works), do: notify(record) + + defp notify(record) do + send(self(), {:state_change_notified, record.id}) + :ok + end +end diff --git a/test/support/workflows/upsert_workflow.ex b/test/support/workflows/upsert_workflow.ex index d2144ee0..c6445ac8 100644 --- a/test/support/workflows/upsert_workflow.ex +++ b/test/support/workflows/upsert_workflow.ex @@ -14,7 +14,7 @@ defmodule AshWorkflowTest.UpsertWorkflow do end workflow do - scheduler AshWorkflow.Scheduler.Precise + scheduler AshWorkflowTest.NotifyingScheduler transition_log AshWorkflowTest.UpsertLog step :open do From d2b10af039471372c529ebfe0f198c2b6d2e1e41 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 13:26:14 +0200 Subject: [PATCH 03/15] fix: log no transition when an upsert_condition skips the update A create action with `upsert_condition` returns the existing row with `upsert_skipped: true` metadata when the condition does not match and `return_skipped_upsert?` is set. That row carries no `upsert_action` metadata, so `AshWorkflow.Changes.RecordEvent` appended an `:initial` log row and called `AshWorkflow.Scheduler.notify_state_change/1` for it. Both are now skipped, the same as for an upsert that updated the row. --- lib/ash_workflow/changes/record_event.ex | 8 +++++++- test/ash_workflow/upsert_test.exs | 15 +++++++++++++++ test/support/workflows/upsert_workflow.ex | 8 ++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/ash_workflow/changes/record_event.ex b/lib/ash_workflow/changes/record_event.ex index c9f7a5cf..5525db1e 100644 --- a/lib/ash_workflow/changes/record_event.ex +++ b/lib/ash_workflow/changes/record_event.ex @@ -205,12 +205,18 @@ defmodule AshWorkflow.Changes.RecordEvent do record end - # A create that upserts onto an existing row leaves it in the step it was in. + # A create that upserts onto an existing row leaves it in the step it was in, + # whether the row was updated or the `upsert_condition` skipped the update. defp upserted_onto_existing_row?(%{action_type: :create}, %{ __metadata__: %{upsert_action: :update} }), do: true + defp upserted_onto_existing_row?(%{action_type: :create}, %{ + __metadata__: %{upsert_skipped: true} + }), + do: true + defp upserted_onto_existing_row?(_changeset, _record), do: false # The span opens here rather than in the after_action hook because this is diff --git a/test/ash_workflow/upsert_test.exs b/test/ash_workflow/upsert_test.exs index bd324c3e..3670fd1e 100644 --- a/test/ash_workflow/upsert_test.exs +++ b/test/ash_workflow/upsert_test.exs @@ -87,6 +87,21 @@ defmodule AshWorkflow.UpsertTest do assert id == record.id end + test "an upsert skipped by its upsert_condition logs nothing and does not tell the scheduler" do + first = "f" |> open() |> close() + flush_notifications(first.id) + + skipped = + Workflow + |> Ash.Changeset.for_create(:open_while_open, %{code: "f"}) + |> Ash.create!(return_skipped_upsert?: true) + + assert skipped.id == first.id + assert skipped.__metadata__.upsert_skipped + assert log_states(first) == [:closed, :open] + refute_received {:state_change_notified, _id} + end + test "an upsert onto an existing row still closes the span it opened" do first = "e" |> open() |> close() attach_span_handler() diff --git a/test/support/workflows/upsert_workflow.ex b/test/support/workflows/upsert_workflow.ex index c6445ac8..96f84358 100644 --- a/test/support/workflows/upsert_workflow.ex +++ b/test/support/workflows/upsert_workflow.ex @@ -34,6 +34,14 @@ defmodule AshWorkflowTest.UpsertWorkflow do upsert_fields [] end + create :open_while_open do + accept [:code] + upsert? true + upsert_identity :unique_code + upsert_fields [:code] + upsert_condition expr(state == :open) + end + # The identity's `pre_check_with` adds a `before_action` hook, which an # atomic update cannot run. update :close do From acdefe937f9303e650a31e72ef07fb969303bb00 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 13:26:39 +0200 Subject: [PATCH 04/15] fix: require Ash 3.29, the first release with ETS upsert_action metadata `AshWorkflow.Changes.RecordEvent` reads `upsert_action` metadata to tell an upsert that inserted a row from one that updated it. Ash 3.29.0 added that metadata to `Ash.DataLayer.Ets` and `Ash.DataLayer.Mnesia`. With an older Ash, every upsert on ETS still logs an `:initial` row. AshPostgres sets the metadata from 2.10.0 on PostgreSQL 17 and later, and from 2.13.1 on every PostgreSQL version. AshPostgres is not a runtime dependency, so `mix.exs` cannot raise that floor for users. --- mix.exs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mix.exs b/mix.exs index 0b9d5276..bad09505 100644 --- a/mix.exs +++ b/mix.exs @@ -108,7 +108,7 @@ defmodule AshWorkflow.MixProject do defp deps do [ {:mix_test_watch, "~> 1.2", only: [:dev, :test], runtime: false}, - {:ash, "~> 3.0"}, + {:ash, "~> 3.29"}, {:ash_state_machine, "~> 0.2"}, {:ash_oban, "~> 0.2"}, {:jason, "~> 1.4"}, From fe1fc70a371a99650effcf8443aa84bd5c875d3b Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 13:28:25 +0200 Subject: [PATCH 05/15] test: cover upserts on Postgres and through Ash.bulk_create/4 `AshWorkflowTest.Postgres.UpsertWorkflow` upserts on a unique `code` and logs to `AshWorkflowTest.Postgres.UpsertTransition`. Its tests check that a single upsert and a bulk upsert onto an existing row write no second `:initial` row. On ETS, `AshWorkflow.UpsertTest` checks that a bulk upsert of one existing and one new code logs only the new row and does not notify the scheduler for the existing one. --- .../20261022112716_add_upsert_workflow.exs | 55 ++++++++ .../upsert_transitions/20261022112724.json | 125 ++++++++++++++++++ .../repo/upsert_workflows/20261022112725.json | 83 ++++++++++++ test/ash_workflow/upsert_test.exs | 16 +++ test/postgres/upsert_test.exs | 53 ++++++++ test/support/postgres/domain.ex | 2 + test/support/postgres/upsert_transition.ex | 46 +++++++ test/support/postgres/upsert_workflow.ex | 49 +++++++ 8 files changed, 429 insertions(+) create mode 100644 priv/repo/migrations/20261022112716_add_upsert_workflow.exs create mode 100644 priv/resource_snapshots/repo/upsert_transitions/20261022112724.json create mode 100644 priv/resource_snapshots/repo/upsert_workflows/20261022112725.json create mode 100644 test/postgres/upsert_test.exs create mode 100644 test/support/postgres/upsert_transition.ex create mode 100644 test/support/postgres/upsert_workflow.ex diff --git a/priv/repo/migrations/20261022112716_add_upsert_workflow.exs b/priv/repo/migrations/20261022112716_add_upsert_workflow.exs new file mode 100644 index 00000000..c06ef4ba --- /dev/null +++ b/priv/repo/migrations/20261022112716_add_upsert_workflow.exs @@ -0,0 +1,55 @@ +defmodule AshWorkflowTest.Repo.Migrations.AddUpsertWorkflow do + @moduledoc """ + Updates resources based on their most recent snapshots. + + This file was autogenerated with `mix ash_postgres.generate_migrations` + """ + + use Ecto.Migration + + def up do + create table(:upsert_workflows, primary_key: false) do + add(:id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true) + add(:code, :text, null: false) + + add(:state_entered_at, :utc_datetime_usec, + null: false, + default: fragment("(now() AT TIME ZONE 'utc')") + ) + + add(:state, :text, null: false, default: "open") + end + + create unique_index(:upsert_workflows, [:code], name: "upsert_workflows_unique_code_index") + + create table(:upsert_transitions, primary_key: false) do + add(:id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true) + add(:from_state, :text) + add(:to_state, :text, null: false) + add(:transition_name, :text, null: false) + add(:occurred_at, :utc_datetime_usec, null: false) + add(:triggered_by, :text, null: false) + + add( + :workflow_id, + references(:upsert_workflows, + column: :id, + name: "upsert_transitions_workflow_id_fkey", + type: :uuid, + prefix: "public" + ), + null: false + ) + end + end + + def down do + drop(table(:upsert_transitions)) + + drop_if_exists( + unique_index(:upsert_workflows, [:code], name: "upsert_workflows_unique_code_index") + ) + + drop(table(:upsert_workflows)) + end +end diff --git a/priv/resource_snapshots/repo/upsert_transitions/20261022112724.json b/priv/resource_snapshots/repo/upsert_transitions/20261022112724.json new file mode 100644 index 00000000..ce17691d --- /dev/null +++ b/priv/resource_snapshots/repo/upsert_transitions/20261022112724.json @@ -0,0 +1,125 @@ +{ + "attributes": [ + { + "allow_nil?": false, + "default": "fragment(\"uuid_generate_v7()\")", + "generated?": false, + "precision": null, + "primary_key?": true, + "references": null, + "scale": null, + "size": null, + "source": "id", + "type": "uuid" + }, + { + "allow_nil?": true, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "from_state", + "type": "text" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "to_state", + "type": "text" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "transition_name", + "type": "text" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "occurred_at", + "type": "utc_datetime_usec" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "triggered_by", + "type": "text" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": { + "deferrable": false, + "destination_attribute": "id", + "destination_attribute_default": null, + "destination_attribute_generated": null, + "index?": false, + "index_where": null, + "match_tenant?": false, + "match_type": null, + "match_with": null, + "multitenancy": { + "attribute": null, + "global": null, + "strategy": null + }, + "name": "upsert_transitions_workflow_id_fkey", + "on_delete": null, + "on_update": null, + "primary_key?": true, + "schema": "public", + "table": "upsert_workflows" + }, + "scale": null, + "size": null, + "source": "workflow_id", + "type": "uuid" + } + ], + "base_filter": null, + "check_constraints": [], + "create_table_options": null, + "custom_indexes": [], + "custom_statements": [], + "has_create_action": true, + "hash": "82B7C906383F6098308552408389B50588CC1AE20D9B345366655C78878DD6B3", + "identities": [], + "multitenancy": { + "attribute": null, + "global": null, + "strategy": null + }, + "repo": "Elixir.AshWorkflowTest.Repo", + "schema": null, + "table": "upsert_transitions" +} \ No newline at end of file diff --git a/priv/resource_snapshots/repo/upsert_workflows/20261022112725.json b/priv/resource_snapshots/repo/upsert_workflows/20261022112725.json new file mode 100644 index 00000000..11b16331 --- /dev/null +++ b/priv/resource_snapshots/repo/upsert_workflows/20261022112725.json @@ -0,0 +1,83 @@ +{ + "attributes": [ + { + "allow_nil?": false, + "default": "fragment(\"uuid_generate_v7()\")", + "generated?": false, + "precision": null, + "primary_key?": true, + "references": null, + "scale": null, + "size": null, + "source": "id", + "type": "uuid" + }, + { + "allow_nil?": false, + "default": "nil", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "code", + "type": "text" + }, + { + "allow_nil?": false, + "default": "fragment(\"(now() AT TIME ZONE 'utc')\")", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "state_entered_at", + "type": "utc_datetime_usec" + }, + { + "allow_nil?": false, + "default": "\"open\"", + "generated?": false, + "precision": null, + "primary_key?": false, + "references": null, + "scale": null, + "size": null, + "source": "state", + "type": "text" + } + ], + "base_filter": null, + "check_constraints": [], + "create_table_options": null, + "custom_indexes": [], + "custom_statements": [], + "has_create_action": true, + "hash": "47E740AEBD6627BC75837574D67DDE80D61A24411862B7C8CEB5FE2442C1BA8B", + "identities": [ + { + "all_tenants?": false, + "base_filter": null, + "index_name": "upsert_workflows_unique_code_index", + "keys": [ + { + "type": "atom", + "value": "code" + } + ], + "name": "unique_code", + "nils_distinct?": true, + "where": null + } + ], + "multitenancy": { + "attribute": null, + "global": null, + "strategy": null + }, + "repo": "Elixir.AshWorkflowTest.Repo", + "schema": null, + "table": "upsert_workflows" +} \ No newline at end of file diff --git a/test/ash_workflow/upsert_test.exs b/test/ash_workflow/upsert_test.exs index 3670fd1e..16eee10f 100644 --- a/test/ash_workflow/upsert_test.exs +++ b/test/ash_workflow/upsert_test.exs @@ -71,6 +71,22 @@ defmodule AshWorkflow.UpsertTest do assert open("b") |> log_states() == [:open] end + test "a bulk upsert logs only the rows it inserted" do + existing = "g" |> open() |> close() + flush_notifications(existing.id) + + %Ash.BulkResult{status: :success, records: records} = + Ash.bulk_create([%{code: "g"}, %{code: "h"}], Workflow, :open, return_records?: true) + + inserted = Enum.find(records, &(&1.code == "h")) + existing_id = existing.id + + assert Enum.find(records, &(&1.code == "g")).id == existing_id + assert log_states(existing) == [:closed, :open] + assert log_states(inserted) == [:open] + refute_received {:state_change_notified, ^existing_id} + end + test "an upsert onto an existing row does not tell the scheduler" do first = "c" |> open() |> close() flush_notifications(first.id) diff --git a/test/postgres/upsert_test.exs b/test/postgres/upsert_test.exs new file mode 100644 index 00000000..bdfeee3e --- /dev/null +++ b/test/postgres/upsert_test.exs @@ -0,0 +1,53 @@ +defmodule AshWorkflowTest.Postgres.UpsertTest do + @moduledoc """ + An upsert onto an existing row takes the `ON CONFLICT DO UPDATE` branch, + which AshPostgres reports as `upsert_action: :update` metadata. That create + enters no step, so it writes no second `:initial` log row. + """ + use AshWorkflowTest.DataCase + + require Ash.Query + + alias AshWorkflowTest.Postgres.UpsertTransition + alias AshWorkflowTest.Postgres.UpsertWorkflow + + defp open(code) do + UpsertWorkflow + |> Ash.Changeset.for_create(:open, %{code: code}) + |> Ash.create!() + end + + defp log_rows(record) do + UpsertTransition + |> Ash.Query.filter(workflow_id == ^record.id) + |> Ash.read!() + |> Enum.map(&{&1.to_state, &1.triggered_by}) + |> Enum.sort() + end + + test "an upsert onto an existing row keeps its state and logs nothing" do + first = open("a") + Ash.update!(first, action: :close) + + again = open("a") + + assert again.id == first.id + assert again.__metadata__.upsert_action == :update + assert again.state == :closed + assert log_rows(first) == [{:closed, :manual}, {:open, :initial}] + end + + test "a bulk upsert onto an existing row logs nothing" do + first = open("b") + + %Ash.BulkResult{status: :success, records: [again]} = + Ash.bulk_create([%{code: "b"}], UpsertWorkflow, :open, return_records?: true) + + assert again.id == first.id + assert log_rows(first) == [{:open, :initial}] + end + + test "an upsert that inserts a row logs its initial step" do + assert open("c") |> log_rows() == [{:open, :initial}] + end +end diff --git a/test/support/postgres/domain.ex b/test/support/postgres/domain.ex index a9a54f7d..40125051 100644 --- a/test/support/postgres/domain.ex +++ b/test/support/postgres/domain.ex @@ -14,5 +14,7 @@ defmodule AshWorkflowTest.Postgres.Domain do resource AshWorkflowTest.Postgres.EveryUntilWorkflow resource AshWorkflowTest.Postgres.StaleTransitionWorkflow resource AshWorkflowTest.Postgres.ActionTimeoutWorkflow + resource AshWorkflowTest.Postgres.UpsertWorkflow + resource AshWorkflowTest.Postgres.UpsertTransition end end diff --git a/test/support/postgres/upsert_transition.ex b/test/support/postgres/upsert_transition.ex new file mode 100644 index 00000000..af2a1ae6 --- /dev/null +++ b/test/support/postgres/upsert_transition.ex @@ -0,0 +1,46 @@ +defmodule AshWorkflowTest.Postgres.UpsertTransition do + @moduledoc """ + The transition log for `AshWorkflowTest.Postgres.UpsertWorkflow`. + """ + + use Ash.Resource, + domain: AshWorkflowTest.Postgres.Domain, + data_layer: AshPostgres.DataLayer + + postgres do + table "upsert_transitions" + repo(AshWorkflowTest.Repo) + end + + actions do + defaults [:read] + + create :create do + accept [ + :workflow_id, + :from_state, + :to_state, + :transition_name, + :occurred_at, + :triggered_by + ] + end + end + + attributes do + uuid_v7_primary_key :id + attribute :from_state, :atom, public?: true + attribute :to_state, :atom, allow_nil?: false, public?: true + attribute :transition_name, :atom, allow_nil?: false, public?: true + attribute :occurred_at, :utc_datetime_usec, allow_nil?: false, public?: true + attribute :triggered_by, :atom, allow_nil?: false, public?: true + end + + relationships do + belongs_to :workflow, AshWorkflowTest.Postgres.UpsertWorkflow, + allow_nil?: false, + public?: true, + attribute_public?: true, + attribute_writable?: true + end +end diff --git a/test/support/postgres/upsert_workflow.ex b/test/support/postgres/upsert_workflow.ex new file mode 100644 index 00000000..aa0ee266 --- /dev/null +++ b/test/support/postgres/upsert_workflow.ex @@ -0,0 +1,49 @@ +defmodule AshWorkflowTest.Postgres.UpsertWorkflow do + @moduledoc """ + Postgres-backed logged workflow whose create action upserts on an identity, + so a second create for the same code takes the `ON CONFLICT DO UPDATE` + branch and returns the existing row. + + open ──(close)──▶ closed + """ + + use Ash.Resource, + domain: AshWorkflowTest.Postgres.Domain, + data_layer: AshPostgres.DataLayer, + extensions: [AshWorkflow, AshOban] + + postgres do + table "upsert_workflows" + repo(AshWorkflowTest.Repo) + end + + workflow do + transition_log AshWorkflowTest.Postgres.UpsertTransition + + step :open do + transition :close, to: :closed + end + + step :closed, terminal: true + end + + actions do + defaults [:read] + + create :open do + accept [:code] + upsert? true + upsert_identity :unique_code + upsert_fields [:code] + end + end + + attributes do + uuid_v7_primary_key :id + attribute :code, :string, allow_nil?: false, public?: true + end + + identities do + identity :unique_code, [:code] + end +end From 3764ef2683f242256f90cb9e0d68f0bee8281606 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 13:28:42 +0200 Subject: [PATCH 06/15] docs: add the upsert fix and the Ash 3.29 floor to the changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fdc8563..fba2f3ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `mix ash_workflow.gen.expiry` adds an expiry workflow to a resource: a sibling expiry resource with `active`, `expired` and an optional `expiring` step, whose deadlines read `expires_at` and move when the expiry is renewed. The subject gains `has_one :expiry` and an `expired?` calculation. Who may create an expiry and who may renew one live in generated `Checks.CanCreate` and `Checks.CanRenew` modules, which deny everyone until the application fills them in. See the [expiry recipe](documentation/recipes/expiry.md). - `mix ash_workflow.gen.transition_log` accepts a workflow resource generated earlier in the same Igniter run, before it has compiled, by reading its source. A resource on disk that fails to compile is still reported as an issue. +### Fixed + +- A create action that upserts onto an existing row no longer appends an `:initial` row to the transition log or calls `AshWorkflow.Scheduler.notify_state_change/1`. The row stays in the step it was in. `AshWorkflow.Changes.RecordEvent` skips both when the returned record carries `upsert_action: :update` metadata, or `upsert_skipped: true` metadata from an `upsert_condition` that did not match. This covers `Ash.create/2` and `Ash.bulk_create/4`. The `[:ash_workflow, :transition]` span still emits `:stop`, because its `:start` event fires before the data layer reports whether the row was inserted. ash_workflow now requires Ash 3.29 or later, the first release that sets `upsert_action` on ETS and Mnesia. AshPostgres sets it from 2.10.0 on PostgreSQL 17 and later, and from 2.13.1 on every PostgreSQL version. With an older AshPostgres, an upsert onto an existing row is still logged. + ## [0.10.1] - 2026-10-19 ### Upgrading from 0.10.0 From beb8fec2fe42471ab3ebfc031aca7079a168f853 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Sun, 18 Oct 2026 21:00:59 +0200 Subject: [PATCH 07/15] docs: add the acknowledgement recipe design --- .../design/acknowledgement-recipe.md | 184 ++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 documentation/design/acknowledgement-recipe.md diff --git a/documentation/design/acknowledgement-recipe.md b/documentation/design/acknowledgement-recipe.md new file mode 100644 index 00000000..8bafb032 --- /dev/null +++ b/documentation/design/acknowledgement-recipe.md @@ -0,0 +1,184 @@ +# Design: acknowledgement recipe generator + +Status: implemented. + +## The problem + +Policy attestations and terms updates share one pattern. A document is published, a list of people must each confirm they have read it, and the people who have not confirmed are chased once a deadline passes. Each application writes the same table of who has been asked, the same "has this person acknowledged it" query and the same rule that nobody may acknowledge on someone else's behalf. + +`mix ash_workflow.gen.acknowledgement` layers that workflow onto a subject resource. It is a request recipe in [`recipes.md`](recipes.md), after [`gen.approval`](approval-recipe.md) and [`gen.expiry`](expiry-recipe.md). + +## The split between generated code and the application + +The generator owns the acknowledgement lifecycle: the states, the overdue deadline, the identity that allows one row per person per subject, and the rule that only the row's own person may acknowledge it. + +The application owns two things: + +- When a request is opened, and for whom. The application calls `PolicyAcknowledgement.request/3` for one person, or `request_many/3` for a list of people, from wherever that makes sense: a publish action, an onboarding step, an Oban job that adds new starters. +- What happens on entering `:overdue`, such as a reminder email. The generator adds no notifier and no action timeout for it. + +The generated code never holds a list of who must acknowledge. The rows the application creates are that list. + +## The command + +```bash +mix ash_workflow.gen.acknowledgement MyApp.Policies.Policy \ + --person MyApp.Accounts.User \ + --overdue-after 14d +``` + +| Option | Default | Effect | +|---|---|---| +| `--person` | required | The actor resource. Each acknowledgement `belongs_to :person` of this resource. | +| `--module` | `Acknowledgement` | Name of the generated acknowledgement resource. | +| `--domain` | the subject's domain | Domain for a subject the generator creates. Required only when the subject does not exist. | +| `--overdue-after` | none | Move an unacknowledged request to `:overdue` this long after `requested_at`. Omitted means no `:overdue` step. | +| `--transition-log` | `true` | Composes `ash_workflow.gen.transition_log` with `--actor` set to the person. `--no-transition-log` skips it. | + +`--overdue-after` accepts `10s`, `30m`, `12h`, `2d` and `2w`, parsed by `Mix.AshWorkflow.Recipe.parse_duration/2` as approval's flag of the same name is. + +When the subject does not exist, the generator creates it with `ash.gen.resource`. The created subject takes its data layer from `--person`, as approval takes it from `--approver`, and falls back to the resources in `--domain` the same way. When neither has an ETS or Postgres data layer, the generator stops with an Igniter issue. + +## The acknowledgement is a sibling resource + +The generator adds `MyApp.Policies.PolicyAcknowledgement` next to the subject, for the reason approval does: a resource has one `workflow`, and the subject may already run one. + +Acknowledgement is a request recipe. A subject has many acknowledgements, one for each person asked. The identity `:unique_person` on `(subject_id, person_id)` stops a person being asked twice about the same subject. On a data layer without unique constraints, such as ETS, it sets `pre_check_with` to the domain. On Postgres, a table name long enough to push the default index name past 63 bytes gets a shortened `identity_index_names` entry. + +The subject gains, by `Ash.Resource.Igniter` edits, and nothing else: + +- `has_many :acknowledgements, MyApp.Policies.PolicyAcknowledgement` +- `calculate :acknowledged_by_actor?, :boolean, expr(exists(acknowledgements, person_id == ^actor(:id) and state == :acknowledged))` + +The generator adds no change, argument or policy to the subject's actions. Gating a subject action on `acknowledged_by_actor?` is an application decision. + +### No `latest_acknowledgement` + +[`recipes.md`](recipes.md) gives every request recipe a `has_one :latest_`. Acknowledgement does not get one. Approval opens one request at a time, so its latest row is the subject's current approval. Acknowledgement opens one row per person at once, so the latest row belongs to whichever person was asked last. The answer an application wants is per person, and `acknowledged_by_actor?` gives it. + +### The calculation reads the actor + +Three shapes were considered for the subject's calculation: + +| Shape | Answers | Survives a second run | Chosen | +|---|---|---|---| +| `acknowledged_by_actor?`, reading `^actor(:id)` | Has the person loading the subject acknowledged it | Yes, it is a three-argument `calculate` | Yes | +| `acknowledged?` with a `person_id` argument | Has a given person acknowledged it | No. The `argument` needs a `do` block, and `Ash.Resource.Igniter.defines_calculation/3` only matches a three-argument `calculate` | No | +| `acknowledged?` meaning every row is acknowledged | Has everyone asked acknowledged it | Yes | No. It is true for a subject nobody has been asked about | + +The actor shape answers the question a UI asks: show a banner on this policy until the current user has acknowledged it. Loading the calculation without an actor returns `false`. A report on who has not acknowledged reads the acknowledgement rows with a filter on `state`, not the subject's calculation. + +## The workflow + +```mermaid +stateDiagram-v2 + [*] --> pending + pending --> acknowledged: acknowledge + pending --> overdue: timeout overdue_after + overdue --> acknowledged: acknowledge +``` + +Generated for the command above: + +```elixir +workflow do + step :pending do + transition :acknowledge, to: :acknowledged + + timeout :overdue, fire_after: {14, :days}, field: :requested_at, transition_to: :overdue + end + + step :overdue do + transition :acknowledge, to: :acknowledged + end + + step :acknowledged, terminal: true +end +``` + +`:overdue` is a step, not a flag, for the reason approval's is. A query can filter on `state == :overdue`, and an application can add its own `timeout` or `every` to the step for reminders. A person in `:overdue` can still acknowledge. The `:overdue` step is only generated when `--overdue-after` is given. + +There is no cancel or withdraw transition. A person who leaves before acknowledging keeps a `:pending` or `:overdue` row. See the open questions. + +### The deadline reads `requested_at` + +The overdue timeout is anchored on `requested_at`, not `state_entered_at`. Nothing in the generated workflow re-enters `:pending`, so today the two hold the same instant. They diverge as soon as an application adds a transition that loops back into `:pending`, such as a `remind` that records a reminder was sent. Anchored on `state_entered_at`, that reminder would restart the overdue clock. `requested_at` is written once, by the `:request` create action, so the deadline stays where it was. + +`requested_at` is an attribute, so `AshWorkflow.Transformers.AddIndexes` gives the timeout a `(state, requested_at)` index on Postgres. + +## The resource + +`PolicyAcknowledgement` attributes: `subject_id`, `person_id`, `requested_at` and `acknowledged_at`. + +```elixir +actions do + defaults [:read] + + create :request do + accept [:subject_id, :person_id] + upsert? true + upsert_identity :unique_person + upsert_fields [] + change set_attribute(:requested_at, &DateTime.utc_now/0) + end + + update :acknowledge do + require_atomic? false + change set_attribute(:acknowledged_at, &DateTime.utc_now/0) + end +end + +code_interface do + define :request, args: [:subject_id, :person_id] + define :request_many, action: :request, args: [:subject_id] + define :acknowledge +end +``` + +### Opening rows for a list of people + +`request_many/3` is a second code interface on the same `:request` action. A create code interface given a list of maps runs `Ash.bulk_create/4`, and `args: [:subject_id]` merges the subject into each map: + +```elixir +PolicyAcknowledgement.request_many(policy.id, Enum.map(people, &%{person_id: &1.id})) +``` + +A generic action taking `person_ids` was the alternative. Its `subject_id` argument would need the subject's primary key type, which the generator would have to read from an existing subject. The code interface takes its types from the `belongs_to` attributes instead. + +### `:request` is an upsert + +`:request` upserts on `:unique_person` with no `upsert_fields`. Asking a person who already has a row returns that row unchanged: its state, `requested_at` and `acknowledged_at` stay as they were. An application can therefore call `request_many/3` with everyone who must acknowledge, each time that list grows, without first removing the people it already asked. + +The alternative was a plain create that fails on the identity. Every caller adding a new starter would then have to read the existing rows and subtract them first, which is the race the identity exists to close. + +A person acknowledges a subject once. A terms update that must be acknowledged again is a new subject row, such as a new version of the terms, not a second acknowledgement of the old one. + +## Who may acknowledge + +The only human transition is `acknowledge`, and its rule is the same in every application: the person asked is the person who confirms. The generator writes that rule as a built-in check rather than a deny-by-default check module. + +```elixir +policies do + policy action(:acknowledge) do + authorize_if relates_to_actor_via(:person) + end +end +``` + +Approval and expiry generate a check module that denies everyone, because who may approve or renew differs per application and an open default is unsafe. Acknowledgement has no such open default to avoid. A check module that denied everyone would make every application write the same `relates_to_actor_via(:person)` line before the recipe did anything. The generator therefore writes no check module, and its notice names the policy instead. + +`AshWorkflow.Transformers.AddPolicies` allows `:request`, reads and the scheduler's overdue timeout. Who may open a request is the application's decision, made where it calls `request/3`. + +## Composing the transition log + +The generator composes `ash_workflow.gen.transition_log` with `--actor` set to `--person`, so each transition records who made it. It composes the log only when it creates the acknowledgement resource. A second run finds the resource and skips it. + +## Code shared with the other recipes + +The generator uses `Mix.AshWorkflow.Recipe` as it stands: `parse_duration/2`, `ensure_subject/5`, `add_subject_edits/4`, `compose_transition_log/3` and the rendering helpers. It adds nothing to the module. + +## Open questions + +1. Withdrawing a request. A person who leaves, or a request opened by mistake, has no way out of `:pending` or `:overdue` in the generated workflow. A `withdraw` transition to a terminal `:withdrawn` step is the likely addition. It would need its own deny-by-default check, since who may withdraw differs per application. +2. A subject-wide outcome. `acknowledged_by_actor?` answers for one person. An "everyone asked has acknowledged" calculation is true for a subject nobody was asked about, so it is left to the application, which knows whether an empty list means done. +3. Who opened a request. The generated row has no `requested_by`, because rows are often opened by a system job with no actor. An application that wants it adds `relate_actor(:requested_by, allow_nil?: true)` to `:request`. From 9207d5d58b2a88dec30ddebaa16fa9571ebffcc1 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Sun, 18 Oct 2026 21:16:36 +0200 Subject: [PATCH 08/15] feat: add the ash_workflow.gen.acknowledgement recipe --- config/config.exs | 1 + .../tasks/ash_workflow.gen.acknowledgement.ex | 276 +++++++++++++ test/mix/ash_workflow/recipe_test.exs | 6 +- .../ash_workflow.gen_acknowledgement_test.exs | 361 ++++++++++++++++++ .../recipe_fixtures/acknowledgement/domain.ex | 9 + .../recipe_fixtures/acknowledgement/policy.ex | 26 ++ .../recipe_fixtures/acknowledgement/user.ex | 19 + 7 files changed, 696 insertions(+), 2 deletions(-) create mode 100644 lib/mix/tasks/ash_workflow.gen.acknowledgement.ex create mode 100644 test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs create mode 100644 test/support/recipe_fixtures/acknowledgement/domain.ex create mode 100644 test/support/recipe_fixtures/acknowledgement/policy.ex create mode 100644 test/support/recipe_fixtures/acknowledgement/user.ex diff --git a/config/config.exs b/config/config.exs index ac6f19f1..310efd49 100644 --- a/config/config.exs +++ b/config/config.exs @@ -40,6 +40,7 @@ if Mix.env() == :test do # `use Ash.Domain` to it. `test_helper.exs` leaves them out of the Oban # config, and the Postgres fixture sets `migrate? false`. recipe_fixture_domains = [ + AshWorkflowTest.RecipeFixtures.Acknowledgement.Domain, AshWorkflowTest.RecipeFixtures.Approval.Domain, AshWorkflowTest.RecipeFixtures.Expiry.Domain, AshWorkflowTest.RecipeFixtures.TransitionLog.Domain, diff --git a/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex new file mode 100644 index 00000000..c5461986 --- /dev/null +++ b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex @@ -0,0 +1,276 @@ +defmodule Mix.Tasks.AshWorkflow.Gen.Acknowledgement.Docs do + @moduledoc false + + def short_doc do + "Adds an acknowledgement workflow to a resource" + end + + def example do + "mix ash_workflow.gen.acknowledgement MyApp.Policies.Policy --person MyApp.Accounts.User --overdue-after 14d" + end + + def long_doc do + """ + #{short_doc()} + + Generates an acknowledgement resource with one row per person asked to + acknowledge a subject. Only the row's own person may acknowledge it. + The subject gains `has_many :acknowledgements` and an + `acknowledged_by_actor?` calculation. When the subject does not exist, it + is created with `mix ash.gen.resource` first. + + ## Example + + ```bash + #{example()} + ``` + + ## Options + + * `--person` - required. The actor resource. Each acknowledgement belongs + to one person. + * `--module` - the acknowledgement resource's module name. Defaults to + the subject's name with `Acknowledgement` appended. + * `--domain` - the domain for a subject the task creates. Required only + when the subject does not exist. + * `--overdue-after` - moves an unacknowledged request to `:overdue` this + long after it was requested, given as `10s`, `30m`, `12h`, `2d` or + `2w`. Without it, no `:overdue` step is generated. + * `--transition-log` - also generates a transition log for the + acknowledgement with `mix ash_workflow.gen.transition_log`. Defaults to + `true`. + """ + end +end + +# Guarded on the struct this task builds rather than on `Igniter` itself. See +# `Mix.Tasks.AshWorkflow.Gen.TransitionLog` for why. +if Code.ensure_loaded?(Igniter.Mix.Task.Info) do + defmodule Mix.Tasks.AshWorkflow.Gen.Acknowledgement do + @shortdoc "#{__MODULE__.Docs.short_doc()}" + @moduledoc __MODULE__.Docs.long_doc() + + use Igniter.Mix.Task + + alias Ash.Domain.Igniter, as: DomainIgniter + alias Igniter.Project.Module, as: ProjectModule + alias Mix.AshWorkflow.Recipe + + @impl Igniter.Mix.Task + def info(_argv, _composing_task) do + %Igniter.Mix.Task.Info{ + group: :ash, + example: __MODULE__.Docs.example(), + positional: [:subject], + composes: ["ash.gen.resource", "ash_workflow.gen.transition_log"], + schema: [ + person: :string, + module: :string, + domain: :string, + overdue_after: :string, + transition_log: :boolean + ], + defaults: [transition_log: true], + required: [:person] + } + end + + @impl Igniter.Mix.Task + def igniter(igniter) do + options = igniter.args.options + subject = ProjectModule.parse(igniter.args.positional.subject) + + case Recipe.parse_duration(options[:overdue_after], "--overdue-after") do + {:ok, overdue_after} -> + person = ProjectModule.parse(options[:person]) + + config = %{ + subject: subject, + person: person, + acknowledgement: acknowledgement_module(subject, options[:module]), + overdue_after: overdue_after, + transition_log?: options[:transition_log] + } + + # A created subject stores its records the same way the person does. + case Recipe.ensure_subject( + igniter, + subject, + options[:domain], + "acknowledgement", + [person] + ) do + {:ok, igniter, storage} -> generate_with_key_types(igniter, config, storage) + {:error, igniter} -> igniter + end + + {:error, message} -> + Igniter.add_issue(igniter, message) + end + end + + defp acknowledgement_module(subject, nil), + do: Module.concat([inspect(subject) <> "Acknowledgement"]) + + defp acknowledgement_module(_subject, module), do: ProjectModule.parse(module) + + # A subject created in this run does not compile yet and gets + # ash.gen.resource's uuid_v7 key. + defp generate_with_key_types(igniter, config, storage) do + with {:ok, subject_type} <- Recipe.key_type(config.subject, "acknowledgement", :uuid_v7), + {:ok, person_type} <- Recipe.key_type(config.person, "acknowledgement", nil) do + key_types = %{subject: subject_type, person: person_type} + generate(igniter, Map.put(config, :key_types, key_types), storage) + else + {:error, message} -> Igniter.add_issue(igniter, message) + end + end + + defp generate(igniter, config, storage) do + {exists?, igniter} = ProjectModule.module_exists(igniter, config.acknowledgement) + + igniter + |> Recipe.add_subject_edits( + config.subject, + [ + acknowledgements: """ + has_many :acknowledgements, #{inspect(config.acknowledgement)} do + destination_attribute :subject_id + public? true + end + """ + ], + acknowledged_by_actor?: + "calculate :acknowledged_by_actor?, :boolean, expr(exists(acknowledgements, person_id == ^actor(:id) and state == :acknowledged) || false)" + ) + |> then(fn igniter -> + if exists?, do: igniter, else: create_acknowledgement(igniter, config, storage) + end) + end + + defp create_acknowledgement(igniter, config, storage) do + igniter + |> ProjectModule.create_module( + config.acknowledgement, + acknowledgement_contents(config, storage) + ) + |> DomainIgniter.add_resource_reference(storage.domain, config.acknowledgement) + |> compose_transition_log(config) + |> Igniter.add_notice(""" + Generated #{inspect(config.acknowledgement)} to acknowledge #{inspect(config.subject)}. + + Only the person a request was opened for may acknowledge it, as the \ + policy on :acknowledge states. Open requests with request/3 or \ + request_many/3. + """) + end + + defp compose_transition_log(igniter, %{transition_log?: false}), do: igniter + + defp compose_transition_log(igniter, config), + do: Recipe.compose_transition_log(igniter, config.acknowledgement, config.person) + + defp acknowledgement_contents(config, storage) do + """ + use Ash.Resource, + domain: #{inspect(storage.domain)}, + #{Recipe.data_layer_option(storage)} + authorizers: [Ash.Policy.Authorizer], + extensions: [AshWorkflow, AshOban] + + #{Recipe.postgres_block(storage, config.acknowledgement, Recipe.identity_index_name(config.acknowledgement, :unique_person))} + + workflow do + step :pending do + transition :acknowledge, to: :acknowledged + + #{overdue_timeout(config.overdue_after)} + end + + #{overdue_step(config.overdue_after)} + + step :acknowledged, terminal: true + end + + code_interface do + define :request, args: [:subject_id, :person_id] + define :request_many, action: :request, args: [:subject_id] + define :acknowledge + end + + actions do + defaults [:read] + + # Asking a person who already has a row returns that row unchanged. + create :request do + accept [:subject_id, :person_id] + upsert? true + upsert_identity :unique_person + upsert_fields [] + change set_attribute(:requested_at, &DateTime.utc_now/0) + end + + update :acknowledge do + require_atomic? false + change set_attribute(:acknowledged_at, &DateTime.utc_now/0) + end + end + + policies do + policy action(:acknowledge) do + authorize_if relates_to_actor_via(:person) + end + end + + attributes do + uuid_v7_primary_key :id + attribute :requested_at, :utc_datetime_usec, allow_nil?: false, public?: true + attribute :acknowledged_at, :utc_datetime_usec, public?: true + timestamps() + end + + relationships do + #{Recipe.belongs_to(:subject, config.subject, config.key_types.subject)} + #{Recipe.belongs_to(:person, config.person, config.key_types.person)} + end + + identities do + identity :unique_person, [:subject_id, :person_id]#{Recipe.pre_check_with(storage)} + end + """ + end + + defp overdue_timeout(nil), do: "" + + defp overdue_timeout(duration) do + "timeout :overdue, fire_after: #{inspect(duration)}, field: :requested_at, transition_to: :overdue" + end + + defp overdue_step(nil), do: "" + + defp overdue_step(_duration) do + """ + step :overdue do + transition :acknowledge, to: :acknowledged + end + """ + end + end +else + defmodule Mix.Tasks.AshWorkflow.Gen.Acknowledgement do + @shortdoc "#{__MODULE__.Docs.short_doc()} | Install `igniter` to use" + @moduledoc __MODULE__.Docs.long_doc() + + use Mix.Task + + def run(_argv) do + Mix.shell().error(""" + The task 'ash_workflow.gen.acknowledgement' requires igniter. Please install igniter and try again. + + For more information, see: https://hexdocs.pm/igniter/readme.html#installation + """) + + exit({:shutdown, 1}) + end + end +end diff --git a/test/mix/ash_workflow/recipe_test.exs b/test/mix/ash_workflow/recipe_test.exs index af2b31a8..3ad72ce1 100644 --- a/test/mix/ash_workflow/recipe_test.exs +++ b/test/mix/ash_workflow/recipe_test.exs @@ -10,7 +10,8 @@ defmodule Mix.AshWorkflow.RecipeTest do for {task, argv} <- [ {"ash_workflow.gen.approval", ["--approver", inspect(User)]}, - {"ash_workflow.gen.expiry", []} + {"ash_workflow.gen.expiry", []}, + {"ash_workflow.gen.acknowledgement", ["--person", inspect(User)]} ] do test "#{task} stops when a missing subject has no data layer to copy" do igniter = @@ -34,7 +35,8 @@ defmodule Mix.AshWorkflow.RecipeTest do for {task, argv} <- [ {"ash_workflow.gen.approval", ["--approver", inspect(User)]}, - {"ash_workflow.gen.expiry", []} + {"ash_workflow.gen.expiry", []}, + {"ash_workflow.gen.acknowledgement", ["--person", inspect(User)]} ] do test "#{task} stops when an existing subject has no data layer" do igniter = diff --git a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs new file mode 100644 index 00000000..35c91e58 --- /dev/null +++ b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs @@ -0,0 +1,361 @@ +defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do + use AshWorkflow.RecipeCase, async: true + + alias AshWorkflow.Scheduler.Precise.Timeline + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.Domain + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.Policy + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.PolicyAcknowledgement + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.PolicyAcknowledgementTransition + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.Terms + alias AshWorkflowTest.RecipeFixtures.Acknowledgement.User + + @fixtures "test/support/recipe_fixtures/acknowledgement" + @files ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex", "#{@fixtures}/policy.ex"] + + defp generate(files \\ @files, argv) do + files + |> project() + |> run_task("ash_workflow.gen.acknowledgement", argv) + end + + defp acknowledgement_for_policies(tmp_dir, argv \\ ["--overdue-after", "14d"]) do + [inspect(Policy), "--person", inspect(User) | argv] + |> generate() + |> compile(tmp_dir) + end + + defp user(recipe, name \\ "person") do + recipe.modules[User] + |> Ash.Changeset.for_create(:create, %{name: name}) + |> Ash.create!() + end + + defp policy(recipe) do + recipe.modules[Policy] + |> Ash.Changeset.for_create(:create, %{title: "Code of conduct"}) + |> Ash.create!() + end + + defp request(recipe, subject, person) do + recipe.modules[PolicyAcknowledgement] + |> Ash.Changeset.for_create(:request, %{subject_id: subject.id, person_id: person.id}) + |> Ash.create!() + end + + defp requested_days_ago(recipe, subject, person, days) do + recipe.modules[PolicyAcknowledgement] + |> Ash.Changeset.for_create(:request, %{subject_id: subject.id, person_id: person.id}) + |> Ash.Changeset.force_change_attribute( + :requested_at, + DateTime.add(DateTime.utc_now(), -days, :day) + ) + |> Ash.create!() + end + + defp acknowledge(acknowledgement, actor) do + acknowledgement + |> Ash.Changeset.for_update(:acknowledge, %{}, actor: actor) + |> Ash.update() + end + + defp acknowledged_by?(subject, actor) do + Ash.load!(subject, :acknowledged_by_actor?, actor: actor).acknowledged_by_actor? + end + + defp reload(acknowledgement), do: Ash.get!(acknowledgement.__struct__, acknowledgement.id) + + defp step_names(resource), do: resource |> AshWorkflow.Info.steps() |> Enum.map(& &1.name) + + describe "an existing subject" do + test "keeps its own attributes and actions and gains only the acknowledgement edits", %{ + tmp_dir: tmp_dir + } do + recipe = acknowledgement_for_policies(tmp_dir) + subject = recipe.modules[Policy] + + assert attributes(subject) == attributes(Policy) + assert actions(subject) == actions(Policy) + + assert names(Ash.Resource.Info.relationships(subject)) -- + names(Ash.Resource.Info.relationships(Policy)) == [:acknowledgements] + + assert names(Ash.Resource.Info.calculations(subject)) -- + names(Ash.Resource.Info.calculations(Policy)) == [:acknowledged_by_actor?] + end + + test "is acknowledged by the actor once their own request is", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir) + policy = policy(recipe) + person = user(recipe) + other = user(recipe, "other") + + acknowledgement = request(recipe, policy, person) + request(recipe, policy, other) + assert acknowledged_by?(policy, person) == false + + assert {:ok, %{state: :acknowledged}} = acknowledge(acknowledgement, person) + + assert acknowledged_by?(policy, person) + refute acknowledged_by?(policy, other) + assert acknowledged_by?(policy, nil) == false + end + + test "records each transition with the person who made it", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir) + person = user(recipe) + + {:ok, _acknowledged} = recipe |> request(policy(recipe), person) |> acknowledge(person) + + log = Ash.read!(recipe.modules[PolicyAcknowledgementTransition]) + + assert log |> Enum.map(& &1.to_state) |> Enum.sort() == [:acknowledged, :pending] + assert %{user_id: user_id} = Enum.find(log, &(&1.to_state == :acknowledged)) + assert user_id == person.id + end + end + + test "creates a missing subject in the given domain and acknowledges against it", %{ + tmp_dir: tmp_dir + } do + recipe = + ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex"] + |> generate([inspect(Terms), "--person", inspect(User), "--domain", inspect(Domain)]) + |> compile(tmp_dir) + + terms_module = recipe.modules[Terms] + + acknowledgement_module = + recipe.modules[AshWorkflowTest.RecipeFixtures.Acknowledgement.TermsAcknowledgement] + + assert Ash.Resource.Info.data_layer(terms_module) == Ash.DataLayer.Ets + assert terms_module in Ash.Domain.Info.resources(recipe.modules[Domain]) + + terms = terms_module |> Ash.Changeset.for_create(:create, %{}) |> Ash.create!() + person = user(recipe) + + acknowledgement = + acknowledgement_module + |> Ash.Changeset.for_create(:request, %{subject_id: terms.id, person_id: person.id}) + |> Ash.create!() + + assert acknowledgement.state == :pending + assert {:ok, %{state: :acknowledged}} = acknowledge(acknowledgement, person) + assert acknowledged_by?(terms, person) + end + + test "running the task a second time changes nothing" do + argv = [inspect(Policy), "--person", inspect(User), "--overdue-after", "14d"] + first = generate(argv) + second = run_task(first.igniter, "ash_workflow.gen.acknowledgement", argv) + + assert second.changed == %{} + assert second.warnings == [] + end + + describe "acknowledge" do + test "is allowed only for the request's own person", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir) + person = user(recipe) + acknowledgement = request(recipe, policy(recipe), person) + + assert {:error, %Ash.Error.Forbidden{}} = + acknowledge(acknowledgement, user(recipe, "other")) + + assert {:error, %Ash.Error.Forbidden{}} = acknowledge(acknowledgement, nil) + assert reload(acknowledgement).state == :pending + + assert {:ok, %{state: :acknowledged} = acknowledged} = acknowledge(acknowledgement, person) + assert %DateTime{} = acknowledged.acknowledged_at + + assert Enum.any?(recipe.notices, &String.contains?(&1, "Only the person")) + end + end + + describe "request" do + test "a person is asked at most once per subject", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir) + policy = policy(recipe) + person = user(recipe) + + first = request(recipe, policy, person) + {:ok, acknowledged} = acknowledge(first, person) + + again = request(recipe, policy, person) + + assert again.id == first.id + assert again.state == :acknowledged + assert again.requested_at == first.requested_at + assert again.acknowledged_at == acknowledged.acknowledged_at + assert [_one] = Ash.read!(recipe.modules[PolicyAcknowledgement]) + + log = + recipe.modules[PolicyAcknowledgementTransition] |> Ash.read!() |> Enum.map(& &1.to_state) + + assert Enum.sort(log) == [:acknowledged, :pending] + end + + test "request_many opens a row for each person, keeping rows already open", %{ + tmp_dir: tmp_dir + } do + recipe = acknowledgement_for_policies(tmp_dir) + acknowledgement_module = recipe.modules[PolicyAcknowledgement] + policy = policy(recipe) + asked = user(recipe, "asked") + {:ok, _acknowledged} = recipe |> request(policy, asked) |> acknowledge(asked) + people = [asked, user(recipe, "new"), user(recipe, "newer")] + + result = + acknowledgement_module.request_many( + policy.id, + Enum.map(people, &%{person_id: &1.id}), + bulk_options: [return_records?: true, return_errors?: true] + ) + + assert result.status == :success + + by_person = + acknowledgement_module |> Ash.read!() |> Map.new(&{&1.person_id, &1.state}) + + assert by_person == %{ + asked.id => :acknowledged, + Enum.at(people, 1).id => :pending, + Enum.at(people, 2).id => :pending + } + end + end + + describe "--overdue-after" do + test "moves an unacknowledged request to overdue once the deadline passes", %{ + tmp_dir: tmp_dir + } do + recipe = acknowledgement_for_policies(tmp_dir) + acknowledgement_module = recipe.modules[PolicyAcknowledgement] + policy = policy(recipe) + late_person = user(recipe, "late") + + fresh = request(recipe, policy, user(recipe)) + late = requested_days_ago(recipe, policy, late_person, 15) + + assert Timeline.run_due(acknowledgement_module) == 1 + assert reload(fresh).state == :pending + assert reload(late).state == :overdue + + assert {:ok, %{state: :acknowledged}} = late |> reload() |> acknowledge(late_person) + assert acknowledged_by?(policy, late_person) + end + + test "leaves an acknowledged request alone after the deadline", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir) + person = user(recipe) + late = requested_days_ago(recipe, policy(recipe), person, 15) + + {:ok, _acknowledged} = acknowledge(late, person) + + assert Timeline.run_due(recipe.modules[PolicyAcknowledgement]) == 0 + assert reload(late).state == :acknowledged + end + + test "without it, no overdue step is generated", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir, []) + acknowledgement_module = recipe.modules[PolicyAcknowledgement] + + assert step_names(acknowledgement_module) == [:pending, :acknowledged] + assert AshWorkflow.Info.scheduled_work(acknowledgement_module) == [] + end + + for {flag, duration} <- [ + {"10s", {10, :seconds}}, + {"30m", {30, :minutes}}, + {"12h", {12, :hours}}, + {"2d", {2, :days}}, + {"2w", {14, :days}} + ] do + test "parses #{flag} as #{inspect(duration)}" do + recipe = + generate([inspect(Policy), "--person", inspect(User), "--overdue-after", unquote(flag)]) + + assert source!( + recipe, + "lib/ash_workflow_test/recipe_fixtures/acknowledgement/policy_acknowledgement.ex" + ) =~ + "fire_after: #{inspect(unquote(Macro.escape(duration)))}, field: :requested_at" + end + end + + test "reports an issue for a duration it cannot parse" do + igniter = + @files + |> project() + |> Igniter.compose_task("ash_workflow.gen.acknowledgement", [ + inspect(Policy), + "--person", + inspect(User), + "--overdue-after", + "2y" + ]) + + assert Enum.any?(igniter.issues, &String.contains?(&1, "--overdue-after must look like")) + end + end + + test "generates a Postgres-backed resource on the subject's repo", %{tmp_dir: tmp_dir} do + recipe = + [ + "test/support/recipe_fixtures/transition_log/postgres_domain.ex", + "test/support/recipe_fixtures/transition_log/postgres_ticket.ex" + ] + |> generate([ + "AshWorkflowTest.RecipeFixtures.TransitionLog.PostgresTicket", + "--person", + "AshWorkflowTest.RecipeFixtures.TransitionLog.Reviewer", + "--overdue-after", + "7d" + ]) + |> compile(tmp_dir) + + for {module, table} <- [ + PostgresTicketAcknowledgement: "postgres_ticket_acknowledgements", + PostgresTicketAcknowledgementTransition: "postgres_ticket_acknowledgements_transitions" + ] do + resource = + recipe.modules[Module.concat(AshWorkflowTest.RecipeFixtures.TransitionLog, module)] + + assert AshPostgres.DataLayer.Info.repo(resource) == AshWorkflowTest.Repo + assert AshPostgres.DataLayer.Info.table(resource) == table + end + end + + test "--no-transition-log generates no transition log" do + recipe = generate([inspect(Policy), "--person", inspect(User), "--no-transition-log"]) + + refute Enum.any?(Map.keys(recipe.changed), &String.ends_with?(&1, "_transition.ex")) + end + + test "reports an issue for a missing subject without --domain" do + igniter = + @files + |> project() + |> Igniter.compose_task("ash_workflow.gen.acknowledgement", [ + inspect(Terms), + "--person", + inspect(User) + ]) + + assert Enum.any?(igniter.issues, &String.contains?(&1, "Pass --domain to create it")) + end + + defp names(entities), do: Enum.map(entities, & &1.name) + + # Spark metadata records the file each entity was compiled from, which + # differs between the fixture and the generated copy. + defp attributes(resource) do + resource |> Ash.Resource.Info.attributes() |> Enum.map(&Map.delete(&1, :__spark_metadata__)) + end + + defp actions(resource) do + for action <- Ash.Resource.Info.actions(resource) do + changes = action |> Map.get(:changes, []) |> Enum.map(& &1.change) + {action.name, action.type, Map.get(action, :accept), changes, names(action.arguments)} + end + end +end diff --git a/test/support/recipe_fixtures/acknowledgement/domain.ex b/test/support/recipe_fixtures/acknowledgement/domain.ex new file mode 100644 index 00000000..1c73d482 --- /dev/null +++ b/test/support/recipe_fixtures/acknowledgement/domain.ex @@ -0,0 +1,9 @@ +defmodule AshWorkflowTest.RecipeFixtures.Acknowledgement.Domain do + @moduledoc false + use Ash.Domain, validate_config_inclusion?: false + + resources do + resource AshWorkflowTest.RecipeFixtures.Acknowledgement.Policy + resource AshWorkflowTest.RecipeFixtures.Acknowledgement.User + end +end diff --git a/test/support/recipe_fixtures/acknowledgement/policy.ex b/test/support/recipe_fixtures/acknowledgement/policy.ex new file mode 100644 index 00000000..58b245e5 --- /dev/null +++ b/test/support/recipe_fixtures/acknowledgement/policy.ex @@ -0,0 +1,26 @@ +defmodule AshWorkflowTest.RecipeFixtures.Acknowledgement.Policy do + @moduledoc false + use Ash.Resource, + domain: AshWorkflowTest.RecipeFixtures.Acknowledgement.Domain, + data_layer: Ash.DataLayer.Ets + + actions do + defaults [:read, :destroy] + + create :create do + accept [:title] + end + + update :revise do + accept [:title] + change set_attribute(:revised?, true) + end + end + + attributes do + uuid_v7_primary_key :id + attribute :title, :string, allow_nil?: false, public?: true + attribute :revised?, :boolean, default: false, public?: true + timestamps() + end +end diff --git a/test/support/recipe_fixtures/acknowledgement/user.ex b/test/support/recipe_fixtures/acknowledgement/user.ex new file mode 100644 index 00000000..8e932df0 --- /dev/null +++ b/test/support/recipe_fixtures/acknowledgement/user.ex @@ -0,0 +1,19 @@ +defmodule AshWorkflowTest.RecipeFixtures.Acknowledgement.User do + @moduledoc false + use Ash.Resource, + domain: AshWorkflowTest.RecipeFixtures.Acknowledgement.Domain, + data_layer: Ash.DataLayer.Ets + + actions do + defaults [:read] + + create :create do + accept [:name] + end + end + + attributes do + uuid_v7_primary_key :id + attribute :name, :string, allow_nil?: false, public?: true + end +end From afa68f65a056bc0526640fe0fa5d413e0433f2a7 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Sun, 18 Oct 2026 21:17:21 +0200 Subject: [PATCH 09/15] docs: add the acknowledgement recipe page --- .../design/acknowledgement-recipe.md | 2 + documentation/recipes/acknowledgement.md | 131 ++++++++++++++++++ documentation/recipes/index.md | 2 +- mix.exs | 1 + 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 documentation/recipes/acknowledgement.md diff --git a/documentation/design/acknowledgement-recipe.md b/documentation/design/acknowledgement-recipe.md index 8bafb032..cec732ec 100644 --- a/documentation/design/acknowledgement-recipe.md +++ b/documentation/design/acknowledgement-recipe.md @@ -151,6 +151,8 @@ A generic action taking `person_ids` was the alternative. Its `subject_id` argum The alternative was a plain create that fails on the identity. Every caller adding a new starter would then have to read the existing rows and subtract them first, which is the race the identity exists to close. +`AshWorkflow.Changes.RecordEvent` runs on every create and appended an `:initial` log row each time, including on an upsert that returned an existing row. A repeated `request` then logged the person as entering their current step a second time. This PR fixes it in the library: `RecordEvent` writes no log row when a create's record carries `upsert_action: :update` metadata, which both `Ash.DataLayer.Ets` and AshPostgres set on an upsert that found an existing row. + A person acknowledges a subject once. A terms update that must be acknowledged again is a new subject row, such as a new version of the terms, not a second acknowledgement of the old one. ## Who may acknowledge diff --git a/documentation/recipes/acknowledgement.md b/documentation/recipes/acknowledgement.md new file mode 100644 index 00000000..612399da --- /dev/null +++ b/documentation/recipes/acknowledgement.md @@ -0,0 +1,131 @@ +# Acknowledgement + +`mix ash_workflow.gen.acknowledgement` adds an acknowledgement workflow to a resource. Your application opens one request per person who must acknowledge a record, such as a policy or a terms update. Each person acknowledges their own request, and a request nobody has acknowledged moves to `:overdue` once its deadline passes. + +## The command + +```bash +mix ash_workflow.gen.acknowledgement MyApp.Policies.Policy \ + --person MyApp.Accounts.User \ + --overdue-after 14d +``` + +| Option | Default | Effect | +|---|---|---| +| `--person` | required | The actor resource. Each acknowledgement belongs to one person. | +| `--module` | `Acknowledgement` | Name of the generated acknowledgement resource. | +| `--domain` | the subject's domain | Domain for a subject the task creates. Required only when the subject does not exist. | +| `--overdue-after` | none | Moves an unacknowledged request to `:overdue` this long after `requested_at`. Accepts `10s`, `30m`, `12h`, `2d` and `2w`. Without it, no `:overdue` step is generated. | +| `--transition-log` | `true` | Also runs `mix ash_workflow.gen.transition_log` for the acknowledgement resource, recording the person who made each transition. Pass `--no-transition-log` to skip it. | + +When the subject does not exist, the task creates it with `mix ash.gen.resource`, using the data layer of the `--person` resource, or else the data layer of the first ETS or Postgres resource in `--domain`. When neither the person resource nor any resource there uses ETS or Postgres, the task stops with an issue and writes nothing. Create the subject resource first, or pass a `--domain` that has one. Running the task again on the same subject changes nothing. + +## What it generates + +For the command above, the task writes one module and edits the subject: + +- `MyApp.Policies.PolicyAcknowledgement` runs the workflow. It belongs to the policy and to a person, and holds `requested_at` and `acknowledged_at`. An identity on `(subject_id, person_id)` allows one request per person per policy. +- `MyApp.Policies.Policy` gains `has_many :acknowledgements` and an `acknowledged_by_actor?` calculation. The task adds no change, argument or policy to the subject's actions. + +The acknowledgement is a separate resource rather than a `workflow` block on the subject, so a subject that already runs a workflow keeps it. + +## The workflow + +```mermaid +stateDiagram-v2 + [*] --> pending + pending --> acknowledged: acknowledge + pending --> overdue: timeout overdue_after + overdue --> acknowledged: acknowledge +``` + +```elixir +workflow do + step :pending do + transition :acknowledge, to: :acknowledged + + timeout :overdue, fire_after: {14, :days}, field: :requested_at, transition_to: :overdue + end + + step :overdue do + transition :acknowledge, to: :acknowledged + end + + step :acknowledged, terminal: true +end +``` + +Without `--overdue-after`, there is no `:overdue` step and no timeout. + +A person in `:overdue` can still acknowledge. The overdue deadline reads `requested_at`, which `:request` writes once. A transition you add that loops back into `:pending`, such as a reminder, does not move the deadline. + +## The policies + +```elixir +policies do + policy action(:acknowledge) do + authorize_if relates_to_actor_via(:person) + end +end +``` + +Only the person a request was opened for may acknowledge it. Nobody can acknowledge on someone else's behalf, and an acknowledgement without an actor is forbidden. + +The `:request` create action has no policy, so anyone can open a request. Add a policy to it if your application needs to restrict who opens requests. + +## What your application does next + +### Open requests + +Call `request/3` for one person, or `request_many/3` for a list of people, wherever acknowledgement should start, such as a publish action or an onboarding step: + +```elixir +MyApp.Policies.PolicyAcknowledgement.request(policy.id, user.id) + +MyApp.Policies.PolicyAcknowledgement.request_many( + policy.id, + Enum.map(staff, &%{person_id: &1.id}) +) +``` + +`request_many/3` runs `Ash.bulk_create/4`. Pass `bulk_options: [return_records?: true]` to get the rows back. + +`:request` is an upsert on the `(subject_id, person_id)` identity. Asking a person who already has a request returns that request unchanged, with its state and dates as they were. Call `request_many/3` with everyone who must acknowledge each time the list grows, and only the new people get new requests. + +A person acknowledges a record once. To ask everyone again after a change, open requests against a new subject record, such as a new version of the policy. + +### Acknowledge + +```elixir +MyApp.Policies.PolicyAcknowledgement.acknowledge(acknowledgement, actor: current_user) +``` + +### React to overdue + +The task generates no reminder. Add a timeout with an `action` or an `every` to the `:overdue` step to chase the person, or use an Ash notifier on the acknowledgement resource. + +### Use the outcome + +`acknowledged_by_actor?` on the subject is true when the actor loading it has acknowledged it. Load it with the current user to decide whether to show a banner: + +```elixir +Ash.load!(policy, :acknowledged_by_actor?, actor: current_user) +``` + +To list who has not acknowledged, read the acknowledgement rows: + +```elixir +MyApp.Policies.PolicyAcknowledgement +|> Ash.Query.filter(subject_id == ^policy.id and state != :acknowledged) +|> Ash.read!() +``` + +### Generate the migrations + +On AshPostgres, run `mix ash.codegen add_policy_acknowledgement` to create the acknowledgement and transition log tables. + +## Limits + +There is no transition to withdraw a request. A person who leaves before acknowledging keeps a `:pending` or `:overdue` request. Add a transition to a terminal step if you need one. + +`acknowledged_by_actor?` returns `false` when it is loaded without an actor. diff --git a/documentation/recipes/index.md b/documentation/recipes/index.md index c2f17fba..b2dc6e09 100644 --- a/documentation/recipes/index.md +++ b/documentation/recipes/index.md @@ -15,7 +15,7 @@ A recipe without a link has not been released yet. Each row links to its page on | `gen.review` | `in_review → changes_requested → in_review → approved` | Content, design review, sign-off | | `gen.publication` | `draft → scheduled → published → unpublished` | Posts, announcements, listings | | `gen.invitation` | `sent → accepted \| declined \| expired`, with `resend` | Team invites, RSVPs, access grants | -| `gen.acknowledgement` | `pending → acknowledged \| overdue` | Policy attestations, terms updates | +| [`gen.acknowledgement`](acknowledgement.md) | `pending → acknowledged \| overdue` | Policy attestations, terms updates | | `gen.deletion` | `requested → scheduled → deleted`, with `restore` | Account closure, GDPR erasure | | `gen.dormancy` | `active → dormant → archived` | Accounts, projects, leads | | `gen.verification` | `submitted → verifying → verified \| rejected` | Identity documents, registrations | diff --git a/mix.exs b/mix.exs index bad09505..5ca6f038 100644 --- a/mix.exs +++ b/mix.exs @@ -156,6 +156,7 @@ defmodule AshWorkflow.MixProject do {"documentation/recipes/index.md", filename: "recipes"}, "documentation/recipes/approval.md", "documentation/recipes/expiry.md", + "documentation/recipes/acknowledgement.md", "documentation/dsls/DSL-AshWorkflow.md" ], groups_for_extras: [ From b5cc3d281b8c1adf449be196b82f75530204e37c Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 14:31:58 +0200 Subject: [PATCH 10/15] test: assert request_many logs one initial row per person across repeated calls --- .../ash_workflow.gen_acknowledgement_test.exs | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs index 35c91e58..cf554080 100644 --- a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs +++ b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs @@ -204,23 +204,35 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do {:ok, _acknowledged} = recipe |> request(policy, asked) |> acknowledge(asked) people = [asked, user(recipe, "new"), user(recipe, "newer")] - result = - acknowledgement_module.request_many( - policy.id, - Enum.map(people, &%{person_id: &1.id}), - bulk_options: [return_records?: true, return_errors?: true] - ) - - assert result.status == :success + for listed <- [Enum.take(people, 2), people] do + result = + acknowledgement_module.request_many( + policy.id, + Enum.map(listed, &%{person_id: &1.id}), + bulk_options: [return_records?: true, return_errors?: true] + ) + + assert result.status == :success + end - by_person = - acknowledgement_module |> Ash.read!() |> Map.new(&{&1.person_id, &1.state}) + acknowledgements = Ash.read!(acknowledgement_module) + by_person = Map.new(acknowledgements, &{&1.person_id, &1.state}) assert by_person == %{ asked.id => :acknowledged, Enum.at(people, 1).id => :pending, Enum.at(people, 2).id => :pending } + + person_by_acknowledgement = Map.new(acknowledgements, &{&1.id, &1.person_id}) + + initial_rows_by_person = + recipe.modules[PolicyAcknowledgementTransition] + |> Ash.read!() + |> Enum.filter(&(&1.triggered_by == :initial)) + |> Enum.frequencies_by(&person_by_acknowledgement[&1.workflow_id]) + + assert initial_rows_by_person == Map.new(people, &{&1.id, 1}) end end From 6eda385c77737fe975105be45cb5582655c940b8 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 14:37:19 +0200 Subject: [PATCH 11/15] feat: deny acknowledgement requests until the application allows them --- .../design/acknowledgement-recipe.md | 14 ++- documentation/recipes/acknowledgement.md | 30 ++++- .../tasks/ash_workflow.gen.acknowledgement.ex | 24 +++- .../ash_workflow.gen_acknowledgement_test.exs | 111 ++++++++++++++++-- 4 files changed, 156 insertions(+), 23 deletions(-) diff --git a/documentation/design/acknowledgement-recipe.md b/documentation/design/acknowledgement-recipe.md index cec732ec..c6e5532a 100644 --- a/documentation/design/acknowledgement-recipe.md +++ b/documentation/design/acknowledgement-recipe.md @@ -155,21 +155,27 @@ The alternative was a plain create that fails on the identity. Every caller addi A person acknowledges a subject once. A terms update that must be acknowledged again is a new subject row, such as a new version of the terms, not a second acknowledgement of the old one. -## Who may acknowledge +## Who may request and acknowledge + +Who may open a request differs per application, so `:request` follows the other recipes. The generator writes `PolicyAcknowledgement.Checks.CanRequest`, a check that denies everyone, and gates `:request` on it. `request_many/3` runs the same action through `Ash.bulk_create/4`, so the same policy authorizes each row of a bulk call. The only human transition is `acknowledge`, and its rule is the same in every application: the person asked is the person who confirms. The generator writes that rule as a built-in check rather than a deny-by-default check module. ```elixir policies do + policy action(:request) do + authorize_if MyApp.Policies.PolicyAcknowledgement.Checks.CanRequest + end + policy action(:acknowledge) do authorize_if relates_to_actor_via(:person) end end ``` -Approval and expiry generate a check module that denies everyone, because who may approve or renew differs per application and an open default is unsafe. Acknowledgement has no such open default to avoid. A check module that denied everyone would make every application write the same `relates_to_actor_via(:person)` line before the recipe did anything. The generator therefore writes no check module, and its notice names the policy instead. +A check module for `:acknowledge` that denied everyone would make every application write the same `relates_to_actor_via(:person)` line before the recipe did anything. The generator therefore writes no check module for it, and its notice names the policy instead. -`AshWorkflow.Transformers.AddPolicies` allows `:request`, reads and the scheduler's overdue timeout. Who may open a request is the application's decision, made where it calls `request/3`. +`AshWorkflow.Transformers.AddPolicies` allows `:request`, reads and the scheduler's overdue timeout. Ash requires every policy that applies to an action to pass, so `CanRequest` still decides `:request`. ## Composing the transition log @@ -177,7 +183,7 @@ The generator composes `ash_workflow.gen.transition_log` with `--actor` set to ` ## Code shared with the other recipes -The generator uses `Mix.AshWorkflow.Recipe` as it stands: `parse_duration/2`, `ensure_subject/5`, `add_subject_edits/4`, `compose_transition_log/3` and the rendering helpers. It adds nothing to the module. +The generator uses `Mix.AshWorkflow.Recipe` as it stands: `parse_duration/2`, `ensure_subject/5`, `add_subject_edits/4`, `compose_transition_log/3`, `key_type/3`, `belongs_to/3`, `deny_check_contents/2`, `create_policy/2` and the rendering helpers. It adds nothing to the module. ## Open questions diff --git a/documentation/recipes/acknowledgement.md b/documentation/recipes/acknowledgement.md index 612399da..4041195f 100644 --- a/documentation/recipes/acknowledgement.md +++ b/documentation/recipes/acknowledgement.md @@ -22,9 +22,10 @@ When the subject does not exist, the task creates it with `mix ash.gen.resource` ## What it generates -For the command above, the task writes one module and edits the subject: +For the command above, the task writes two modules and edits the subject: - `MyApp.Policies.PolicyAcknowledgement` runs the workflow. It belongs to the policy and to a person, and holds `requested_at` and `acknowledged_at`. An identity on `(subject_id, person_id)` allows one request per person per policy. +- `MyApp.Policies.PolicyAcknowledgement.Checks.CanRequest` decides who may open a request. It denies everyone as generated. - `MyApp.Policies.Policy` gains `has_many :acknowledgements` and an `acknowledged_by_actor?` calculation. The task adds no change, argument or policy to the subject's actions. The acknowledgement is a separate resource rather than a `workflow` block on the subject, so a subject that already runs a workflow keeps it. @@ -63,6 +64,10 @@ A person in `:overdue` can still acknowledge. The overdue deadline reads `reques ```elixir policies do + policy action(:request) do + authorize_if MyApp.Policies.PolicyAcknowledgement.Checks.CanRequest + end + policy action(:acknowledge) do authorize_if relates_to_actor_via(:person) end @@ -71,20 +76,37 @@ end Only the person a request was opened for may acknowledge it. Nobody can acknowledge on someone else's behalf, and an acknowledgement without an actor is forbidden. -The `:request` create action has no policy, so anyone can open a request. Add a policy to it if your application needs to restrict who opens requests. +`CanRequest` gates `:request`, so it also gates `request_many/3`, which runs the same action in bulk. Nobody can open a request until you change it. ## What your application does next +### Decide who may open a request + +`CanRequest` denies everyone, so no request can be opened until you change it. Replace its `match?/3`, or replace the `authorize_if` line in the `:request` policy with a built-in check: + +```elixir +policies do + policy action(:request) do + authorize_if actor_attribute_equals(:role, :compliance_officer) + end +end +``` + +Code that opens requests on the application's behalf, such as an onboarding job, can pass `authorize?: false` instead. + +Reads stay open by default. `AshWorkflow` authorizes `:read` on the acknowledgement resource for every actor. Add a read policy if acknowledgements are private. + ### Open requests Call `request/3` for one person, or `request_many/3` for a list of people, wherever acknowledgement should start, such as a publish action or an onboarding step: ```elixir -MyApp.Policies.PolicyAcknowledgement.request(policy.id, user.id) +MyApp.Policies.PolicyAcknowledgement.request(policy.id, user.id, actor: current_user) MyApp.Policies.PolicyAcknowledgement.request_many( policy.id, - Enum.map(staff, &%{person_id: &1.id}) + Enum.map(staff, &%{person_id: &1.id}), + actor: current_user ) ``` diff --git a/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex index c5461986..11d179d2 100644 --- a/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex +++ b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex @@ -19,6 +19,9 @@ defmodule Mix.Tasks.AshWorkflow.Gen.Acknowledgement.Docs do `acknowledged_by_actor?` calculation. When the subject does not exist, it is created with `mix ash.gen.resource` first. + Nobody may open a request until the application defines who can, in the + generated `Checks.CanRequest` module. + ## Example ```bash @@ -83,11 +86,13 @@ if Code.ensure_loaded?(Igniter.Mix.Task.Info) do case Recipe.parse_duration(options[:overdue_after], "--overdue-after") do {:ok, overdue_after} -> person = ProjectModule.parse(options[:person]) + acknowledgement = acknowledgement_module(subject, options[:module]) config = %{ subject: subject, person: person, - acknowledgement: acknowledgement_module(subject, options[:module]), + acknowledgement: acknowledgement, + can_request: Module.concat([acknowledgement, Checks, CanRequest]), overdue_after: overdue_after, transition_log?: options[:transition_log] } @@ -154,14 +159,18 @@ if Code.ensure_loaded?(Igniter.Mix.Task.Info) do config.acknowledgement, acknowledgement_contents(config, storage) ) + |> ProjectModule.create_module(config.can_request, can_request_contents(config)) |> DomainIgniter.add_resource_reference(storage.domain, config.acknowledgement) |> compose_transition_log(config) |> Igniter.add_notice(""" Generated #{inspect(config.acknowledgement)} to acknowledge #{inspect(config.subject)}. + Nobody can open a request yet. Define who may open one in \ + #{inspect(config.can_request)}, which denies everyone as generated. \ + Open requests with request/3 or request_many/3. + Only the person a request was opened for may acknowledge it, as the \ - policy on :acknowledge states. Open requests with request/3 or \ - request_many/3. + policy on :acknowledge states. """) end @@ -217,6 +226,8 @@ if Code.ensure_loaded?(Igniter.Mix.Task.Info) do end policies do + #{Recipe.create_policy(:request, config.can_request)} + policy action(:acknowledge) do authorize_if relates_to_actor_via(:person) end @@ -240,6 +251,13 @@ if Code.ensure_loaded?(Igniter.Mix.Task.Info) do """ end + defp can_request_contents(config) do + Recipe.deny_check_contents( + "Decides who may open an `#{inspect(config.acknowledgement)}` request.", + "actor may open an acknowledgement request" + ) + end + defp overdue_timeout(nil), do: "" defp overdue_timeout(duration) do diff --git a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs index cf554080..fa601899 100644 --- a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs +++ b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs @@ -11,6 +11,8 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do @fixtures "test/support/recipe_fixtures/acknowledgement" @files ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex", "#{@fixtures}/policy.ex"] + @checks "lib/ash_workflow_test/recipe_fixtures/acknowledgement/policy_acknowledgement/checks" + @deny_all "def match?(_actor, _context, _opts), do: false" defp generate(files \\ @files, argv) do files @@ -21,15 +23,33 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do defp acknowledgement_for_policies(tmp_dir, argv \\ ["--overdue-after", "14d"]) do [inspect(Policy), "--person", inspect(User) | argv] |> generate() + |> allow_requesters() |> compile(tmp_dir) end + # What an application does once it has generated the recipe: fill in + # CanRequest. Here any actor may open a request. + defp allow_requesters(recipe, checks \\ @checks) do + edit_source(recipe, "#{checks}/can_request.ex", fn source -> + String.replace(source, @deny_all, "def match?(actor, _context, _opts), do: is_map(actor)") + end) + end + + # `compile/2` reads every file from the project, not only the changed ones. + defp edit_source(recipe, path, fun) do + recipe + |> update_in([Access.key!(:changed), path], fun) + |> update_in([Access.key!(:igniter), Access.key!(:assigns), :test_files, path], fun) + end + defp user(recipe, name \\ "person") do recipe.modules[User] |> Ash.Changeset.for_create(:create, %{name: name}) |> Ash.create!() end + defp requester(recipe), do: user(recipe, "requester") + defp policy(recipe) do recipe.modules[Policy] |> Ash.Changeset.for_create(:create, %{title: "Code of conduct"}) @@ -37,14 +57,42 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do end defp request(recipe, subject, person) do + {:ok, acknowledgement} = open_request(recipe, subject, person) + acknowledgement + end + + defp open_request(recipe, subject, person), + do: open_request(recipe, subject, person, requester(recipe)) + + defp open_request(recipe, subject, person, actor) do recipe.modules[PolicyAcknowledgement] - |> Ash.Changeset.for_create(:request, %{subject_id: subject.id, person_id: person.id}) - |> Ash.create!() + |> Ash.Changeset.for_create( + :request, + %{subject_id: subject.id, person_id: person.id}, + actor: actor + ) + |> Ash.create() + end + + defp request_many(recipe, subject, people), + do: request_many(recipe, subject, people, requester(recipe)) + + defp request_many(recipe, subject, people, actor) do + recipe.modules[PolicyAcknowledgement].request_many( + subject.id, + Enum.map(people, &%{person_id: &1.id}), + actor: actor, + bulk_options: [return_records?: true, return_errors?: true] + ) end defp requested_days_ago(recipe, subject, person, days) do recipe.modules[PolicyAcknowledgement] - |> Ash.Changeset.for_create(:request, %{subject_id: subject.id, person_id: person.id}) + |> Ash.Changeset.for_create( + :request, + %{subject_id: subject.id, person_id: person.id}, + actor: requester(recipe) + ) |> Ash.Changeset.force_change_attribute( :requested_at, DateTime.add(DateTime.utc_now(), -days, :day) @@ -120,6 +168,9 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do recipe = ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex"] |> generate([inspect(Terms), "--person", inspect(User), "--domain", inspect(Domain)]) + |> allow_requesters( + "lib/ash_workflow_test/recipe_fixtures/acknowledgement/terms_acknowledgement/checks" + ) |> compile(tmp_dir) terms_module = recipe.modules[Terms] @@ -135,7 +186,11 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do acknowledgement = acknowledgement_module - |> Ash.Changeset.for_create(:request, %{subject_id: terms.id, person_id: person.id}) + |> Ash.Changeset.for_create( + :request, + %{subject_id: terms.id, person_id: person.id}, + actor: requester(recipe) + ) |> Ash.create!() assert acknowledgement.state == :pending @@ -205,14 +260,7 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do people = [asked, user(recipe, "new"), user(recipe, "newer")] for listed <- [Enum.take(people, 2), people] do - result = - acknowledgement_module.request_many( - policy.id, - Enum.map(listed, &%{person_id: &1.id}), - bulk_options: [return_records?: true, return_errors?: true] - ) - - assert result.status == :success + assert %{status: :success} = request_many(recipe, policy, listed) end acknowledgements = Ash.read!(acknowledgement_module) @@ -236,6 +284,45 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do end end + describe "CanRequest" do + test "denies everyone as generated", %{tmp_dir: tmp_dir} do + recipe = + [inspect(Policy), "--person", inspect(User)] + |> generate() + |> compile(tmp_dir) + + policy = policy(recipe) + person = user(recipe) + + assert {:error, %Ash.Error.Forbidden{}} = open_request(recipe, policy, person) + assert {:error, %Ash.Error.Forbidden{}} = open_request(recipe, policy, person, nil) + + assert %{status: :error, errors: [%Ash.Error.Forbidden{} | _]} = + request_many(recipe, policy, [person, user(recipe, "other")]) + + assert Ash.read!(recipe.modules[PolicyAcknowledgement]) == [] + assert Enum.any?(recipe.notices, &String.contains?(&1, "Nobody can open a request yet")) + end + + test "lets a requester open requests once the application permits them", %{ + tmp_dir: tmp_dir + } do + recipe = acknowledgement_for_policies(tmp_dir) + policy = policy(recipe) + people = [user(recipe), user(recipe, "other")] + + assert {:error, %Ash.Error.Forbidden{}} = open_request(recipe, policy, hd(people), nil) + + assert %{status: :error, errors: [%Ash.Error.Forbidden{} | _]} = + request_many(recipe, policy, people, nil) + + assert Ash.read!(recipe.modules[PolicyAcknowledgement]) == [] + + assert %{status: :success, records: [_, _]} = request_many(recipe, policy, people) + assert {:ok, %{state: :pending}} = open_request(recipe, policy, user(recipe, "third")) + end + end + describe "--overdue-after" do test "moves an unacknowledged request to overdue once the deadline passes", %{ tmp_dir: tmp_dir From 7c7c944e4995466c763e4c973543ed161892dc71 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Thu, 22 Oct 2026 14:37:29 +0200 Subject: [PATCH 12/15] docs: note that the acknowledgement upsert relies on RecordEvent from #147 and Ash 3.29 --- documentation/design/acknowledgement-recipe.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/documentation/design/acknowledgement-recipe.md b/documentation/design/acknowledgement-recipe.md index c6e5532a..3b9b07f5 100644 --- a/documentation/design/acknowledgement-recipe.md +++ b/documentation/design/acknowledgement-recipe.md @@ -151,7 +151,7 @@ A generic action taking `person_ids` was the alternative. Its `subject_id` argum The alternative was a plain create that fails on the identity. Every caller adding a new starter would then have to read the existing rows and subtract them first, which is the race the identity exists to close. -`AshWorkflow.Changes.RecordEvent` runs on every create and appended an `:initial` log row each time, including on an upsert that returned an existing row. A repeated `request` then logged the person as entering their current step a second time. This PR fixes it in the library: `RecordEvent` writes no log row when a create's record carries `upsert_action: :update` metadata, which both `Ash.DataLayer.Ets` and AshPostgres set on an upsert that found an existing row. +The upsert relies on `AshWorkflow.Changes.RecordEvent` as fixed in #147, and on Ash 3.29 or later. Before #147, `RecordEvent` appended an `:initial` log row on every create, including an upsert that returned an existing row. A repeated `request` then logged the person as entering their current step a second time. After #147, `RecordEvent` writes no log row and leaves the scheduler alone when a create's record carries `upsert_action: :update` metadata. AshPostgres sets that metadata on an upsert that found an existing row, and `Ash.DataLayer.Ets` sets it from Ash 3.29. #147 tests the Postgres upsert in the library's own suite. The recipe's tests run on ETS, because the Postgres fixture resources set `migrate? false`. A person acknowledges a subject once. A terms update that must be acknowledged again is a new subject row, such as a new version of the terms, not a second acknowledgement of the old one. From 73d696729486c9de329cbfe01c12b0668334acb8 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Fri, 23 Oct 2026 08:40:57 +0200 Subject: [PATCH 13/15] feat: reject an acknowledgement --overdue-after below the scheduler's precision floor --- .../design/acknowledgement-recipe.md | 2 +- documentation/recipes/acknowledgement.md | 2 +- .../tasks/ash_workflow.gen.acknowledgement.ex | 61 ++++++++++--------- .../mix/ash_workflow/recipe_interval_test.exs | 23 +++++++ .../ash_workflow.gen_acknowledgement_test.exs | 17 +++--- 5 files changed, 63 insertions(+), 42 deletions(-) diff --git a/documentation/design/acknowledgement-recipe.md b/documentation/design/acknowledgement-recipe.md index 3b9b07f5..90e3438d 100644 --- a/documentation/design/acknowledgement-recipe.md +++ b/documentation/design/acknowledgement-recipe.md @@ -35,7 +35,7 @@ mix ash_workflow.gen.acknowledgement MyApp.Policies.Policy \ | `--overdue-after` | none | Move an unacknowledged request to `:overdue` this long after `requested_at`. Omitted means no `:overdue` step. | | `--transition-log` | `true` | Composes `ash_workflow.gen.transition_log` with `--actor` set to the person. `--no-transition-log` skips it. | -`--overdue-after` accepts `10s`, `30m`, `12h`, `2d` and `2w`, parsed by `Mix.AshWorkflow.Recipe.parse_duration/2` as approval's flag of the same name is. +`--overdue-after` accepts `30m`, `12h`, `2d` and `2w`, parsed by `Mix.AshWorkflow.Recipe.parse_duration/2` as approval's flag of the same name is. A duration under a minute needs `AshWorkflow.Scheduler.Precise`. When the subject does not exist, the generator creates it with `ash.gen.resource`. The created subject takes its data layer from `--person`, as approval takes it from `--approver`, and falls back to the resources in `--domain` the same way. When neither has an ETS or Postgres data layer, the generator stops with an Igniter issue. diff --git a/documentation/recipes/acknowledgement.md b/documentation/recipes/acknowledgement.md index 4041195f..85079a2f 100644 --- a/documentation/recipes/acknowledgement.md +++ b/documentation/recipes/acknowledgement.md @@ -15,7 +15,7 @@ mix ash_workflow.gen.acknowledgement MyApp.Policies.Policy \ | `--person` | required | The actor resource. Each acknowledgement belongs to one person. | | `--module` | `Acknowledgement` | Name of the generated acknowledgement resource. | | `--domain` | the subject's domain | Domain for a subject the task creates. Required only when the subject does not exist. | -| `--overdue-after` | none | Moves an unacknowledged request to `:overdue` this long after `requested_at`. Accepts `10s`, `30m`, `12h`, `2d` and `2w`. Without it, no `:overdue` step is generated. | +| `--overdue-after` | none | Moves an unacknowledged request to `:overdue` this long after `requested_at`. Accepts `30m`, `12h`, `2d` and `2w`. A duration under a minute needs `AshWorkflow.Scheduler.Precise`. Without it, no `:overdue` step is generated. | | `--transition-log` | `true` | Also runs `mix ash_workflow.gen.transition_log` for the acknowledgement resource, recording the person who made each transition. Pass `--no-transition-log` to skip it. | When the subject does not exist, the task creates it with `mix ash.gen.resource`, using the data layer of the `--person` resource, or else the data layer of the first ETS or Postgres resource in `--domain`. When neither the person resource nor any resource there uses ETS or Postgres, the task stops with an issue and writes nothing. Create the subject resource first, or pass a `--domain` that has one. Running the task again on the same subject changes nothing. diff --git a/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex index 11d179d2..34c748bb 100644 --- a/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex +++ b/lib/mix/tasks/ash_workflow.gen.acknowledgement.ex @@ -37,8 +37,9 @@ defmodule Mix.Tasks.AshWorkflow.Gen.Acknowledgement.Docs do * `--domain` - the domain for a subject the task creates. Required only when the subject does not exist. * `--overdue-after` - moves an unacknowledged request to `:overdue` this - long after it was requested, given as `10s`, `30m`, `12h`, `2d` or - `2w`. Without it, no `:overdue` step is generated. + long after it was requested, given as `30m`, `12h`, `2d` or `2w`. A + duration under a minute needs `AshWorkflow.Scheduler.Precise`. Without + it, no `:overdue` step is generated. * `--transition-log` - also generates a transition log for the acknowledgement with `mix ash_workflow.gen.transition_log`. Defaults to `true`. @@ -83,34 +84,34 @@ if Code.ensure_loaded?(Igniter.Mix.Task.Info) do options = igniter.args.options subject = ProjectModule.parse(igniter.args.positional.subject) - case Recipe.parse_duration(options[:overdue_after], "--overdue-after") do - {:ok, overdue_after} -> - person = ProjectModule.parse(options[:person]) - acknowledgement = acknowledgement_module(subject, options[:module]) - - config = %{ - subject: subject, - person: person, - acknowledgement: acknowledgement, - can_request: Module.concat([acknowledgement, Checks, CanRequest]), - overdue_after: overdue_after, - transition_log?: options[:transition_log] - } - - # A created subject stores its records the same way the person does. - case Recipe.ensure_subject( - igniter, - subject, - options[:domain], - "acknowledgement", - [person] - ) do - {:ok, igniter, storage} -> generate_with_key_types(igniter, config, storage) - {:error, igniter} -> igniter - end - - {:error, message} -> - Igniter.add_issue(igniter, message) + with {:ok, overdue_after} <- + Recipe.parse_duration(options[:overdue_after], "--overdue-after"), + :ok <- Recipe.validate_interval(overdue_after, "--overdue-after") do + person = ProjectModule.parse(options[:person]) + acknowledgement = acknowledgement_module(subject, options[:module]) + + config = %{ + subject: subject, + person: person, + acknowledgement: acknowledgement, + can_request: Module.concat([acknowledgement, Checks, CanRequest]), + overdue_after: overdue_after, + transition_log?: options[:transition_log] + } + + # A created subject stores its records the same way the person does. + case Recipe.ensure_subject( + igniter, + subject, + options[:domain], + "acknowledgement", + [person] + ) do + {:ok, igniter, storage} -> generate_with_key_types(igniter, config, storage) + {:error, igniter} -> igniter + end + else + {:error, message} -> Igniter.add_issue(igniter, message) end end diff --git a/test/mix/ash_workflow/recipe_interval_test.exs b/test/mix/ash_workflow/recipe_interval_test.exs index 6ab88a61..d856b7de 100644 --- a/test/mix/ash_workflow/recipe_interval_test.exs +++ b/test/mix/ash_workflow/recipe_interval_test.exs @@ -52,4 +52,27 @@ defmodule Mix.AshWorkflow.RecipeIntervalTest do assert approval("30s").issues == [] end + + test "reports an acknowledgement --overdue-after below the default scheduler's floor" do + Application.delete_env(:ash_workflow, :scheduler) + + issues = + [ + "test/support/recipe_fixtures/acknowledgement/domain.ex", + "test/support/recipe_fixtures/acknowledgement/user.ex", + "test/support/recipe_fixtures/acknowledgement/policy.ex" + ] + |> project() + |> Igniter.compose_task("ash_workflow.gen.acknowledgement", [ + "AshWorkflowTest.RecipeFixtures.Acknowledgement.Policy", + "--person", + "AshWorkflowTest.RecipeFixtures.Acknowledgement.User", + "--overdue-after", + "30s" + ]) + |> Map.fetch!(:issues) + + assert [issue] = issues + assert issue =~ "--overdue-after is shorter than AshWorkflow.Scheduler.Oban can honour" + end end diff --git a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs index fa601899..97eb146c 100644 --- a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs +++ b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs @@ -363,21 +363,18 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do end for {flag, duration} <- [ - {"10s", {10, :seconds}}, {"30m", {30, :minutes}}, {"12h", {12, :hours}}, {"2d", {2, :days}}, {"2w", {14, :days}} ] do - test "parses #{flag} as #{inspect(duration)}" do - recipe = - generate([inspect(Policy), "--person", inspect(User), "--overdue-after", unquote(flag)]) - - assert source!( - recipe, - "lib/ash_workflow_test/recipe_fixtures/acknowledgement/policy_acknowledgement.ex" - ) =~ - "fire_after: #{inspect(unquote(Macro.escape(duration)))}, field: :requested_at" + test "parses #{flag} as #{inspect(duration)}", %{tmp_dir: tmp_dir} do + recipe = acknowledgement_for_policies(tmp_dir, ["--overdue-after", unquote(flag)]) + + assert [%{fire_after: unquote(Macro.escape(duration)), field: :requested_at}] = + recipe.modules[PolicyAcknowledgement] + |> AshWorkflow.Info.steps() + |> Enum.flat_map(& &1.timeouts) end end From e1bce7e0af1e30eba17b713d8ca807144f459ac1 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Fri, 23 Oct 2026 08:41:02 +0200 Subject: [PATCH 14/15] docs: add the acknowledgement recipe to the changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fba2f3ef..3792e582 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **A Workflows lens for Clarity.** With [Clarity](https://hex.pm/packages/clarity) installed, `AshWorkflow.Clarity.Lensmaker` adds a Workflows lens that lists each workflow resource with its steps. `AshWorkflow.Clarity.Introspector` adds an `AshWorkflow.Clarity.Vertex.Step` for each step. A workflow resource gets Workflow Overview, Workflow Diagram and Workflow Timing tabs, and a step gets Step Overview, Step Diagram and Step Timeline tabs. The timing tabs place each automatic action, retry attempt, timeout, `every` firing and undo window at its offset from entering the step, and say how long a record can stay in each step. Clarity is an optional dependency, so a project without it compiles none of these modules. - `mix ash_workflow.gen.approval` adds an approval workflow to a resource: a sibling approval resource with `pending`, `approved`, `rejected`, `cancelled` and an optional `overdue` step, a decision resource, quorum routing, and policies that stop a requester approving their own request. Who may open a request and who may approve live in generated `Checks.CanRequest` and `Checks.CanApprove` modules, which deny everyone until the application fills them in. See the [approval recipe](documentation/recipes/approval.md). - `mix ash_workflow.gen.expiry` adds an expiry workflow to a resource: a sibling expiry resource with `active`, `expired` and an optional `expiring` step, whose deadlines read `expires_at` and move when the expiry is renewed. The subject gains `has_one :expiry` and an `expired?` calculation. Who may create an expiry and who may renew one live in generated `Checks.CanCreate` and `Checks.CanRenew` modules, which deny everyone until the application fills them in. See the [expiry recipe](documentation/recipes/expiry.md). +- `mix ash_workflow.gen.acknowledgement` adds an acknowledgement workflow to a resource: a sibling acknowledgement resource with `pending`, `acknowledged` and an optional `overdue` step, holding one request per person per subject, which only that person may acknowledge. Who may open a request lives in a generated `Checks.CanRequest` module, which denies everyone until the application fills it in. See the [acknowledgement recipe](documentation/recipes/acknowledgement.md). - `mix ash_workflow.gen.transition_log` accepts a workflow resource generated earlier in the same Igniter run, before it has compiled, by reading its source. A resource on disk that fails to compile is still reported as an issue. ### Fixed From 75a8742fad9acc0d296f68c1f7e9d4098ede6a60 Mon Sep 17 00:00:00 2001 From: Conor Sinclair Date: Tue, 3 Nov 2026 14:56:01 +0100 Subject: [PATCH 15/15] Include the fixtures each acknowledgement test's domain references --- .../tasks/ash_workflow.gen_acknowledgement_test.exs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs index 97eb146c..4078a1f1 100644 --- a/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs +++ b/test/mix/tasks/ash_workflow.gen_acknowledgement_test.exs @@ -11,6 +11,12 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do @fixtures "test/support/recipe_fixtures/acknowledgement" @files ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex", "#{@fixtures}/policy.ex"] + # The Postgres subject is acknowledged by `Reviewer`, an ETS fixture whose + # domain also lists `Ticket` and `Auditor`, so they all come along. + @postgres_files Enum.map( + ~w(postgres_domain postgres_ticket domain ticket reviewer auditor), + &"test/support/recipe_fixtures/transition_log/#{&1}.ex" + ) @checks "lib/ash_workflow_test/recipe_fixtures/acknowledgement/policy_acknowledgement/checks" @deny_all "def match?(_actor, _context, _opts), do: false" @@ -166,7 +172,7 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do tmp_dir: tmp_dir } do recipe = - ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex"] + ["#{@fixtures}/domain.ex", "#{@fixtures}/user.ex", "#{@fixtures}/policy.ex"] |> generate([inspect(Terms), "--person", inspect(User), "--domain", inspect(Domain)]) |> allow_requesters( "lib/ash_workflow_test/recipe_fixtures/acknowledgement/terms_acknowledgement/checks" @@ -396,10 +402,7 @@ defmodule Mix.Tasks.AshWorkflow.Gen.AcknowledgementTest do test "generates a Postgres-backed resource on the subject's repo", %{tmp_dir: tmp_dir} do recipe = - [ - "test/support/recipe_fixtures/transition_log/postgres_domain.ex", - "test/support/recipe_fixtures/transition_log/postgres_ticket.ex" - ] + @postgres_files |> generate([ "AshWorkflowTest.RecipeFixtures.TransitionLog.PostgresTicket", "--person",