Skip to content

: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.

perf(signals): read scout runs first in the dispatch guard and reap (#118326)

posthog[bot]b344128a899d
diff --git a/products/signals/backend/scout_harness/run_gates.py b/products/signals/backend/scout_harness/run_gates.py
index 7a1ff9cf7cf2..e4c9932d5c85 100644
--- a/products/signals/backend/scout_harness/run_gates.py
+++ b/products/signals/backend/scout_harness/run_gates.py
@@ -16,6 +16,7 @@ from __future__ import annotations
from datetime import timedelta
from enum import Enum
+from django.db.models import QuerySet
from django.utils import timezone
from posthog.dataclasses import frozen
@@ -136,6 +137,25 @@ def check_spend_gates(team: Team, *, capture_analytics: bool = True) -> ScoutRun
return None
+def lane_has_live_run(lane_runs: QuerySet[SignalScoutRun]) -> bool:
+ """Return whether one of `lane_runs` has a QUEUED or IN_PROGRESS TaskRun newer than `STALE_RUN_CUTOFF_S`.
+
+ The read has two steps on purpose. As one join, the planner can start from `posthog_task_run`
+ and read many task runs of other products to find the few that belong to this lane. The first
+ step reads only the lane's runs inside the cutoff from `signal_scout_run_recent_idx`. The
+ second step joins those few runs to their TaskRuns by primary key.
+ """
+ live_cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
+ recent_run_ids = list(lane_runs.filter(created_at__gte=live_cutoff).values_list("id", flat=True))
+ if not recent_run_ids:
+ return False
+ return lane_runs.filter(
+ id__in=recent_run_ids,
+ task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
+ task_run__created_at__gte=live_cutoff,
+ ).exists()
+
+
def check_run_in_flight(team_id: int, skill_name: str) -> ScoutRunRejection | None:
"""Reject when a *live* run for this `(canonical team, skill)` is already QUEUED or IN_PROGRESS.
@@ -148,22 +168,10 @@ def check_run_in_flight(team_id: int, skill_name: str) -> ScoutRunRejection | No
`_self_heal_stale_runs` reap can clear it, wedging the lane until a scheduled tick happens to
reap it — which never comes for a disabled scout, whose only run path is a trigger.
"""
- live_cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
- in_flight = (
- SignalScoutRun.objects.for_team(team_id)
- .filter(
- skill_name=skill_name,
- # Floors the range scan on signal_scout_run_recent_idx (team, skill_name, -created_at)
- # instead of the scout's whole unpruned history. Same result set as the task_run floor
- # below, since the scout row is written only after its TaskRun exists.
- created_at__gte=live_cutoff,
- task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
- task_run__created_at__gte=live_cutoff,
- )
- .exclude(metadata__has_key="scout_trial")
- .exists()
+ lane_runs = (
+ SignalScoutRun.objects.for_team(team_id).filter(skill_name=skill_name).exclude(metadata__has_key="scout_trial")
)
- if not in_flight:
+ if not lane_has_live_run(lane_runs):
return None
return ScoutRunRejection(
kind=ScoutRunRejectionKind.CONFLICT,
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index e6dd48a0d958..992a411d19fe 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -56,6 +56,7 @@ from products.signals.backend.scout_harness.prompt import (
SignalScoutRunSummary,
build_run_prompt,
)
+from products.signals.backend.scout_harness.run_gates import lane_has_live_run
from products.signals.backend.scout_harness.skill_loader import (
SIGNALS_SCOUT_SKILL_PREFIX,
LoadedSkill,
@@ -1168,21 +1169,13 @@ def _has_running_run(*, team_id: int, skill_name: str) -> bool:
# mid-run would orphan the FK and silently defeat the dedupe in exactly the
# config-churn case it should still cover.
# A run older than `STALE_RUN_CUTOFF_S` is an orphan that `_self_heal_stale_runs` reaps just
- # before this check, so it does not count. The floor also keeps the read to a range scan of
- # `signal_scout_run_recent_idx` instead of the lane's whole history.
- live_cutoff = timezone.now() - timedelta(seconds=STALE_RUN_CUTOFF_S)
- return (
+ # before this check, so it does not count.
+ lane_runs = (
SignalScoutRun.objects.unscoped()
- .filter(
- team_id=team_id,
- skill_name=skill_name,
- created_at__gte=live_cutoff,
- task_run__status__in=(tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS),
- task_run__created_at__gte=live_cutoff,
- )
+ .filter(team_id=team_id, skill_name=skill_name)
.exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
- .exists()
)
+ return lane_has_live_run(lane_runs)
def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
@@ -1215,22 +1208,25 @@ def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
now = timezone.now()
cutoff = now - timedelta(seconds=STALE_RUN_CUTOFF_S)
active_statuses = (tasks_facade.TaskRunStatus.QUEUED, tasks_facade.TaskRunStatus.IN_PROGRESS)
- recent_run_ids = (
+ # Read the IDs before the join, not as a subquery, so the join starts from these few runs and not
+ # from `posthog_task_run`.
+ recent_run_ids = list(
SignalScoutRun.objects.unscoped()
.filter(team_id=team_id, skill_name=skill_name)
.exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
.order_by("-created_at")
- .values("id")[:ORPHAN_RECENT_RUNS]
+ .values_list("id", flat=True)[:ORPHAN_RECENT_RUNS]
)
+ if not recent_run_ids:
+ return
closed_by_inactivity = Q(
task_run__status__in=(tasks_facade.TaskRunStatus.COMPLETED, tasks_facade.TaskRunStatus.FAILED),
**{f"task_run__state__{tasks_facade.TIMED_OUT_INACTIVITY_STATE_KEY}": True},
)
stale_runs = list(
SignalScoutRun.objects.unscoped()
- .filter(team_id=team_id, skill_name=skill_name, id__in=recent_run_ids, task_run__created_at__lt=cutoff)
+ .filter(team_id=team_id, id__in=recent_run_ids, task_run__created_at__lt=cutoff)
.filter(Q(task_run__status__in=active_statuses) | closed_by_inactivity)
- .exclude(metadata__has_key=SCOUT_TRIAL_METADATA_KEY)
.exclude(metadata__has_key=SCOUT_RUN_REAPED_METADATA_KEY)
.select_related("task_run")
)