rails: Possible race condition in postgresql type_map initialization

Steps to reproduce

Since upgrading from Rails 7.0 to 7.1 we’ve started to see the following exception:

# activerecord (7.1.3.2) lib/active_record/connection_adapters/postgresql_adapter.rb in get_oid_type
undefined method `key?' for nil:NilClass (NoMethodError)
          if !type_map.key?(oid)
                      ^^^^^

I haven’t been able to replicate the behavior outside of production where it occurs when the application briefly loses its connection to the postgres database while under load. This is a multi-threaded environment. The server never recovers after entering this state.

I know there was a change to type_map initialization at https://github.com/rails/rails/commit/dc4420c564565affadcd0d68db1af7ce2183bea4, and it looks to me like it’s possible there’s a race condition here. I’ll update this issue with steps to replicate if I can manage to trigger this outside of production.

Expected behavior

The application should recover from a brief database outage and reconnect.

Actual behavior

The server is never able to reconnect.

System configuration

Rails version: 7.1.3.2

Ruby version: 3.2.4

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 47
  • Comments: 90 (41 by maintainers)

Commits related to this issue

Most upvoted comments

I backported the fix all the way to 7-1-stable. Not sure when a release will happen, but if you point your apps to the corresponding stable branch, this should fix the problem. Confirmation that the problem is gone is welcome.

Sorry again for not noticing this issue sooner, the timing was really unfortunate 😕

I believe I have found the issue. I’ll run a few more tests locally and try to create a reproduction environment. If all goes well, I’ll submit PRs (I might need to write multiple PRs as the adapter internals changed a lot from 7.0 to 8.0)

Ack.

I didn’t notice this issue before I suspect you had the bad luck of opening it during a major conference, sorry.

But something is definitely wrong here. I’m making a note to look at it tomorrow.

Even if I can’t repro the bug, I think we got more than enough converging reports that merging a tentative fix would be sensible.

Investigation update

I have been able to identify two points that appear to have introduced this bug:

  • This commit refactored all configuration of adapters (which includes the the initialization of @type_map in PostgreSQLAdapter) to configure_connection. configure_connection is called by verify!, reconnect! and reset!. At this point in git history, calling checkout on the ConnectionPool would also call verify! on the adapter before returning it, ensuring that configure_connection was called and @type_map was initialized before any query was attempted on the adapter.
  • This commit modified ConnectionPool#checkout_and_verify to checkout and clean (making the name become misleading, as it does not verify the connection anymore). So running any queries on a connection obtained with pool.checkout or pool.with_connection { |conn| } (which calls checkout_and_verify under the hood) is no longer guaranteed to return a verified connection.

I haven’t yet, however, been able to reproduce the scenario where an unverified connection checked out from the pool raises this error. I believe (not sure though) the verification is being done accidentally as a side effect somewhere else, which is why this is so hard to reproduce in a non-production environment. What I have noticed, however, is that this error does not appear to be triggered by a query from the ActiveRecord models, but somewhere while loading the schema cache for the connection (this other fix has partially addressed the problem).

I have read a lot of ActiveRecord source code to be able to understand it better and hopefully fix the issue, but so far, I haven’t been able to pinpoint the exact issue. Perhaps @matthewd and @byroot could chime in here now that I have been able to provide a little more context.

That leads me to believe the race condition happens when trying to load the schema cache with a PostgreSQLAdapter instance that may not have been verified yet. I also think the whole NullLock vs LoadInterlockAwareMonitor was a red herring.

In the meantime, I believe this monkey patch inspired by @byroot’s commit will work for all cases (I’ve tested it in Rails 7.1 and 7.2, but I suspect it will also work for Rails 8.0 since the adapter hasn’t changed much from 7.2 to 8.0):

module PostgreSQLAdapterExtensions
  extend ActiveSupport::Concern

  included do
    private

    def type_map
      return @type_map unless @type_map.nil?

      verify!

      @type_map
    end
  end
end

ActiveSupport.on_load(:active_record_postgresqladapter) do |klass|
  klass.include(PostgreSQLAdapterExtensions) unless klass.included_modules.include?(PostgreSQLAdapterExtensions)
end

At the very least, I would argue that a connection obtained with pool.checkout or pool.with_connection is no longer safe to run queries against. If you have any gem that relies on checking out connections from the pool, it may be a good idea to call verify! immediately after check out as a preventive measure until the issue is permanently resolved. I believe that is the case for rage-rb.

I would also recommend checking your Gemfile dependencies for any gem that handles connections from the pool directly and please let us know in the comments what you find. In my case, I was seeing this error with the gem I maintain (active_record_proxy_adapters). We haven’t seen this on production without the gem installed.

I merged and backported a fix to make Active Record more resilient to Timeout.timeout being used.

Please upgrade and let me know if that solves the problem.

Hello!

We’d like to share some insights regarding the issue:

1. Fixing the TypeError

We resolved the TypeError issue (wrong argument type nil (expected PG::TypeMap)) by implementing a reconnect! mechanism, as shown below:

module DatabaseStatementsPatch
  def query(*)
    super
  rescue TypeError => e
    if e.message != 'wrong argument type nil (expected PG::TypeMap)' || @type_map_for_results
      raise e
    end

    reconnect!(restore_transactions: true)
    retry
  end
end

ActiveRecord::ConnectionAdapters::PostgreSQL::DatabaseStatements.prepend(DatabaseStatementsPatch)

This solution resolves the issue by re-establishing the connection and properly configuring it. Once reconnect! is executed, the TypeError no longer recurs for the same connection instance.

2. configure_connection Not Being Called

We suspect that configure_connection isn’t being invoked when the error occurs. In our Rails 7.1 setup, we observed verify! being called multiple times, but configure_connection wasn’t triggered.

Here’s the state of the internal variables at the time of the error:

active? # => true
@raw_connection.class # => PG::Connection
!!@verified # => false

3. Testing for Concurrency Issues

We also experimented with forcing @lock to use an instance of ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new, suspecting a concurrency issue. However, this change didn’t resolve the error. 😄

Alright, I got a repro which I think is more realistic. It’s fairly similar in concept though:

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  # gem "rails", "7.1.5.1" # only raises MyError and maybe ActiveRecord::ConnectionTimeoutError ✅
  # gem "rails", "7.2.2.1" # also see TypeError on PG::Result#type_map= ❌
  # gem "rails", "8.0.1" # also see TypeError on PG::Result#type_map= ❌

  gem "rails", path: "/Users/byroot/src/github.com/byroot/rails"

  gem "pg"
end

require "active_record/railtie"
require "minitest/autorun"

ENV["DATABASE_URL"] = "postgresql:test?pool=20" # need local pg db named test

class TestApp < Rails::Application
  config.load_defaults Rails::VERSION::STRING.to_f
  config.eager_load = true
  config.logger = Logger.new($stdout)
  config.secret_key_base = "secret_key_base"

  config.active_record.encryption.primary_key = "primary_key"
  config.active_record.encryption.deterministic_key = "deterministic_key"
  config.active_record.encryption.key_derivation_salt = "key_derivation_salt"
end
Rails.application.initialize!

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end
end

class Post < ActiveRecord::Base
end

$rand_fail = true

PG::Connection.prepend(Module.new{
  def async_exec(sql, ...)
    if $rand_fail && rand(10) == 1
      raise PG::Error, "Whoops"
    else
      super
    end
  end
})

class BugTest < ActiveSupport::TestCase
  def test_association_stuff
    10.times.map do
      Thread.new do
        begin
          Post.last
        rescue ActiveRecord::StatementInvalid
          retry
        end
      end
    end.each(&:join)
    $rand_fail = false

    10.times.map do
      Thread.new do
        Post.last
      end
    end.each(&:join)
  end
end

This one does work fine on 7-0-stabe, but raises with TypeError: wrong argument type nil (expected PG::TypeMap) on 7-1-stable, which gives me some level of confidence that it’s a good enough repro to iterate on the bug.

@skipkayhil we’re seeing this with vanilla Puma, no Async or Fibers in sight

Alright, thanks to @matthewd’s suggestions, I found a repro that makes sense, involving Timeout.timeout:

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  # gem "rails", "7.1.5.1" # only raises MyError and maybe ActiveRecord::ConnectionTimeoutError ✅
  # gem "rails", "7.2.2.1" # also see TypeError on PG::Result#type_map= ❌
  # gem "rails", "8.0.1" # also see TypeError on PG::Result#type_map= ❌

  gem "rails", path: "/Users/byroot/src/github.com/byroot/rails"

  gem "pg"
end

require "active_record/railtie"
require "minitest/autorun"

ENV["DATABASE_URL"] = "postgresql:test?pool=20" # need local pg db named test

class TestApp < Rails::Application
  config.load_defaults Rails::VERSION::STRING.to_f
  config.eager_load = true
  config.logger = Logger.new($stdout)
  config.secret_key_base = "secret_key_base"

  config.active_record.encryption.primary_key = "primary_key"
  config.active_record.encryption.deterministic_key = "deterministic_key"
  config.active_record.encryption.key_derivation_salt = "key_derivation_salt"
end
Rails.application.initialize!

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end

  create_table :comments, force: true do |t|
    t.references :post
  end
end

class Post < ActiveRecord::Base
  has_many :comments
end

$timeout = false
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.prepend(Module.new {
  def reload_type_map
    if $timeout
      sleep 5
    end
    super
  end
})

class BugTest < ActiveSupport::TestCase
  def test_association_stuff
    Post.create!
    post = Post.last

    ActiveRecord.disconnect_all!

    $timeout = true
    assert_raises Timeout::Error do
      Timeout.timeout(1) do
        Post.all.to_a
      end
    end
    $timeout = false

    Post.all.to_a
  end
end

I got a quick fix: https://github.com/byroot/rails/commit/6b2dafea265602af9c64b88ef3f64d5df94384aa that makes the repro pass.

I’ll clean it up, and try to port that repro into a proper unit test.

We thought for a moment that the monkey patch worked on rails 8.0.0 but last night we randomly had ~1500 occurrences of this error again (thanks Sentry)

TypeError
wrong argument type nil (expected PG::TypeMap) (TypeError)

		self.type_map = type_map

It would be nice if someone from the Rails team could give us an update on this, because Postgres is a popular database for Rails and it seems like ever since 7.2 it’s been partially broken, especially for production work

For us any monkey patches sadly didn’t fix the issue. We’ve also been seeing a lot of wrong argument type nil (expected PG::TypeMap), which seems to be somewhat in the same vein? We’re reverting back to Rails 7.0 now, since it doesn’t seem to have this issue.

I’m seeing a lots of potentially related changes in https://github.com/rails/rails/pull/44570, https://github.com/rails/rails/pull/44591 and other closely associated PRs. @matthewd is there any chance those changes could be related to this at all? 🙏🏼

Happy to provide any more info if needed!

I’m sorry but I’m afraid I did all I could do without experiencing the issue myself. I can’t see how a connection could end up corrupted in such a way by just reviewing the code.

For anyone still experiencing such issue, I’m afraid you will have to put some extra logs and such in production to figure out where it is coming from. If someone comes up with a repro, or at least a good description of what the trigger is, I’ll do my best to address it, but I can’t investigate this any further on my own.

Alright, I think the proper patch is https://github.com/rails/rails/pull/54710, I’ll try to get some feedback from @matthewd, but if it’s OK I’ll just apply it to all branches from 7.1 upwards.

Maybe it’s a coincidence but we’ve been running a rails app with servers under load for a long time without seeing this issue. Today we installed rack-timeout and a few hours later this error occured.

NoMethodError
undefined method `key?' for nil (NoMethodError)

          if !type_map.key?(oid)
        # active_record/connection_adapters/postgresql_adapter.rb in get_oid_type at line 829
        def get_oid_type(oid, fmod, column_name, sql_type = "")
          if !type_map.key?(oid)
            load_additional_types([oid])
          end

