: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
feat(signals): add a run budget for the background scout lane (#116339)
posthog[bot]81e74ae4a460
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 29c2048155af..fdad165bd259 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -99,6 +99,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eThe `background` block (`_parse_background` → `BackgroundEnrollment`: `enabled`, `skill_name`, `team_ids`, `interval_minutes`, `max_new_teams_per_tick`, `bands`) is the pilot cohort that runs one scout without a person asking. The coordinator creates one `managed_by=background` config per listed team whose organization approved AI data processing, seeding only that skill, and pauses a background config with `background_removed` when its team leaves the list. Background configs dispatch only through `_collect_background_runs`, which checks consent again, so the kill switch (`enabled: false`) and the consent check gate every background run. A malformed block parses to `None`, and the coordinator then does nothing, so a typo in `team_ids` cannot pause the whole cohort.`background.bands` samples a percentage of each activity band on top of the hand-picked `team_ids`. `background_bands.py` writes the bands once a day to `SignalScoutBackgroundBand` (the `refresh_signal_scout_background_bands` Celery task). Eligibility, the band rules, and the one fleet-wide ClickHouse read are in its module docstring. A project in band `n` is sampled when `background_sample_bucket(team_id) < bands[n].percent`. The bucket is a stable digest, so a higher percent keeps every project a lower one sampled. A sampled project gets its config through the same creation path and `max_new_teams_per_tick` cap, with the band's `interval_minutes`, and `SignalScoutConfig.background_band` records the band. A lower percent, a band at 0, or a project that leaves its band removes the team from the listed set, so the existing `background_removed` pause applies, and a `managed_by=team` config never pauses. A malformed band entry counts as 0 percent for that band alone. A hand-picked team keeps no band. The runner stamps `background_band` on the run metadata and on both lifecycle events, next to `managed_by`.`background.backoff` (`enabled`, `factor`, `max_interval_minutes`) slows down a background config that nobody engages with. `SignalScoutConfig.background_backoff_level` counts the runs in a row with no engagement, and the coordinator makes the config due at `min(run_interval_minutes × factor^level, max_interval_minutes)`, so `run_interval_minutes` keeps the nominal band cadence. The stamp moves the level when it dispatches a run: up by one when the previous dispatch created a `SignalScoutRun` and no member engaged since, and back to 0 when one did. A previous dispatch that the child skipped (quota, daily report limit, an active run) keeps the level. Planning reads the same engagement, so engagement makes a backed-off config due at the band interval at once. Engagement is a `SignalReportAction` row of any type or a person-attributed dismissal or log artefact on the team's reports, read for all due teams together (`_engaged_team_ids`). A login is not engagement. A config above level 0 is stamped at the tick start rather than at its slot anchor, because a slot on a changing period would dispatch it early. Without the block, nothing reads or moves the level, and a `managed_by=team` config never backs off. The runner stamps `background_backoff_level` and `background_effective_interval_minutes` next to `background_band`; both describe the cadence after the run.+ `background.budget` (`max_runs_per_day`, optional `max_runs_per_tick`) caps the background runs one region dispatches in a trailing 24h window. The coordinator counts the `SignalScoutRun` rows stamped with the background origin (`BACKGROUND_RUN_METADATA`), and each tick admits at most `min(max_runs_per_day - runs_last_24h, max_runs_per_tick)` due background runs, including breaker probes. Without `max_runs_per_tick`, the day spreads evenly across the ticks of one day. The order is never-run first, then backoff level 0, then most overdue, then band and config pk. The rest are not stamped, so they stay due for the next tick, and their backoff level does not move. `0` stops background dispatch and keeps every config as it is. A missing or malformed block means no lane budget. A `managed_by=team` config and a scout a person enabled never count against the budget. Each tick that runs the lane logs and captures `signals_scout_background_tick` with `due`, `dispatched`, `deferred`, `runs_last_24h`, `max_runs_per_day`, `never_run_due`, and `oldest_due_age_s`.Kept free of the temporalio stack so it stays cheap to import on the API path; both the coordinator and the metadata endpoint import from here so the reported caps never drift from what dispatch allows. `resolve_team_metadata()` backs the metadata viewset;`seed_config_layers_for_team()` lets the on-demand `sync` endpoint seed the same launch posture.- `derived_metadata.py`diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex e8f1ee9340f9..93719c86dfd9 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -10,6 +10,7 @@ path; both sides import from here so the reported caps never drift from what disfrom __future__ import annotationsimport json+import mathimport hashlibfrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass, field@@ -27,7 +28,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Teamfrom products.signals.backend.models import SignalScoutRun-from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM+from products.signals.backend.scout_harness.limits import COORDINATOR_INTERVAL_MINUTES, MAX_ENABLED_SCOUTS_PER_TEAMlogger = structlog.get_logger(__name__)@@ -262,6 +263,26 @@ class BackgroundBackoff:return current + 1+TICKS_PER_DAY = 24 * 60 // COORDINATOR_INTERVAL_MINUTES+++@dataclass(frozen=True)+class BackgroundBudget:+ """Parsed `background.budget`: the run budget of the whole background lane in one region.++ `max_runs_per_day` bounds the background runs dispatched in the trailing `DAILY_BUDGET_WINDOW`.+ `0` stops background dispatch and keeps every config as it is. `max_runs_per_tick` is `None`+ when unset, so the day spreads evenly across `TICKS_PER_DAY`.+ """++ max_runs_per_day: int+ max_runs_per_tick: int | None = None++ def tick_allowance(self, runs_last_24h: int) -> int:+ tick_cap = self.max_runs_per_tick or math.ceil(self.max_runs_per_day / TICKS_PER_DAY)+ return max(0, min(self.max_runs_per_day - runs_last_24h, tick_cap))++@dataclass(frozen=True)class BackgroundEnrollment:"""Parsed `background` block from the `signals-scout` flag payload.@@ -280,6 +301,8 @@ class BackgroundEnrollment:bands: Mapping[int, BackgroundBand] = field(default_factory=dict)# `None` turns the backoff off, so every background config runs at its band interval.backoff: BackgroundBackoff | None = None+ # `None` means no lane budget, so every due background run goes on to the shared tick caps.+ budget: BackgroundBudget | None = Nonedef band_interval_minutes(self, band: int | None) -> int | None:entry = self.bands.get(band) if band is not None else None@@ -292,6 +315,10 @@ def _positive_int_or_none(value: object) -> int | None:return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None+def _non_negative_int_or_none(value: object) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None++def _parse_background_bands(raw: object) -> dict[int, BackgroundBand]:"""Parse `background.bands`. A malformed entry drops out, so that band samples 0 percent.@@ -324,6 +351,21 @@ def _parse_background_backoff(raw: object) -> BackgroundBackoff | None:return BackgroundBackoff(factor=factor, max_interval_minutes=max_interval_minutes)+def _parse_background_budget(raw: object) -> BackgroundBudget | None:+ """Parse `background.budget`. A missing or malformed block means no lane budget.++ A malformed `max_runs_per_tick` alone falls back to the even spread and keeps the daily budget.+ """+ if not isinstance(raw, dict):+ return None+ max_runs_per_day = _non_negative_int_or_none(raw.get("max_runs_per_day"))+ if max_runs_per_day is None:+ return None+ return BackgroundBudget(+ max_runs_per_day=max_runs_per_day, max_runs_per_tick=_positive_int_or_none(raw.get("max_runs_per_tick"))+ )++def resolve_background_backoff() -> BackgroundBackoff | None:"""One flag-payload read of `background.backoff`, for callers outside the coordinator."""background = _parse_background(_read_flag_payload())@@ -380,8 +422,8 @@ def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:that is not a non-empty string, or a `team_ids` that is not a list of integer ids. A malformed`team_ids` must not read as an empty list, because an empty list pauses every backgroundconfig. `enabled` is on only for a literal `true`. An absent or malformed `interval_minutes`,- `max_new_teams_per_tick`, `bands` entry, or `backoff` falls back to its default and does not- invalidate the block.+ `max_new_teams_per_tick`, `bands` entry, `backoff`, or `budget` falls back to its default and does+ not invalidate the block."""if payload is None:return None@@ -408,6 +450,7 @@ def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:max_new_teams_per_tick=max_new if max_new is not None else DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,bands=_parse_background_bands(raw.get("bands")),backoff=_parse_background_backoff(raw.get("backoff")),+ budget=_parse_background_budget(raw.get("budget")),)diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 42b6fba364e9..80b29c0bf839 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -7,11 +7,13 @@ from dataclasses import dataclassfrom datetime import UTC, datetime, timedelta, tzinfofrom uuid import UUID+from django.conf import settingsfrom django.db import transactionfrom django.db.models import Case, DateTimeField, Max, PositiveSmallIntegerField, Q, Value, Whenfrom django.utils import timezoneimport structlog+import posthoganalyticsfrom croniter import CroniterError, croniterfrom temporalio import activity, workflowfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicy@@ -30,6 +32,7 @@ from products.signals.backend.models import (SignalScoutRun,)from products.signals.backend.report_check_execution import run_due_report_checks+from products.signals.backend.scout_authorship import BACKGROUND_RUN_METADATAfrom products.signals.backend.scout_harness.config_registry import (MAX_RUN_INTERVAL_MINUTES,MIN_RUN_INTERVAL_MINUTES,@@ -62,6 +65,7 @@ from products.signals.backend.scout_harness.limits import (from products.signals.backend.scout_harness.team_limits import (DAILY_BUDGET_WINDOW,BackgroundBackoff,+ BackgroundBudget,BackgroundEnrollment,Enrollment,_canonicalize_team_config_keys,@@ -102,6 +106,10 @@ MAX_RUNS_PER_TICK = 1000# size lanes off the cadence dispatch actually produces; it is imported above.TICK_SECONDS = COORDINATOR_INTERVAL_MINUTES * 60+# One event per region per tick that runs the background lane, to chart its backlog and time to first run.+BACKGROUND_TICK_EVENT = "signals_scout_background_tick"+BACKGROUND_TICK_DISTINCT_ID = "internal_signals_scout_coordinator"+@dataclassclass PlannedRun:@@ -479,6 +487,16 @@ class _DueRun:skill_name: str+@dataclass(frozen=True)+class _BackgroundDueRun:+ run: _DueRun+ never_run: bool+ backed_off: bool+ band: int | None+ # Seconds since the config became due. A never-run config counts from its creation.+ due_age_s: float++def _collect_planned_runs(enrollment: Enrollment,team_configs: dict[int, dict] | None = None,@@ -592,25 +610,113 @@ def _collect_planned_runs(team_count=skipped_without_consent,)+ background_due: list[_BackgroundDueRun] = []+ runs_last_24h: int | None = Noneif background is not None and background.enabled:- due.extend(_collect_background_runs(background, background_team_ids, team_configs, default_team_config, now))-- if not due:- return []+ background_due = _collect_background_runs(+ background, background_team_ids, team_configs, default_team_config, now+ )+ admitted = [d.run for d in background_due]+ if background.budget is not None and background_due:+ runs_last_24h = _background_runs_since(background, background_team_ids, now - DAILY_BUDGET_WINDOW)+ admitted = _apply_background_budget(background_due, background.budget, runs_last_24h)+ due.extend(admitted)- # Only count runs for teams that actually have a resolved daily budget — for the default- # rollout (no `max_runs_per_day` set anywhere) this skips the aggregate query entirely.- capped_team_ids = {- d.team_id for d in due if _resolve_max_runs_per_day(d.team_id, team_configs, default_team_config) is not None- }- runs_today = _runs_today_by_team(capped_team_ids, now - DAILY_BUDGET_WINDOW)- selected = _allocate_tick_budget(due, team_configs, default_team_config, runs_today, max_runs_per_tick)+ selected: list[_DueRun] = []+ if due:+ # Only count runs for teams that actually have a resolved daily budget — for the default+ # rollout (no `max_runs_per_day` set anywhere) this skips the aggregate query entirely.+ capped_team_ids = {+ d.team_id+ for d in due+ if _resolve_max_runs_per_day(d.team_id, team_configs, default_team_config) is not None+ }+ runs_today = _runs_today_by_team(capped_team_ids, now - DAILY_BUDGET_WINDOW)+ selected = _allocate_tick_budget(due, team_configs, default_team_config, runs_today, max_runs_per_tick)+ if background is not None and background.enabled:+ _capture_background_tick(background_due, selected, background.budget, runs_last_24h)planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in selected]# Stable order for predictable child-workflow ids within the tick.planned.sort(key=lambda p: (p.team_id, p.skill_name))return planned+def _background_runs_since(background: BackgroundEnrollment, listed_team_ids: set[int], since: datetime) -> int:+ """Background runs that started since `since` in this region, in one aggregate query.++ Counts the bridge rows stamped with the background origin, so a run still counts after a person+ takes its config over. The team and skill filters keep the read on the per-scout run index. A+ run dispatched this tick is not counted until its row lands; the tick allowance bounds that window.+ """+ if not listed_team_ids:+ return 0+ return SignalScoutRun.all_teams.filter(+ team_id__in=listed_team_ids,+ skill_name=background.skill_name,+ created_at__gte=since,+ metadata__contains=BACKGROUND_RUN_METADATA,+ ).count()+++def _apply_background_budget(+ background_due: list[_BackgroundDueRun], budget: BackgroundBudget, runs_last_24h: int+) -> list[_DueRun]:+ """The due background runs the lane budget admits this tick, highest priority first.++ Coverage before cadence (never run first), then engaged before backed off, then most overdue,+ with band and config pk as deterministic tiebreaks.++ The rest stay unstamped, so they are still due next tick: the deferred runs are the queue, and+ nothing new is stored. A deferred config keeps its backoff level, because only a stamp moves it.+ """+ allowance = budget.tick_allowance(runs_last_24h)+ ordered = sorted(+ background_due,+ key=lambda d: (not d.never_run, d.backed_off, -d.run.overdue_s, d.band or 0, d.run.config_pk),+ )+ if len(ordered) > allowance:+ logger.info(+ "signals_scout coordinator: background budget defers due runs",+ due=len(ordered),+ allowance=allowance,+ runs_last_24h=runs_last_24h,+ max_runs_per_day=budget.max_runs_per_day,+ )+ return [d.run for d in ordered[:allowance]]+++def _capture_background_tick(+ background_due: list[_BackgroundDueRun],+ selected: list[_DueRun],+ budget: BackgroundBudget | None,+ runs_last_24h: int | None,+) -> None:+ """Log and capture the backlog of the background lane for this tick.++ `dispatched` counts the background runs that also pass the shared tick caps, so `due`,+ `dispatched`, and `deferred` always add up.+ """+ selected_pks = {d.config_pk for d in selected}+ dispatched = sum(1 for d in background_due if d.run.config_pk in selected_pks)+ properties = {+ "region": settings.CLOUD_DEPLOYMENT,+ "due": len(background_due),+ "dispatched": dispatched,+ "deferred": len(background_due) - dispatched,+ "runs_last_24h": runs_last_24h,+ "max_runs_per_day": budget.max_runs_per_day if budget is not None else None,+ "never_run_due": sum(1 for d in background_due if d.never_run),+ "oldest_due_age_s": max((d.due_age_s for d in background_due), default=0.0),+ }+ logger.info("signals_scout coordinator: background tick", **properties)+ try:+ posthoganalytics.capture(+ event=BACKGROUND_TICK_EVENT, distinct_id=BACKGROUND_TICK_DISTINCT_ID, properties=properties+ )+ except Exception:+ logger.warning("signals_scout coordinator: failed to capture background tick event")++def _allocate_tick_budget(due: list[_DueRun],team_configs: dict[int, dict] | None = None,@@ -1065,7 +1171,7 @@ def _collect_background_runs(team_configs: dict[int, dict],default_team_config: dict,now: datetime,-) -> list[_DueRun]:+) -> list[_BackgroundDueRun]:"""Due runs for background configs on listed teams whose organization approved AI data processing.Checks consent again at dispatch, because an organization can withdraw it after its config was@@ -1094,7 +1200,7 @@ def _collect_background_runs(team_id__in=listed_team_ids, name=background.skill_name, is_latest=True, deleted=False).values_list("team_id", flat=True))- due: list[_DueRun] = []+ due: list[_BackgroundDueRun] = []live_skills = {background.skill_name}engaged = (_engaged_team_ids(@@ -1112,17 +1218,28 @@ def _collect_background_runs(continueif background.skill_name in _resolve_withheld_skills(config.team_id, team_configs, default_team_config):continue+ backoff = background.backoff if config.team_id not in engaged else None+ never_run = config.last_run_at is Noneif not config.enabled:- due.extend(_collect_probe_runs([config], live_skills, now))- continue- interval_minutes = None- if background.backoff is not None and config.team_id not in engaged:- interval_minutes = background.backoff.effective_interval_minutes(- config.run_interval_minutes, config.background_backoff_level+ runs = _collect_probe_runs([config], live_skills, now)+ else:+ interval_minutes = None+ if backoff is not None:+ interval_minutes = backoff.effective_interval_minutes(+ config.run_interval_minutes, config.background_backoff_level+ )+ overdue_s = _overdue_seconds(config, now, config.team.timezone_info, interval_minutes=interval_minutes)+ runs = [] if overdue_s is None else [_DueRun(overdue_s, str(config.pk), config.team_id, config.skill_name)]+ for run in runs:+ due.append(+ _BackgroundDueRun(+ run=run,+ never_run=never_run,+ backed_off=backoff is not None and bool(config.background_backoff_level),+ band=config.background_band,+ due_age_s=(now - config.created_at).total_seconds() if never_run else max(0.0, run.overdue_s),+ ))- overdue_s = _overdue_seconds(config, now, config.team.timezone_info, interval_minutes=interval_minutes)- if overdue_s is not None:- due.append(_DueRun(overdue_s, str(config.pk), config.team_id, config.skill_name))return duediff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex c653ac9f5fdc..be8a59ad49b4 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -49,6 +49,7 @@ from products.signals.backend.scout_harness.team_limits import (SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,BackgroundBackoff,BackgroundBand,+ BackgroundBudget,BackgroundEnrollment,Enrollment,_default_team_config,@@ -722,12 +723,59 @@ _GENERAL = "signals-scout-general"{"background": {"enabled": True, "team_ids": [3], "backoff": {"enabled": True, "factor": 1}}},BackgroundEnrollment(True, _GENERAL, frozenset({3}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),),+ (+ {"background": {"enabled": True, "team_ids": [3], "budget": {"max_runs_per_day": 0}}},+ BackgroundEnrollment(+ True,+ _GENERAL,+ frozenset({3}),+ None,+ DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,+ budget=BackgroundBudget(max_runs_per_day=0),+ ),+ ),+ (+ {+ "background": {+ "enabled": True,+ "team_ids": [3],+ "budget": {"max_runs_per_day": 2000, "max_runs_per_tick": "100"},+ }+ },+ BackgroundEnrollment(+ True,+ _GENERAL,+ frozenset({3}),+ None,+ DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,+ budget=BackgroundBudget(max_runs_per_day=2000),+ ),+ ),+ (+ # A malformed budget means no lane budget and never costs the block its `team_ids`.+ {"background": {"enabled": True, "team_ids": [3], "budget": {"max_runs_per_day": -1}}},+ BackgroundEnrollment(True, _GENERAL, frozenset({3}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),+ ),],)def test_parse_background(payload, expected):assert _parse_background(payload) == expected+ "budget,runs_last_24h,expected",+ [+ (BackgroundBudget(max_runs_per_day=2000), 0, 42), # the day spreads over 48 ticks+ (BackgroundBudget(max_runs_per_day=2000, max_runs_per_tick=100), 0, 100),+ (BackgroundBudget(max_runs_per_day=2000, max_runs_per_tick=100), 1950, 50),+ (BackgroundBudget(max_runs_per_day=2000, max_runs_per_tick=100), 2100, 0),+ (BackgroundBudget(max_runs_per_day=0, max_runs_per_tick=100), 0, 0),+ ],+)+def test_background_budget_tick_allowance(budget, runs_last_24h, expected):+ assert budget.tick_allowance(runs_last_24h) == expected++def _background(team_ids: set[int],*,@@ -735,8 +783,9 @@ def _background(max_new: int = 5,bands: dict[int, BackgroundBand] | None = None,backoff: BackgroundBackoff | None = None,+ budget: BackgroundBudget | None = None,) -> BackgroundEnrollment:- return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new, bands or {}, backoff)+ return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new, bands or {}, backoff, budget)_WEEK_MINUTES = 7 * 24 * 60@@ -891,7 +940,7 @@ class TestBackgroundEnrollment:self._record_run(team, config, at + timedelta(minutes=1))return dispatched- def _record_run(self, team: Team, config: SignalScoutConfig, at: datetime) -> None:+ def _record_run(self, team: Team, config: SignalScoutConfig, at: datetime, metadata: dict | None = None) -> None:with time_machine.travel(at, tick=False):task = Task.objects.create(team=team,@@ -905,7 +954,68 @@ class TestBackgroundEnrollment:scout_config=config,skill_name=_GENERAL,skill_version=1,+ metadata=metadata or {},+ )++ @parameterized.expand(+ [+ ("absent", None, [True, True, True]),+ ("partly_spent", BackgroundBudget(max_runs_per_day=4, max_runs_per_tick=10), [True, True, False]),+ ("exhausted", BackgroundBudget(max_runs_per_day=2, max_runs_per_tick=10), [False, False, False]),+ ]+ )+ def test_lane_budget_defers_in_priority_order(self, _name, budget, expected):+ at = datetime(2026, 3, 2, tzinfo=UTC)+ with time_machine.travel(at, tick=False):+ never_run_team, engaged_team, backed_off_team, person_team = (self._team() for _ in range(4))+ never_run = self._weekly_background_config(never_run_team)+ # Less overdue than the backed-off config, but level 0 dispatches first.+ self._weekly_background_config(engaged_team, last_run_at=at - timedelta(days=8))+ backed_off = self._weekly_background_config(+ backed_off_team, last_run_at=at - timedelta(days=60), background_backoff_level=2)+ with team_scope(person_team.id, canonical=True):+ _create_skill(person_team, "signals-scout-errors")+ _create_config(person_team, "signals-scout-errors")+ for hours_ago, metadata in (+ (1, {"managed_by": "background"}),+ (2, {"managed_by": "background"}),+ (3, {}),+ (25, {"managed_by": "background"}),+ ):+ self._record_run(backed_off_team, backed_off, at - timedelta(hours=hours_ago), metadata)+ self._record_run(never_run_team, never_run, at - timedelta(hours=1), {})+ background = _background(+ {never_run_team.id, engaged_team.id, backed_off_team.id}, backoff=_BACKOFF, budget=budget+ )++ with (+ time_machine.travel(at, tick=False),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator.register_missing_configs",+ return_value={"signals-scout-errors"},+ ),+ patch("products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.capture") as capture,+ ):+ planned = _collect_planned_runs(+ Enrollment(wildcard=False, explicit={person_team.id}, skip=set()), background=background+ )++ assert [+ PlannedRun(team_id=team.id, skill_name=_GENERAL) in planned+ for team in (never_run_team, engaged_team, backed_off_team)+ ] == expected+ assert PlannedRun(team_id=person_team.id, skill_name="signals-scout-errors") in planned+ properties = capture.call_args.kwargs["properties"]+ assert {+ key: properties[key] for key in ("due", "dispatched", "deferred", "runs_last_24h", "never_run_due")+ } == {+ "due": 3,+ "dispatched": sum(expected),+ "deferred": 3 - sum(expected),+ "runs_last_24h": None if budget is None else 2,+ "never_run_due": 1,+ }@parameterized.expand([