authentik.core.tests.test_application_pagination

User application pagination regressions and policy-filtering cost measurements.

  1"""User application pagination regressions and policy-filtering cost measurements."""
  2
  3from statistics import median
  4from time import perf_counter
  5from unittest.mock import patch
  6
  7from django.core.cache import cache
  8from django.db import connection
  9from django.test.utils import CaptureQueriesContext
 10from django.urls import reverse
 11from rest_framework.test import APIRequestFactory, APITestCase, force_authenticate
 12
 13from authentik.core.api.applications import ApplicationViewSet
 14from authentik.core.models import Application
 15from authentik.core.tests.utils import create_test_admin_user, create_test_user
 16from authentik.policies.expression.models import ExpressionPolicy
 17from authentik.policies.models import PolicyBinding
 18from authentik.policies.types import CACHE_PREFIX
 19
 20
 21class TestUserApplicationPagination(APITestCase):
 22    """Pages and totals must describe the target user's accessible applications."""
 23
 24    def setUp(self):
 25        self.admin = create_test_admin_user()
 26        self.user = create_test_user()
 27        self.client.force_login(self.admin)
 28        self.url = reverse("authentik_api:application-accessible")
 29        self.apps = []
 30        # Denied applications before, between, and after allowed applications.
 31        for index in range(7):
 32            app = Application.objects.create(name=f"app-{index}", slug=f"app-{index}")
 33            PolicyBinding.objects.create(
 34                target=app, user=self.user if index % 2 else self.admin, order=0
 35            )
 36            self.apps.append(app)
 37
 38    def test_pages(self):
 39        """Denied objects must not consume slots or inflate any pagination metadata."""
 40        for page, indices, expected_pagination in (
 41            (
 42                1,
 43                [1, 3],
 44                dict(
 45                    next=2,
 46                    previous=0,
 47                    count=3,
 48                    current=1,
 49                    total_pages=2,
 50                    start_index=1,
 51                    end_index=2,
 52                ),
 53            ),
 54            (
 55                2,
 56                [5],
 57                dict(
 58                    next=0,
 59                    previous=1,
 60                    count=3,
 61                    current=2,
 62                    total_pages=2,
 63                    start_index=3,
 64                    end_index=3,
 65                ),
 66            ),
 67        ):
 68            with self.subTest(page=page):
 69                response = self.client.get(
 70                    self.url, {"for_user": self.user.pk, "page_size": 2, "page": page}
 71                )
 72                self.assertEqual(response.status_code, 200)
 73                self.assertEqual(response.data["pagination"], expected_pagination)
 74                self.assertEqual(
 75                    [app["slug"] for app in response.data["results"]],
 76                    [self.apps[index].slug for index in indices],
 77                )
 78        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2, "page": 3})
 79        self.assertEqual(response.status_code, 404)
 80
 81    def test_empty(self):
 82        """A user with no access gets an empty first page with a zero count."""
 83        response = self.client.get(self.url, {"for_user": create_test_user().pk, "page_size": 2})
 84        self.assertEqual(response.status_code, 200)
 85        self.assertEqual(response.data["results"], [])
 86        self.assertEqual(
 87            response.data["pagination"],
 88            dict(next=0, previous=0, count=0, current=1, total_pages=1, start_index=0, end_index=0),
 89        )
 90
 91    def test_filters_and_ordering(self):
 92        """Hidden objects and search filters are excluded; ordering survives policy filtering."""
 93        self.apps[3].meta_hide = True
 94        self.apps[3].save()
 95        response = self.client.get(
 96            self.url,
 97            {"for_user": self.user.pk, "page_size": 1, "ordering": "-name", "search": "app"},
 98        )
 99        self.assertEqual(response.status_code, 200)
