Skip to content

Draft: Cache organization owner checks in RequestStore

What does this MR do and why?

Cache organization owner checks in RequestStore

  • Organization owner checks in BasePolicy#owns_organization? were not being cached in RequestStore, leading to repeated database queries when the same check was performed multiple times in a single request.

  • While Organizations::Organization#owner_user_ids is memoized at the instance level, policy checks can happen multiple times per request with different policy instances, causing the query to run repeatedly.

  • This change wraps the ownership check in Gitlab::SafeRequestStore to cache the result per user/organization pair for the duration of the request.

Changelog: performance

References

n/a

Screenshots or screen recordings

n/a

How to set up and validate locally

  • Run spec: bundle exec rspec spec/policies/base_policy_spec.rb or...
  • In rails console
    org = Organizations::Organization.first || FactoryBot.create(:organization) 
    user = FactoryBot.create(:user) 
    org.add_owner(user)
    
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    RequestStore.begin!
    policy = BasePolicy.new(user, nil)
    
    # You should see only ONE query for owner_user_ids despite multiple calls. Look for a query like: 
    # SELECT "organization_users"."user_id" FROM "organization_users" WHERE "organization_users"."organization_id" = XX AND "organization_users"."access_level" = 50 
    
    5.times { policy.send(:owns_organization?, org) }

MR acceptance checklist

Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by SAM FIGUEROA

Merge request reports

Loading