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): materialize background scout configs from the flag payload (#109012)

posthog[bot]a1579303dd18
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 749984a3563a..33a9c81dd35e 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -86,6 +86,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
Also the failure-streak circuit breaker's knobs: `failure_streak_pause_threshold(runs_in_tolerance_window)` — consecutive failed runs before the breaker pauses the lane, derived per-lane so the same wall-clock tolerance holds at every cadence (one failure past the runs the schedule fits into `FAILURE_STREAK_MIN_SPAN_MINUTES` of continuous failure, `FAILURE_STREAK_MIN_RUNS` floor, capped at `FAILURE_STREAK_MAX_RUNS` + 1), with `interval_runs_in_tolerance_window` sizing the evenly spaced case — and `AUTO_PAUSE_PROBE_INTERVAL_S` (how long a paused lane holds before the coordinator dispatches one probe).
- `team_limits.py`
Single source of truth for a team's effective scout caps + metadata, resolved from the `signals-scout` flag payload in one read. The same three-layer cap resolution (`team_configs[team]` → `default_team_config` → code constant) the coordinator enforces at dispatch — for the run budgets and for `max_enabled_scouts`, the ceiling on how many scouts a project may have switched on, which `resolve_max_enabled_scouts` / `max_enabled_scouts_for_team` serve to the config write surfaces, auto-registration and the system resume alike, plus enrollment (`_parse_enrollment` → `guaranteed_team_ids` / `skip_team_ids`, with a cloud/dev-gated fallback) and the editorial banner string. `guaranteed_team_ids` may contain the `"*"` wildcard (`ENROLL_ALL_TOKEN`): with it, enrollment inverts from an explicit allowlist to "every team that has enabled scout configs" — the self-serve gate, where the product-autonomy- gated UI creates the configs; explicit ids alongside `"*"` are still force-provisioned and `skip_team_ids` still hard-excludes. The global per-tick ceiling is flag-tunable too (`_resolve_global_max_runs_per_tick` ← `max_runs_per_tick_global`, default `MAX_RUNS_PER_TICK`).
+ The `background` block (`_parse_background` → `BackgroundEnrollment`: `enabled`, `skill_name`, `team_ids`, `interval_minutes`, `max_new_teams_per_tick`) 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.
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.py
index 13973f1117a6..05672a4d0e10 100644
--- a/products/signals/backend/scout_harness/team_limits.py
+++ b/products/signals/backend/scout_harness/team_limits.py
@@ -220,6 +220,71 @@ def _parse_enrollment(payload: dict | None) -> Enrollment:
return Enrollment(wildcard=wildcard, explicit=explicit, skip=skip)
+# Flag payload block that enrolls a pilot cohort in one scout that PostHog sets up without a person
+# asking. Separate from `guaranteed_team_ids`: a background team gets one config for one skill, not
+# the full catalog seed.
+BACKGROUND_KEY = "background"
+DEFAULT_BACKGROUND_SKILL_NAME = "signals-scout-general"
+# Bounds how many teams get a new background config in one tick, so a large list starts over
+# several ticks instead of in one burst.
+DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK = 5
+
+
+@dataclass(frozen=True)
+class BackgroundEnrollment:
+ """Parsed `background` block from the `signals-scout` flag payload.
+
+ `enabled` → the coordinator creates and dispatches background configs. A valid block with
+ `enabled` off still pauses configs whose team left `team_ids`. `interval_minutes` is `None`
+ when unset, so the created row keeps the model default.
+ """
+
+ enabled: bool
+ skill_name: str
+ team_ids: frozenset[int]
+ interval_minutes: int | None
+ max_new_teams_per_tick: int
+
+
+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 _parse_background(payload: dict | None) -> BackgroundEnrollment | None:
+ """Parse the `background` block, or return `None` when the coordinator must not act on it.
+
+ `None` for a missing payload, a missing block, a block that is not an object, a `skill_name`
+ 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 background
+ config. `enabled` is on only for a literal `true`. An absent or malformed `interval_minutes` or
+ `max_new_teams_per_tick` falls back to its default and does not invalidate the block.
+ """
+ if payload is None:
+ return None
+ raw = payload.get(BACKGROUND_KEY)
+ if not isinstance(raw, dict):
+ return None
+
+ skill_name = raw.get("skill_name", DEFAULT_BACKGROUND_SKILL_NAME)
+ if not isinstance(skill_name, str) or not skill_name.strip():
+ return None
+
+ raw_team_ids = raw.get("team_ids", [])
+ if not isinstance(raw_team_ids, list) or not all(
+ isinstance(team_id, int) and not isinstance(team_id, bool) for team_id in raw_team_ids
+ ):
+ return None
+
+ max_new = _positive_int_or_none(raw.get("max_new_teams_per_tick"))
+ return BackgroundEnrollment(
+ enabled=raw.get("enabled") is True,
+ skill_name=skill_name.strip(),
+ team_ids=frozenset(raw_team_ids),
+ interval_minutes=_positive_int_or_none(raw.get("interval_minutes")),
+ max_new_teams_per_tick=max_new if max_new is not None else DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
+ )
+
+
def _enrolled_team_ids(payload: dict | None) -> set[int]:
"""Explicit enrolled project ids (skip removed) — the back-compat view of `_parse_enrollment`
for the metadata path and existing callers.
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 9d82233f9dbc..bf3674b03619 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -24,13 +24,22 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.report_check_execution import run_due_report_checks
from products.signals.backend.scout_harness.config_registry import (
+ MAX_RUN_INTERVAL_MINUTES,
+ MIN_RUN_INTERVAL_MINUTES,
canonical_operational_skill_names,
+ enabled_scout_count,
live_scout_skill_names,
operational_configs_needing_reconcile,
reconcile_operational_configs,
register_missing_configs,
)
-from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
+from products.signals.backend.scout_harness.lazy_seed import (
+ canonical_config_tags_for,
+ canonical_display_name_for,
+ canonical_skill_names,
+ discover_canonical_skills,
+ sync_canonical_skills,
+)
from products.signals.backend.scout_harness.limits import (
AUTO_PAUSE_PROBE_INTERVAL_S,
COORDINATOR_INTERVAL_MINUTES,
@@ -45,9 +54,11 @@ from products.signals.backend.scout_harness.limits import (
# them unqualified and tests can patch them on this module.
from products.signals.backend.scout_harness.team_limits import (
DAILY_BUDGET_WINDOW,
+ BackgroundEnrollment,
Enrollment,
_canonicalize_team_config_keys,
_default_team_config,
+ _parse_background,
_parse_enrollment,
_read_flag_payload,
_resolve_dispatch_smear_seconds,
@@ -67,6 +78,7 @@ from products.signals.backend.temporal.metrics import (
increment_coordinator_dispatch,
increment_coordinator_tick,
)
+from products.skills.backend.models.skills import LLMSkill
logger = structlog.get_logger(__name__)
@@ -183,6 +195,7 @@ async def fetch_enabled_signals_scout_runs_activity(
# configs are derived from the same snapshot so they can't disagree across two reads.
payload = await asyncio.to_thread(_read_flag_payload)
enrollment = _parse_enrollment(payload)
+ background = _parse_background(payload)
team_configs = _team_configs(payload)
default_team_config = _default_team_config(payload)
# The global per-tick ceiling is flag-tunable (no deploy): resolve it here off the same
@@ -191,7 +204,7 @@ async def fetch_enabled_signals_scout_runs_activity(
global_max_runs_per_tick = _resolve_global_max_runs_per_tick(payload, MAX_RUNS_PER_TICK)
smear_seconds = _resolve_dispatch_smear_seconds(payload, DISPATCH_SMEAR_SECONDS)
planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(
- enrollment, team_configs, default_team_config, global_max_runs_per_tick
+ enrollment, team_configs, default_team_config, global_max_runs_per_tick, background
)
logger.info("signals_scout coordinator: planned runs", count=len(planned))
increment_coordinator_tick(len(planned))
@@ -336,17 +349,28 @@ def _collect_planned_runs(
team_configs: dict[int, dict] | None = None,
default_team_config: dict | None = None,
max_runs_per_tick: int | None = None,
+ background: BackgroundEnrollment | None = None,
) -> list[PlannedRun]:
"""Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt.
Takes the parsed enrollment (explicit allowlist + the `"*"` wildcard), the optional per-team
- config overrides, the fleet-wide default config, and the resolved global per-tick ceiling — so
- the flag reads all stay off this DB pool.
+ config overrides, the fleet-wide default config, the resolved global per-tick ceiling, and the
+ parsed `background` block — so the flag reads all stay off this DB pool.
+
+ Background configs are dispatched only through `_collect_background_runs`, never through the
+ participating-team loop, so the consent check and the background kill switch gate every one.
"""
now = timezone.now()
team_configs = _canonicalize_team_config_keys(team_configs or {})
default_team_config = default_team_config or {}
due: list[_DueRun] = []
+ background_team_ids: set[int] = set()
+ if background is not None:
+ background_team_ids = _canonicalize_team_ids(set(background.team_ids)) - _canonicalize_team_ids(enrollment.skip)
+ try:
+ _reconcile_background_configs(background, background_team_ids, team_configs, default_team_config)
+ except Exception:
+ logger.exception("signals_scout coordinator: background reconcile failed; continuing")
paused_by_team = _breaker_paused_configs_by_team()
reconcile_by_team = operational_configs_needing_reconcile() if enrollment.wildcard else {}
for team, needs_seed in _participating_teams(enrollment, reconcile_team_ids=set(reconcile_by_team)):
@@ -402,13 +426,18 @@ def _collect_planned_runs(
# Skip enabled configs whose 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.
- for config in SignalScoutConfig.all_teams.filter(team_id=team.id, enabled=True, skill_name__in=live_skills):
+ for config in SignalScoutConfig.all_teams.filter(
+ team_id=team.id, enabled=True, skill_name__in=live_skills
+ ).exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND):
overdue_s = _overdue_seconds(config, now, team.timezone_info)
if overdue_s is None:
continue
due.append(_DueRun(overdue_s, str(config.pk), team.id, config.skill_name))
due.extend(_collect_probe_runs(paused_by_team.get(team.id, []), live_skills, now))
+ if 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 []
@@ -589,6 +618,7 @@ def _participating_teams(enrollment: Enrollment, reconcile_team_ids: set[int] |
pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
)
)
+ .exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
.values_list("team_id", flat=True)
.distinct()
)
@@ -616,7 +646,7 @@ def _breaker_paused_configs_by_team() -> dict[int, list[SignalScoutConfig]]:
paused = SignalScoutConfig.all_teams.filter(
status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
- )
+ ).exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
for config in paused:
paused_by_team.setdefault(config.team_id, []).append(config)
return paused_by_team
@@ -666,6 +696,195 @@ def _collect_probe_runs(paused_configs: list[SignalScoutConfig], live_skills: se
return probes
+def _ai_data_processing_approved(team: Team) -> bool:
+ return team.organization.is_ai_data_processing_approved is True
+
+
+def _reconcile_background_configs(
+ background: BackgroundEnrollment,
+ listed_team_ids: set[int],
+ team_configs: dict[int, dict],
+ default_team_config: dict,
+) -> None:
+ """Move background configs toward the `background` block of the flag payload.
+
+ Runs on a valid block only, because an unreadable block must never read as an empty list. The
+ pause of departed teams runs even with `enabled` off, so an operator can drain one team without
+ stopping the pilot. Creation and resume run only with `enabled` on.
+ """
+ _pause_departed_background_configs(listed_team_ids)
+ if not background.enabled:
+ return
+ if background.skill_name not in canonical_skill_names():
+ logger.warning(
+ "signals_scout coordinator: background skill is not a canonical scout; skipping background setup",
+ skill_name=background.skill_name,
+ )
+ return
+ eligible = [
+ team
+ for team in Team.objects.filter(id__in=listed_team_ids).select_related("organization").order_by("id")
+ if _ai_data_processing_approved(team)
+ and background.skill_name not in _resolve_withheld_skills(team.id, team_configs, default_team_config)
+ ]
+ _resume_background_configs(background, eligible, team_configs, default_team_config)
+ _create_background_configs(background, eligible, team_configs, default_team_config)
+
+
+def _pause_departed_background_configs(listed_team_ids: set[int]) -> None:
+ """Pause every runnable background config whose team is no longer listed.
+
+ `transition_status_by_system` refuses a row a person paused or another writer owns, so this
+ only ever pauses what the background coordinator may still change.
+ """
+ departed = SignalScoutConfig.all_teams.filter(
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ status__in=SignalScoutConfig.RUNNABLE_STATUSES,
+ ).exclude(team_id__in=listed_team_ids)
+ for config in departed:
+ if config.transition_status_by_system(
+ SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
+ pause_reason=SignalScoutConfig.PauseReason.BACKGROUND_REMOVED,
+ ):
+ logger.info(
+ "signals_scout coordinator: paused background scout for a team that left the list",
+ team_id=config.team_id,
+ skill_name=config.skill_name,
+ )
+
+
+def _resume_background_configs(
+ background: BackgroundEnrollment,
+ eligible_teams: list[Team],
+ team_configs: dict[int, dict],
+ default_team_config: dict,
+) -> None:
+ """Resume the background configs this coordinator paused, for teams that are listed again."""
+ paused = SignalScoutConfig.all_teams.filter(
+ team_id__in=[team.id for team in eligible_teams],
+ skill_name=background.skill_name,
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
+ pause_reason=SignalScoutConfig.PauseReason.BACKGROUND_REMOVED,
+ )
+ for config in paused:
+ config.transition_status_by_system(
+ SignalScoutConfig.Status.ACTIVE,
+ pause_reason=SignalScoutConfig.PauseReason.BACKGROUND_REMOVED,
+ max_enabled_scouts=resolve_max_enabled_scouts(
+ [team_configs.get(config.team_id) or {}, default_team_config]
+ ),
+ )
+
+
+def _create_background_configs(
+ background: BackgroundEnrollment,
+ eligible_teams: list[Team],
+ team_configs: dict[int, dict],
+ default_team_config: dict,
+) -> None:
+ """Create one background config for the background skill on each listed team that has none.
+
+ Seeds only the background skill, not the canonical catalog that `guaranteed_team_ids` seeds,
+ and creates only this one config. A team that already has a config for the skill keeps it
+ untouched, whoever created it. At most `max_new_teams_per_tick` teams are set up per tick.
+ """
+ has_config = set(
+ SignalScoutConfig.all_teams.filter(
+ team_id__in=[team.id for team in eligible_teams], skill_name=background.skill_name
+ ).values_list("team_id", flat=True)
+ )
+ pending = [team for team in eligible_teams if team.id not in has_config]
+ if not pending:
+ return
+ interval = background.interval_minutes
+ defaults: dict = {"managed_by": SignalScoutConfig.ManagedBy.BACKGROUND}
+ if interval is not None and MIN_RUN_INTERVAL_MINUTES <= interval <= MAX_RUN_INTERVAL_MINUTES:
+ defaults["run_interval_minutes"] = interval
+ if tags := canonical_config_tags_for(background.skill_name):
+ defaults["tags"] = list(tags)
+ if display_name := canonical_display_name_for(background.skill_name):
+ defaults["display_name"] = display_name
+ other_canonical_names = {canonical.name for canonical in discover_canonical_skills()} - {background.skill_name}
+
+ created = 0
+ for team in pending:
+ if created >= background.max_new_teams_per_tick:
+ break
+ max_enabled = resolve_max_enabled_scouts([team_configs.get(team.id) or {}, default_team_config])
+ if enabled_scout_count(team.id) >= max_enabled:
+ logger.info(
+ "signals_scout coordinator: team at enabled-scout cap, skipping background setup",
+ team_id=team.id,
+ cap=max_enabled,
+ )
+ continue
+ try:
+ sync_canonical_skills(team, withheld_skill_names=other_canonical_names)
+ except Exception:
+ logger.exception(
+ "signals_scout coordinator: background skill seed failed for team; continuing",
+ team_id=team.id,
+ )
+ continue
+ _, was_created = SignalScoutConfig.objects.for_team(team.id).get_or_create(
+ team_id=team.id, skill_name=background.skill_name, defaults=defaults
+ )
+ if was_created:
+ created += 1
+ logger.info(
+ "signals_scout coordinator: created background scout config",
+ team_id=team.id,
+ skill_name=background.skill_name,
+ )
+
+
+def _collect_background_runs(
+ background: BackgroundEnrollment,
+ listed_team_ids: set[int],
+ team_configs: dict[int, dict],
+ default_team_config: dict,
+ now: datetime,
+) -> list[_DueRun]:
+ """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
+ created. Breaker-paused background configs get their probes here too, so no background run
+ skips the consent check.
+ """
+ if not listed_team_ids:
+ return []
+ configs = SignalScoutConfig.all_teams.filter(
+ Q(enabled=True)
+ | Q(
+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
+ pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
+ ),
+ team_id__in=listed_team_ids,
+ skill_name=background.skill_name,
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ ).select_related("team__organization")
+ live_team_ids = set(
+ LLMSkill.objects.filter(
+ team_id__in=listed_team_ids, name=background.skill_name, is_latest=True, deleted=False
+ ).values_list("team_id", flat=True)
+ )
+ due: list[_DueRun] = []
+ live_skills = {background.skill_name}
+ for config in configs:
+ if config.team_id not in live_team_ids or not _ai_data_processing_approved(config.team):
+ continue
+ if background.skill_name in _resolve_withheld_skills(config.team_id, team_configs, default_team_config):
+ continue
+ if not config.enabled:
+ due.extend(_collect_probe_runs([config], live_skills, now))
+ continue
+ overdue_s = _overdue_seconds(config, now, config.team.timezone_info)
+ if overdue_s is not None:
+ due.append(_DueRun(overdue_s, str(config.pk), config.team_id, config.skill_name))
+ return due
+
+
def _overdue_seconds(config: SignalScoutConfig, now: datetime, project_timezone: tzinfo) -> float | None:
"""Seconds past due, or None if not yet due. Never-run rolling schedules are maximally overdue."""
if config.run_cron_schedule:
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 7f5f312d9a62..f4e5f4b1b7b0 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -38,11 +38,14 @@ from products.signals.backend.scout_harness.limits import (
# defined there are imported and patched there (see `_PAYLOAD_PATH` / `_IS_CLOUD_PATH`).
from products.signals.backend.scout_harness.serializers import SignalScoutConfigUpdateSerializer
from products.signals.backend.scout_harness.team_limits import (
+ DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
DEFAULT_ENROLLED_TEAM_IDS,
SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,
+ BackgroundEnrollment,
Enrollment,
_default_team_config,
_enrolled_team_ids,
+ _parse_background,
_parse_enrollment,
_read_flag_payload,
_resolve_dispatch_smear_seconds,
@@ -69,6 +72,7 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
StampDispatchedRunsInput,
_allocate_tick_budget,
_breaker_paused_configs_by_team,
+ _collect_planned_runs,
_collect_probe_runs,
_dispatch_batches,
_dispatch_slot,
@@ -622,6 +626,126 @@ async def test_config_whose_skill_is_gone_is_skipped(ateam, live_name, ghost_nam
assert [p.skill_name for p in planned] == [live_name]
+# ── Background enrollment: one scout on a pilot cohort, set up without a person asking ──────
+
+_GENERAL = "signals-scout-general"
+
+
+ "payload,expected",
+ [
+ (None, None),
+ ({}, None),
+ ({"background": "nope"}, None),
+ ({"background": {"enabled": True, "team_ids": "nope"}}, None), # malformed list must not drain the pilot
+ ({"background": {"enabled": True, "team_ids": [1, True]}}, None),
+ ({"background": {"enabled": True, "skill_name": " ", "team_ids": [1]}}, None),
+ (
+ {"background": {"enabled": True, "team_ids": [1, 2]}},
+ BackgroundEnrollment(True, _GENERAL, frozenset({1, 2}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),
+ ),
+ (
+ {
+ "background": {
+ "enabled": "true",
+ "skill_name": "signals-scout-errors",
+ "team_ids": [],
+ "interval_minutes": 0,
+ "max_new_teams_per_tick": "5",
+ }
+ },
+ BackgroundEnrollment(
+ False, "signals-scout-errors", frozenset(), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK
+ ),
+ ),
+ (
+ {"background": {"enabled": True, "team_ids": [3], "interval_minutes": 720, "max_new_teams_per_tick": 2}},
+ BackgroundEnrollment(True, _GENERAL, frozenset({3}), 720, 2),
+ ),
+ ],
+)
+def test_parse_background(payload, expected):
+ assert _parse_background(payload) == expected
+
+
+def _background(team_ids: set[int], *, enabled: bool = True, max_new: int = 5) -> BackgroundEnrollment:
+ return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new)
+
+
+_NO_ENROLLMENT = Enrollment(wildcard=False, explicit=set(), skip=set())
+
+
+class TestBackgroundEnrollment:
+ def _team(self, *, approved: bool = True) -> Team:
+ org = Organization.objects.create(name="background-org", is_ai_data_processing_approved=approved)
+ return Team.objects.create(organization=org, name="background-team")
+
+ def test_creates_only_the_background_config_on_consented_teams(self):
+ approved, unapproved = self._team(), self._team(approved=False)
+
+ _collect_planned_runs(_NO_ENROLLMENT, background=_background({approved.id, unapproved.id}))
+
+ configs = list(SignalScoutConfig.all_teams.filter(team__in=[approved, unapproved]))
+ assert [(c.team_id, c.skill_name, c.managed_by, c.run_interval_minutes) for c in configs] == [
+ (approved.id, _GENERAL, SignalScoutConfig.ManagedBy.BACKGROUND, 720)
+ ]
+
+ def test_max_new_teams_per_tick_spreads_setup_over_ticks(self):
+ teams = [self._team(), self._team()]
+ background = _background({t.id for t in teams}, max_new=1)
+
+ _collect_planned_runs(_NO_ENROLLMENT, background=background)
+ assert SignalScoutConfig.all_teams.filter(team__in=teams).count() == 1
+
+ _collect_planned_runs(_NO_ENROLLMENT, background=background)
+ assert SignalScoutConfig.all_teams.filter(team__in=teams).count() == 2
+
+ @pytest.mark.parametrize(
+ "approved,block,expect_dispatch",
+ [
+ (True, "enabled", True),
+ (False, "enabled", False), # consent withdrawn after setup
+ (True, "disabled", False), # kill switch
+ (True, "absent", False), # explicit enrollment alone never runs a background config
+ ],
+ )
+ def test_dispatch_is_gated_on_consent_and_the_block(self, approved, block, expect_dispatch):
+ team = self._team(approved=approved)
+ with team_scope(team.id, canonical=True):
+ _create_skill(team, _GENERAL)
+ _create_config(team, _GENERAL, managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
+ background = None if block == "absent" else _background({team.id}, enabled=block == "enabled")
+ enrollment = Enrollment(wildcard=False, explicit={team.id}, skip=set())
+
+ with patch("products.signals.backend.temporal.agentic.scout_coordinator.register_missing_configs") as seed:
+ seed.return_value = {_GENERAL}
+ planned = _collect_planned_runs(enrollment, background=background)
+
+ expected = [PlannedRun(team_id=team.id, skill_name=_GENERAL)] if expect_dispatch else []
+ assert planned == expected
+
+ def test_departed_team_is_paused_and_resumes_when_listed_again(self):
+ team = self._team()
+ with team_scope(team.id, canonical=True):
+ background_config = _create_config(team, _GENERAL, managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
+ user_config = _create_config(team, "signals-scout-errors")
+
+ _collect_planned_runs(_NO_ENROLLMENT, background=_background(set(), enabled=False))
+
+ background_config.refresh_from_db()
+ user_config.refresh_from_db()
+ assert background_config.status == SignalScoutConfig.Status.PAUSED_BY_SYSTEM
+ assert background_config.pause_reason == SignalScoutConfig.PauseReason.BACKGROUND_REMOVED
+ assert user_config.status == SignalScoutConfig.Status.ACTIVE
+
+ _collect_planned_runs(_NO_ENROLLMENT, background=_background({team.id}))
+
+ background_config.refresh_from_db()
+ assert background_config.status == SignalScoutConfig.Status.ACTIVE
+ assert background_config.enabled is True
+
+
# ── Schedule: deterministic due-check, no sampling ──────────────────────────────