100        self.assertEqual(response.data["pagination"]["count"], 2)
101        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-5"])
102        response = self.client.get(self.url, {"for_user": self.user.pk, "search": "app-1"})
103        self.assertEqual(response.status_code, 200)
104        self.assertEqual(response.data["pagination"]["count"], 1)
105        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-1"])
106
107    def test_expression_uses_target_user(self):
108        """Dynamic policies also evaluate as the target user, including HTTP request context."""
109        PolicyBinding.objects.all().delete()
110        policy = ExpressionPolicy.objects.create(
111            name="target-user",
112            expression=(
113                f"return request.user.pk == {self.user.pk} "
114                f"and request.http_request.user.pk == {self.user.pk} "
115                "and request.obj.slug in ('app-3', 'app-5')"
116            ),
117        )
118        for app in self.apps:
119            PolicyBinding.objects.create(target=app, policy=policy, order=0)
120        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2})
121        self.assertEqual(response.status_code, 200)
122        self.assertEqual(response.data["pagination"]["count"], 2)
123        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-3", "app-5"])
124
125    def test_invalid_target(self):
126        """Malformed and nonexistent user IDs still fail validation."""
127        for target in ("invalid", -1):
128            with self.subTest(target=target):
129                response = self.client.get(self.url, {"for_user": target})
130                self.assertEqual(response.status_code, 400)
131
132    def test_requires_user_applications_permission(self):
133        """An unprivileged caller cannot list another user's applications."""
134        self.client.force_login(self.user)
135        response = self.client.get(self.url, {"for_user": self.admin.pk})
136        self.assertEqual(response.status_code, 400)
137
138
139class TestApplicationPaginationCost(APITestCase):
140    """Compare the old and new filtering pipelines, excluding HTTP/authentication overhead.
141
142    Measures real SQL, policy evaluation, and serialization with 10% accessible apps.
143    Reports median elapsed time and query count over three runs, with cold and warm
144    policy caches. Timings are informational; assertions cover policy execution
145    counts and query budgets rather than machine-dependent deadlines. Run with --no-capture to see
146    the table. These simple expressions do not model slow external policy calls.
147    """
148
149    def test_filtering_cost(self):
150        """Expose full-set evaluation costs and guard against static-binding N+1 queries."""
151        admin = create_test_admin_user()
152        user = create_test_user()
153        policy = ExpressionPolicy.objects.create(
154            name="pagination-cost",
155            expression="return int(request.obj.slug.split('-')[-1]) % 10 == 0",
156        )
157        apps = []
158        print("\napps policy cache pipeline median_ms queries policy_executions")
159        for size in (20, 140, 1000):
160            for index in range(len(apps), size):
161                apps.append(
162                    Application.objects.create(name=f"app-{index:04d}", slug=f"app-{index:04d}")
163                )
164            for dynamic in (False, True):
165                PolicyBinding.objects.filter(target__in=apps).delete()
166                PolicyBinding.objects.bulk_create(
167                    [
168                        PolicyBinding(
169                            target=app,
170                            policy=policy if dynamic else None,
171                            user=None if dynamic else (user if index % 10 == 0 else admin),
172                            order=0,
173                        )
174                        for index, app in enumerate(apps)
175                    ]
176                )
177                for warm in (False, True) if dynamic else (False,):
178                    for full_set in (False, True):
179                        durations, queries, executions = [], [], []
180                        for _ in range(3):
181                            cache.delete_many(cache.keys(f"{CACHE_PREFIX}*"))
182                            if warm:
183                                self._run_pipeline(admin, user, full_set)
184                            with (
185                                CaptureQueriesContext(connection) as captured,
186                                patch.object(
187                                    ExpressionPolicy,
188                                    "passes",
189                                    autospec=True,
190                                    side_effect=ExpressionPolicy.passes,
191                                ) as passes,
192                            ):
193                                start = perf_counter()
194                                response = self._run_pipeline(admin, user, full_set)
195                                durations.append((perf_counter() - start) * 1000)
196                            queries.append(len(captured))
197                            executions.append(passes.call_count)
198                            evaluated = size if full_set else 20
199                            self.assertEqual(
200                                passes.call_count, evaluated if dynamic and not warm else 0
201                            )
202                            self.assertEqual(
203                                len(response.data["results"]),
204                                min(size // 10, 20) if full_set else 2,
205                            )
206                            self.assertEqual(
207                                response.data["pagination"]["count"],
208                                size // 10 if full_set else size,
209                            )
210                        print(
211                            size,
212                            "expression" if dynamic else "user-binding",
213                            "warm" if warm else "cold",
214                            "filter-first" if full_set else "page-first",
215                            f"{median(durations):.2f}",
216                            median(queries),
217                            median(executions),
218                        )
219                        if not dynamic and full_set:
220                            # Observed baseline: 18 queries. Allow small variations from
221                            # cache state/setup, but keep the budget fixed as apps grow
222                            # so per-application queries still fail this check.
223                            self.assertLessEqual(
224                                median(queries),
225                                25,
226                                f"Static bindings for {size} apps exceeded query budget: {queries}",
227                            )
228
229    def _run_pipeline(self, admin, user, full_set):
230        """Reproduce each pipeline with fresh querysets and identical page size/serialization."""
231        raw_request = APIRequestFactory().get("/", {"page_size": 20, "for_user": user.pk})
232        force_authenticate(raw_request, user=admin)
233        view = ApplicationViewSet(action="accessible", **ApplicationViewSet.accessible.kwargs)
234        view.action_map = {"get": "accessible"}
235        view.request = view.initialize_request(raw_request)
236        view.format_kwarg = None
237        queryset = view.filter_queryset(view.get_queryset()).exclude(meta_hide=True)
238        if full_set:
239            allowed = view._get_allowed_applications(queryset, user=user)
240            page = view.paginator.paginate_queryset(allowed, view.request)
241        else:
242            candidates = view.paginator.paginate_queryset(queryset, view.request)
243            page = view._get_allowed_applications(candidates, user=user)
244        return view.get_paginated_response(view.get_serializer(page, many=True).data)
class TestUserApplicationPagination(rest_framework.test.APITestCase):
 22class TestUserApplicationPagination(APITestCase):
 23    """Pages and totals must describe the target user's accessible applications."""
 24
 25    def setUp(self):
 26        self.admin = create_test_admin_user()
 27        self.user = create_test_user()
 28        self.client.force_login(self.admin)
 29        self.url = reverse("authentik_api:application-accessible")
 30        self.apps = []
 31        # Denied applications before, between, and after allowed applications.
 32        for index in range(7):
 33            app = Application.objects.create(name=f"app-{index}", slug=f"app-{index}")
 34            PolicyBinding.objects.create(
 35                target=app, user=self.user if index % 2 else self.admin, order=0
 36            )
 37            self.apps.append(app)
 38
 39    def test_pages(self):
 40        """Denied objects must not consume slots or inflate any pagination metadata."""
 41        for page, indices, expected_pagination in (
 42            (
 43                1,
 44                [1, 3],
 45                dict(
 46                    next=2,
 47                    previous=0,
 48                    count=3,
 49                    current=1,
 50                    total_pages=2,
 51                    start_index=1,
 52                    end_index=2,
 53                ),
 54            ),
 55            (
 56                2,
 57                [5],
 58                dict(
 59                    next=0,
 60                    previous=1,
 61                    count=3,
 62                    current=2,
 63                    total_pages=2,
 64                    start_index=3,
 65                    end_index=3,
 66                ),
 67            ),
 68        ):
 69            with self.subTest(page=page):
 70                response = self.client.get(
 71                    self.url, {"for_user": self.user.pk, "page_size": 2, "page": page}
 72                )
 73                self.assertEqual(response.status_code, 200)
 74                self.assertEqual(response.data["pagination"], expected_pagination)
 75                self.assertEqual(
 76                    [app["slug"] for app in response.data["results"]],
 77                    [self.apps[index].slug for index in indices],
 78                )
 79        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2, "page": 3})
 80        self.assertEqual(response.status_code, 404)
 81
 82    def test_empty(self):
 83        """A user with no access gets an empty first page with a zero count."""
 84        response = self.client.get(self.url, {"for_user": create_test_user().pk, "page_size": 2})
 85        self.assertEqual(response.status_code, 200)
 86        self.assertEqual(response.data["results"], [])
 87        self.assertEqual(
 88            response.data["pagination"],
 89            dict(next=0, previous=0, count=0, current=1, total_pages=1, start_index=0, end_index=0),
 90        )
 91
 92    def test_filters_and_ordering(self):
 93        """Hidden objects and search filters are excluded; ordering survives policy filtering."""
 94        self.apps[3].meta_hide = True
 95        self.apps[3].save()
 96        response = self.client.get(
 97            self.url,
 98            {"for_user": self.user.pk, "page_size": 1, "ordering": "-name", "search": "app"},
 99        )
