Skip to content

Refactor ConnectionPool management - #37296

Merged
matthewd merged 1 commit into
rails:masterfrom
Shopify:db-config-pool
Oct 2, 2019
Merged

matthewd merged 1 commit into
rails:masterfrom
Shopify:db-config-pool

Conversation

@casperisfine

Copy link
Copy Markdown
Contributor

Followup to #37253

This is one more step toward the topology idea we discussed. The main change here is that DatabaseConfig is now responsible for managing it's connection pool (and schema_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:

  • A connection used before the fork but never after seem like quite the edge case
  • Even if it happens, how much memory are we talking about, does it matter that much?

Let me know what you think, and I can try to bring the behavior back if needed.

cc @eileencodes @seejohnrun @etiennebarrie @rafaelfranca @Edouard-chin

@matthewd

Copy link
Copy Markdown
Member

A connection used before the fork but never after seem like quite the edge case

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.

Even if it happens, how much memory are we talking about, does it matter that much?

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 ancestor_pool thing.)

@byroot

byroot commented Sep 25, 2019

Copy link
Copy Markdown
Member

@matthewd thanks, that's much more clear now. I'll try to bring that logic back tomorrow then.

@casperisfine
casperisfine force-pushed the db-config-pool branch 2 times, most recently from 069143c to bb1f709 Compare September 26, 2019 10:56
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@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 DescendantTracker does.
  • 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Of course, one second after I braindump I get a better idea...

What if:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

"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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@matthewd can I have your feedback on this PoC: 82860e1 ?

I did both fork hooking and provide a check! method in case we want to support extensions using fork(2).

Also let me know if you'd like to see it a a PR or included in the current refactor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll PR the fork thing separately, that will be easier for review.

And good point about the block less call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

PR created: #37312

@casperisfine

Copy link
Copy Markdown
Contributor Author

@matthewd I rebased on top of master, and now rely on the after_fork callback.

CI should go green.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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#fork or Process#fork so ForkTracker.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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 ForkTracker and DatabaseConfig so that we make sure to only trigger the callbacks we care about?

@rafaelfranca @matthewd opinions welcome.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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_fork work 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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

an instance becomes unreferenced, then a fork occurs, and then GC runs in the forked process before the after_fork is 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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@matthewd should be good now!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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. 👍

@casperisfine
casperisfine force-pushed the db-config-pool branch 2 times, most recently from 33ce837 to bcc6dc2 Compare October 2, 2019 09:55
@casperisfine
casperisfine force-pushed the db-config-pool branch 2 times, most recently from 6cc1ddb to 54cd690 Compare October 2, 2019 17:05
@matthewd

matthewd commented Oct 2, 2019

Copy link
Copy Markdown
Member

Thanks for persevering through this -- even on its own, I really like the API and implementation changes here! 💯

@matthewd
matthewd merged commit 4ea7769 into rails:master Oct 2, 2019

@pool.discard!
@pool = nil
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

👋 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

eileencodes added a commit to eileencodes/rails that referenced this pull request Oct 11, 2019
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.
eileencodes added a commit that referenced this pull request Oct 14, 2019
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.
casperisfine pushed a commit to Shopify/rails that referenced this pull request Apr 6, 2021
`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.
Kutomore added a commit to Kutomore/rails that referenced this pull request Oct 23, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants