diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py index a611d873dae..067a0403a3b 100644 --- a/api/src/backend/api/v1/views.py +++ b/api/src/backend/api/v1/views.py @@ -7484,14 +7484,17 @@ def _split_computed_aggregate_filters( 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)