From 735698a500c36673a065f632c4af2e641e2bc10b Mon Sep 17 00:00:00 2001 From: Cody Maffucci <46459665+Maffooch@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:09:56 -0700 Subject: [PATCH 1/2] perf(prefetch): load prefetched locations' tags once per page ?prefetch=location serialized each location with LocationSerializer, whose tags and inherited_tags read Location.readable_tags. The prefetcher loaded neither tag relation nor the tag-readability check, so each prefetched location cost three more queries (a page of 250 references to distinct locations: about 750). Prefetch tags and inherited_tags for Location like the other prefetched models, and set the readability flag for the whole page with mark_tags_readable, as the locations list view already does. Co-Authored-By: Claude Opus 5.5 --- dojo/api_v2/prefetch/prefetcher.py | 10 ++ ...st_apiv2_prefetch_location_tags_queries.py | 102 ++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 unittests/test_apiv2_prefetch_location_tags_queries.py diff --git a/dojo/api_v2/prefetch/prefetcher.py b/dojo/api_v2/prefetch/prefetcher.py index 3c31f6cb560..9a5322e7ff5 100644 --- a/dojo/api_v2/prefetch/prefetcher.py +++ b/dojo/api_v2/prefetch/prefetcher.py @@ -18,6 +18,7 @@ ) from dojo.location.feature import locations_enabled from dojo.location.models import Location, LocationFindingReference, LocationProductReference +from dojo.location.queries import mark_tags_readable from dojo.models import Endpoint, FileUpload, Finding, Notes, Test from dojo.notes.helper import notes_prefetch from dojo.vulnerability.queries import vulnerability_id_prefetch @@ -59,6 +60,8 @@ def _finding_prefetch_related(): _PREFETCH_PREFETCH_RELATED = { Endpoint: ("endpoint_params", "findings", "tags"), Finding: _finding_prefetch_related, + # LocationSerializer returns tags and inherited_tags through Location.readable_tags + Location: ("tags", "inherited_tags"), Notes: ("history__current_editor", "history__note_type"), # TestSerializer nests every finding group in the test with its JIRA issue and that issue's url, and every note Test: ( @@ -391,6 +394,7 @@ def _prefetch_many(self, field_to_fetch, field_values, authorized_qs, extra_seri authorized = list(authorized_qs.filter(pk__in=all_ids)) if not authorized: return + self._mark_location_tags_readable(authorized) serializer = extra_serializer(**serializer_kwargs) _prefetch_shown_relations(authorized, serializer) field_data = serializer.to_representation(authorized) @@ -417,6 +421,7 @@ def _prefetch_single(self, field_to_fetch, field_values, authorized_qs, extra_se authorized = list(first_by_pk.values()) if prefetch_related := _prefetch_related_for(type(field_values[0])): prefetch_related_objects(authorized, *prefetch_related) + self._mark_location_tags_readable(authorized) # One serializer for all of them, as a list serializer reuses its child: building a serializer's fields is # most of the cost of serializing a finding, and it does not depend on the object serializer = extra_serializer(**serializer_kwargs) @@ -430,6 +435,11 @@ def _prefetch_single(self, field_to_fetch, field_values, authorized_qs, extra_se data = serializer.to_representation(field_value) self._prefetch_data[field_to_fetch][data["id"]] = data + def _mark_location_tags_readable(self, objects): + # Location.readable_tags checks per row whether the caller may read its tag set: check the page at once + if objects and isinstance(objects[0], Location): + mark_tags_readable(objects, user=getattr(self._request, "user", None)) + @property def prefetched_data(self): return self._prefetch_data diff --git a/unittests/test_apiv2_prefetch_location_tags_queries.py b/unittests/test_apiv2_prefetch_location_tags_queries.py new file mode 100644 index 00000000000..9a58d981a9a --- /dev/null +++ b/unittests/test_apiv2_prefetch_location_tags_queries.py @@ -0,0 +1,102 @@ +""" +``?prefetch=location`` on the location reference endpoints reads each location's tags once per page. + +``LocationSerializer`` returns ``tags`` and ``inherited_tags`` through ``Location.readable_tags``, +which checks whether the caller may read the row's shared tag set and then reads both tag +relations. The prefetcher serialized every prefetched location without loading either, so a page +of N references to N distinct locations cost a readability check plus two tag reads per location. + +These tests pin a page's query count as flat in the number of prefetched locations, and check +that the prefetched payload still carries each location's own tags. +""" + +from django.db import connection +from django.test import override_settings +from django.test.utils import CaptureQueriesContext +from django.utils.timezone import now + +from dojo.location.models import Location, LocationFindingReference +from dojo.location.status import FindingLocationStatus +from dojo.models import ( + Dojo_User, + Engagement, + Finding, + Product, + Product_Type, + Test, + Test_Type, +) +from unittests.dojo_test_case import DojoAPITestCase + + +@override_settings(V3_FEATURE_LOCATIONS=True, SECURE_SSL_REDIRECT=False) +class PrefetchLocationTagsQueryCountTest(DojoAPITestCase): + + @classmethod + def setUpTestData(cls): + prod_type, _ = Product_Type.objects.get_or_create(name="PrefetchLocationTags PT") + test_type, _ = Test_Type.objects.get_or_create(name="PrefetchLocationTags Scan") + cls.admin = Dojo_User.objects.create_superuser( + username="admin", + email="admin@prefetch-location-tags.example", + password="prefetch-location-tags-not-a-real-password", # noqa: S106 -- test-only account + ) + product = Product.objects.create(name="PrefetchLocationTags Product", description="n/a", prod_type=prod_type) + engagement = Engagement.objects.create( + name="PrefetchLocationTags Engagement", product=product, target_start=now(), target_end=now(), + ) + cls.test = Test.objects.create( + engagement=engagement, test_type=test_type, target_start=now(), target_end=now(), lead=cls.admin, + ) + + def setUp(self): + self.login_as_admin() + + def _finding_with_locations(self, label, count): + finding = Finding.objects.create( + title=f"PrefetchLocationTags {label}", + test=self.test, + reporter=self.admin, + severity="Info", + numerical_severity="S4", + ) + for index in range(count): + location = Location.objects.create( + location_type="URL", + location_value=f"https://{label}-{index}.prefetch-location-tags.example.com/", + ) + location.tags.add(f"{label}-tag-{index}") + LocationFindingReference.objects.create( + location=location, finding=finding, status=FindingLocationStatus.Active, + ) + return finding + + def _get(self, finding): + return self.client.get( + "/api/v2/location_findings/", + {"prefetch": "location", "finding_includes": str(finding.pk), "limit": 250}, + format="json", + ) + + def _query_count(self, finding): + # Warm per-process caches (system settings, feature flags) so they don't skew the first count + self._get(finding) + with CaptureQueriesContext(connection) as queries: + response = self._get(finding) + self.assertEqual(200, response.status_code, response.content[:500]) + return len(queries) + + def test_query_count_does_not_grow_with_prefetched_locations(self): + few = self._finding_with_locations("few", 2) + many = self._finding_with_locations("many", 8) + self.assertEqual(self._query_count(few), self._query_count(many)) + + def test_prefetched_locations_carry_their_own_tags(self): + finding = self._finding_with_locations("tags", 3) + response = self._get(finding) + self.assertEqual(200, response.status_code, response.content[:500]) + prefetched = response.json()["prefetch"]["location"] + self.assertEqual(3, len(prefetched)) + for data in prefetched.values(): + index = data["location_value"].split("-")[1].split(".")[0] + self.assertEqual([f"tags-tag-{index}"], data["tags"]) From d55c3ce4cae032f22c846636e835899182ea0742 Mon Sep 17 00:00:00 2001 From: Cody Maffucci <46459665+Maffooch@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:26:21 -0700 Subject: [PATCH 2/2] test(prefetch): skip the location prefetch query test when Locations routes are not mounted Co-Authored-By: Claude Opus 5.5 --- unittests/test_apiv2_prefetch_location_tags_queries.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/unittests/test_apiv2_prefetch_location_tags_queries.py b/unittests/test_apiv2_prefetch_location_tags_queries.py index 9a58d981a9a..c7d4097e087 100644 --- a/unittests/test_apiv2_prefetch_location_tags_queries.py +++ b/unittests/test_apiv2_prefetch_location_tags_queries.py @@ -10,6 +10,9 @@ that the prefetched payload still carries each location's own tags. """ +from unittest import skipUnless + +from django.conf import settings from django.db import connection from django.test import override_settings from django.test.utils import CaptureQueriesContext @@ -29,6 +32,7 @@ from unittests.dojo_test_case import DojoAPITestCase +@skipUnless(settings.V3_FEATURE_LOCATIONS, "the location reference routes are mounted at import time") @override_settings(V3_FEATURE_LOCATIONS=True, SECURE_SSL_REDIRECT=False) class PrefetchLocationTagsQueryCountTest(DojoAPITestCase):