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.

feat(signals): drive scout enrollment from signals-scout flag payload (#61806)

Andrew Maguirea520cdbfb0f4
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index d8670f804695..b5b2784f3390 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -293,7 +293,7 @@ Defined in `backend/temporal/agentic/scout_coordinator.py`.
**Flow:**
-1. Activity `fetch_enabled_signals_scout_runs_activity` bounds candidates to dogfood teams — those with a `signals-scout-*` skill or config, gated by the `signals-scout` feature flag (`_participating_teams`). For each, it calls `sync_canonical_skills(team, prune=True)` to mirror the on-disk `signals-scout-*` skills onto the team's `LLMSkill` rows, then auto-registers a `SignalScoutConfig` for any scout skill missing one (`_register_missing_configs`). Failures here are logged and the tick continues — a stale skill is preferable to a dead tick.
+1. Activity `fetch_enabled_signals_scout_runs_activity` bounds candidates to the teams enrolled via the `signals-scout` feature flag's JSON payload allowlist — `guaranteed_team_ids` minus `skip_team_ids`, with a hardcoded fail-safe default (`_participating_teams` → `_enrolled_team_ids`, modeled on `posthog/temporal/ai_observability/team_discovery.py`). Enrollment is flag-driven: editing the payload in the flag UI enrolls or drains a team next tick with no manual seed. For each enrolled team it calls `sync_canonical_skills(team, prune=True)` to mirror the on-disk `signals-scout-*` skills onto the team's `LLMSkill` rows, then auto-registers a `SignalScoutConfig` for any scout skill missing one (`_register_missing_configs`). Failures here are logged and the tick continues — a stale skill is preferable to a dead tick.
2. For each enabled config, the coordinator computes how overdue the scout is: due when `last_run_at is None`, or `now - last_run_at >= run_interval_minutes`. There is no sampling — every due scout is planned.
3. Due runs are sorted most-overdue-first and truncated at `MAX_RUNS_PER_TICK` (50 per tick; the cost bound — overflow catches up next tick). `last_run_at` is advanced via `.update()` for everything dispatched (bypasses `save()`, so the per-tick write never hits the activity log). Planned runs are re-sorted by `(team_id, skill_name)` for stable child IDs.
4. Each `PlannedRun` becomes a child `RunSignalsScoutWorkflow` started with `ParentClosePolicy.ABANDON` and a deterministic workflow ID per `(team_id, skill_name, tick_id)` so retried coordinators can't double-launch within a tick.
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index d8d8d23f4ea4..5703391babd7 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -1,9 +1,11 @@
from __future__ import annotations
import json
+import asyncio
from dataclasses import dataclass
from datetime import datetime, timedelta
+from django.conf import settings
from django.db.models import Q
from django.utils import timezone
@@ -13,6 +15,7 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.cloud_utils import is_cloud
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.sync import database_sync_to_async
@@ -26,10 +29,18 @@ from products.signals.backend.temporal.agentic.scout_scheduler import RunSignals
logger = structlog.get_logger(__name__)
-# Team-level dogfood gate. The single team gate (no per-team model boolean): the flag
-# picks which teams run scouts; per-scout SignalScoutConfig rows pick which scouts/schedules.
+# Team-level dogfood gate. The single team gate (no per-team model boolean): the flag's JSON
+# payload picks which teams run scouts; per-scout SignalScoutConfig rows pick which
+# scouts/schedules.
SIGNALS_SCOUT_DOGFOOD_FLAG = "signals-scout"
+# Fixed distinct_id for the payload read — enrollment is team-list-in-payload, not per-user.
+SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID = "internal_signals_scout_team_discovery"
+
+# Fail-safe allowlist used when the flag payload is missing/invalid — but only on PostHog
+# Cloud or local dev (see `_fallback_team_ids`). 1 (local dev), 2 (internal), 148051 (dev).
+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
@@ -91,7 +102,11 @@ async def fetch_enabled_signals_scout_runs_activity(
schedule is due — most-overdue first, capped at MAX_RUNS_PER_TICK.
"""
async with Heartbeater():
- planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)()
+ # Read the flag payload off the DB thread pool — the SDK call can block on a cold
+ # cache, and database_sync_to_async's pool is sized for DB-bound work (mirrors the
+ # asyncio.to_thread split in ai_observability/team_discovery.py).
+ enrolled_team_ids = await asyncio.to_thread(_enrolled_team_ids)
+ planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(enrolled_team_ids)
logger.info("signals_scout coordinator: planned runs", count=len(planned))
return FetchEnabledRunsOutput(planned_runs=planned)
@@ -132,11 +147,14 @@ class _DueRun:
skill_name: str
-def _collect_planned_runs() -> list[PlannedRun]:
- """Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt."""
+def _collect_planned_runs(enrolled_team_ids: set[int]) -> list[PlannedRun]:
+ """Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt.
+
+ Takes the already-resolved enrolled team ids so the flag read stays off this DB pool.
+ """
now = timezone.now()
due: list[_DueRun] = []
- for team in _participating_teams():
+ for team in _participating_teams(enrolled_team_ids):
# Sync canonical scouts so a freshly-enrolled team has skills to register on.
# `prune=True`: the periodic tick is a deliberate reconciliation path, so it also
# tombstones rows whose canonical was removed from disk (the runner cold-start sync
@@ -180,56 +198,65 @@ def _collect_planned_runs() -> list[PlannedRun]:
return planned
-def _participating_teams() -> list[Team]:
- """Canonical dogfood teams: those with a scout skill or config, gated by the flag.
+def _participating_teams(enrolled: set[int]) -> list[Team]:
+ """Resolve enrolled team ids to canonical `Team`s to run scouts on.
- Bounded to teams that have opted into scouts (canonical fleet seeded or a user-authored
- `signals-scout-*` skill) so the flag isn't evaluated against every team.
+ Enrollment is flag-driven: a team runs scouts iff its id is in the `signals-scout` flag
+ payload allowlist (resolved by `_enrolled_team_ids`, passed in). Adding an id in the flag
+ UI enrolls the team on the next tick with no manual seed — the tick body seeds canonical
+ skills + registers configs for it; removing it (or listing it in `skip_team_ids`) drains
+ it the next tick. Child envs canonicalize to their parent project so the per-project
+ singleton config is found once.
"""
- team_ids = set(
- LLMSkill.objects.filter(
- name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,
- is_latest=True,
- deleted=False,
- )
- .values_list("team_id", flat=True)
- .distinct()
- )
- team_ids |= set(SignalScoutConfig.all_teams.values_list("team_id", flat=True).distinct())
- candidates = Team.objects.filter(id__in=team_ids)
+ if not enrolled:
+ return []
+ candidates = Team.objects.filter(id__in=enrolled)
canonical_ids = {team.parent_team_id or team.id for team in candidates}
- canonical_teams = Team.objects.filter(id__in=canonical_ids).order_by("id")
- return [team for team in canonical_teams if _team_passes_rollout_flag(team)]
+ return list(Team.objects.filter(id__in=canonical_ids).order_by("id"))
+
+def _fallback_team_ids() -> list[int]:
+ """Default allowlist when the flag payload is absent/unreadable — gated to PostHog Cloud
+ and local dev. A self-hosted instance (where teams 1/2 exist but no one opted into scouts)
+ fails closed instead, so the coordinator never starts LLM scout runs for an unintended
+ tenant; a self-hoster opts in by setting the payload explicitly."""
+ return list(DEFAULT_ENROLLED_TEAM_IDS) if (is_cloud() or settings.DEBUG) else []
-def _team_passes_rollout_flag(team: Team) -> bool:
- """Whether the `signals-scout` dogfood flag is on for this team.
- Passes organization + project group context — mirroring the inbox gate in
- `backend/access.py` and the house pattern in `posthog/permissions.py` — so the flag is
- targetable per project/org from the PostHog UI. A group-aggregated release condition only
- matches when its group is supplied here, so without this the flag could only ever be a
- blanket rollout %. Remote eval; fails closed (eval error → team dropped).
+def _enrolled_team_ids() -> set[int]:
+ """Project ids enrolled in scouts, read from the `signals-scout` flag's JSON payload.
+
+ Flag-driven enrollment, no deploy: edit `guaranteed_team_ids` in the flag UI to enroll (or
+ drain) a team on the next tick; `skip_team_ids` is an override kill-switch. The flag must
+ stay 100%-on so the payload is served for the synthetic discovery distinct_id —
+ `match_value=True` additionally forces the true-variant payload under local evaluation.
+ Fail-safe: a missing/invalid payload or a read error falls back to `_fallback_team_ids`.
+ Mirrors `posthog/temporal/ai_observability/team_discovery.py`.
"""
- org_id = str(team.organization_id)
- project_id = str(team.id)
+ fallback = _fallback_team_ids()
try:
- return bool(
- posthoganalytics.feature_enabled(
- SIGNALS_SCOUT_DOGFOOD_FLAG,
- project_id,
- groups={"organization": org_id, "project": project_id},
- group_properties={
- "organization": {"id": org_id},
- "project": {"id": project_id},
- },
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
+ payload = posthoganalytics.get_feature_flag_payload(
+ SIGNALS_SCOUT_DOGFOOD_FLAG, SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID, match_value=True
)
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ if not isinstance(payload, dict):
+ return set(fallback)
+
+ # Absent key or malformed value → fallback. An explicit empty list is honored as an
+ # intentional "drain all teams" — not coerced to the fallback.
+ guaranteed = payload.get("guaranteed_team_ids", fallback)
+ if not isinstance(guaranteed, list) or not all(isinstance(t, int) for t in guaranteed):
+ guaranteed = fallback
+
+ skip = payload.get("skip_team_ids", [])
+ if not isinstance(skip, list) or not all(isinstance(t, int) for t in skip):
+ skip = []
+
+ return set(guaranteed) - set(skip)
except Exception as error:
capture_exception(error)
- return False
+ return set(fallback)
def _register_missing_configs(team: Team) -> set[str]:
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index eb390e7b735f..1e5f051a7444 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -7,6 +7,7 @@ from typing import Any
import pytest
from unittest.mock import AsyncMock, patch
+from django.test import override_settings
from django.utils import timezone
import pytest_asyncio
@@ -22,24 +23,32 @@ from products.ai_observability.backend.models.skills import LLMSkill
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.temporal.agentic.scout_coordinator import (
+ DEFAULT_ENROLLED_TEAM_IDS,
+ SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,
CoordinatorWorkflowInput,
CoordinatorWorkflowOutput,
FetchEnabledRunsInput,
PlannedRun,
SignalsScoutCoordinatorWorkflow,
StampDispatchedRunsInput,
+ _enrolled_team_ids,
fetch_enabled_signals_scout_runs_activity,
stamp_dispatched_signals_scout_runs_activity,
)
-_FLAG_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.feature_enabled"
+_PAYLOAD_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.get_feature_flag_payload"
+_IS_CLOUD_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.is_cloud"
-# The coordinator scans every team in the DB. These async tests commit (no transaction
-# rollback across the worker thread), so leftover teams from other modules can leak into
-# the scan. Flag only the teams this module created to keep the scan deterministic.
+# Enrollment is driven by the `signals-scout` flag payload allowlist. These async tests commit
+# (no transaction rollback across the worker thread), so leftover teams from other modules can
+# leak in. Enroll only the teams this module created to keep the scan deterministic.
_FLAGGED_TEAM_IDS: set[str] = set()
+def _allowlist_payload() -> dict:
+ return {"guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS]}
+
+
@pytest_asyncio.fixture
async def aorganization():
organization = await sync_to_async(Organization.objects.create)(
@@ -90,15 +99,15 @@ def _create_config(team: Team, skill_name: str, **kwargs: Any) -> SignalScoutCon
@pytest.fixture(autouse=True)
def _flag_on(request):
- """Treat every team as in the dogfood flag by default.
+ """Enroll every team this module created via the `signals-scout` flag payload allowlist.
- Tests covering the gate itself opt out with `@pytest.mark.flag_off` and set their own
- `feature_enabled` behavior.
+ Tests covering enrollment itself opt out with `@pytest.mark.flag_off` and set their own
+ payload.
"""
if request.node.get_closest_marker("flag_off"):
yield
return
- with patch(_FLAG_PATH, side_effect=lambda key, distinct_id, *a, **k: distinct_id in _FLAGGED_TEAM_IDS):
+ with patch(_PAYLOAD_PATH, side_effect=lambda *a, **k: _allowlist_payload()):
yield
@@ -124,64 +133,93 @@ async def _run_activity() -> list[PlannedRun]:
return output.planned_runs
-# ── Gate: the signals-scout flag is the single team-level gate ───────────────────
+# ── Enrollment: the signals-scout flag payload allowlist is the single gate ──────
+ "payload,expected",
+ [
+ ({"guaranteed_team_ids": [5, 6]}, {5, 6}),
+ ({"guaranteed_team_ids": [5, 6], "skip_team_ids": [6]}, {5}),
+ ('{"guaranteed_team_ids": [7]}', {7}), # JSON string payload
+ ({"guaranteed_team_ids": []}, set()), # explicit empty list → intentional drain-all
+ ({}, set(DEFAULT_ENROLLED_TEAM_IDS)), # absent key → defaults
+ (None, set(DEFAULT_ENROLLED_TEAM_IDS)), # no payload → defaults
+ ({"guaranteed_team_ids": "nope"}, set(DEFAULT_ENROLLED_TEAM_IDS)), # wrong type → defaults
+ ({"guaranteed_team_ids": [5, 6], "skip_team_ids": "nope"}, {5, 6}), # bad skip ignored
+ ],
+)
@pytest.mark.flag_off
-async def test_team_not_in_flag_is_skipped(ateam):
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
- await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=True)
+def test_enrolled_team_ids_parses_payload(payload, expected):
+ # is_cloud → True so the fallback resolves to DEFAULT_ENROLLED_TEAM_IDS (see the
+ # off-cloud fail-closed case below).
+ with patch(_PAYLOAD_PATH, return_value=payload), patch(_IS_CLOUD_PATH, return_value=True):
+ assert _enrolled_team_ids() == expected
- with patch(_FLAG_PATH, return_value=False):
- planned = await _run_activity()
- assert planned == []
+def test_enrolled_team_ids_uses_match_value_true():
+ # The team list lives in the payload, not the release conditions — assert we request the
+ # true-variant payload so a group-targeted/disabled flag can't starve discovery.
+ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [9]}) as mock_payload:
+ _enrolled_team_ids()
+ args, kwargs = mock_payload.call_args
+ assert args[0] == "signals-scout"
+ assert args[1] == SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID
+ assert kwargs.get("match_value") is True
-async def test_disabled_config_is_skipped(ateam):
- await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
- await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=False)
+def test_enrolled_team_ids_falls_back_to_defaults_on_error():
+ with patch(_PAYLOAD_PATH, side_effect=RuntimeError("flag service down")), patch(_IS_CLOUD_PATH, return_value=True):
+ assert _enrolled_team_ids() == set(DEFAULT_ENROLLED_TEAM_IDS)
- assert await _run_activity() == []
+
+@override_settings(DEBUG=False)
+def test_enrolled_team_ids_fails_closed_off_cloud():
+ # Self-hosted (not cloud, not debug): a missing payload enrolls no one, so the coordinator
+ # never starts scout runs for an unintended tenant. An explicit payload is still honored.
+ with patch(_IS_CLOUD_PATH, return_value=False):
+ with patch(_PAYLOAD_PATH, return_value=None):
+ assert _enrolled_team_ids() == set()
+ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [5]}):
+ assert _enrolled_team_ids() == {5}
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.flag_off
-async def test_rollout_flag_evaluated_with_project_group(ateam):
- # The flag is group-aggregated on the project, so the call must supply project (+org) group
- # context or no release condition could ever match. Locks that contract in.
+async def test_team_not_in_allowlist_is_skipped(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=True)
- with patch(_FLAG_PATH, return_value=True) as mock_flag:
- await _run_activity()
-
- org_id = str(ateam.organization_id)
- project_id = str(ateam.id)
- mock_flag.assert_called_once_with(
- "signals-scout",
- project_id,
- groups={"organization": org_id, "project": project_id},
- group_properties={"organization": {"id": org_id}, "project": {"id": project_id}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
+ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": []}):
+ planned = await _run_activity()
+
+ assert planned == []
@pytest.mark.asyncio
@pytest.mark.django_db
@pytest.mark.flag_off
-async def test_rollout_flag_eval_error_fails_closed(ateam):
+async def test_skip_team_ids_drains_an_enrolled_team(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
- with patch(_FLAG_PATH, side_effect=RuntimeError("flag service down")):
+ # Enrolled via guaranteed but overridden by skip → drained.
+ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [ateam.id], "skip_team_ids": [ateam.id]}):
planned = await _run_activity()
- assert planned == []
+ assert all(p.team_id != ateam.id for p in planned)
+
+
+async def test_disabled_config_is_skipped(ateam):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-errors", enabled=False)
+
+ assert await _run_activity() == []
# ── Auto-register: author a skill, get a scout ──────────────────────────────────
@@ -380,6 +418,27 @@ async def test_enrolled_team_registers_and_runs_canonical_fleet(ateam):
assert {p.skill_name for p in planned} == seeded
[email protected]_canonical_sync
+async def test_payload_enrolled_unseeded_team_is_seeded_by_tick(ateam):
+ # The flag-driven path with no manual seed: ateam is enrolled via the payload (autouse
+ # fixture) but has no scout skills yet. The tick itself must seed the canonical fleet,
+ # register configs, and dispatch — proving an operator only edits the flag payload.
+ pre_seeded = await database_sync_to_async(
+ lambda: LLMSkill.objects.filter(team=ateam, name__startswith="signals-scout-").exists()
+ )()
+ assert pre_seeded is False
+
+ planned = await _run_activity()
+
+ config_names = await database_sync_to_async(
+ lambda: set(SignalScoutConfig.all_teams.filter(team=ateam).values_list("skill_name", flat=True))
+ )()
+ assert config_names # fleet seeded + configs auto-registered by the tick
+ assert {p.skill_name for p in planned} == config_names
+
+
# ── Workflow-level dispatch ─────────────────────────────────────────────────────
#
# The coordinator dispatches children fire-and-forget via `start_child_workflow` with
diff --git a/products/signals/skills/AGENTS.md b/products/signals/skills/AGENTS.md
index 64b206f036e3..6c276e88be5b 100644
--- a/products/signals/skills/AGENTS.md
+++ b/products/signals/skills/AGENTS.md
@@ -53,10 +53,13 @@ There is no sampling. Each scout has its own `SignalScoutConfig` row (one per
`(team, skill_name)`) carrying a `run_interval_minutes` schedule (default 1440 =
daily) and a `last_run_at` stamp. Every tick the coordinator:
-1. Bounds candidates to dogfood teams — those with a `signals-scout-*` skill or
- config, gated by the `signals-scout` feature flag (`_participating_teams`).
+1. Bounds candidates to the teams enrolled via the `signals-scout` feature flag's
+ JSON payload allowlist (`guaranteed_team_ids` minus `skip_team_ids`,
+ `_participating_teams` → `_enrolled_team_ids`). Editing the payload in the flag UI
+ enrolls or drains a team next tick — no manual seed.
2. Auto-registers a config for any `signals-scout-*` skill missing one
- (`_register_missing_configs`) — authoring a skill is enough to get a scout.
+ (`_register_missing_configs`) — on an enrolled team, authoring a skill is enough
+ to get a scout.
3. Dispatches every enabled scout whose schedule is due (`last_run_at is None`, or
`now - last_run_at >= run_interval_minutes`), most-overdue first, capped at
`MAX_RUNS_PER_TICK` per tick. Each due scout becomes one `RunSignalsScoutWorkflow`