100        self.assertEqual(response.status_code, 200)
101        self.assertEqual(response.data["pagination"]["count"], 2)
102        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-5"])
103        response = self.client.get(self.url, {"for_user": self.user.pk, "search": "app-1"})
104        self.assertEqual(response.status_code, 200)
105        self.assertEqual(response.data["pagination"]["count"], 1)
106        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-1"])
107
108    def test_expression_uses_target_user(self):
109        """Dynamic policies also evaluate as the target user, including HTTP request context."""
110        PolicyBinding.objects.all().delete()
111        policy = ExpressionPolicy.objects.create(
112            name="target-user",
113            expression=(
114                f"return request.user.pk == {self.user.pk} "
115                f"and request.http_request.user.pk == {self.user.pk} "
116                "and request.obj.slug in ('app-3', 'app-5')"
117            ),
118        )
119        for app in self.apps:
120            PolicyBinding.objects.create(target=app, policy=policy, order=0)
121        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2})
122        self.assertEqual(response.status_code, 200)
123        self.assertEqual(response.data["pagination"]["count"], 2)
124        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-3", "app-5"])
125
126    def test_invalid_target(self):
127        """Malformed and nonexistent user IDs still fail validation."""
128        for target in ("invalid", -1):
129            with self.subTest(target=target):
130                response = self.client.get(self.url, {"for_user": target})
131                self.assertEqual(response.status_code, 400)
132
133    def test_requires_user_applications_permission(self):
134        """An unprivileged caller cannot list another user's applications."""
135        self.client.force_login(self.user)
136        response = self.client.get(self.url, {"for_user": self.admin.pk})
137        self.assertEqual(response.status_code, 400)

