Skip to content

Fix race condition in Tesla.Mock.agent_set#768

Merged
yordis merged 1 commit intoelixir-tesla:masterfrom
tomekowal:tkowal/fix-race-condition-in-tesla-mock-agent_set
Apr 28, 2025
Merged

Fix race condition in Tesla.Mock.agent_set#768
yordis merged 1 commit intoelixir-tesla:masterfrom
tomekowal:tkowal/fix-race-condition-in-tesla-mock-agent_set

Conversation

@tomekowal
Copy link
Contributor

@tomekowal tomekowal commented Apr 28, 2025

Hi!
I've run into an issue while running tests:

     ** (RuntimeError) failed to start child with the spec %{id: Tesla.Mock, start: {Agent, :start_link, [#Function<1.5545190/0 in Tesla.Mock.agent_set/1>, [name: Tesla.Mock]]}}.
     Reason: bad child specification, got: {:already_started, #PID<0.8504.0>}
     code: {:ok, activity} = create_successful_payment(%{"barcode" => tok.barcode}, acq, @payment_method)
     stacktrace:
       (ex_unit 1.18.2) lib/ex_unit/callbacks.ex:590: ExUnit.Callbacks.start_supervised!/2
       (tesla 1.14.0) lib/tesla/mock.ex:152: Tesla.Mock.mock_global/1

Quick debugging session showed that it is a race condition in the agent_set function.

It performed:

case Process.whereis(__MODULE__) do
      nil ->
        # here another process already started the mock agent
        # so the next line failed
        ExUnit.Callbacks.start_supervised!(...)

My fix removes the check and tries to start the agent immediately.

  • it uses start_supervised (without !) to not crash on error
  • handles the {error, {:already_started, pid}} case
  • in other cases it throws an error to preserve existing behaviour.

I checked if similar pattern is used elsewhere, but the only other usage of Process.whereis is in agent_get which is invoked later and doesn't start anything.

@tomekowal tomekowal force-pushed the tkowal/fix-race-condition-in-tesla-mock-agent_set branch from 4ec0138 to 9cf14dd Compare April 28, 2025 10:09
@yordis yordis merged commit 8cf7745 into elixir-tesla:master Apr 28, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants