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