Pages and totals must describe the target user's accessible applications.

def setUp(self):
25    def setUp(self):
26        self.admin = create_test_admin_user()
27        self.user = create_test_user()
28        self.client.force_login(self.admin)
29        self.url = reverse("authentik_api:application-accessible")
30        self.apps = []
31        # Denied applications before, between, and after allowed applications.
32        for index in range(7):
33            app = Application.objects.create(name=f"app-{index}", slug=f"app-{index}")
34            PolicyBinding.objects.create(
35                target=app, user=self.user if index % 2 else self.admin, order=0
36            )
37            self.apps.append(app)

Hook method for setting up the test fixture before exercising it.

def test_pages(self):
39    def test_pages(self):
40        """Denied objects must not consume slots or inflate any pagination metadata."""
41        for page, indices, expected_pagination in (
42            (
43                1,
44                [1, 3],
45                dict(
46                    next=2,
47                    previous=0,
48                    count=3,
49                    current=1,
50                    total_pages=2,
51                    start_index=1,
52                    end_index=2,
53                ),
54            ),
55            (
56                2,
57                [5],
58                dict(
59                    next=0,
60                    previous=1,
61                    count=3,
62                    current=2,
63                    total_pages=2,
64                    start_index=3,
65                    end_index=3,
66                ),
67            ),
68        ):
69            with self.subTest(page=page):
70                response = self.client.get(
71                    self.url, {"for_user": self.user.pk, "page_size": 2, "page": page}
72                )
73                self.assertEqual(response.status_code, 200)
74                self.assertEqual(response.data["pagination"], expected_pagination)
75                self.assertEqual(
76                    [app["slug"] for app in response.data["results"]],
77                    [self.apps[index].slug for index in indices],
78                )
79        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2, "page": 3})
80        self.assertEqual(response.status_code, 404)

