From 81226cd8373f92d5a4c5065a4f2d57643e2ae632 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Pe=C3=B1a?= Date: Thu, 28 May 2026 13:46:15 +0200 Subject: [PATCH] perf(api): use literal scan_ids in finding-groups /latest aggregation (#11380) --- api/src/backend/api/v1/views.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py index a611d873da..067a0403a3 100644 --- a/api/src/backend/api/v1/views.py +++ b/api/src/backend/api/v1/views.py @@ -7484,14 +7484,17 @@ class FindingGroupViewSet(BaseRLSViewSet): def _get_latest_findings_per_provider(self, filtered_queryset): """Keep only findings from each provider's most recent completed scan.""" - latest_scan_ids = ( + # Materialize to a literal IN list. Left as a subquery, Postgres can't + # estimate the match count and picks a serial nested loop on + # resource_finding_mappings when one scan dominates findings + latest_scan_ids = list( Scan.objects.filter( tenant_id=self.request.tenant_id, state=StateChoices.COMPLETED, ) .order_by("provider_id", "-completed_at", "-inserted_at") .distinct("provider_id") - .values("id") + .values_list("id", flat=True) ) return filtered_queryset.filter(scan_id__in=latest_scan_ids)