perf: eliminate source health N plus one queries

This commit is contained in:
Jens
2026-07-22 20:37:01 +02:00
parent ee915742bf
commit 5f435d030e
2 changed files with 28 additions and 3 deletions
+9 -3
View File
@@ -4,6 +4,7 @@ from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime, timedelta
from django.db.models import Prefetch
from django.utils import timezone
from apps.sources.models import Source, SourcePolicyReview, SourceRun
@@ -214,12 +215,17 @@ def _determine_health_action(runs: list[SourceRun]) -> tuple[str | None, str | N
def collect_source_health(
*, runs_to_consider: int = SOURCE_HEALTH_RUN_WINDOW
) -> list[SourceHealth]:
sources = Source.objects.order_by("name").all()
sources = Source.objects.prefetch_related(
Prefetch(
"runs",
queryset=SourceRun.objects.order_by("-started_at")[:runs_to_consider],
to_attr="health_runs",
)
).order_by("name")
rows: list[SourceHealth] = []
for source in sources:
run_queryset = SourceRun.objects.filter(source=source).order_by("-started_at")
runs = list(run_queryset[:runs_to_consider])
runs = source.health_runs
monitored_runs = len(runs)
success_runs = [run for run in runs if run.status == SourceRun.Status.SUCCESS]