Denied objects must not consume slots or inflate any pagination metadata.

def test_empty(self):
82    def test_empty(self):
83        """A user with no access gets an empty first page with a zero count."""
84        response = self.client.get(self.url, {"for_user": create_test_user().pk, "page_size": 2})
85        self.assertEqual(response.status_code, 200)
86        self.assertEqual(response.data["results"], [])
87        self.assertEqual(
88            response.data["pagination"],
89            dict(next=0, previous=0, count=0, current=1, total_pages=1, start_index=0, end_index=0),
90        )

A user with no access gets an empty first page with a zero count.

def test_filters_and_ordering(self):
 92    def test_filters_and_ordering(self):
 93        """Hidden objects and search filters are excluded; ordering survives policy filtering."""
 94        self.apps[3].meta_hide = True
 95        self.apps[3].save()
 96        response = self.client.get(
 97            self.url,
 98            {"for_user": self.user.pk, "page_size": 1, "ordering": "-name", "search": "app"},
 99        )
100        self.assertEqual(response.status_code, 200)
101        self.assertEqual(response.data["pagination"]["count"], 2)
102        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-5"])
103        response = self.client.get(self.url, {"for_user": self.user.pk, "search": "app-1"})
104        self.assertEqual(response.status_code, 200)
105        self.assertEqual(response.data["pagination"]["count"], 1)
106        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-1"])

Hidden objects and search filters are excluded; ordering survives policy filtering.

def test_expression_uses_target_user(self):
108    def test_expression_uses_target_user(self):
109        """Dynamic policies also evaluate as the target user, including HTTP request context."""
110        PolicyBinding.objects.all().delete()
111        policy = ExpressionPolicy.objects.create(
112            name="target-user",
113            expression=(
114                f"return request.user.pk == {self.user.pk} "
115                f"and request.http_request.user.pk == {self.user.pk} "
116                "and request.obj.slug in ('app-3', 'app-5')"
117            ),
118        )
119        for app in self.apps:
120            PolicyBinding.objects.create(target=app, policy=policy, order=0)
121        response = self.client.get(self.url, {"for_user": self.user.pk, "page_size": 2})
122        self.assertEqual(response.status_code, 200)
123        self.assertEqual(response.data["pagination"]["count"], 2)
124        self.assertEqual([app["slug"] for app in response.data["results"]], ["app-3", "app-5"])

Dynamic policies also evaluate as the target user, including HTTP request context.

def test_invalid_target(self):
126    def test_invalid_target(self):
127        """Malformed and nonexistent user IDs still fail validation."""
128        for target in ("invalid", -1):
129            with self.subTest(target=target):
130                response = self.client.get(self.url, {"for_user": target})
131                self.assertEqual(response.status_code, 400)

Malformed and nonexistent user IDs still fail validation.

def test_requires_user_applications_permission(self):
133    def test_requires_user_applications_permission(self):
134        """An unprivileged caller cannot list another user's applications."""
135        self.client.force_login(self.user)
136        response = self.client.get(self.url, {"for_user": self.admin.pk})
137        self.assertEqual(response.status_code, 400)

An unprivileged caller cannot list another user's applications.