Ruby: ruby 3.3.5 (2024-09-03 revision ef084cc8f4) +YJIT activerecord: 7.2.2.1 activerecord-postgis-adapter: 9.0.2

If there’s a concurrency [or other similarly subtle multi-interaction-based] issue here (and given the number of reports, it sure sounds like there is), someone needs to stare at the code and identify where it can occur, or profile in production and identify where it does occur.

I don’t have a production repro, and so far none of my staring sessions have revealed the source of the problem.

I believe the only discussion so far in this issue has been various forms of papering-over patches that attempt to make the misbehaviour less likely, without any full understanding of what sequence causes things to go wrong.

From all my read-throughs, if we’re running arbitrary queries on a connection that doesn’t have a type_map, that implies it hasn’t been through configure_connection. That’s obviously not supposed to happen, but also suggests we have no idea what else might be wrong with the connection when it’s in that state. That seems bad.

Based purely on intuition / recollection of related changes, I could maybe imagine potential for trouble to have arisen in the period after #46519 and before #48716 – but they were both first introduced in 7.1.0.

A full backtrace from 8.0 would be helpful, just because a number of internals have (benignly) moved around recently… but I assume it’s not going to tell us any more than the older ones have – which is where we are when the problem is noticed, but that’s not where we were (or some other thread is) when the connection got into the bad state in the first place.

