: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 per-team guardrails for scout configs and dispatch (#63309)
Andrew Maguire3be9dd06ad06
diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex 7d7fde3b3e24..264daa2e504a 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -9,18 +9,40 @@ goes through the write-scoped config `create` endpoint.from __future__ import annotations+import structlog+from products.ai_observability.backend.models.skills import LLMSkillfrom products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+logger = structlog.get_logger(__name__)+++def enabled_scout_count(team_id: int, *, exclude_skill: str | None = None) -> int:+ """Count of enabled scout configs for the team — the quantity the per-team cap bounds.++ `exclude_skill` leaves one skill's own row out of the count, so re-asserting+ `enabled=True` on an already-enabled scout doesn't read as exceeding the cap.+ """+ queryset = SignalScoutConfig.objects.for_team(team_id).filter(enabled=True)+ if exclude_skill is not None:+ queryset = queryset.exclude(skill_name=exclude_skill)+ return queryset.count()+def register_missing_configs(team_id: int) -> set[str]:- """Auto-create an enabled, default-schedule config for each scout skill lacking a row.+ """Auto-create a default-schedule config for each scout skill lacking a row.Idempotent — `get_or_create` keyed on the `(team, skill_name)` unique constraint, soconcurrent callers (coordinator tick racing an API call) converge on one row. Returnsthe set of live `signals-scout-*` skill names for the team, so the caller can skipdispatching configs whose skill is gone.++ New rows default to enabled until the team hits `MAX_ENABLED_SCOUTS_PER_TEAM`; past+ the cap they register disabled, so the scout is still visible and tunable but never+ silently adds spend. The check is best-effort (count + create, no lock) — a race can+ briefly overshoot by one, which the coordinator's per-tick caps still bound."""skill_names = set(LLMSkill.objects.filter(@@ -32,8 +54,27 @@ def register_missing_configs(team_id: int) -> set[str]:)configs = SignalScoutConfig.objects.for_team(team_id)existing = set(configs.values_list("skill_name", flat=True))- for name in sorted(skill_names - existing):+ missing = sorted(skill_names - existing)+ if not missing:+ return skill_names++ enabled = enabled_scout_count(team_id)+ for name in missing:+ at_cap = enabled >= MAX_ENABLED_SCOUTS_PER_TEAM# `team_id` must be passed as a kwarg: `get_or_create` builds the created row from# kwargs/defaults only — the queryset's team filter does not propagate into `create`.- configs.get_or_create(team_id=team_id, skill_name=name)+ _, created = configs.get_or_create(+ team_id=team_id,+ skill_name=name,+ defaults={"enabled": False} if at_cap else {},+ )+ if created and at_cap:+ logger.info(+ "signals_scout: enabled-scout cap reached, auto-registered config disabled",+ team_id=team_id,+ skill_name=name,+ cap=MAX_ENABLED_SCOUTS_PER_TEAM,+ )+ elif created:+ enabled += 1return skill_namesdiff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.pyindex d15b1ba6701c..72aa7f8a48c4 100644--- a/products/signals/backend/scout_harness/limits.py+++ b/products/signals/backend/scout_harness/limits.py@@ -16,3 +16,11 @@ ACTIVITY_SLACK_S = 60# providing a heartbeat window before Temporal's own timeout fires. The stale-RUNNING# self-heal in `runner.py` uses this as the staleness base.WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S++# Per-team ceiling on ENABLED scout configs — the per-team cost cap. Each enabled scout+# is a recurring LLM sandbox run, so this bounds what one team can switch on. Set high so+# teams can freely author scouts with minimal friction; it's a backstop against runaway+# spend, not a routine limit (the canonical fleet is ~16 scouts). Enforced at the write+# surfaces (config create/update) and in auto-registration, which falls back to registering+# new scouts disabled once the team is at the cap.+MAX_ENABLED_SCOUTS_PER_TEAM = 100diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 9feeb3234923..15af9fa189c0 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -42,6 +42,8 @@ from posthog.permissions import APIScopePermissionfrom products.ai_observability.backend.models.skills import LLMSkillfrom products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutEmission, SignalScoutRun+from products.signals.backend.scout_harness.config_registry import enabled_scout_count+from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.signals.backend.scout_harness.serializers import (EmitFindingRequestSerializer,EmitFindingResponseSerializer,@@ -571,6 +573,25 @@ class SignalProjectProfileViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSereturn Response(ProjectProfileSerializer(profile.as_dict()).data)+def _reject_if_enabled_cap_reached(team_id: int, skill_name: str) -> None:+ """Raise when enabling this scout would push the team past the per-team enabled cap.++ Counts every enabled config except this skill's own row, so re-asserting+ `enabled=True` on an already-enabled scout is always allowed. Best-effort+ (count + write, no lock): a concurrent enable can overshoot by one, which the+ coordinator's per-tick caps still bound.+ """+ if enabled_scout_count(team_id, exclude_skill=skill_name) >= MAX_ENABLED_SCOUTS_PER_TEAM:+ raise exceptions.ValidationError(+ {+ "enabled": (+ f"This project already has {MAX_ENABLED_SCOUTS_PER_TEAM} enabled scouts (the maximum). "+ "Disable one before enabling another."+ )+ }+ )++def _skill_descriptions_for(team_id: int, skill_names: list[str]) -> dict[str, str]:"""Map each scout `skill_name` to the latest `LLMSkill.description` on the team.@@ -639,7 +660,10 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):description="A config already existed for this skill; the provided fields were applied to it.",),400: OpenApiResponse(- description="No such skill on this project, or the name lacks the `signals-scout-` prefix."+ description=(+ "No such skill on this project, the name lacks the `signals-scout-` prefix, "+ "or the project is already at its enabled-scouts maximum."+ )),},summary="Create a scout config",@@ -662,6 +686,17 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):{"skill_name": "No skill with this name exists on this project. Author the skill first."})tunables = {key: value for key, value in serializer.validated_data.items() if key != "skill_name"}+ # The per-team cap only gates net-new enables: a fresh row defaulting (or set) to+ # enabled, or an upsert flipping a disabled row on. Tuning an already-enabled scout+ # stays exempt via the exclude-self count.+ existing = SignalScoutConfig.objects.for_team(team_id).filter(skill_name=skill_name).first()+ will_enable = (+ tunables.get("enabled", True)+ if existing is None+ else (not existing.enabled and tunables.get("enabled") is True)+ )+ if will_enable:+ _reject_if_enabled_cap_reached(team_id, skill_name)# `team_id` stays in the kwargs: `get_or_create` builds the created row from# kwargs/defaults only — the queryset's team filter does not propagate into `create`.config, created = SignalScoutConfig.objects.for_team(team_id).get_or_create(@@ -693,6 +728,9 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):request=SignalScoutConfigSerializer,responses={200: OpenApiResponse(response=SignalScoutConfigSerializer, description="Updated config."),+ 400: OpenApiResponse(+ description="Invalid fields, or enabling would exceed the project's enabled-scouts maximum."+ ),404: OpenApiResponse(description="Config not found for this project."),},summary="Update a scout config",@@ -711,9 +749,12 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):raise exceptions.NotFound()serializer = SignalScoutConfigSerializer(config, data=request.data, partial=True)serializer.is_valid(raise_exception=True)+ enabling = not config.enabled and serializer.validated_data.get("enabled")+ if enabling:+ _reject_if_enabled_cap_reached(team_id, config.skill_name)# Fold `enabled_by` into the same save so enabling logs one activity entry, not two.save_kwargs = {}- if not config.enabled and serializer.validated_data.get("enabled"):+ if enabling:save_kwargs["enabled_by"] = request.userinstance = serializer.save(**save_kwargs)descriptions = _skill_descriptions_for(team_id, [instance.skill_name])diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex aa59cce38163..86b8fbf12713 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -42,7 +42,16 @@ DEFAULT_ENROLLED_TEAM_IDS: list[int] = [1, 2, 148051]# Hard cap on dispatches per tick. The cost bound: when more scouts are due than this,# we run the most-overdue first and the rest catch up next tick (a poor-man's queue).-MAX_RUNS_PER_TICK = 50+# Set generously for now while scouts roll out to more teams — the per-team tick cap and+# round-robin allocation do the day-to-day fairness work; this is the global ceiling.+MAX_RUNS_PER_TICK = 1000++# Per-team slice of the tick budget. Bounds what one team can consume per tick (and thus+# per day: cap × ticks/day), so a team registering many scouts degrades its own cadence,+# not everyone else's. Sized well above the canonical fleet (~16 scouts) so a fully-enrolled+# team is never trimmed; round-robin allocation still keeps any one team from starving the+# others even when this is close to the global cap.+MAX_RUNS_PER_TEAM_PER_TICK = 50# Coordinator tick cadence. Per-scout schedules are enforced via the due-check, so this is# just the polling granularity — the floor on how often any scout can run.@@ -184,21 +193,60 @@ def _collect_planned_runs(enrolled_team_ids: set[int]) -> list[PlannedRun]:if not due:return []- # Cost bound: when more scouts are due than the cap, run the most-overdue first and let- # the rest catch up next tick. Deterministic — no sampling.- due.sort(key=lambda d: d.overdue_s, reverse=True)- if len(due) > MAX_RUNS_PER_TICK:+ selected = _allocate_tick_budget(due)+ 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 _allocate_tick_budget(due: list[_DueRun]) -> list[_DueRun]:+ """Apply the per-team and global tick caps fairly. Deterministic — no sampling.++ Each team's due runs are ordered most-overdue-first and trimmed to+ `MAX_RUNS_PER_TEAM_PER_TICK`; the global `MAX_RUNS_PER_TICK` budget is then filled+ round-robin across teams (one run per team per round) so a single team with many due+ scouts can't monopolize the tick. Deferred runs stay unstamped, so they're the most+ overdue next tick — a poor-man's queue, same catch-up semantics as before.+ """+ by_team: dict[int, list[_DueRun]] = {}+ for d in due:+ by_team.setdefault(d.team_id, []).append(d)+ for team_id, runs in by_team.items():+ runs.sort(key=lambda d: (-d.overdue_s, d.skill_name))+ if len(runs) > MAX_RUNS_PER_TEAM_PER_TICK:+ logger.warning(+ "signals_scout coordinator: team over per-tick cap, deferring overflow",+ team_id=team_id,+ due=len(runs),+ cap=MAX_RUNS_PER_TEAM_PER_TICK,+ )+ del runs[MAX_RUNS_PER_TEAM_PER_TICK:]++ # Count after per-team trimming — that's the real candidate pool the global cap defers+ # against, so the warning doesn't fire on runs already dropped by the per-team caps.+ total_after_team_caps = sum(len(runs) for runs in by_team.values())+ if total_after_team_caps > MAX_RUNS_PER_TICK:logger.warning("signals_scout coordinator: more due than cap, deferring overflow",- due=len(due),+ due=total_after_team_caps,cap=MAX_RUNS_PER_TICK,)- due = due[:MAX_RUNS_PER_TICK]- planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in due]- # Stable order for predictable child-workflow ids within the tick.- planned.sort(key=lambda p: (p.team_id, p.skill_name))- return planned+ # Most-overdue team first, team id as the deterministic tiebreak.+ team_order = sorted(by_team, key=lambda t: (-by_team[t][0].overdue_s, t))+ selected: list[_DueRun] = []+ for round_idx in range(MAX_RUNS_PER_TEAM_PER_TICK):+ if len(selected) >= MAX_RUNS_PER_TICK:+ break+ for team_id in team_order:+ runs = by_team[team_id]+ if round_idx >= len(runs):+ continue+ selected.append(runs[round_idx])+ if len(selected) >= MAX_RUNS_PER_TICK:+ break+ return selecteddef _participating_teams(enrolled: set[int]) -> list[Team]:diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex 923e46f110e5..47a1ebd318e7 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -379,6 +379,74 @@ async def test_cap_dispatches_most_overdue_first(ateam):assert sorted(p.skill_name for p in planned) == ["signals-scout-mid", "signals-scout-most"]+async def test_per_team_tick_cap_defers_overflow(ateam):+ now = timezone.now()+ for name, hours in [("signals-scout-most", 10), ("signals-scout-mid", 5), ("signals-scout-least", 2)]:+ await database_sync_to_async(_create_skill)(ateam, name)+ await database_sync_to_async(_create_config)(+ ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)+ )++ with patch("products.signals.backend.temporal.agentic.scout_coordinator.MAX_RUNS_PER_TEAM_PER_TICK", 2):+ planned = await _run_activity()++ assert sorted(p.skill_name for p in planned) == ["signals-scout-mid", "signals-scout-most"]+++async def test_global_cap_is_split_fairly_across_teams(ateam, aother_team):+ # Team A has three due scouts, all more overdue than team B's two. With the global cap+ # at 3, pure most-overdue-first would hand A the whole tick; round-robin must give B a+ # slot in the first round.+ now = timezone.now()+ for name, hours in [("signals-scout-a1", 30), ("signals-scout-a2", 20), ("signals-scout-a3", 10)]:+ await database_sync_to_async(_create_skill)(ateam, name)+ await database_sync_to_async(_create_config)(+ ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)+ )++ def _seed_other():+ with team_scope(aother_team.id, canonical=True):+ for name, hours in [("signals-scout-b1", 5), ("signals-scout-b2", 4)]:+ _create_skill(aother_team, name)+ _create_config(+ aother_team, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)+ )++ await database_sync_to_async(_seed_other)()++ with patch("products.signals.backend.temporal.agentic.scout_coordinator.MAX_RUNS_PER_TICK", 3):+ planned = await _run_activity()++ assert sorted((p.team_id, p.skill_name) for p in planned) == [+ (ateam.id, "signals-scout-a1"),+ (ateam.id, "signals-scout-a2"),+ (aother_team.id, "signals-scout-b1"),+ ]+++async def test_auto_register_past_enabled_cap_creates_disabled_config(ateam):+ # One enabled scout puts the team at the (patched) cap; a freshly authored skill must+ # still get a config row — but disabled, so it adds no spend and isn't planned.+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-existing")+ await database_sync_to_async(_create_config)(ateam, "signals-scout-existing", enabled=True)+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-fresh")++ with patch("products.signals.backend.scout_harness.config_registry.MAX_ENABLED_SCOUTS_PER_TEAM", 1):+ planned = await _run_activity()++ fresh = await database_sync_to_async(+ lambda: SignalScoutConfig.all_teams.get(team_id=ateam.id, skill_name="signals-scout-fresh")+ )()+ assert fresh.enabled is False+ assert sorted(p.skill_name for p in planned) == ["signals-scout-existing"]++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_planned_runs_sorted_by_team_then_skill(ateam, aother_team):diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 4a2c2dd3ce35..b0a973e9fec4 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -790,6 +790,66 @@ class TestScoutHarnessConfigAPI(APIBaseTest):assert config.emit is Trueassert config.run_interval_minutes == 120+ _CAP_PATCH = "products.signals.backend.scout_harness.views.MAX_ENABLED_SCOUTS_PER_TEAM"++ def test_create_disabled_config_is_allowed_at_team_cap(self) -> None:+ self._make_skill("signals-scout-first")+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)+ self._make_skill("signals-scout-second")++ with patch(self._CAP_PATCH, 1):+ response = self.client.post(+ self._list_url(), data={"skill_name": "signals-scout-second", "enabled": False}, format="json"+ )++ assert response.status_code == status.HTTP_201_CREATED+ config = SignalScoutConfig.objects.get(team=self.team, skill_name="signals-scout-second")+ assert config.enabled is False++ @parameterized.expand(["create", "partial_update"])+ def test_enable_past_team_cap_is_rejected(self, surface: str) -> None:+ # Both write surfaces enforce the same cap: with one enabled scout filling the+ # (patched) cap, flipping a second scout on must 400 and leave it disabled.+ self._make_skill("signals-scout-first")+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)+ self._make_skill("signals-scout-second")+ second = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-second", enabled=False)++ with patch(self._CAP_PATCH, 1):+ if surface == "create":+ response = self.client.post(+ self._list_url(), data={"skill_name": "signals-scout-second", "enabled": True}, format="json"+ )+ else:+ response = self.client.patch(self._detail_url(str(second.id)), data={"enabled": True}, format="json")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "enabled scouts" in response.json()["detail"]+ second.refresh_from_db()+ assert second.enabled is False++ @parameterized.expand(+ [+ # Re-asserting `enabled=True` on the already-enabled scout: it's excluded from+ # its own cap count, so the upsert must not read as exceeding the cap.+ ("create_reassert_enabled", "create", {"skill_name": "signals-scout-first", "enabled": True}),+ # Tuning a field on an already-enabled scout isn't a net-new enable, so the cap+ # check is skipped entirely.+ ("partial_update_tune", "partial_update", {"run_interval_minutes": 120}),+ ]+ )+ def test_tuning_enabled_scout_is_allowed_at_team_cap(self, _name: str, surface: str, data: dict) -> None:+ self._make_skill("signals-scout-first")+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)++ with patch(self._CAP_PATCH, 1):+ if surface == "create":+ response = self.client.post(self._list_url(), data=data, format="json")+ else:+ response = self.client.patch(self._detail_url(str(config.id)), data=data, format="json")++ assert response.status_code == status.HTTP_200_OK+@parameterized.expand([("unknown_skill", "signals-scout-nonexistent"),