class TestApplicationPaginationCost(rest_framework.test.APITestCase):
140class TestApplicationPaginationCost(APITestCase):
141    """Compare the old and new filtering pipelines, excluding HTTP/authentication overhead.
142
143    Measures real SQL, policy evaluation, and serialization with 10% accessible apps.
144    Reports median elapsed time and query count over three runs, with cold and warm
145    policy caches. Timings are informational; assertions cover policy execution
146    counts and query budgets rather than machine-dependent deadlines. Run with --no-capture to see
147    the table. These simple expressions do not model slow external policy calls.
148    """
149
150    def test_filtering_cost(self):
151        """Expose full-set evaluation costs and guard against static-binding N+1 queries."""
152        admin = create_test_admin_user()
153        user = create_test_user()
154        policy = ExpressionPolicy.objects.create(
155            name="pagination-cost",
156            expression="return int(request.obj.slug.split('-')[-1]) % 10 == 0",
157        )
158        apps = []
159        print("\napps policy cache pipeline median_ms queries policy_executions")
160        for size in (20, 140, 1000):
161            for index in range(len(apps), size):
162                apps.append(
163                    Application.objects.create(name=f"app-{index:04d}", slug=f"app-{index:04d}")
164                )
165            for dynamic in (False, True):
166                PolicyBinding.objects.filter(target__in=apps).delete()
167                PolicyBinding.objects.bulk_create(
168                    [
169                        PolicyBinding(
170                            target=app,
171                            policy=policy if dynamic else None,
172                            user=None if dynamic else (user if index % 10 == 0 else admin),
173                            order=0,
174                        )
175                        for index, app in enumerate(apps)
176                    ]
177                )
178                for warm in (False, True) if dynamic else (False,):
179                    for full_set in (False, True):
180                        durations, queries, executions = [], [], []
181                        for _ in range(3):
182                            cache.delete_many(cache.keys(f"{CACHE_PREFIX}*"))
183                            if warm:
184                                self._run_pipeline(admin, user, full_set)
185                            with (
186                                CaptureQueriesContext(connection) as captured,
187                                patch.object(
188                                    ExpressionPolicy,
189                                    "passes",
190                                    autospec=True,
191                                    side_effect=ExpressionPolicy.passes,
192                                ) as passes,
193                            ):
194                                start = perf_counter()
195                                response = self._run_pipeline(admin, user, full_set)
196                                durations.append((perf_counter() - start) * 1000)
197                            queries.append(len(captured))
198                            executions.append(passes.call_count)
199                            evaluated = size if full_set else 20
200                            self.assertEqual(
201                                passes.call_count, evaluated if dynamic and not warm else 0
202                            )
203                            self.assertEqual(
204                                len(response.data["results"]),
205                                min(size // 10, 20) if full_set else 2,
206                            )
207                            self.assertEqual(
208                                response.data["pagination"]["count"],
209                                size // 10 if full_set else size,
210                            )
211                        print(
212                            size,
213                            "expression" if dynamic else "user-binding",
214                            "warm" if warm else "cold",
215                            "filter-first" if full_set else "page-first",
216                            f"{median(durations):.2f}",
217                            median(queries),
218                            median(executions),
219                        )
220                        if not dynamic and full_set:
221                            # Observed baseline: 18 queries. Allow small variations from
222                            # cache state/setup, but keep the budget fixed as apps grow
223                            # so per-application queries still fail this check.
224                            self.assertLessEqual(
225                                median(queries),
226                                25,
227                                f"Static bindings for {size} apps exceeded query budget: {queries}",
228                            )
229
230    def _run_pipeline(self, admin, user, full_set):
231        """Reproduce each pipeline with fresh querysets and identical page size/serialization."""
232        raw_request = APIRequestFactory().get("/", {"page_size": 20, "for_user": user.pk})
233        force_authenticate(raw_request, user=admin)
234        view = ApplicationViewSet(action="accessible", **ApplicationViewSet.accessible.kwargs)
235        view.action_map = {"get": "accessible"}
236        view.request = view.initialize_request(raw_request)
237        view.format_kwarg = None
238        queryset = view.filter_queryset(view.get_queryset()).exclude(meta_hide=True)
239        if full_set:
240            allowed = view._get_allowed_applications(queryset, user=user)
241            page = view.paginator.paginate_queryset(allowed, view.request)
242        else:
243            candidates = view.paginator.paginate_queryset(queryset, view.request)
244            page = view._get_allowed_applications(candidates, user=user)
245        return view.get_paginated_response(view.get_serializer(page, many=True).data)

Compare the old and new filtering pipelines, excluding HTTP/authentication overhead.

Measures real SQL, policy evaluation, and serialization with 10% accessible apps. Reports median elapsed time and query count over three runs, with cold and warm policy caches. Timings are informational; assertions cover policy execution counts and query budgets rather than machine-dependent deadlines. Run with --no-capture to see the table. These simple expressions do not model slow external policy calls.

def test_filtering_cost(self):
150    def test_filtering_cost(self):
151        """Expose full-set evaluation costs and guard against static-binding N+1 queries."""
152        admin = create_test_admin_user()
153        user = create_test_user()
154        policy = ExpressionPolicy.objects.create(
155            name="pagination-cost",
156            expression="return int(request.obj.slug.split('-')[-1]) % 10 == 0",
157        )
158        apps = []
159        print("\napps policy cache pipeline median_ms queries policy_executions")
160        for size in (20, 140, 1000):
161            for index in range(len(apps), size):
162                apps.append(
163                    Application.objects.create(name=f"app-{index:04d}", slug=f"app-{index:04d}")
164                )
165            for dynamic in (False, True):
166                PolicyBinding.objects.filter(target__in=apps).delete()
167                PolicyBinding.objects.bulk_create(
168                    [
169                        PolicyBinding(
170                            target=app,
171                            policy=policy if dynamic else None,
172                            user=None if dynamic else (user if index % 10 == 0 else admin),
173                            order=0,
174                        )
175                        for index, app in enumerate(apps)
176                    ]
177                )
178                for warm in (False, True) if dynamic else (False,):
179                    for full_set in (False, True):
180                        durations, queries, executions = [], [], []
181                        for _ in range(3):
182                            cache.delete_many(cache.keys(f"{CACHE_PREFIX}*"))
183                            if warm:
184                                self._run_pipeline(admin, user, full_set)
185                            with (
186                                CaptureQueriesContext(connection) as captured,
187                                patch.object(
188                                    ExpressionPolicy,
189                                    "passes",
190                                    autospec=True,
191                                    side_effect=ExpressionPolicy.passes,
192                                ) as passes,
193                            ):
194                                start = perf_counter()
195                                response = self._run_pipeline(admin, user, full_set)
196                                durations.append((perf_counter() - start) * 1000)
197                            queries.append(len(captured))
198                            executions.append(passes.call_count)
199                            evaluated = size if full_set else 20
200                            self.assertEqual(
201                                passes.call_count, evaluated if dynamic and not warm else 0
202                            )
203                            self.assertEqual(
204                                len(response.data["results"]),
205                                min(size // 10, 20) if full_set else 2,
206                            )
207                            self.assertEqual(
208                                response.data["pagination"]["count"],
209                                size // 10 if full_set else size,
210                            )
211                        print(
212                            size,
213                            "expression" if dynamic else "user-binding",
214                            "warm" if warm else "cold",
215                            "filter-first" if full_set else "page-first",
216                            f"{median(durations):.2f}",
217                            median(queries),
218                            median(executions),
219                        )
220                        if not dynamic and full_set:
221                            # Observed baseline: 18 queries. Allow small variations from
222                            # cache state/setup, but keep the budget fixed as apps grow
223                            # so per-application queries still fail this check.
224                            self.assertLessEqual(
225                                median(queries),
226                                25,
227                                f"Static bindings for {size} apps exceeded query budget: {queries}",
228                            )

Expose full-set evaluation costs and guard against static-binding N+1 queries.