last night we randomly had ~1500 occurrences of this error

Did other errors occur (possibly in much smaller number) immediately before these? Did the event coincide with a database connectivity issue? Did it stop failing by itself or require intervention? How does the 1500 occurrences relate to your number of workers / DB connections? Did one worker suddenly get Very Unhappy, or did many all enter this state at the same time?

@byroot @jhawthorn We ran into this issue on 7.1.5.1. I noticed that 7.1.5.1 doesn’t have the patches yet that attempted to address this issue. Would you be able to release a new 7.1 release with the changes?

@shayonj your script uses Rails 8.0.1, if I upgrade to 8.0.2 your script passes.

We do not use rack-timeout and still encountered the issue

We’re also seeing the same problem. Ruby 3.2.4 and Rails 7.1.3.2

FWIW, I’m sharing a full stack trace of this issue still happening on Rails 8.0.2:

If your app uses Timeout.timeout you can try 8-0-stable as there was a small followup for that case.

Otherwise see: https://github.com/rails/rails/issues/51780#issuecomment-2733371688

@skipkayhil unfortunately it isn’t that simple, because previously, the same bug could have happened (unconfigured connection) but @type_map would be empty instead of nil so many query would still work.

So I have a pretty big suspicion that this bug has been possible for a very long time, it was just harder to notice.

Confirmation that the problem is gone is welcome.

@byroot we have updated our project to 7-2-stable but the issue seems to persist still. Let me know if I can help somehow, stacktrace or anything

Repro (may have to run a few times to observe failures)

So, this one is interesting, and it’s probably something similar happening, the problem however is that it emulate a failure in PG#server_version which shouldn’t be possible, as it doesn’t do any network call, the version is already stored in memory after connecting.

But based on the report I’ve read (I haven’t read them all sorry), it does indeed sounds like a connection that fail at some point during configure_connection and is then left in an unrecoverable state.

I’ll keep reviewing the code, see if I can come up with a more realistic repro, but overall I think this warrant a more generic, resiliency oriented fix.

The root cause of the issue IMO is that contrary to other adapters, Postgres require to fetch a lot of server infos to be usable, so the generic AbstractAdapter implementations think the connection is usable, but it’s not.

I think we need to introduce an extra interface to ask the concrete adapter: “are you ready to perform queries, or should we redo the configuration dance?”. Which is a bit of a shame because this is totally overkill for other databases.

We ran into this as well (with 7.2.2.1) and while I couldn’t replicate the if !type_map.key?(oid) NoMethodError which we were seeing, I managed to replicate the TypeError that @jwoodrow shared in their stacktrace here. Seems to only show up on 7.2.x and 8.0.x. Sharing in case it helps.

Repro (may have to run a few times to observe failures)
# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  # gem "rails", "7.1.5.1" # only raises MyError and maybe ActiveRecord::ConnectionTimeoutError ✅
  # gem "rails", "7.2.2.1" # also see TypeError on PG::Result#type_map= ❌
  gem "rails", "8.0.1" # also see TypeError on PG::Result#type_map= ❌

  gem "pg"
end

require "active_record/railtie"
require "minitest/autorun"

ENV["DATABASE_URL"] = "postgresql:test" # need local pg db named test

class TestApp < Rails::Application
  config.load_defaults Rails::VERSION::STRING.to_f
  config.eager_load = true
  config.logger = Logger.new($stdout)
  config.secret_key_base = "secret_key_base"

  config.active_record.encryption.primary_key = "primary_key"
  config.active_record.encryption.deterministic_key = "deterministic_key"
  config.active_record.encryption.key_derivation_salt = "key_derivation_salt"
end
Rails.application.initialize!

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end
end

class Post < ActiveRecord::Base
end

ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do
  class MyError < StandardError; end

  # Patch to control raising an error during configure_connection, which we also
  # observed in conjunction with the one reported in this issue due to a db failover.
  # This is raised cause AR caches the version in the config but libpq returns 0 on
  # a failed connection.
  #
  # Refs:
  # - https://github.com/postgres/postgres/blob/cf07a47dc0c3b16778291e62d730537b45da51ef/src/interfaces/libpq/fe-connect.c#L6789-L6797
  # - https://github.com/rails/rails/blob/aa2bfad1a137c9add1b35de118b391494e13ca06/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L665-L669
  def check_version
    raise MyError if $raise_in_check_version
  end
end

class BugTest < ActiveSupport::TestCase
  def test_association_stuff
    30.times.map do
      Thread.new do
        sleep rand(0.01..0.1)
        # not synchronized, but should be fine, we just want to randomize
        $raise_in_check_version = !!(rand(100) > 50)
        Post.last
      end
    end.each(&:join)
  end
end

@byroot May I also bring https://github.com/rails/rails/issues/54502 to your attention. It’s somewhat related (AR type map lookup) but specific to 7.2.

We see Flipper in our stack trace, and we’re investigating whether it could be interfering with the Active Record adapter. As a next step, we’ll test removing Flipper integration to see if it mitigates the issue.

We’re not using flipper.

We just got it again on 7.2.2 even with the monkey patch (perhaps our monkey patch wasn’t correct 😅 ). Here’s the monkey patch:

if defined?(ActiveRecord)
  unless Rails.version == "7.2.2"
    raise "Please update the monkeypatch for ActiveRecord::ConnectionAdapters::ConnectionPool#new_connection"
  end

  module ActiveRecord
    module ConnectionAdapters
      class ConnectionPool
        def new_connection
          db_config.new_connection
          # connection.pool = self

        rescue ConnectionNotEstablished => e
          raise e.set_pool(self)
        end
      end
    end
  end
end

The error we got on production was:

