TELunus

TELunus

I seem to be having an issue making some code asynchronous. I’m running

    stream = Task.Supervisor.async_stream_nolink(
      Module.TaskSupervisor,
      enum,
      fn (item) -> my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

which gives me 12:31:22.290 [error] Postgrex.Protocol (#PID<0.678.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.1768.0> exited while client #PID<0.1771.0> is still running with: shutdown

part of the code that’s run by my_func is an ecto call

IO.puts("before")
Repo.get(schema, id)
IO.puts("after")

and I’m seeing the "before" get printed right before the error message, but I’m not seeing the "after"
On the other hand if I change my code to run synchronously as

    stream = Enum.map(enum, fn (item) -> my_func(item, 2) end)
    results = Enum.to_list(stream)

then everything works fine. There’s no error message, and both print statements get run.

Any thoughts on what I could be doing wrong or how I can fix this?

Showing Posts 1 to 10

alco

alco

Are you running this code in tests with Ecto.Adapters.SQL.Sandbox?

TELunus

TELunus OP

I’m running from mix test with

config :project, Project.Repo,
  pool: Ecto.Adapters.SQL.Sandbox,

in my config/test.exs so I take it I am.

alco

alco

You can either use :shared mode with Ecto.Adapters.SQL.Sandbox and disable async tests for your test module or explicitly transfer the Ecto connection to the spawned task process. See Ecto.Adapters.SQL.Sandbox — Ecto SQL v3.14.0 for more details.

TELunus

TELunus OP

It looks like the project is already doing that. The test file starts with

defmodule Project.Module do
    use Project.ModelCase

And in model_case.ex we’ve got

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

    unless tags[:async] do
      Ecto.Adapters.SQL.Sandbox.mode(Project.Repo, {:shared, self()})
    end

    :ok
  end

So since :async isn’t included in the use line I believe that means we’re using shared mode, so any process should be able to connect to the DB connection.

TELunus

TELunus OP

I’m not sure how relevant it is, but while searching for Adapters.SQL.Sandbox in the project I discovered that it shows up in test/test_helpers.ex:

ExUnit.configure formatters: [JUnitFormatter, ExUnit.CLIFormatter]

ExUnit.start(exclude: [
  :skip,
])

Faker.start()

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

Which seems to set the mode without setting :shared

alco

alco

Try spawning your tasks with Task.async_stream. If that works, then I think the problem is that in your original code task processes are started by a supervisor process and that’s why they don’t see the DB connection checked out by the test process. Performing a manual allowance in the task process should work.

TELunus

TELunus OP

Thanks for the suggestions. I just tried with async_stream:

    parent = self()
    stream = Task.Supervisor.async_stream(
      Module.TaskSupervisor,
      enum,
      fn (item) -> my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

then with a manual allow:

    parent = self()
    stream = Task.Supervisor.async_stream_nolink(
      Module.TaskSupervisor,
      enum,
      fn (item) ->
        Ecto.Adapters.SQL.Sandbox.allow(Repo, parent, self())
        my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

as well as with both:

    parent = self()
    stream = Task.Supervisor.async_stream(
      Module.TaskSupervisor,
      enum,
      fn (item) ->
        Ecto.Adapters.SQL.Sandbox.allow(Repo, parent, self())
        my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

all unfortunately to no noticeable effect:
14:12:25.494 [error] Postgrex.Protocol (#PID<0.658.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.1745.0> exited while client #PID<0.1748.0> is still running with: shutdown

As for the dependency update route, that looks like a great idea. Alas we’re still on Elixir 1.6 in this project, and I think it would be a fairly large undertaking to get everything working under 1.8. I think we should probably do it at some point, but I don’t think now is the time.

TELunus

TELunus OP

Oops, it looks like I got your suggestion wrong, and had switched from Task.Supervisor.async_stream_nolink to Task.Supervisor.async_stream instead of Task.async_stream.

I’ve now tried switching to Task.async_stream both with a manual allow:

    parent = self()
    stream = Task.async_stream(
      enum,
      fn (item) ->
        Ecto.Adapters.SQL.Sandbox.allow(Repo, parent, self())
        my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

and without:

    stream = Task.async_stream(
      enum,
      fn (item) ->
        my_func(item, 2) end,
      [ordered: false, max_concurrency: 1]
    )
    results = Enum.to_list(stream)

And again unfortunately all to no noticeable effect: 19:08:14.135 [error] Postgrex.Protocol (#PID<0.658.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.1748.0> exited while client #PID<0.1751.0> is still running with: shutdown

alco

alco

I’ve realized that I misdiagnosed your problem.

When I tried to reproduce the error you’re getting, I realized that I had been thinking of the other error that occurs when a process cannot find a checked out connection. It looks like this:

11:14:40.287 [error] Task #PID<0.244.0> started from #PID<0.241.0> terminating                                                                                              
** (DBConnection.OwnershipError) cannot find ownership process for #PID<0.244.0>.                                                                                           
                                                                                                                                                                            
When using ownership, you must manage connections in one                                                                                                                    
of the four ways:                                                                                                                                                           

[...it goes on for a while...]

However, the error you’re getting must be caused by the test process exiting before another process stopped using the DB connection. I was only able to reproduce this as follows:

  test "Task.Supervisor.async_stream" do
    enum = [1, 2, 3]

    stream =
      Task.Supervisor.async_stream_nolink(
        Module.TaskSupervisor,
        enum,
        fn item -> my_func(item, 2) end,
        ordered: false,
        max_concurrency: 1
      )

    _result = Enum.to_list(stream)

    # We have to sleep here to allow the process spawned by my_func() 
    # to enter a transaction
    on_exit(fn ->
      Process.sleep(100)
    end)
  end

  defp my_func(user_id, _n) do
    Project.Repo.get(Project.User, user_id)

    # I could only get the error to occur when I spawned another process here.
    spawn(fn ->
      # This transaction starts before the test process exits but it sleeps for a while
      # to let the test process terminate. Then, when Project.Repo.get() is called, it'll
      # raise the error
      # Postgrex.Protocol (#PID<0.210.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.241.0> exited
      Project.Repo.transaction(fn ->
        Process.sleep(100)
        Project.Repo.get(Project.User, user_id)
      end)
    end)
  end

The full error I’m getting looks a bit different from yours, but I think it happen in a similar circumstance:

11:19:10.365 [error] Postgrex.Protocol (#PID<0.210.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.241.0> exited                                           
                                                                                                                                                                            
Client #PID<0.247.0> is still using a connection from owner at location:                                                                                                    
                                                                                                                                                                            
    (elixir) lib/process.ex:228: Process.sleep/1                                                                                                                            
    test/sandbox_test.exs:29: anonymous fn/1 in SandboxTest.my_func/2                                                                                                       
    (ecto_sql) lib/ecto/adapters/sql.ex:814: anonymous fn/3 in Ecto.Adapters.SQL.checkout_or_transaction/4                                                                  
    (db_connection) lib/db_connection.ex:1349: DBConnection.run_transaction/4                                                                                               
                                                                                                                                                                            
The connection itself was checked out by #PID<0.247.0> at location: 

In the end, you were right about your tests running with async: false since that the default, so my analysis was wrong in that regard. However, I think there’s something else going on in your test suite outside of the code snippets you’ve shared so far.

Where Next? Top

Trending in Questions Top

water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews