Fix potential scope leakage in ThroughAssociationPatch #167
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #166
Problem
This PR fixes bug where scopes from one
has_many :throughassociation leak into queries for other through associations when the owner model has adefault_scopewith an ORDER BY clause. This bug was introduced in version 4.2.1 with theThroughAssociationPatchand affects all versions through the current (5.4.0).The
ThroughAssociationPatchmodule enables auto-including through associations after the through association has been loaded. However, when the owner model has adefault_scope, Rails' association preloader incorrectly reuses scoped queries across different through associations, causing scope leakage. This is arguably a Rails bug in the association preloader, but we need to work around it in Goldiloader by detecting when this pattern exists and disabling the optimization in those cases.Fix
This PR adds a
has_scope_leakage_risk?check to theThroughAssociationPatchthat:default_scopewith ORDER BYfalsefromauto_include?when that case exists, preventing scope leakageThe fix uses instance-level caching for performance, ensuring the detection logic only runs once per association.
And again, this may be more of a "workaround" then a fix, as the function of this PR is to disable the optimzation added in 4.2.1 when this buggy case exists.
Changes
has_scope_leakage_risk?detection method toThroughAssociationPatchresolve_check_class,class_has_order_default_scope?,has_other_scoped_through_associations?@order_scope_cache,@scoped_through_cache)Testing
Tests cases show that Goldiloader:
Conclusion
The fix does add some complexity but should be performant and backwards compatible.The fix ensures these apps with these cases get correct query results while maintaining Goldiloader's performance benefits where safe to do so.