Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't clear ActiveRecord connections when run_synchronously is enabled #393

Merged

Conversation

tomgi
Copy link
Contributor

@tomgi tomgi commented May 18, 2023

Clearing active connection in run_synchronously mode can lead to unexpected behaviour, especially when executed within a database transaction.

Aa a result a connection with active transaction can be released back to the pool and picked up by another thread.

Have a look at the following simplified code snippet that illustrates the issue:

Que::Job.run_synchronously = true

ActiveRecord::Base.transaction do
  ActiveRecord::Base.connection_pool.active_connection? # true
  ActiveRecord::Base.connection.transaction_open? # true
  # ^ we have an active connection and are currently within a DB transaction

  SomeQueJob.enqueue(...)
  # ^ the job runs synchronously and calls ::ActiveRecord::Base.clear_active_connections!

  ActiveRecord::Base.connection_pool.active_connection? # nil
  # ^ our connection with open transaction got returned back to the pool
  
  # someone (possibly another thread) picks up a connection back from the pool
  ActiveRecord::Base.connection

  ActiveRecord::Base.connection_pool.active_connection? # true
  ActiveRecord::Base.connection.transaction_open? # true
  # ^ it's the same connection with the previously opened transaction
end

Copy link
Member

@ZimbiX ZimbiX left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! Thanks =)

@ZimbiX ZimbiX requested a review from oeoeaio May 18, 2023 12:36
Copy link
Contributor

@oeoeaio oeoeaio left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this seems sensible and I assume that anyone depending on this behaviour will be doing so by accident.

@oeoeaio oeoeaio merged commit 218149a into que-rb:master Oct 16, 2023
17 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.

None yet

3 participants