: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): seed scouts from flag enabled_skills allowlist (#64830)
Andrew Maguireab3d223e5f0c
diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex 587d984dad0d..2f9557308731 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -12,12 +12,20 @@ from __future__ import annotationsimport structlogfrom products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, canonical_skill_namesfrom products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIXfrom products.skills.backend.models.skills import LLMSkilllogger = structlog.get_logger(__name__)+# Mirror the `SignalScoutConfig.run_interval_minutes` model + serializer bounds (10–43200). A+# seed interval comes from arbitrary flag JSON and is written via `get_or_create`, which bypasses+# model validators — so an out-of-range value is validated here and treated as absent rather than+# persisted (a large enough int would otherwise raise a DB error and abort the coordinator tick).+MIN_RUN_INTERVAL_MINUTES = 10+MAX_RUN_INTERVAL_MINUTES = 43200+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.@@ -31,27 +39,92 @@ def enabled_scout_count(team_id: int, *, exclude_skill: str | None = None) -> inreturn queryset.count()-def register_missing_configs(team_id: int) -> set[str]:- """Auto-create a default-schedule config for each scout skill lacking a row.+def _resolve_seed_posture(seed_config_layers: list[dict] | None) -> tuple[set[str] | None, int | None]:+ """Resolve the seed posture across ordered config layers, most-specific first.++ Each field is resolved independently: the first layer carrying a VALID value for that key+ wins; a layer whose value is absent or malformed falls through to the next — the same per-key+ fallback as `_resolve_max_runs_per_tick` does for the tick cap, so a typo'd per-team override+ doesn't silently drop the fleet default (e.g. a team passing `enabled_skills` as a string+ still inherits the fleet allowlist rather than enabling everything).++ Returns `(enabled_skills, enabled_interval_minutes)`:+ - `enabled_skills`: allowlist of canonical scouts that auto-enable on seed; the rest register+ disabled. `None` (no valid layer) means "no allowlist" — every scout enables, historical.+ - `enabled_interval_minutes`: cadence stamped on the auto-enabled rows, validated against the+ model's 10–43200 bounds; `None` keeps the model default.+ """+ layers = [layer for layer in (seed_config_layers or []) if isinstance(layer, dict)]++ enabled_skills: set[str] | None = None+ for layer in layers:+ raw_skills = layer.get("enabled_skills")+ if isinstance(raw_skills, list) and all(isinstance(s, str) for s in raw_skills):+ enabled_skills = {str(s) for s in raw_skills}+ break++ enabled_interval: int | None = None+ for layer in layers:+ raw_interval = layer.get("enabled_interval_minutes")+ if (+ isinstance(raw_interval, int)+ and not isinstance(raw_interval, bool)+ and MIN_RUN_INTERVAL_MINUTES <= raw_interval <= MAX_RUN_INTERVAL_MINUTES+ ):+ enabled_interval = raw_interval+ break++ return enabled_skills, enabled_interval+++def register_missing_configs(team_id: int, seed_config_layers: list[dict] | None = None) -> set[str]:+ """Auto-create a config for each scout skill lacking a row, honouring an optional seed posture.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.+ `seed_config_layers` are the team's flag config layers, most-specific first (its `team_configs`+ override, then the fleet `default_team_config`); `_resolve_seed_posture` resolves them per key.+ When an `enabled_skills` allowlist is in force, only those **canonical** (harness-seeded)+ scouts auto-enable (at `enabled_interval_minutes` if set) and the rest register disabled — the+ launch posture (e.g. general-only, once a day). Hand-authored **custom** scouts are never gated+ by the allowlist: "author a skill, get a scout" still auto-enables them, so a launch team's own+ scout isn't silently muted. With no allowlist, every scout enables at the model-default+ schedule. Either way, a scout disabled at seed stays visible and tunable but adds no spend.++ Posture only shapes rows at creation (forward-only) — existing configs are never re-stamped,+ so flipping the flag later doesn't disturb teams already seeded, and a user enabling a scout+ won't be reverted on the next tick.++ The per-team `MAX_ENABLED_SCOUTS_PER_TEAM` cap is an independent second gate: even an+ allowlisted scout registers disabled once the team is at the cap. Both checks are 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(+ enabled_skills, enabled_interval = _resolve_seed_posture(seed_config_layers)+ rows = list(LLMSkill.objects.filter(team_id=team_id,name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,is_latest=True,deleted=False,- ).values_list("name", flat=True)+ ).values_list("name", "metadata"))+ skill_names = {name for name, _ in rows}+ # The allowlist governs the canonical fleet only; custom (hand-authored or duplicated) scouts+ # always auto-enable. A scout is canonical iff it BOTH carries the harness `seeded_by` tag AND+ # matches an on-disk canonical name — same dual check as `views._scout_origin`. The tag alone+ # isn't enough: `duplicate_skill` copies metadata verbatim, so a user's duplicate of a+ # canonical scout keeps the tag under a new, non-canonical name and must not be gated.+ on_disk_canonical = canonical_skill_names()+ canonical_names = {+ name+ for name, metadata in rows+ if (metadata or {}).get("seeded_by") == HARNESS_SEEDED_BY and name in on_disk_canonical+ }+configs = SignalScoutConfig.objects.for_team(team_id)existing = set(configs.values_list("skill_name", flat=True))missing = sorted(skill_names - existing)@@ -61,20 +134,31 @@ def register_missing_configs(team_id: int) -> set[str]:enabled = enabled_scout_count(team_id)for name in missing:at_cap = enabled >= MAX_ENABLED_SCOUTS_PER_TEAM+ # A canonical scout is gated by the allowlist (when one is set); a custom scout never is.+ # The explicit `is not None` keeps the membership check well-typed (mypy can't carry the+ # narrowing through `gated`).+ gated = enabled_skills is not None and name in canonical_names+ in_allowlist = (not gated) or (enabled_skills is not None and name in enabled_skills)+ seed_enabled = in_allowlist and not at_cap++ defaults: dict = {} if seed_enabled else {"enabled": False}+ # The launch cadence applies to scouts enabled via the allowlist; custom scouts keep+ # the model default so a user's own scout isn't forced onto the fleet's schedule.+ if seed_enabled and gated and enabled_interval is not None:+ defaults["run_interval_minutes"] = enabled_interval+# `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`.- _, created = configs.get_or_create(- team_id=team_id,- skill_name=name,- defaults={"enabled": False} if at_cap else {},- )- if created and at_cap:+ _, created = configs.get_or_create(team_id=team_id, skill_name=name, defaults=defaults)+ if not created:+ continue+ if seed_enabled:+ enabled += 1+ elif in_allowlist 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/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 379032b81513..4ad397e63c4e 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -190,6 +190,7 @@ def _collect_planned_runs("""now = timezone.now()team_configs = _canonicalize_team_config_keys(team_configs or {})+ default_team_config = default_team_config or {}due: list[_DueRun] = []for team in _participating_teams(enrolled_team_ids):# Sync canonical scouts so a freshly-enrolled team has skills to register on.@@ -205,7 +206,12 @@ def _collect_planned_runs("signals_scout coordinator: canonical skill sync failed for team; continuing",team_id=team.id,)- live_skills = register_missing_configs(team.id)+ # This team's seed posture resolves like the tick cap: its own `team_configs` override+ # layered over the fleet-wide `default_team_config`, most-specific first. Passing the+ # layers (not a shallow merge) lets `_resolve_seed_posture` fall back per key, so a+ # malformed per-team value doesn't clobber a valid fleet default.+ seed_config_layers = [team_configs.get(team.id) or {}, default_team_config]+ live_skills = register_missing_configs(team.id, seed_config_layers)# Skip enabled configs whose `signals-scout-*` skill was deleted or is no longer the# latest version: dispatching them would spawn a child workflow that fails fast in# load_skill_for_run on every tick.diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex 3beed289bc3e..dda0026bfeb3 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -20,7 +20,7 @@ from posthog.models.scoping import team_scopefrom posthog.sync import database_sync_to_asyncfrom products.signals.backend.models import SignalScoutConfig-from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills+from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, sync_canonical_skillsfrom products.signals.backend.temporal.agentic.scout_coordinator import (DEFAULT_ENROLLED_TEAM_IDS,SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,@@ -92,8 +92,11 @@ async def aother_team(aorganization):await sync_to_async(team.delete)()-def _create_skill(team: Team, name: str) -> LLMSkill:- return LLMSkill.objects.create(team=team, name=name, description="d", body="b")+def _create_skill(team: Team, name: str, *, seeded: bool = True) -> LLMSkill:+ # Default to a canonical (harness-seeded) skill — the realistic case; pass seeded=False for a+ # hand-authored custom scout (no `seeded_by` tag), which the seed allowlist must not gate.+ metadata = {"seeded_by": HARNESS_SEEDED_BY} if seeded else {}+ return LLMSkill.objects.create(team=team, name=name, description="d", body="b", metadata=metadata)def _create_config(team: Team, skill_name: str, **kwargs: Any) -> SignalScoutConfig:@@ -622,6 +625,119 @@ async def test_auto_register_past_enabled_cap_creates_disabled_config(ateam):assert sorted(p.skill_name for p in planned) == ["signals-scout-existing"]+# ── Seed posture via the flag (enabled_skills allowlist + interval) ───────────────+++ "default_cfg,team_cfg,skills,expected_enabled",+ [+ # An allowlist enables only the listed canonical scout; the rest seed disabled.+ # (error-tracking / surveys are real on-disk canonical names, so the tag gates them.)+ (+ {"enabled_skills": ["signals-scout-general"]},+ None,+ [("signals-scout-general", True), ("signals-scout-error-tracking", True), ("signals-scout-surveys", True)],+ {"signals-scout-general": True, "signals-scout-error-tracking": False, "signals-scout-surveys": False},+ ),+ # No allowlist → every scout enables (back-compat, unchanged from before seed posture).+ (+ {},+ None,+ [("signals-scout-general", True), ("signals-scout-error-tracking", True)],+ {"signals-scout-general": True, "signals-scout-error-tracking": True},+ ),+ # A per-team override widens the fleet default for one team (close-partner case).+ (+ {"enabled_skills": ["signals-scout-general"]},+ {"enabled_skills": ["signals-scout-general", "signals-scout-error-tracking"]},+ [("signals-scout-general", True), ("signals-scout-error-tracking", True), ("signals-scout-surveys", True)],+ {"signals-scout-general": True, "signals-scout-error-tracking": True, "signals-scout-surveys": False},+ ),+ # A malformed per-team override falls back to the fleet default, not "no allowlist".+ (+ {"enabled_skills": ["signals-scout-general"]},+ {"enabled_skills": "signals-scout-general"},+ [("signals-scout-general", True), ("signals-scout-error-tracking", True)],+ {"signals-scout-general": True, "signals-scout-error-tracking": False},+ ),+ # A hand-authored custom scout (no seeded_by tag) auto-enables even under an allowlist.+ (+ {"enabled_skills": ["signals-scout-general"]},+ None,+ [("signals-scout-general", True), ("signals-scout-custom", False)],+ {"signals-scout-general": True, "signals-scout-custom": True},+ ),+ # A duplicated canonical scout keeps the seeded_by tag but on a non-canonical name, so it's+ # treated as custom and still auto-enables (not gated by the allowlist).+ (+ {"enabled_skills": ["signals-scout-general"]},+ None,+ [("signals-scout-general", True), ("signals-scout-general-copy", True)],+ {"signals-scout-general": True, "signals-scout-general-copy": True},+ ),+ ],+)+async def test_seed_posture_enabled_map(ateam, default_cfg, team_cfg, skills, expected_enabled):+ # Which scouts seed enabled vs disabled, across allowlist / no-allowlist / per-team-override /+ # malformed-override / custom-scout / duplicated-scout scenarios. `skills` is+ # (name, seeded_with_harness_tag) pairs; only a tag AND an on-disk canonical name = gated.+ for name, seeded in skills:+ await database_sync_to_async(_create_skill)(ateam, name, seeded=seeded)++ def _payload(*_a, **_k):+ payload: dict[str, Any] = {"guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS]}+ if default_cfg:+ payload["default_team_config"] = default_cfg+ if team_cfg is not None:+ payload["team_configs"] = {str(ateam.id): team_cfg}+ return payload++ with patch(_PAYLOAD_PATH, side_effect=_payload):+ await _run_activity()++ rows = await database_sync_to_async(+ lambda: {c.skill_name: c.enabled for c in SignalScoutConfig.all_teams.filter(team_id=ateam.id)}+ )()+ assert rows == expected_enabled+++ "interval,expected",+ [+ (1440, 1440), # in-bounds cadence is stamped on the auto-enabled scout+ (5, None), # below the 10-min model floor → ignored, model default kept+ (99999, None), # above the 43200-min ceiling → ignored, model default kept+ ],+)+async def test_seed_enabled_interval_validates_bounds(ateam, interval, expected):+ # enabled_interval_minutes sets the cadence on allowlisted scouts, but only within the model's+ # 10–43200 bounds (get_or_create bypasses validators); out-of-range falls back to the default.+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-general")++ def _payload(*_a, **_k):+ return {+ "guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS],+ "default_team_config": {"enabled_skills": ["signals-scout-general"], "enabled_interval_minutes": interval},+ }++ with patch(_PAYLOAD_PATH, side_effect=_payload):+ await _run_activity()++ general = await database_sync_to_async(+ lambda: SignalScoutConfig.all_teams.get(team_id=ateam.id, skill_name="signals-scout-general")+ )()+ assert general.enabled is True+ if expected is not None:+ assert general.run_interval_minutes == expected+ else:+ # Unchanged from the model default (not the out-of-range value).+ assert general.run_interval_minutes != interval++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_planned_runs_sorted_by_team_then_skill(ateam, aother_team):