Skip to content

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.

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.

3 participants