CodeSampleX

Sample

ecto 3.12.5: Construct transactional pipelines with Ecto.Multi: handle Ecto 3's two-arity run callback requirement, contrast with one-arity dynamic operation builders, and inspect pipeline stages

Verified sample for hex ecto 3.12.5: Construct transactional pipelines with Ecto.Multi: handle Ecto 3's two-arity run callback requirement, contrast with…

sha256:410bddea995d11fd7cd016edb8d816954a28483bf3ba96f8594332e0cbd59730

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment elixir linux x64 elixir elixir mix

Verification-run environments

Environment Contract Stages Run
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-16
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

Case

HOW
Goal
Construct transactional pipelines with Ecto.Multi: handle Ecto 3's two-arity run callback requirement, contrast with one-arity dynamic operation builders, and inspect pipeline stages
Packages
Symbols
  • Ecto.Multi.new
  • Ecto.Multi.run
  • Ecto.Multi.insert
  • Ecto.Multi.merge
  • Ecto.Multi.to_list
  • Ecto.Multi.prepend
  • Ecto.Multi.append
Environment
elixir
Created
2026-08-16T14:59:28Z

Contract

  1. assert Ecto.Multi.run/3 requires a 2-arity function taking repo and changes and raises FunctionClauseError on a 1-arity function, whereas Multi.insert/3 and Multi.merge/2 accept 1-arity functions receiving only changes
  2. assert Multi.run/5 with MFA stores the module, function, and arguments tuple, and dispatches with repo and changes prepended as the first two arguments
  3. assert Multi operations enforce strictly unique step names across the pipeline, raising RuntimeError on single step collisions
  4. assert Multi.to_list/1 returns operations in chronological pipeline order, whereas internal struct operations store them reversed
  5. assert Multi.prepend/2 and Multi.append/2 combine distinct transaction pipelines, preserving execution order and rejecting shared names with ArgumentError

Files

  • .formatter.exs
  • .gitignore
  • NOTES.md
  • csx.json
  • lib/csx_ecto_multi/transaction_pipeline.ex
  • mix.exs
  • mix.lock
  • test/contract_test.exs
  • test/test_helper.exs

Download the source artifact (tar.gz)

Source

.formatter.exs
# Used by "mix format"
[
  inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
.gitignore
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where third-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
csx_ecto_multi-*.tar

# Temporary files, for example, from tests.
/tmp/
NOTES.md
# Ecto 3 Multi Semantics and Callback Arity

## Known Solutions Search

A search via `search_known_solution` returned existing samples covering `Ecto.Changeset` standalone map validation (`sha256:ec1c423e61b01693526ccce5e694e6c68ed968878f00b8331b3d82c953abea87`), parameterized types (`sha256:c069af3c66e9ae5208f2cc544fe78a61db6c37868e4e9a224c66ca6592ead421`), and enum mapping (`sha256:2765ae1d56912ffca2012a1325fccaa3cc315c7ad0a7855021f517369078ef2e`). None covered transactional pipeline construction with `Ecto.Multi`.

## Failure Mode Across Major Versions

In Ecto 2, `Ecto.Multi.run/3` accepted a 1-arity callback `fn changes -> ... end` and MFA dispatch prepended only `changes`.

In Ecto 3, `Ecto.Multi.run/3` strictly requires a 2-arity function `fn repo, changes -> ... end` and MFA dispatch prepends `[repo, changes | args]`. Code written with Ecto 2 expectations fails loudly:
- Passing a 1-arity function to `Ecto.Multi.run/3` crashes at pipeline construction with `FunctionClauseError: no function clause matching in Ecto.Multi.run/3`.
- Passing an MFA tuple expecting `(changes, ...)` crashes during execution with `BadArityError` / `FunctionClauseError` due to the extra `repo` argument.
- Dynamic changeset builders (`Multi.insert/4`, `Multi.update/4`, `Multi.delete/4`) and `Multi.merge/2` retain 1-arity callbacks `(changes)`, making the `Multi.run/3` 2-arity requirement an asymmetrical trap within the same module.
- Attempting to add a duplicate step name fails loudly with `RuntimeError` (`:name is already a member of the Ecto.Multi`), whereas merging multi structs with `Multi.append/2` or `Multi.prepend/2` fails with `ArgumentError`.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Ecto.Multi.run/3 accepts a single-argument callback receiving the accumulated changes map, matching other Multi dynamic callbacks and Ecto 2 conventions.","caseId":"case:sha256:7ab8a11ef0e876ae87db510701447e96cc1427435f71a520f933e22a217eba91","contract":["assert Ecto.Multi.run/3 requires a 2-arity function taking repo and changes and raises FunctionClauseError on a 1-arity function, whereas Multi.insert/3 and Multi.merge/2 accept 1-arity functions receiving only changes","assert Multi.run/5 with MFA stores the module, function, and arguments tuple, and dispatches with repo and changes prepended as the first two arguments","assert Multi operations enforce strictly unique step names across the pipeline, raising RuntimeError on single step collisions","assert Multi.to_list/1 returns operations in chronological pipeline order, whereas internal struct operations store them reversed","assert Multi.prepend/2 and Multi.append/2 combine distinct transaction pipelines, preserving execution order and rejecting shared names with ArgumentError"],"goal":"Construct transactional pipelines with Ecto.Multi: handle Ecto 3's two-arity run callback requirement, contrast with one-arity dynamic operation builders, and inspect pipeline stages","kind":"HOW","packages":["pkg:hex/ecto@3.12.5"],"schemaVersion":1,"symbols":["Ecto.Multi.new","Ecto.Multi.run","Ecto.Multi.insert","Ecto.Multi.merge","Ecto.Multi.to_list","Ecto.Multi.prepend","Ecto.Multi.append"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/ecto@3.12.5"],"schemaVersion":1,"symbols":["Ecto.Multi.new","Ecto.Multi.run","Ecto.Multi.insert","Ecto.Multi.merge","Ecto.Multi.to_list","Ecto.Multi.prepend","Ecto.Multi.append"],"verifierAdapter":"hex@1"}
lib/csx_ecto_multi/transaction_pipeline.ex
defmodule CsxEctoMulti.Account do
  @moduledoc """
  Embedded account schema used for multi-operation demonstration.
  """
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: false}
  embedded_schema do
    field :name, :string
    field :balance, :integer, default: 0
    field :status, :string, default: "active"
  end

  def changeset(account \\ %__MODULE__{}, params) do
    account
    |> cast(params, [:id, :name, :balance, :status])
    |> validate_required([:name])
    |> validate_number(:balance, greater_than_or_equal_to: 0)
  end
