Skip to content

perf: reduce per-assignment Casbin calls in visible assignments fast path#278

Draft
mariajgrimaldi wants to merge 12 commits into
mainfrom
MJG/perf-visible-assignments
Draft

perf: reduce per-assignment Casbin calls in visible assignments fast path#278
mariajgrimaldi wants to merge 12 commits into
mainfrom
MJG/perf-visible-assignments

Conversation

@mariajgrimaldi
Copy link
Copy Markdown
Member

@mariajgrimaldi mariajgrimaldi commented May 7, 2026

Description

Cut latency in get_visible_role_assignments_for_user and get_visible_user_role_assignments_filtered_by_current_user for the admin console assignments view, as described in ADR 0014.

Three independent changes:

Pre-filter before authorization: A new _filter_assignments_by_params function applies org, scope, and role filters on the flat assignment list before any authorization check. Previously, the full list was authorized first and filtered afterward on the grouped result. Assignments dropped by the filters are never evaluated for visibility.

Scope-based visibility check to avoid calling enforcer() N times: _filter_allowed_assignments now delegates to filter_role_assignments_visible_to_subject (in openedx_authz.api.roles). Instead of calling enforcer.enforce() once per assignment, it calls get_scopes_for_subject_and_permission once per distinct permission type (one enforcer lookup per type, not one per assignment), then uses key_match_func to match each assignment's scope against the viewer's accessible scopes. Because key_match_func bypasses the enforcer entirely, is_admin_or_superuser_check never runs on this path. Staff and superusers return early before the filter to preserve the access that check would have granted them.

Memoize role permission lookups in get_role_assignments: get_permissions_for_single_role was called once per policy entry even when multiple assignments shared the same role. A local _perm_cache dict skips the lookup for role keys already resolved in the same call.

Performance reports

Profiled with pyinstrument on muscat (GET /api/authz/v1/assignments/). Reports attached below.
Each enforce() call costs 20 to 80ms due to Casbin evaluating the full policy graph per (subject, action, object) triple, including role graph traversal via has_link and the custom matcher function.

_filter_allowed_assignments / filter_role_assignments_visible_to_subject:

Branch User type Time
main admin 8.38s (N Casbin enforce() calls)
main non-admin 16.74s (N Casbin enforce() calls)
MJG/perf-visible-assignments admin 0.08s (1 enforcer lookup per permission type)
MJG/perf-visible-assignments non-admin 0.04s (1 enforcer lookup per permission type)

get_visible_role_assignments_for_user total:

Branch User type Time
main admin 11.58s
main non-admin 20.39s
MJG/perf-visible-assignments admin 0.40s
MJG/perf-visible-assignments non-admin 0.13s

Total request wall time (muscat):

Branch User type Total
main admin ~11.7s
main non-admin ~20.7s
MJG/perf-visible-assignments admin ~1.9s
MJG/perf-visible-assignments non-admin ~0.2s

Both branches returned identical results on muscat against the same dataset (25 assignments, same content).

Pyinstrument reports:

Testing instructions

Use the pyinstrument-instrumented endpoint to reproduce. Requires ProfilerMiddleware active in the LMS settings: GET https://muscat.eu1.edunext.cloud/api/authz/v1/assignments/?profile

  1. Hit the endpoint as an admin user. Confirm get_visible_role_assignments_for_user is no longer the dominant cost and _filter_allowed_assignments does not appear in the trace.
  2. Hit as a non-admin user with library_admin in one scope. Confirm the response contains only assignments within that scope and filter_role_assignments_visible_to_subject replaces the old is_user_allowed loop.
  3. Add ?org=OrgX or ?role=library_admin query params and confirm the pre-filter is applied before the authorization pass.

Merge checklist:

  • Version bumped
  • Changelog record added
  • Documentation updated - ADR 0014 added
  • Fixup commits are squashed away
  • Unit tests added/updated
  • Manual testing instructions provided
  • Noted any: Concerns, dependencies, migration issues, deadlines, tickets

…path

Three changes to cut latency in get_visible_role_assignments_for_user:

1. Pre-filter by org/scope/role before the authorization pass so Casbin
   never evaluates assignments that would be filtered out anyway.

2. Replace the per-assignment enforcer.enforce() loop in
   _filter_allowed_assignments with a single batch_enforce() call.

3. Memoize get_permissions_for_single_role within get_role_assignments
   so the same role key is not expanded multiple times in one call.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@openedx-webhooks openedx-webhooks added open-source-contribution PR author is not from Axim or 2U core contributor PR author is a Core Contributor (who may or may not have write access to this repo). labels May 7, 2026
@openedx-webhooks
Copy link
Copy Markdown

Thanks for the pull request, @mariajgrimaldi!

This repository is currently maintained by @openedx/committers-openedx-authz.

Once you've gone through the following steps feel free to tag them in a comment and let them know that your changes are ready for engineering review.

🔘 Get product approval

If you haven't already, check this list to see if your contribution needs to go through the product review process.

  • If it does, you'll need to submit a product proposal for your contribution, and have it reviewed by the Product Working Group.
    • This process (including the steps you'll need to take) is documented here.
  • If it doesn't, simply proceed with the next step.
🔘 Provide context

To help your reviewers and other members of the community understand the purpose and larger context of your changes, feel free to add as much of the following information to the PR description as you can:

  • Dependencies

    This PR must be merged before / after / at the same time as ...

  • Blockers

    This PR is waiting for OEP-1234 to be accepted.

  • Timeline information

    This PR must be merged by XX date because ...

  • Partner information

    This is for a course on edx.org.

  • Supporting documentation
  • Relevant Open edX discussion forum threads
🔘 Get a green build

If one or more checks are failing, continue working on your changes until this is no longer the case and your build turns green.

🔘 Update the status of your PR

Your PR is currently marked as a draft. After completing the steps above, update its status by clicking "Ready for Review", or removing "WIP" from the title, as appropriate.


Where can I find more information?

If you'd like to get more details on all aspects of the review process for open source pull requests (OSPRs), check out the following resources:

When can I expect my changes to be merged?

Our goal is to get community contributions seen and reviewed as efficiently as possible.

However, the amount of time that it takes to review and merge a PR can vary significantly based on factors such as:

  • The size and impact of the changes that it introduces
  • The need for product review
  • Maintenance status of the parent repository

💡 As a result it may take up to several weeks or months to complete a review and merge your PR.

mariajgrimaldi and others added 2 commits May 7, 2026 19:29
… assignments

Bypass Casbin enforce() entirely in _filter_allowed_assignments:
- Check staff/superuser once via Django User query (early return)
- Call get_scopes_for_subject_and_permission once per distinct permission
  type (typically 1-2 calls total) instead of N enforce() calls
- Filter in Python using key_match_func for glob scope support

This eliminates the is_admin_or_superuser_check overhead (ScopeData/UserData
construction per item, RequestCache lookups) that dominated the previous
batch_enforce path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ser_staff_or_superuser

- Add filter_role_assignments_visible_to_subject to roles.py as a public
  API function for the scope-based visibility check previously inlined in
  _filter_allowed_assignments.

- Add is_user_staff_or_superuser to utils.py, using RequestCache to avoid
  repeated DB lookups within the same request and falling back to a DB
  query for non-request contexts. Both users.py and matcher.py now delegate
  to it instead of duplicating the cache and lookup logic.

- Move the staff/superuser shortcut out of _filter_allowed_assignments and
  up to the public callers (get_visible_role_assignments_for_user and
  get_visible_user_role_assignments_filtered_by_current_user).

- Rename _prefilter_assignments to _filter_assignments_by_params.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@mphilbrick211 mphilbrick211 moved this from Needs Triage to Waiting on Author in Contributions May 14, 2026
mariajgrimaldi and others added 9 commits May 21, 2026 13:13
Remove the is_user_staff_or_superuser guard from get_visible_role_assignments_for_user
and get_visible_user_role_assignments_filtered_by_current_user. The scope-based approach
introduced in the previous commit is fast enough for the common case; the short-circuit
can be added later with an explicit test for the staff/superuser path.

Also remove the corresponding short-circuit section from ADR 0014.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…le pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Revert engine/matcher.py to the original RequestCache-based approach.
The is_user_staff_or_superuser utility was introduced alongside the
short-circuit that was dropped, so remove it from utils.py as well.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…t_visible_role_assignments_for_user

- Rewrite TestGetVisibleRoleAssignmentsForUser with proper Expected result
  docstrings, AAA structure, and a setUpClass that creates Django User
  records so assertions are not vacuously true.
- Add TestFilterRoleAssignmentsVisibleToSubject in test_roles.py to cover
  the new public filter_role_assignments_visible_to_subject function directly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…d_assignments

filter_role_assignments_visible_to_subject uses key_match instead of enforce(),
so the enforcer never runs is_admin_or_superuser_check. Without the early return,
staff and superusers silently lose the access that check would have granted them.

is_user_staff_or_superuser is added to utils with RequestCache to avoid repeated
DB lookups within the same request.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core contributor PR author is a Core Contributor (who may or may not have write access to this repo). open-source-contribution PR author is not from Axim or 2U

Projects

Status: Waiting on Author

Development

Successfully merging this pull request may close these issues.

GET /api/authz/v1/assignments/ is slow due to too many queries on PolicyCacheControl

3 participants