NoMethodError: undefined method `key?' for nil (NoMethodError)

          if !type_map.key?(oid)
                      ^^^^^
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:829:in `get_oid_type'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:72:in `block (2 levels) in internal_exec_query'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:69:in `each'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:69:in `each_with_index'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:69:in `block in internal_exec_query'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:877:in `execute_and_clear'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:66:in `internal_exec_query'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:647:in `select'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:73:in `select_all'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:248:in `block in select_all'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:286:in `block (2 levels) in cache_sql'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:80:in `compute_if_absent'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:284:in `block in cache_sql'
  from activesupport (7.2.2) lib/active_support/concurrency/null_lock.rb:9:in `synchronize'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:283:in `cache_sql'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:248:in `select_all'
  from activerecord (7.2.2) lib/active_record/querying.rb:70:in `_query_by_sql'
  from activerecord (7.2.2) lib/active_record/relation.rb:1431:in `block (2 levels) in exec_main_query'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:421:in `with_connection'
  from activerecord (7.2.2) lib/active_record/connection_handling.rb:296:in `with_connection'
  from activerecord (7.2.2) lib/active_record/relation.rb:1430:in `block in exec_main_query'
  from activerecord (7.2.2) lib/active_record/relation.rb:1452:in `skip_query_cache_if_necessary'
  from activerecord (7.2.2) lib/active_record/relation.rb:1414:in `exec_main_query'
  from activerecord (7.2.2) lib/active_record/relation.rb:1392:in `block in exec_queries'
  from activerecord (7.2.2) lib/active_record/relation.rb:1452:in `skip_query_cache_if_necessary'
  from activerecord (7.2.2) lib/active_record/relation.rb:1386:in `exec_queries'
  from activerecord (7.2.2) lib/active_record/relation.rb:1167:in `load'
  from activerecord (7.2.2) lib/active_record/relation.rb:336:in `records'
  from activerecord (7.2.2) lib/active_record/relation/finder_methods.rb:586:in `find_take'
  from activerecord (7.2.2) lib/active_record/relation/finder_methods.rb:129:in `take'
  from activerecord (7.2.2) lib/active_record/relation/finder_methods.rb:112:in `find_by'
  from activerecord (7.2.2) lib/active_record/relation.rb:296:in `find_or_initialize_by'
  from activerecord (7.2.2) lib/active_record/querying.rb:24:in `find_or_initialize_by'
  ...

Now, checking a little bit deeper, it seems to me that there’s a difference in how type maps are handled for different adapters. For example trilogy and sqlite have pretty much same approach where they initialize the type maps during loading of the code:

Sqlite Trilogy

Where the type_map is set to nil initially for each PG connection:

https://github.com/rails/rails/blob/8-0-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L336

And only later on it’s being initialized during setting up the connection as the last step:

https://github.com/rails/rails/blob/4df235f7c0149ac7be86580d41a74a7785cb9bb9/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L991

So what I suspect happens is that “somewhere” along the way, there is issue while configuring connection. It may not be reconfigured again and thus type map may never get initialized.

EDIT:

Here’s the error that we got after above errors started happening:

PG::SystemError: FATAL:  could not get connection from the pool - AllServersDown (PG::SystemError)
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:1003:in `set_client_encoding'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:1003:in `configure_connection'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:670:in `block (2 levels) in reconnect!'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:393:in `reset_transaction'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:668:in `block in reconnect!'
  from activesupport (7.2.2) lib/active_support/concurrency/null_lock.rb:9:in `synchronize'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:661:in `reconnect!'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:763:in `block in verify!'
  from activesupport (7.2.2) lib/active_support/concurrency/null_lock.rb:9:in `synchronize'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:754:in `verify!'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:995:in `block in with_raw_connection'
  from activesupport (7.2.2) lib/active_support/concurrency/null_lock.rb:9:in `synchronize'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:976:in `with_raw_connection'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:893:in `block in exec_no_cache'
  from activesupport (7.2.2) lib/active_support/notifications/instrumenter.rb:58:in `instrument'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract_adapter.rb:1119:in `log'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:892:in `exec_no_cache'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql_adapter.rb:872:in `execute_and_clear'
  from activerecord (7.2.2) lib/active_record/connection_adapters/postgresql/database_statements.rb:66:in `internal_exec_query'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:647:in `select'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/database_statements.rb:73:in `select_all'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:248:in `block in select_all'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:286:in `block (2 levels) in cache_sql'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:80:in `compute_if_absent'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:284:in `block in cache_sql'
  from activesupport (7.2.2) lib/active_support/concurrency/null_lock.rb:9:in `synchronize'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:283:in `cache_sql'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/query_cache.rb:248:in `select_all'
  from activerecord (7.2.2) lib/active_record/querying.rb:70:in `_query_by_sql'
  from activerecord (7.2.2) lib/active_record/querying.rb:53:in `block in find_by_sql'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:415:in `with_connection'
  from activerecord (7.2.2) lib/active_record/connection_handling.rb:296:in `with_connection'
  from activerecord (7.2.2) lib/active_record/querying.rb:52:in `find_by_sql'
  from activerecord (7.2.2) lib/active_record/statement_cache.rb:150:in `execute'
  from activerecord (7.2.2) lib/active_record/core.rb:447:in `block in cached_find_by'
  from activerecord (7.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:421:in `with_connection'
  from activerecord (7.2.2) lib/active_record/connection_handling.rb:296:in `with_connection'
  from activerecord (7.2.2) lib/active_record/core.rb:434:in `cached_find_by'
  from activerecord (7.2.2) lib/active_record/core.rb:315:in `find_by'

So what I assume happened is that we couldn’t get PG connection since database server had issues at the time and ended up with weird state of connection after that. We use PGCat as well so that could be the reason as well.

I’ve worked around this problem by monkey-patching the PostgreSQL adapter with the following

def get_oid_type(...)
  reload_type_map if type_map.nil?

  super
end

We’re experiencing the same issue running

  • rails 7.1.3.4
  • pg 1.5.5
  • unicorn 6.1.0

For us the error does not seem to be related to memory usage on the postgres server but instead seems to happen whenever the web-servers come under heavy load.

  1. I’m having this same issue, only in production, and it’s preventing us from upgrading to 7.1
  2. I don’t think this is related to the database being under load
  3. I have the impression the thread-safety logic changed somewhere: I’m seeing that ApplicationRecord.connection.instance_variable_get(:@lock) is an ActiveSupport::Concurrency::LoadInterlockAwareMonitor on 7.0 but is a ActiveSupport::Concurrency::NullLock on 7.1
  4. As its name suggests, ActiveSupport::Concurrency::NullLock is not thread-safe

We run into this issue periodically after upgrading to rails (7.1.3.4), and running on pg (1.5.6), and ruby 3.3.2.

It happens during deployment of new pods, and sometimes will resolve it self after some time (Possibly only when the pod is restarted. I haven’t been able to confirm).

We have had a couple of variants of this error happen (only in production). First one matches the one from the ticket description:

NoMethodError: undefined method `key?' for nil
get_oid_type(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql_adapter.rb:829)
block (2 levels) in internal_exec_query(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:70)
each(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:67)
each_with_index(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:67)
block in internal_exec_query(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:67)
execute_and_clear(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql_adapter.rb:877)
internal_exec_query(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/postgresql/database_statements.rb:64)
select(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/database_statements.rb:630)
select_all(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/database_statements.rb:71)
block in select_all(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/query_cache.rb:112)
block in cache_sql(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/query_cache.rb:152)
synchronize(/usr/local/bundle/gems/activesupport-7.1.3.4/lib/active_support/concurrency/null_lock.rb:9)
cache_sql(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/query_cache.rb:147)
select_all(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/connection_adapters/abstract/query_cache.rb:112)
_query_by_sql(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/querying.rb:62)
find_by_sql(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/querying.rb:51)
execute(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/statement_cache.rb:150)
cached_find_by(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/core.rb:431)
find_by(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/core.rb:300)
find_by!(/usr/local/bundle/gems/activerecord-7.1.3.4/lib/active_record/core.rb:304)
...

And this one we’ve seen more often:

ActiveRecord::StatementInvalid: wrong argument type nil (expected PG::TypeMap)
rescue in cached_find_by(/usr/local/bundle/gems/activerecord-7.1.3.3/lib/active_record/core.rb:433)
cached_find_by(/usr/local/bundle/gems/activerecord-7.1.3.3/lib/active_record/core.rb:430)
find_by(/usr/local/bundle/gems/activerecord-7.1.3.3/lib/active_record/core.rb:300)
find_by!(/usr/local/bundle/gems/activerecord-7.1.3.3/lib/active_record/core.rb:304)