end

defmodule CsxEctoMulti.Transfer do
  @moduledoc """
  Embedded transfer record representing a funds transfer between accounts.
  """
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: false}
  embedded_schema do
    field :from_id, :binary_id
    field :to_id, :binary_id
    field :amount, :integer
    field :memo, :string
  end

  def changeset(transfer \\ %__MODULE__{}, params) do
    transfer
    |> cast(params, [:id, :from_id, :to_id, :amount, :memo])
    |> validate_required([:from_id, :to_id, :amount])
    |> validate_number(:amount, greater_than: 0)
  end
end

defmodule CsxEctoMulti.TransactionPipeline do
  @moduledoc """
  Demonstrates transactional workflows with Ecto.Multi in Ecto 3.

  Key Ecto 3 Multi semantics:
  - `Multi.run/3` requires a 2-arity function `(repo, changes)` rather than
    the 1-arity `(changes)` function of Ecto 2.
  - `Multi.run/5` with MFA prepends `repo` and `changes` as the first two arguments:
    `apply(mod, fun, [repo, changes | args])`.
  - In contrast, dynamic operation callbacks like `Multi.insert/4`, `Multi.update/4`,
    and `Multi.delete/4` accept 1-arity functions `(changes)`.
  - `Multi.merge/2` accepts a 1-arity function `(changes)` returning a new Multi.
  - Operation names must be unique across the Multi; adding a duplicate name raises `RuntimeError`.
  """

  alias CsxEctoMulti.Account
  alias CsxEctoMulti.Transfer

  @doc """
  Builds a transfer Multi pipeline combining static changesets, dynamic 1-arity
  changeset builders, and 2-arity run callbacks.
  """
  def build_transfer_multi(%Account{} = from_account, %Account{} = to_account, amount, reference_code) do
    transfer_params = %{
      id: "transfer-#{reference_code}",
      from_id: from_account.id,
      to_id: to_account.id,
      amount: amount,
      memo: "Transfer #{reference_code}"
    }

    Ecto.Multi.new()
    |> Ecto.Multi.insert(:transfer, Transfer.changeset(%Transfer{}, transfer_params))
    |> Ecto.Multi.run(:verify_funds, fn _repo, %{transfer: tx} ->
      if from_account.balance >= tx.changes.amount do
        {:ok, %{available: from_account.balance, deducted: tx.changes.amount}}
      else
        {:error, :insufficient_funds}
      end
    end)
    |> Ecto.Multi.run(:audit_step, __MODULE__, :record_audit_event, [reference_code])
  end

  @doc """
  Audit step called via Multi.run/5 (MFA).
  In Ecto 3, Multi.run prepends `repo` and `changes` to the arguments list,
  requiring an arity of length(args) + 2.
  """
  def record_audit_event(_repo, %{transfer: tx, verify_funds: funds}, reference_code) do
    {:ok,
     %{
       code: reference_code,
       amount: tx.changes.amount,
       remaining: funds.available - funds.deducted,
       timestamp: "2026-08-16T00:00:00Z"
     }}
  end
