Skip to content

providers/scim: fix per-user PolicyEngine evaluation in get_object_qs - #22009

Closed
ryanpesek wants to merge 1 commit into
goauthentik:mainfrom
ryanpesek:optimize-scim-users
Closed

ryanpesek wants to merge 1 commit into
goauthentik:mainfrom
ryanpesek:optimize-scim-users

Conversation

@ryanpesek

Copy link
Copy Markdown
Contributor

Details

PR #13947 introduced this filter in SCIMProvider.get_object_qs(User):

if self.backchannel_application:
    base = base.filter(
        pk__in=[
            user.pk
            for user in base
            if PolicyEngine(self.backchannel_application, user, None).build().passing
        ]
    )

This iterates every user in the database and instantiates PolicyEngine once per user. get_object_qs(User) is called once per page-sync task (one per sync_page_size users), once per signal-driven sync, and once during _sync_cleanup. With N users and N/page_size pages, that's O(N²/page_size) PolicyEngine evaluations per full sync per provider; each evaluation runs a recursive group-membership CTE plus the static-binding aggregation. On a instance with thousands of users and multiple SCIM providers, this produced:

  • several hundred thousand PolicyEngine evaluations per provider per full sync
  • 15–20 minute per-page sync tasks (each task processes only 100 users but evaluates all users)
  • Sustained high database load
  • Millions of P_ENG: Found static bindings log lines

The fix:
Replace the Python loop with a SQL-level translation of PolicyEngine.compute_static_bindings:

  • Fast path (purely static bindings, no Policy objects): translate each binding into a Q expression and combine with OR (MODE_ANY) or chained .filter() calls (MODE_ALL — since Q(groups__in=g1) & Q(groups__in=g2) collapses to a single M2M JOIN that can never match, chained filters force separate JOINs). Group bindings use with_descendants() to honor
    hierarchy, matching PolicyEngine's user.all_groups(). Negated bindings become ~Q(...). The application's policy_engine_mode is honored. Zero PolicyEngine instantiations.
  • Slow path (real Policy objects bound): we can't translate user-defined Python policies to SQL, so fall back to per-user
    PolicyEngine. For MODE_ALL, pre-filter candidates via the static-binding SQL filter first (a static-failing user can never pass MODE_ALL overall). For MODE_ANY, still iterate every user since a static-failing user might pass via policy.
  • AppAccessWithoutBindings tenant flag is honored at the SQL level (returning base or base.none() when no bindings exist) and on the slow path (setting engine.empty_result per instance). Related cleanups (in the same code paths)
  • sync_signal_direct / sync_signal_m2m: drop not queryset (which calls bool → _fetch_all() and materializes the entire queryset just to test non-emptiness) in favor of a single .exists() call. Also remove a no-op .filter() in sync_signal_m2m.
  • _sync_cleanup: pass the in-scope queryset as a subquery rather than materializing it into a Python set, avoiding a NOT IN (...) clause with thousands of parameters.
  • SCIMProvider.get_object_qs(Group): drop the prefetch_related on scimprovidergroup_set — never accessed during sync iteration (write() does its own per-object connection lookup; values_list() in cleanup bypasses prefetches).

Checklist

  • Local tests pass (ak test authentik/)
  • The code has been formatted (make lint-fix)

If an API change has been made

  • The API schema and clients have been updated (make gen)

If changes to the frontend have been made

  • The code has been formatted (make web)

If applicable

  • The documentation has been updated
  • The documentation has been formatted (make docs)

@ryanpesek
ryanpesek requested a review from a team as a code owner May 1, 2026 14:04
@netlify

netlify Bot commented May 1, 2026

Copy link
Copy Markdown

✅ Deploy Preview for authentik-docs ready!

Name Link
🔨 Latest commit 9da1c18
🔍 Latest deploy log https://app.netlify.com/projects/authentik-docs/deploys/69f4b2db12501c0008b3d86e
😎 Deploy Preview https://deploy-preview-22009--authentik-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented May 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.43750% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.20%. Comparing base (ebfc01f) to head (9da1c18).
⚠️ Report is 374 commits behind head on main.

Files with missing lines Patch % Lines
authentik/providers/scim/models.py 96.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #22009      +/-   ##
==========================================
- Coverage   93.22%   93.20%   -0.03%     
==========================================
  Files        1024     1024              
  Lines       59153    59265     +112     
  Branches      331      331              
==========================================
+ Hits        55148    55236      +88     
- Misses       4005     4029      +24     
Flag Coverage Δ
conformance 36.22% <4.68%> (-0.06%) ⬇️
e2e 42.00% <4.68%> (-0.08%) ⬇️
integration 32.74% <4.68%> (-0.56%) ⬇️
rust 0.00% <ø> (ø)
unit 92.10% <98.43%> (+0.01%) ⬆️
unit-migrate 92.13% <98.43%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@gergosimonyi gergosimonyi added the backport/version-2026.5 Add this label to PRs to backport changes to version-2026.5 label May 26, 2026

@BeryJu BeryJu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ryanpesek I like the general idea of this and the optimisation for checking policybindings on multiple objects, however I'd much prefer that optimisation to be more re-usable for other things such as listing applications or RAC endpoints. Now rewriting this optimisation to be usable for that will take a bit longer so I'll keep this open and up-to-date as a temporary bug fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport/version-2026.5 Add this label to PRs to backport changes to version-2026.5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants