How can I clean test DB when running tests (using Ecto Sandbox) in distributed mode?

I’m trying to run a distributed test case based on Phoenix’s PubSub test cluster, my test_helper.exs file looks something like this:

ExUnit.configure(exclude: [:cluster])

include = Keyword.get(ExUnit.configuration(), :include, [])
if :cluster in include do
  # this line start my cluster, look a Phoenix PubSub's link above
  {:ok, _} = MyApp.TestCluster.start()
  IO.puts("==> Running tests on single node, to run on cluster mode add: --include cluster")


Ecto.Adapters.SQL.Sandbox.mode(Data.Repo, :manual)

Then my cluster_case.ex file looks like this:

defmodule MyApp.ClusterCase do
  use ExUnit.CaseTemplate
  @timeout 5000

  using do
    quote do
      import unquote(__MODULE__)
      import MyApp.Factory # ex_machina factory
      @moduletag :cluster
      @timeout unquote(@timeout)

  setup do
    :ok = Ecto.Adapters.SQL.Sandbox.checkout(MyApp.Repo)

  def nodes do

  def rpc(func) when is_function(func) do
    parent = self()
    ref = make_ref()
    node = nodes()
      |> Enum.random()

    Node.spawn_link(node, fn ->
      Ecto.Adapters.SQL.Sandbox.allow(MyApp.Repo, parent, self())
      result = func.()
      Kernel.send(parent, {ref, result})
      ref = Process.monitor(parent)
      receive do
        {:DOWN, ^ref, :process, _, _} -> :ok

    receive do
      {^ref, result} -> result
      @timeout -> {:error, :timeout}

Everything works fine if I use mix test, all Ecto transactions are reverted and my test DB is clean after tests run.
When I run mix test --include cluster, Ecto transactions are not reverting, causing some tests to fail, If I check the test DB after test suite runs, I can see my tables are not clean. Is there any setting I’m missing? Or is there a way I can manually revert each transaction?


Trying to debug this case, I found that the problem resides on the master node:

When called from any slave node (by rpc or any other method) the Ecto transaction perfectly cleans the DB, however since we are now running “local” tests from our master node primary@, the transaction is not cleaning correctly.

If I inspect Mix.env(), I get :test, everything looks fine here.
If I inspect the Ecto config from any test via Application.get_env(), I can see the desired test configuration (Sandbox pool).
I just don’t get why the transaction is not cleaning the DB only when running from master node.