end
mix.exs
defmodule CsxEctoMulti.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_ecto_multi,
      version: "0.1.0",
      elixir: "~> 1.17",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp deps do
    [
      {:ecto, "3.12.5"}
    ]
  end
end
mix.lock
%{
  "decimal": {:hex, :decimal, "2.4.1", "6c0fbede12fb122ba685e9ab41c6a40c129e322b3aa192f9e072e61f3a6ffaf2", [:mix], [], "hexpm", "7e618897933a8455f19a727d7c5e50a2c071a544b700e5e724298ecb4340187f"},
  "ecto": {:hex, :ecto, "3.12.5", "4a312960ce612e17337e7cefcf9be45b95a3be6b36b6f94dfb3d8c361d631866", [:mix], [{:decimal, "~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "6eb18e80bef8bb57e17f5a7f068a1719fbda384d40fc37acb8eb8aeca493b6ea"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract_test.exs
defmodule CsxEctoMulti.ContractTest do
  use ExUnit.Case

  alias CsxEctoMulti.Account
  alias CsxEctoMulti.TransactionPipeline

  test "Ecto.Multi.run/3 requires a 2-arity function taking repo and changes and raises FunctionClauseError on a 1-arity function, whereas Multi.insert/3 and Multi.merge/2 accept 1-arity functions receiving only changes" do
    multi = Ecto.Multi.new()

    # In Ecto 2, Multi.run accepted a 1-arity callback: fn changes -> ... end.
    # In Ecto 3, Multi.run/3 strictly requires a 2-arity function: fn repo, changes -> ... end.
    # Passing a 1-arity or 3-arity function raises FunctionClauseError immediately at Multi construction time.
    assert_raise FunctionClauseError, fn ->
      Ecto.Multi.run(multi, :step_one, fn _changes ->
        {:ok, :result}
      end)
    end

    assert_raise FunctionClauseError, fn ->
      Ecto.Multi.run(multi, :step_one, fn _repo, _changes, _extra ->
        {:ok, :result}
      end)
    end

    # Passing a valid 2-arity function succeeds and registers the :run operation.
    two_arity_fn = fn _repo, _changes -> {:ok, "success"} end
    valid_multi = Ecto.Multi.run(multi, :step_one, two_arity_fn)
    assert [{:step_one, {:run, ^two_arity_fn}}] = Ecto.Multi.to_list(valid_multi)

    # In contrast, dynamic operation callbacks (insert, update, delete) accept a 1-arity function
    # taking only (changes) to produce the changeset or struct.
    dynamic_insert_fn = fn %{step_one: _prior} ->
      Account.changeset(%Account{}, %{name: "Alice", balance: 100})
    end

    multi_with_insert = Ecto.Multi.insert(valid_multi, :new_account, dynamic_insert_fn)
    assert [{:step_one, {:run, _}}, {:new_account, {:run, _wrapped}}] =
             Ecto.Multi.to_list(multi_with_insert)

    # Passing a 2-arity function to Multi.insert/3 raises FunctionClauseError because insert expects 1-arity.
    assert_raise FunctionClauseError, fn ->
      Ecto.Multi.insert(valid_multi, :bad_insert, fn _repo, _changes ->
        Account.changeset(%Account{}, %{name: "Alice"})
      end)
    end

    # Multi.merge/2 also expects a 1-arity function (changes -> multi).
    dynamic_merge_fn = fn %{new_account: _acc} ->
      Ecto.Multi.new() |> Ecto.Multi.run(:sub_step, fn _repo, _changes -> {:ok, :sub} end)
    end

    multi_with_merge = Ecto.Multi.merge(multi_with_insert, dynamic_merge_fn)
    assert [{:step_one, _}, {:new_account, _}, {:merge, {:merge, ^dynamic_merge_fn}}] =
             Ecto.Multi.to_list(multi_with_merge)

    # Passing a 2-arity function to Multi.merge/2 raises FunctionClauseError.
    assert_raise FunctionClauseError, fn ->
      Ecto.Multi.merge(multi_with_insert, fn _repo, _changes ->
        Ecto.Multi.new()
      end)
    end
  end

  test "Multi.run/5 with MFA stores the module, function, and arguments tuple, and dispatches with repo and changes prepended as the first two arguments" do
    multi =
      Ecto.Multi.new()
      |> Ecto.Multi.run(:audit, TransactionPipeline, :record_audit_event, ["REF-999"])

    # Ecto.Multi stores MFA specifications inside the {:run, {mod, fun, args}} tuple.
    assert [{:audit, {:run, {TransactionPipeline, :record_audit_event, ["REF-999"]}}}] =
             Ecto.Multi.to_list(multi)

    # When executed by an Ecto.Repo transaction, the dispatch evaluates:
    # apply(mod, fun, [repo, changes | args])
    # The handler must have arity equal to length(args) + 2.
    fake_repo = FakeRepo
    changes_so_far = %{
      transfer: %{changes: %{amount: 250}},
      verify_funds: %{available: 1000, deducted: 250}
    }

    {:run, {mod, fun, extra_args}} = hd(Ecto.Multi.to_list(multi)) |> elem(1)
    result = apply(mod, fun, [fake_repo, changes_so_far | extra_args])

    assert {:ok, %{code: "REF-999", amount: 250, remaining: 750, timestamp: _}} = result
  end

  test "Multi operations enforce strictly unique step names across the pipeline, raising RuntimeError on single step collisions" do
    base =
      Ecto.Multi.new()
      |> Ecto.Multi.run(:validate_user, fn _repo, _changes -> {:ok, true} end)

    # Attempting to register another operation with an existing name raises RuntimeError (not ArgumentError).
    assert_raise RuntimeError, ~r/:validate_user is already a member of the Ecto\.Multi/, fn ->
      Ecto.Multi.run(base, :validate_user, fn _repo, _changes -> {:ok, false} end)
    end

    assert_raise RuntimeError, ~r/:validate_user is already a member of the Ecto\.Multi/, fn ->
      Ecto.Multi.insert(base, :validate_user, %Account{name: "Dup"})
    end

    assert_raise RuntimeError, ~r/:validate_user is already a member of the Ecto\.Multi/, fn ->
      Ecto.Multi.delete(base, :validate_user, %Account{name: "Dup"})
    end
  end

  test "Multi.to_list/1 returns operations in chronological pipeline order, whereas internal struct operations store them reversed" do
    sender = %Account{id: "acc-1", name: "Sender", balance: 500, status: "active"}
    receiver = %Account{id: "acc-2", name: "Receiver", balance: 100, status: "active"}

    pipeline = TransactionPipeline.build_transfer_multi(sender, receiver, 150, "TX-001")

    # Multi struct tracks names in a MapSet.
    assert MapSet.equal?(pipeline.names, MapSet.new([:transfer, :verify_funds, :audit_step]))

    # Multi.to_list/1 returns the ordered pairs of {name, operation_descriptor} in insertion order.
    operations = Ecto.Multi.to_list(pipeline)
    assert length(operations) == 3
    assert Keyword.keys(operations) == [:transfer, :verify_funds, :audit_step]

    # The internal struct field .operations stores elements in reverse prepend order.
    assert Keyword.keys(pipeline.operations) == [:audit_step, :verify_funds, :transfer]

    assert [
             {:transfer, {:insert, %Ecto.Changeset{}, []}},
             {:verify_funds, {:run, _fun}},
             {:audit_step, {:run, {TransactionPipeline, :record_audit_event, ["TX-001"]}}}
           ] = operations
  end

  test "Multi.prepend/2 and Multi.append/2 combine distinct transaction pipelines, preserving execution order and rejecting shared names with ArgumentError" do
    multi_a =
      Ecto.Multi.new()
      |> Ecto.Multi.run(:step_a, fn _repo, _changes -> {:ok, :a} end)
      |> Ecto.Multi.run(:step_b, fn _repo, _changes -> {:ok, :b} end)

    multi_b =
      Ecto.Multi.new()
      |> Ecto.Multi.run(:step_c, fn _repo, _changes -> {:ok, :c} end)
      |> Ecto.Multi.run(:step_d, fn _repo, _changes -> {:ok, :d} end)

    appended = Ecto.Multi.append(multi_a, multi_b)
    assert Keyword.keys(Ecto.Multi.to_list(appended)) == [:step_a, :step_b, :step_c, :step_d]

    prepended = Ecto.Multi.prepend(multi_a, multi_b)
    assert Keyword.keys(Ecto.Multi.to_list(prepended)) == [:step_c, :step_d, :step_a, :step_b]

    # Combining two Multi structs with conflicting step names raises ArgumentError.
    colliding_multi =
      Ecto.Multi.new()
      |> Ecto.Multi.run(:step_b, fn _repo, _changes -> {:ok, :collision} end)

    assert_raise ArgumentError, ~r/both declared operations: \[:step_b\]/, fn ->
      Ecto.Multi.append(multi_a, colliding_multi)
    end
  end
end
test/test_helper.exs
ExUnit.start()

Origin Seeder

csx-seed