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
- Disconnect if `configure_connection` failed Fix: https://github.com/rails/rails/issues/51780 There are a number of scenarios in which one of the queries performed as part of `configure_connection` f... — committed to byroot/rails by byroot 2 years ago
- Disconnect if `configure_connection` failed Fix: https://github.com/rails/rails/issues/51780 There are a number of scenarios in which one of the queries performed as part of `configure_connection` f... — committed to byroot/rails by byroot 2 years ago
- Disconnect if `configure_connection` failed Fix: https://github.com/rails/rails/issues/51780 There are a number of scenarios in which one of the queries performed as part of `configure_connection` f... — committed to byroot/rails by byroot 2 years ago
- Switch to `7-2-stable` branch of Rails (#10720) ## Summary of the problem We are running into a Rails issue in production (https://github.com/rails/rails/issues/51780, https://appsignal.com/hack-clu... — committed to hackclub/hcb by davidcornu a year ago
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:
@type_mapinPostgreSQLAdapter) toconfigure_connection.configure_connectionis called byverify!,reconnect!andreset!. At this point in git history, callingcheckouton theConnectionPoolwould also callverify!on the adapter before returning it, ensuring thatconfigure_connectionwas called and@type_mapwas initialized before any query was attempted on the adapter.ConnectionPool#checkout_and_verifyto checkout and clean (making the name become misleading, as it does not verify the connection anymore). So running any queries on a connection obtained withpool.checkoutorpool.with_connection { |conn| }(which callscheckout_and_verifyunder 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
PostgreSQLAdapterinstance that may not have been verified yet. I also think the wholeNullLockvsLoadInterlockAwareMonitorwas 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):
At the very least, I would argue that a connection obtained with
pool.checkoutorpool.with_connectionis 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 callverify!immediately after check out as a preventive measure until the issue is permanently resolved. I believe that is the case forrage-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.timeoutbeing 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
TypeErrorissue (wrong argument type nil (expected PG::TypeMap)) by implementing areconnect!mechanism, as shown below:This solution resolves the issue by re-establishing the connection and properly configuring it. Once
reconnect!is executed, theTypeErrorno longer recurs for the same connection instance.2.
configure_connectionNot Being CalledWe 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:
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:
This one does work fine on
7-0-stabe, but raises withTypeError: wrong argument type nil (expected PG::TypeMap)on7-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
Asyncor Fibers in sightAlright, thanks to @matthewd’s suggestions, I found a repro that makes sense, involving
Timeout.timeout: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.0but last night we randomly had ~1500 occurrences of this error again (thanks Sentry)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.2it’s been partially broken, especially for production workFor 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.
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 throughconfigure_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.
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
If your app uses
Timeout.timeoutyou can try8-0-stableas 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_mapwould be empty instead ofnilso 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.
@byroot we have updated our project to
7-2-stablebut the issue seems to persist still. Let me know if I can help somehow, stacktrace or anythingSo, this one is interesting, and it’s probably something similar happening, the problem however is that it emulate a failure in
PG#server_versionwhich 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_connectionand 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
AbstractAdapterimplementations 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)NoMethodErrorwhich we were seeing, I managed to replicate theTypeErrorthat @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)
@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’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:
The error we got on production was:
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:
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
We’re experiencing the same issue running
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.
ApplicationRecord.connection.instance_variable_get(:@lock)is anActiveSupport::Concurrency::LoadInterlockAwareMonitoron 7.0 but is aActiveSupport::Concurrency::NullLockon 7.1ActiveSupport::Concurrency::NullLockis not thread-safeWe run into this issue periodically after upgrading to
rails (7.1.3.4), and running onpg (1.5.6), and ruby3.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:
And this one we’ve seen more often: