:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(visual-review): make the flakiness overview reads index-only (#104442)
Julian Bez6c1ef4fca250
diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.pyindex 7bd6289835d5..03ecd5eaef0b 100644--- a/products/visual_review/backend/logic/flakiness.py+++ b/products/visual_review/backend/logic/flakiness.py@@ -214,21 +214,25 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:universe_identifiers = list({key.identifier for key in baseline_hash_by_key})universe_baseline_hashes = list(set(baseline_hash_by_key.values()))- # The window every rate, timestamp and strip tick is measured over. Joined- # on the run rather than passed as a list of run ids: an active repo lands- # hundreds of default-branch runs in a month, and the same predicate- # already serves the neighbouring queries here.+ # The window every rate, timestamp and strip tick is measured over, passed+ # to the activity reads as a list of run ids. A join on the run instead lets+ # the planner scan the whole snapshot table, which holds every repo's+ # history; anchored on run ids, the reads are index-only scans of+ # `snapshot_run_result_covering`, one range per run.strip_start = today - timedelta(days=FLAKINESS_WINDOW_DAYS - 1)rate_start = today - timedelta(days=FLAKINESS_RATE_DAYS - 1)- in_window = Q(- run__repo_id=repo_id,- run__branch__in=run_queries._DEFAULT_BRANCHES,- run__status=RunStatus.COMPLETED,- # Calendar days, matching the strip. A timestamp cutoff would reach into- # the day before the first tick, so `last_flaked_at` could name a day the- # strip does not draw.- run__created_at__date__gte=strip_start,+ window_run_ids = list(+ Run.objects.filter(+ repo_id=repo_id,+ branch__in=run_queries._DEFAULT_BRANCHES,+ status=RunStatus.COMPLETED,+ # Calendar days, matching the strip. A timestamp cutoff would reach into+ # the day before the first tick, so `last_flaked_at` could name a day the+ # strip does not draw.+ created_at__date__gte=strip_start,+ ).values_list("id", flat=True))+ in_window = Q(run_id__in=window_run_ids)# The rate denominator, per run type, over the same calendar days the# numerators are summed over. A timestamp cutoff here instead would cover@@ -237,13 +241,11 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:# reach the numerator. That deflates every rate, and late in the day it can# drop a snapshot failing every run below the `broken` band and mark a# quarantine decision-ready while its last failure is still inside the span.+ #+ # Counted from the captured run ids, so a run that completes between the two+ # reads cannot join the denominator without its rows joining the numerator.rate_runs_by_type: dict[str, int] = dict(- Run.objects.filter(- repo_id=repo_id,- branch__in=run_queries._DEFAULT_BRANCHES,- status=RunStatus.COMPLETED,- created_at__date__gte=rate_start,- )+ Run.objects.filter(id__in=window_run_ids, created_at__date__gte=rate_start).values("run_type").annotate(run_count=Count("id")).values_list("run_type", "run_count")@@ -542,7 +544,7 @@ def _read_activity(queryset.annotate(day=TruncDate("run__created_at")).values("run__run_type", "identifier", "day").annotate(- day_count=Count("id"),+ day_count=Count("*"),latest=Max("run__created_at"),worst_diff=Max("diff_percentage"),)diff --git a/products/visual_review/backend/migrations/0018_runsnapshot_snapshot_run_result_covering.py b/products/visual_review/backend/migrations/0018_runsnapshot_snapshot_run_result_covering.pynew file mode 100644index 000000000000..eb2555c435cc--- /dev/null+++ b/products/visual_review/backend/migrations/0018_runsnapshot_snapshot_run_result_covering.py@@ -0,0 +1,35 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently, SafeRemoveIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("visual_review", "0017_toleratedhash_tolerated_repo_created"),+ ]++ # The covering index keeps the same key as the index it replaces, so every query that used the+ # old one can use the new one. It is built before the old one is dropped.+ operations = [+ SafeAddIndexConcurrently(+ model_name="runsnapshot",+ index=models.Index(+ fields=["run", "result"],+ include=[+ "classification_reason",+ "review_state",+ "identifier",+ "diff_percentage",+ "tolerated_hash_match",+ "team_id",+ ],+ name="snapshot_run_result_covering",+ ),+ ),+ SafeRemoveIndexConcurrently(+ model_name="runsnapshot",+ name="snapshot_run_result",+ ),+ ]diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txtindex a156375b72ae..beb6ed480b2f 100644--- a/products/visual_review/backend/migrations/max_migration.txt+++ b/products/visual_review/backend/migrations/max_migration.txt@@ -1 +1 @@-0017_toleratedhash_tolerated_repo_created+0018_runsnapshot_snapshot_run_result_coveringdiff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.pyindex 3eeb52d927c3..37904e8b69ba 100644--- a/products/visual_review/backend/models.py+++ b/products/visual_review/backend/models.py@@ -292,7 +292,20 @@ class RunSnapshot(ProductTeamModel):models.UniqueConstraint(fields=["run", "identifier"], name="unique_snapshot_identifier_per_run"),]indexes = [- models.Index(fields=["run", "result"], name="snapshot_run_result"),+ # Covering, so the flakiness reads (a run's rows by result, filtered on reason, team and+ # identifier) are index-only scans instead of reads of the whole table.+ models.Index(+ fields=["run", "result"],+ include=[+ "classification_reason",+ "review_state",+ "identifier",+ "diff_percentage",+ "tolerated_hash_match",+ "team_id",+ ],+ name="snapshot_run_result_covering",+ ),models.Index(fields=["run", "review_state"], name="snapshot_run_review_state"),models.Index(fields=["identifier"], name="snapshot_identifier"),models.Index(fields=["current_hash"], name="snapshot_current_hash"),