Repository navigation
Refactor ConnectionPool management - #37296
Conversation
c8d72d1 to
be611c5
Compare
be611c5 to
420a602
Compare
It'd be very unusual for the "main fork" in a master/worker process setup... but less surprising for a specialized "mini fork" block that's just intended to do some work in the background.
It's not about saving the memory, but rather about guaranteeing that we don't run the usual finalizer for the connection, because it may do a protocol-level close (e.g. involving writing a close message of some sort), which breaks the parent process's connection (both because it's now been closed, and more generally because they weren't expecting a second process to be writing to their socket). A secondary point, which is still not really memory-focused, is that we do want to do the OS-level close of the fd, so we don't hold it open when the parent thinks they've closed it. (Do any of those make sense? I'll give this another read-through tomorrow when I'm more awake, but it otherwise looks good. I especially like that it eliminates the whole |
|
@matthewd thanks, that's much more clear now. I'll try to bring that logic back tomorrow then. |
069143c to
bb1f709
Compare
bb1f709 to
5f7b49f
Compare
| Concurrent::Map.new(initial_capacity: 2) do |h, k| | ||
| # Discard the parent's connection pools immediately; we have no need | ||
| # of them | ||
| discard_unowned_pools(h) |
There was a problem hiding this comment.
@matthewd I'm having difficulties to bring this behavior back.
From what I understand, this being the Hash default block, it would be invoked as soon we access the hash with a new Process.pid, and apply to all pools.
With the pid now being recorded inside DatabaseConfig, we can't propagate the discard to other pools.
Not sure to go about this, right now what I'm thinking:
- Keep all instances in a weakref array like
DescendantTrackerdoes. - When we detect an unowned pool, we re-check them all.
I'm really torn on this, in one way it seems cleaner than the old method, but on another it seems a bit excessive.
There was a problem hiding this comment.
Of course, one second after I braindump I get a better idea...
What if:
- Like nakayoshi_fork we hook into the fork method
- We offer a simple
on_forkcallback (in ActiveSupport) - Whenever a fork happens, we discard all pools.
There was a problem hiding this comment.
Yeah, I like the on_fork idea -- that seems like a strict improvement over the existing code's "hope you access a database soon after the fork I guess?" strategy.
(That still uses the weakref array of configs, right? Just a much better trigger mechanism.)
Do you think we should retain the pid check as a protection against e.g. an extension calling fork(2) directly, or are you thinking we'd be safe to rely on on_fork exclusively?
There was a problem hiding this comment.
"hope you access a database soon after the fork I guess?"
Definitely.
That still uses the weakref array of configs, right?
Yes. There a couple different ways to go about it. Either each instance register a callback for itself. Or either we register a single callback on the class, and let the class track the instances.
Do you think we should retain the pid check as a protection against e.g. an extension calling
fork(2)directly, or are you thinking we'd be safe to rely on on_fork exclusively?
That's a hard one.
On one hand I want to say extensions shouldn't do that, and that supporting both doesn't allow to reduce complexity.
On the other I'm wondering wether some servers might do this. I know unicorn uses Kernel#fork, and puma as well.
But I'm not super familiar with passenger, and it seems they might be forking outside of ruby.
We could require them to explictly notify the callback in their own after_fork.
I'll start implementing that in another branch, see if I hit any roadblock.
There was a problem hiding this comment.
I went ahead and merged both this PR and the ForkTracker PoC.
Here's the result: master...Shopify:db-config-pool-on-fork-callback
Seems quite clean to me.
There was a problem hiding this comment.
Yeah, that looks great!
Happy for same PR or separate, up to you -- but we'll keep it in a separate commit even if any other changes here get squashed.
(One implementation note is that we need to handle blockless fork calls too)
There was a problem hiding this comment.
I'll PR the fork thing separately, that will be easier for review.
And good point about the block less call.
5f7b49f to
28994be
Compare
5de2bf9 to
6cc1ddb
Compare
|
@matthewd I rebased on top of master, and now rely on the CI should go green. |
6cc1ddb to
54cd690
Compare
There was a problem hiding this comment.
Should we use ForkTracker here and in the other places? If someone add a after_fork { connect_to_redis } we don't want the object finalizer neither the disconnect! to run that, correct?
There was a problem hiding this comment.
That's a good question. Not sure I have a definitive answer, but I'll braindump a few points:
- Ideally your server/job-runner/whatever used
Kernel#forkorProcess#forksoForkTracker.check!is almost a noop. - The only exception to that we have in mind is passenger, we could probably document this, so that people are recommended to all
check!in Passenger's post fork callback. (or even start talking with passenger people to see if c-level forking is a hard requirement) - For now ForkTracker is private API, people are not supposed to register their own callbacks in it.
- Maybe the actual issue here is the finalizer. I'll try to think about that tomorrow, maybe we can do without it.
There was a problem hiding this comment.
Looking at the PR that introduced this finalizer (#31173), from what I understand the intent here is to discard the connections before the process close them on exit.
So, I'm not to sure where to go from here:
- Maybe we can make a requirement of calling
check!if you fork outside of Ruby. - We refactor
ForkTrackerandDatabaseConfigso that we make sure to only trigger the callbacks we care about?
@rafaelfranca @matthewd opinions welcome.
There was a problem hiding this comment.
My two thoughts are:
- I think it's fine for the finalizer to call
check!-- that doesn't do things, it just gives us a chance to do things if a fork has happened and we haven't noticed yet. If someone has managed to do a sneaky fork and this is the first time we notice, it seems acceptable (though a little pointless, because we're probably in the middle of tearing down the process) to make that redis connection. 🤷🏻♂️ - it might be undesirable to do a potentially-arbitrary amount of
after_forkwork inside a finalizer, given an assumption that others will use ForkTracker... I'm trying to remember whether that's a Bad Thing To Do, or actually fine?
There was a problem hiding this comment.
@FooBarWidget can you help us out with some context here, perhaps? ❤️
Given #37312, we're wary that you might be doing OS-level forks... I note the one mentioned above then does an exec, so that's not relevant. But do you know whether you have anywhere you could be doing a direct fork(2) with a Ruby environment loaded without a matching exec? I have hopes that this bit might be a strong sign the answer's "no", but my lazy search turned up too many incidental matches to be sure.
There was a problem hiding this comment.
an instance becomes unreferenced, then a fork occurs, and then GC runs in the forked process before the
after_forkis invoked?
I won't say it's totally impossible, but the window would be terribly small.
The after_fork callback is the very first thing we invoke in the child, so the GC would have to trigger between the fork and the discard_unowned_connections! call.
"quite unlikely, but in the lifetime of all AR-using applications, occasionally inevitable" bucket?
I think I'd be more likely to win the lottery even though I'm not playing, but yes, that's an eventuality. My stance would be that it's not worth trying to protect ourselves from this, but I might be under-considering the likeliness of such event or how bad it would be.
Let's say it's a one in a trillion occurrence, what's the consequence ? The parent connection might be closed by the child GC?
There was a problem hiding this comment.
The narrowness of the window assumes no-one else has installed an after_fork, or indeed done their own fork wrapping..
The consequence may be a segfault: the C drivers tend to Really Not Like It when someone external messes with the state of their internals, even if that someone is a forked copy of themselves. And if not, it's still a broken (not closed, according to the process's local state) connection, which will at best mean an exception in something undeserving of one.
Given that it's just a one-liner to completely close the window, I think I'd prefer to keep the check!. For all but that one in a trillion, it's a single integer comparison; if it does do any work, we're already in "impossibly rare" territory, and better that causes wasteful computation / extra Redis connections than cross-process errors.
There was a problem hiding this comment.
extra Redis connections
Well, I think @rafaelfranca concerns about this was that it might be some stuffs that aren't safe to do in a finalizer.
But OK, I get your arguments, I'll add the checks back in a couple hours.
There was a problem hiding this comment.
some stuffs that aren't safe to do in a finalizer
Yeah.. I think I share that concern, but feel it's the lesser risk (partly just because it would cause a problem in this process, instead of a different one). And this is still only relevant if you hit the fork-then-GC race.
If we do encounter problems, we can probably shift the work from the finalizer into a thread or something, but I'm happy to defer that until we see an issue, because they'll manifest in a way that blames this code, rather than an ambiguous bug in connection handling in general. 👍
54cd690 to
ba26b0d
Compare
33ce837 to
bcc6dc2
Compare
6cc1ddb to
54cd690
Compare
54cd690 to
d13f43e
Compare
|
Thanks for persevering through this -- even on its own, I really like the API and implementation changes here! 💯 |
|
|
||
| @pool.discard! | ||
| @pool = nil | ||
| end |
There was a problem hiding this comment.
Hey I totally missed this before so that's my bad, but I don't think this belongs in DatabaseConfig.
DatabaseConfig should only be responsible for taking the yaml/provided config and turning it into objects that we then pass around in the pool and whatnot. It shouldn't be responsible for knowing anything about the connection_pool or how to discard the pool. I think this is starting to mix concerns a bit too much.
There was a problem hiding this comment.
I believe we need a object that does what this object is doing right now. It is a aggregation of the database configuration state. It does know how to answer that is the connection pool for that connection, what is the schema cache for that connection and how is the connection configured.
It doesn't make sense to me for the connection pool to own the information about the schema cache and the configuration.
I agree we don't need to reuse an existent object to do that.
There was a problem hiding this comment.
@eileencodes Totally agree that there's two mixed concerns here.
These two concerns will most definitely be split again once I introduce the topology classes/objects, but for now this made the calling code much simpler.
There was a problem hiding this comment.
👋 Just to add a bit here, we discovered this while working through a test failure on #37368 and it definitely makes it harder to pass around and re-use these config objects when they have state on them like @pool.
Thank you for your work on this! ✨
We can help move this around too if you'd like or don't think you'll get to it
There was a problem hiding this comment.
Well, not everything is in place yet, but ultimately I want a "role" class such as:
class Role
@db_config
@pool But it should be simpler to introduce after #37388.
This reverts commit 4ea7769, reversing changes made to 2ef9eca. I'm reverting this PR for now at Rafael's recommendation because some of the changes have caused our Rails upgrade at GitHub to be blocked (we use some private API's) as well as other work to use the db_config to establish a connection. See PR and comments here rails#37408 for more detail.
This reverts commit f54a8d0. I am so sorry. I accidentally applied this on top of another PR to do some testing and then when I merged that one this got merged. I'm reverting this because we don't need to revert this now.
`Process.pid` is not cached on Linux and is surprisingly expensive. These checks are in hotspots, the the cost is not negligible. In rails#37296 (comment) we established that it's pretty much impossible to bypass `Process.fork` / `Kernel#fork`. We still added the checks to protect against user defined `after_fork` hooks that would use the connection. But I don't think the cost is worth this extra safety.
The setup used to remove pool entries left over from other pids so connection lookup couldn't restore the removed connection. rails#37296 removed that lookup, and the cleanup became an unconditional discard_pools! even though the test never forks. That discards unrelated live pools whose users still expect to check their connections back in. In the Ractor suite, Contact's sticky lease on its fake-adapter pool is checked back into the discarded pool during fixture teardown, raising NoMethodError. Fixes rails#59173
Followup to #37253
This is one more step toward the topology idea we discussed. The main change here is that
DatabaseConfigis now responsible for managing it's connection pool (andschema_cache).@matthewd I'd love your input on
discard_unowned_pools, looking at the original commit I understand why we discard old connection after forking, but I'm not quite sure to understand the need to be so eager about it:Let me know what you think, and I can try to bring the behavior back if needed.
cc @eileencodes @seejohnrun @etiennebarrie @rafaelfranca @Edouard-chin