rails: Rails cache prefix is not properly configured for isolated caching during parallel tests.

I’ve been investigating why I am seeing a lot of transient test failures due to cache collisions with parallelized tests. I thought it was because Rails doesn’t update the cache prefix to protect from collisions but after looking at it; it’s looking like Rails tries to do that (by appending Process.pid and Thread.current.object_id to the namespace), but that it isn’t working properly.

For the moment I’ve worked around it by adding namespace delineation myself in the parallelize_setup block of the test helper, but it’d be better if Rails handled this automatically so that no-one has to worry about it.

Steps to reproduce

Replace test/test_helper.rb contents with the following:

module ActiveSupport
  class TestCase
    # Run tests in parallel with specified workers
    parallelize(workers: :number_of_processors)

    # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
    fixtures :all

    parallelize_setup do |worker|
      puts "#{worker.inspect}: #{Rails.cache.options[:namespace]}"
    end

    # Add more helper methods to be used by all tests here...
  end
end

Expected Behavior

The namespaces listed should be unique per worker to isolate the test runners so that they do not collide during parallelization. It should look something like this (assuming that the cache prefix configured is test:20230518:, which is what mine is configured to be).

6: test:20230518:63512:3580:
5: test:20230518:63513:3580:
0: test:20230518:63514:3580:
3: test:20230518:63515:3580:
7: test:20230518:63516:3580:
4: test:20230518:63517:3580:
1: test:20230518:63518:3580:
2: test:20230518:63519:3580:

Actual Behavior

Instead, the namespaces listed all share identical process identifiers and thread identifiers.

6: test:20230518:63512:3580:
5: test:20230518:63512:3580:
0: test:20230518:63512:3580:
3: test:20230518:63512:3580:
7: test:20230518:63512:3580:
4: test:20230518:63512:3580:
1: test:20230518:63512:3580:
2: test:20230518:63512:3580:

System configuration

Rails version:

% fgrep rails Gemfile.lock
      rails-dom-testing (~> 2.0)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.0, >= 1.2.0)
      rails-dom-testing (~> 2.0)
      rails-html-sanitizer (~> 1.1, >= 1.2.0)
    importmap-rails (1.1.6)
    rails (7.0.5)
    rails-dom-testing (2.0.3)
    rails-html-sanitizer (1.6.0)
    sentry-rails (5.9.0)
    sprockets-rails (3.4.2)
    tailwindcss-rails (2.0.29-arm64-darwin)
    tailwindcss-rails (2.0.29-x86_64-darwin)
    tailwindcss-rails (2.0.29-x86_64-linux)
    turbo-rails (1.4.0)
  importmap-rails (~> 1.1)
  rails (~> 7.0.5)
  sentry-rails
  sprockets-rails
  tailwindcss-rails (~> 2.0)
  turbo-rails

Ruby version:

% ruby --version
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [arm64-darwin21]

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 21 (10 by maintainers)

Most upvoted comments

Right, I tracked down the code that was causing the confusion by “attempting” to fix this – it was actually written by me, trying to solve this exact problem, a while ago and then I of course promptly forgot about it. 😬

It was this piece of code in config/environments/test.rb:

# Increase selectivity of cache keys by including process and thread identifiers.
# This protects against cache conflicts while parallelizing tests as well as across runs.
config.cache_store[1][:namespace] += "#{Process.pid}:#{Thread.current.object_id}:"

This approach doesn’t work because it’s too early in the rails boot process to be after the test initialization. So the confusion around “Rails trying to fix this” was completely caused by my initial attempt to fix this, which didn’t work at all. I apologize for the confusion!

I do think that Rails should fix this ultimately, however – it’s a risk for anything that leans on actual cache stores during test runs that are parallelized and it’d be convenient for everyone for it to be handled right from the get-go without needing to have anyone trying to work around this (more than once, even) as I have done.

What I have right now, which as far as I can tell works, is this simple bit of code in spec/test_helper.rb. Within a single test run it protects from collisions by using a worker identifier in the prefix; and then across test runs it protects from collisions with the simple timestamp (so there’s no need to flush the cache, as each subsequent test run will use a new prefix).

    # Protect from collisions during parallelized testing by namespacing our Redis prefix by our worker identifier.
    # Rails doesn't currently protect against this, which means that all test executors are sharing the same cache
    # which can lead to transient test failures due to cache collisions.
    #
    # Once this bug is fixed, this code can probably be dropped: https://github.com/rails/rails/issues/48341
    parallelize_setup do |worker|
      Rails.cache.options[:namespace] = "#{Rails.cache.options[:namespace]}#{Time.now.to_i}.#{worker}:"
      # puts "#{worker}: #{Rails.cache.options[:namespace]}"
    end

So far as I can tell this solves the transient test failures I was seeing from caching conflicts. If there is still a conflict here it’d be caused by multiple test runs within the same second/multiple independent concurrent cache runs. Process.pid would solve that locally, but honestly at that point I think it’d be simpler to just go to a “more unique” prefix like a UUID rather than trying to chain a whole bunch of “somewhat unique” prefixes together (Time.now.to_i + Process.pid + worker).

@byroot I definitely misunderstood then, that’s what I took away from the thread.

I can align with the philosophy of each test being completely independent with regards to cache state, though like the rest of the folks in this thread I don’t know how to get there. There’s no obvious path to achieve that ideal state without deep dependence on things that as you say are beyond Rails’ immediate control (such as enforcing the use of redis and purposefully creating and administering the redis service to permit one database per test runner and then using flushdb in-between tests).

That’s something Rails can’t do for you, so I fear implicit namespacing, while it may work for some people, is absolutely not robust enough to be the default and might lead users to experience weird test failures that would be even harder to debug that what you experienced.

I’d agree, I don’t see any way to get there at the moment particularly since it’s my understanding that Rails needs to support more than just Redis as a caching store, as well.

Where I don’t align with you anymore is at “not robust enough to be the default”, though.

The code as shipped right now is: no help whatsoever for any sort of caching isolation during tests.

What I’m suggesting is: limited help for caching isolation that solves the naive case.

… and then later on it could be replaced if a better solution to approach a more ideal state is found.

As to the coupling of the code, that’s fair enough and 🤔 on that – I wasn’t familiar enough with the Rails codebase to even think about where this code should go so I was assuming that others would know exactly where to insert the line of code to make this happen.

If that’s not the case then that’s harder and I do agree that adding tight coupling might not be ideal here.

What about if this just got generated into test/test_helper.rb so that it was there to help people who hit caching conflicts?

# Protect from collisions during parallelized testing by namespacing our caching prefix by our worker identifier.
# Without this protection, all test executors share the same cache, which can lead to transient failures due to cache collisions.
# This protection is partial -- even with it, cache state still travels across tests executing in the same worker, which the author must be cautious of.
parallelize_setup do |worker|
  Rails.cache.options[:namespace] += "#{Time.now.to_i}.#{worker}:"
end

For myself, with that present in my test_helper, transients have stopped entirely – but, I am always conscious of cache-state when crafting tests… so if a test has a dependency on specific cache state then I curate the test to make sure that it creates that state as necessary to be sure that lingering data in the cache doesn’t cause problems.

I do understand that a solution here that also explicitly protects against cache state leaking across tests in the same worker would be better, but… perfect is the enemy of good here, I think. If there’s an idea for how to actually achieve the perfect solution then cool; but in absence of it this is a change that helps improve the current state.

The assertion seems to be that running clear for the cache at the start of each test is a “better way” of achieving isolation.

Absolutely not, I think there is a big misunderstanding here.

What Dima and I mean, is isolation between two subsequent tests, that’s an isolation you want even without parallelization.

The idea that each test should start with an empty cache, just like how each test should start with an empty database (or reset to a specific state). And Rails should probably do that by default for you to propagate this best practice.

At no point we suggested that calling cache.clear before or after each test would solve the parallel test isolation issue.

Now, why I fear a very imperfect fix is worse that no fix, is that for most cache store the only way to have proper isolation is to have one instance of that store (I mean one memcached server, etc) per parallel test worker. That’s something Rails can’t do for you, so I fear implicit namespacing, while it may work for some people, is absolutely not robust enough to be the default and might lead users to experience weird test failures that would be even harder to debug that what you experienced.

Additionally, test parallelization and cache store are entirely decoupled, so it’s really unclear how we could do what you suggest without making a mess in the codebase.

However I want to re-iterate that I absolutely agree with you that the current situation is totally undesirable, and that we should look at improving this, I’m not closing this issue, I’m not saying there is no problem.

We could indeed automatically namespace, but like Dima said, that’s would be a fairly leaky abstraction, as if you can’t fully clear the cache between each tests, you are leaking state which is a recipe for flaky tests. So I’d prefer to find a better solution.

For Redis, a better solution is to use distinct database per test worker, but by default that limits you to 16 workers (which generally should be plenty), but for Memcached, I don’t think we can.

All this to say, we agree this is imperfect and it would be good to improve the situation, but what you propose isn’t necessarily without flaws.

I’d have to some research in old parallel tests related PRs as well as the documentation what the reasoning was back in the day, and if some solutions were explored before.

why wouldn’t Rails implement this to help the developers using it out?

Because sometimes a solution with big flaws is much worse than no solution. And I fear that’s the case here. But again, this isn’t to say that nothing should be done.