rails: ActiveSupport::Cache.expand_cache_key sometimes returns falsely same key in parallel tests

Steps to reproduce

Thats the hard part here! I still didnt figure out how to reproduce it safely. What i can tell is that this does not happen when i execute a single testcase. It also doesnt happen when i set parallel workers to 1.

When parallel workers is set to processors and all tests are executed via rails test, the following test is breaking repeatedly:

      it "returns updated records omitting cache and returning new etag" do
        get "/apis/v1/me/tickets"
        assert_valid_json_response

        assert_changes ->{ last_response.headers["etag"] } do
          travel 1.second
          tickets(:multi).touch

          get "/apis/v1/me/tickets"
          assert_valid_json_response
        end
      end

The etag header is calculated basically via this line of code which i also found out to return the same wrong key. The updated_at on the record tickets(:multi) changes, but the underlying query fetching the max(tickets.updated_at) seem to return an older timestamp? At least the timestamp in the key remains the same.

ActiveSupport::Cache.expand_cache_key current_user.tickets.visible

The visible scope:

scope :visible, -> { joins(:admittances).where(tickets: {hidden: false}).merge(Admittance.visible).group("tickets.id")}

Expected behavior

The etag header should change in the same way whether i execute a single test or all together without flakiness.

Actual behavior

The etag header remains equal which is wrong. But this happens only when executing all tests parallelized which is kinda flaky.

Notes

I found out that changing the scope implementation from group to distinct fixes it:

scope :visible, -> { joins(:admittances).where(tickets: {hidden: false}).merge(Admittance.visible).select("distinct on (#{table_name}.id) #{table_name}.*")}

System configuration

Rails version: 7.1.2

Ruby version: 3.2.2

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 17 (8 by maintainers)

Most upvoted comments

Oh good catch! I was only able to reproduce by hitting the cache, but what was missing from my repro was a third “unused” ticket.

Now I have a repro! I’ll take a look later tonight.

# frozen_string_literal: true

require "bundler/inline"

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

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails"
  # If you want to test against edge Rails replace the previous line with this:
  # gem "rails", github: "rails/rails", branch: "main"

  gem "sqlite3"
  gem "debug"
end

require "active_record"
require "minitest/autorun"
require "logger"
require "active_support/testing/assertions"
require "active_support/testing/time_helpers"


# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

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

  create_table :tickets, force: true do |t|
    t.integer :user_id
    t.string :name
    t.timestamps
  end

end

class User < ActiveRecord::Base
  has_many :tickets
end

class Ticket < ActiveRecord::Base
  belongs_to :user
  has_many :admittances
end

class BugTest < Minitest::Test
  include ActiveSupport::Testing::Assertions
  include ActiveSupport::Testing::TimeHelpers

  def test_association_stuff
    user = User.create!
    other_ticket = Ticket.create!(user:, name: :other)
    single = Ticket.create!(user:, name: :single)
    multi = Ticket.create!(user:, name: :multi)

    assert_changes -> { pp ActiveSupport::Cache.expand_cache_key(user.tickets.group("tickets.id")) } do
      travel 1.second
      single.tap do |ticket|
        assert_changes -> { ticket.reload.updated_at } do
          ticket.touch
        end
      end
    end
  end
end