: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): wildcard scout enrollment + flag-tunable global tick cap (#65404)
Andrew Maguire2a2de108849a
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 931a64d9bc49..91f22feeac46 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -79,11 +79,17 @@ ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow'sSingle 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, plus enrollment (`guaranteed_team_ids` / `skip_team_ids`, with a cloud/dev-gated- fallback) and the editorial banner string. 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.+ dispatch, 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`).+ 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.- `serializers.py`DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).Annotated for drf-spectacular so the generated MCP tools have informative schemas.diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex f48bea530694..b32153414e35 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -98,6 +98,31 @@ def _resolve_seed_posture(seed_config_layers: list[dict] | None) -> tuple[set[streturn enabled_skills, enabled_interval+def live_scout_skill_names(+ team_id: int,+ withheld_skill_names: frozenset[str] | set[str] | None = None,+) -> set[str]:+ """Live (latest, non-deleted) `signals-scout-*` skill names for a team, minus the holdback set.++ The read-only half of `register_missing_configs`'s skill scan, with no seeding side effects. The+ coordinator dispatches only configs whose skill is in this set, so a config whose skill was+ deleted or superseded isn't run. Used on the wildcard (no-seed) dispatch path — a team that+ self-enrolled through the UI already has its configs, so the per-tick seed/reconcile is skipped+ and this cheap read is what still gates dispatch correctly.+ """+ names = set(+ LLMSkill.objects.filter(+ team_id=team_id,+ name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,+ is_latest=True,+ deleted=False,+ ).values_list("name", flat=True)+ )+ if withheld_skill_names:+ names -= set(withheld_skill_names)+ return names++def register_missing_configs(team_id: int,seed_config_layers: list[dict] | None = None,diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex bd453175f5f5..764af3b997a4 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -1145,7 +1145,11 @@ class ScoutMetadataSerializer(serializers.Serializer):change without a deploy to either app."""enrolled = serializers.BooleanField(- help_text="Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist)."+ help_text=(+ "Whether this project runs scouts. True when the project is in the signals-scout flag's "+ 'enrollment set — either listed explicitly in guaranteed_team_ids or covered by the "*" '+ "wildcard (every project that turns scouts on) — and not in skip_team_ids."+ ))banner_message = serializers.CharField(allow_null=True,diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.pyindex 3a7b904e1e35..31865c79d594 100644--- a/products/signals/backend/scout_harness/team_limits.py+++ b/products/signals/backend/scout_harness/team_limits.py@@ -131,29 +131,83 @@ def _read_flag_payload() -> dict | None:return None-def _enrolled_team_ids(payload: dict | None) -> set[int]:- """Project ids enrolled in scouts, parsed from the `signals-scout` flag payload.+# Sentinel inside `guaranteed_team_ids` that enrolls EVERY team which already has scout configs,+# instead of an explicit per-team allowlist. With `"*"` present, enrollment inverts: the gate+# becomes "does this team have enabled scout configs" (created via the product-autonomy-gated UI /+# the on-demand `sync` materialization), not "is this id listed". Explicit numeric ids can still sit+# alongside `"*"` to force-provision teams that haven't self-enrolled yet (the pinned internal+# projects), and `skip_team_ids` still hard-excludes. So `["*"]` flips scouts to "on for everyone+# who turns them on" while keeping per-team control + the kill switch.+ENROLL_ALL_TOKEN = "*"+++@dataclass(frozen=True)+class Enrollment:+ """Parsed scout enrollment from the `signals-scout` flag 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.- Fail-safe: a missing/invalid payload (`None`) or malformed value falls back to- `_fallback_team_ids`.+ `wildcard` → `"*"` was present: every team with enabled scout configs participates.+ `explicit` → the explicit numeric `guaranteed_team_ids` (skip NOT yet removed). Under a+ wildcard these are still force-provisioned (seeded from nothing); without one they ARE the+ allowlist. `skip` → `skip_team_ids`, the override kill-switch applied over both.+ """++ wildcard: bool+ explicit: set[int]+ skip: set[int]+++def _parse_enrollment(payload: dict | None) -> Enrollment:+ """Parse enrollment (wildcard + explicit ids + skip) from the flag payload in one pass.++ Flag-driven, no deploy: edit `guaranteed_team_ids` in the flag UI to enroll/drain on the next+ tick; `skip_team_ids` is the override kill-switch. Defensive, matching the historical contract:+ a missing/unreadable payload or a malformed `guaranteed_team_ids` value falls back to+ `_fallback_team_ids` (cloud/dev only). A list may mix the `"*"` wildcard token with integer ids;+ ANY other entry type marks the whole list malformed → fallback, so a typo can't silently widen+ or narrow enrollment. An explicit empty list is honored as an intentional "drain all" (no+ wildcard, no ids) — not coerced to the fallback."""fallback = _fallback_team_ids()if payload is None:- return set(fallback)+ return Enrollment(wildcard=False, explicit=set(fallback), skip=set())++ raw = payload.get("guaranteed_team_ids", fallback)+ wildcard = False+ explicit: set[int] = set()+ if isinstance(raw, list):+ malformed = False+ for entry in raw:+ if entry == ENROLL_ALL_TOKEN:+ wildcard = True+ elif isinstance(entry, int) and not isinstance(entry, bool):+ explicit.add(entry)+ else:+ malformed = True+ break+ if malformed:+ wildcard, explicit = False, set(fallback)+ else:+ explicit = set(fallback)++ raw_skip = payload.get("skip_team_ids", [])+ if isinstance(raw_skip, list) and all(isinstance(t, int) and not isinstance(t, bool) for t in raw_skip):+ skip = set(raw_skip)+ else:+ skip = set()++ return Enrollment(wildcard=wildcard, explicit=explicit, skip=skip)- # 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 = []+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.- return set(guaranteed) - set(skip)+ Does NOT reflect the `"*"` wildcard: the coordinator reads `_parse_enrollment` directly so it+ can resolve the config-derived wildcard set, while `enrolled` in the UI metadata folds the+ wildcard in via `_resolve_enrolled`.+ """+ enrollment = _parse_enrollment(payload)+ return enrollment.explicit - enrollment.skipdef _team_configs(payload: dict | None) -> dict[int, dict]:@@ -239,6 +293,29 @@ def _resolve_max_runs_per_day(team_id: int, team_configs: dict[int, dict], defaureturn MAX_RUNS_PER_TEAM_PER_DAY+# Flag payload key overriding the GLOBAL per-tick dispatch ceiling (the coordinator's+# `MAX_RUNS_PER_TICK`). Read fresh each tick like the per-team caps, so the fleet-wide ceiling can+# be raised with no deploy if enrollment grows past the default's headroom (e.g. a launch blast+# enrolls thousands of teams at once via the `"*"` wildcard), or lowered to throttle spend in an+# incident. Absent / malformed / non-positive → the code default the coordinator passes in.+GLOBAL_MAX_RUNS_PER_TICK_KEY = "max_runs_per_tick_global"+++def _resolve_global_max_runs_per_tick(payload: dict | None, default: int) -> int:+ """Effective global per-tick dispatch ceiling: the flag override if valid, else `default`.++ `default` is the coordinator's `MAX_RUNS_PER_TICK` constant, passed in to avoid a circular+ import (the coordinator imports this module, not vice versa). A positive-int override wins+ (raise or lower); anything else falls through to the default rather than failing the tick.+ """+ if payload is None:+ return default+ override = payload.get(GLOBAL_MAX_RUNS_PER_TICK_KEY)+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:+ return override+ return default++def _resolve_withheld_skills(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> set[str]:"""Skill names held back from a team, resolved most-specific layer first.@@ -271,6 +348,30 @@ def withheld_skills_for_team(canonical_team_id: int) -> set[str]:return _resolve_withheld_skills(canonical_team_id, team_configs, _default_team_config(payload))+def resolve_sync_seed_inputs(canonical_team_id: int) -> tuple[list[dict], set[str]]:+ """One flag-payload read → `(seed_config_layers, withheld_skills)` for the on-demand `sync` path.++ The `sync` endpoint needs both the seed posture and the holdback denylist; resolving them from a+ single read keeps them on the same snapshot (the same single-read discipline the coordinator+ uses), so the withheld set and the seed layers can't be derived from two different flag states if+ the flag changes mid-request.++ `seed_config_layers` (most-specific first: the team's `team_configs` override over the fleet+ `default_team_config`) mirror what the coordinator builds for the scheduled path, so the on-demand+ materialization (the product-autonomy-gated wizard's self-driving program) seeds the SAME launch+ posture (e.g. general-only, daily) instead of the full fleet enabled — without this the self-serve+ path silently bypassed the launch cost posture. `canonical_team_id` must be the parent/project id;+ `team_configs` keys are canonicalized so a child-keyed override still resolves. A missing/unreadable+ payload yields `([{}, {}], set())` → the historical full-fleet seed, nothing withheld.+ """+ payload = _read_flag_payload()+ team_configs = _canonicalize_team_config_keys(_team_configs(payload))+ default_team_config = _default_team_config(payload)+ seed_config_layers = [team_configs.get(canonical_team_id) or {}, default_team_config]+ withheld = _resolve_withheld_skills(canonical_team_id, team_configs, default_team_config)+ return seed_config_layers, withheld++def _runs_today_by_team(team_ids: set[int], window_start: datetime) -> dict[int, int]:"""Scout runs dispatched per team within the trailing daily-budget window.@@ -338,6 +439,19 @@ def _is_team_enrolled(canonical_team_id: int, enrolled_ids: set[int]) -> bool:return canonical_team_id in canonical_enrolled+def _resolve_enrolled(canonical_team_id: int, enrollment: Enrollment) -> bool:+ """Whether a project runs scouts, honoring the `"*"` wildcard.++ A skipped team is never enrolled. Otherwise enrolled iff the wildcard is set (everyone is in —+ the UI gates whether they actually HAVE configs) or the team is in the explicit allowlist.+ Canonicalizes child-env ids the same way the coordinator does (`_is_team_enrolled`)."""+ if _is_team_enrolled(canonical_team_id, enrollment.skip):+ return False+ if enrollment.wildcard:+ return True+ return _is_team_enrolled(canonical_team_id, enrollment.explicit)++@dataclass(frozen=True)class ScoutTeamLimits:"""A team's effective scout run caps + current usage, all resolved the way dispatch enforces."""@@ -393,7 +507,7 @@ def resolve_team_metadata(canonical_team_id: int) -> ScoutTeamMetadata:runs_remaining_today = None if max_runs_per_day is None else max(0, max_runs_per_day - runs_today)return ScoutTeamMetadata(- enrolled=_is_team_enrolled(canonical_team_id, _enrolled_team_ids(payload)),+ enrolled=_resolve_enrolled(canonical_team_id, _parse_enrollment(payload)),banner_message=read_banner_message(payload),limits=ScoutTeamLimits(max_runs_per_tick=_resolve_max_runs_per_tick(canonical_team_id, team_configs, default_team_config),diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 56944c2e826c..0daf76ebad8e 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -81,7 +81,11 @@ from products.signals.backend.scout_harness.serializers import (SignalScoutRunDetailSerializer,SignalScoutRunSummarySerializer,)-from products.signals.backend.scout_harness.team_limits import resolve_team_metadata, withheld_skills_for_team+from products.signals.backend.scout_harness.team_limits import (+ resolve_sync_seed_inputs,+ resolve_team_metadata,+ withheld_skills_for_team,+)from products.signals.backend.scout_harness.tools.emit import EvidenceEntry, InvalidEmitError, emit_finding_syncfrom products.signals.backend.scout_harness.tools.profile import get_project_profilefrom products.signals.backend.scout_harness.tools.runs import get_run, search_recent_runs@@ -997,12 +1001,16 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# seed and register against that team so child-environment requests don't fork# a second fleet.team = self.team if self.team.parent_team_id is None else Team.objects.get(id=self.team.parent_team_id)- # Honor the per-scout holdback denylist on this on-demand path too, so a held-back scout- # can't be seeded/enabled by a manual fleet materialization (the coordinator already gates- # the scheduled path).- withheld = withheld_skills_for_team(team.id)+ # Resolve the holdback denylist + the launch seed posture from a single flag read so they+ # can't disagree if the flag changes mid-request (the coordinator reads once and threads the+ # snapshot too). Holdback: a held-back scout can't be seeded/enabled by a manual fleet+ # materialization (the coordinator already gates the scheduled path). Posture: seed the same+ # launch shape the coordinator applies (general-only / daily etc., team_configs over+ # default_team_config) so a self-serve materialization doesn't bypass the launch cost posture+ # by enabling the full fleet.+ seed_config_layers, withheld = resolve_sync_seed_inputs(team.id)sync_canonical_skills(team, withheld_skill_names=withheld)- register_missing_configs(team.id, withheld_skill_names=withheld)+ register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld)# Exclude held-back scouts from the materialized fleet response too: a scout that was# previously seeded and later withheld still has a row, and surfacing it here would# advertise an unreleased scout despite the holdback. Storage is left untouched (nodiff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 02341e8adc2a..2f0e230bef67 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -18,7 +18,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeaterfrom products.signals.backend.models import SignalScoutConfig-from products.signals.backend.scout_harness.config_registry import register_missing_configs+from products.signals.backend.scout_harness.config_registry import live_scout_skill_names, register_missing_configsfrom products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills# Per-team cap resolution + the flag-payload read live in the temporalio-free `team_limits` module@@ -26,10 +26,12 @@ from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skil# them unqualified and tests can patch them on this module.from products.signals.backend.scout_harness.team_limits import (DAILY_BUDGET_WINDOW,+ Enrollment,_canonicalize_team_config_keys,_default_team_config,- _enrolled_team_ids,+ _parse_enrollment,_read_flag_payload,+ _resolve_global_max_runs_per_tick,_resolve_max_runs_per_day,_resolve_max_runs_per_tick,_resolve_withheld_skills,@@ -112,11 +114,15 @@ async def fetch_enabled_signals_scout_runs_activity(# asyncio.to_thread split in ai_observability/team_discovery.py). Enrollment and per-team# configs are derived from the same snapshot so they can't disagree across two reads.payload = await asyncio.to_thread(_read_flag_payload)- enrolled_team_ids = _enrolled_team_ids(payload)+ enrollment = _parse_enrollment(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+ # snapshot, falling back to the code constant. `MAX_RUNS_PER_TICK` is read at call time so+ # tests patching the module global still take effect.+ global_max_runs_per_tick = _resolve_global_max_runs_per_tick(payload, MAX_RUNS_PER_TICK)planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(- enrolled_team_ids, team_configs, default_team_config+ enrollment, team_configs, default_team_config, global_max_runs_per_tick)logger.info("signals_scout coordinator: planned runs", count=len(planned))return FetchEnabledRunsOutput(planned_runs=planned)@@ -159,45 +165,61 @@ class _DueRun:def _collect_planned_runs(- enrolled_team_ids: set[int],+ enrollment: Enrollment,team_configs: dict[int, dict] | None = None,default_team_config: dict | None = None,+ max_runs_per_tick: int | None = None,) -> list[PlannedRun]:"""Sync DB scan. Runs in a worker thread via Django's per-thread connection mgmt.- Takes the already-resolved enrolled team ids, the optional per-team config overrides, and- the fleet-wide default config so the flag reads stay off this DB pool.+ 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."""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):+ for team, needs_seed in _participating_teams(enrollment):# Scouts held back from this team via the `withheld_skills` denylist (resolved most-# specific-first from this team's `team_configs` entry, then the fleet `default_team_config`):# skip seeding the skill, skip seeding/enabling a config, and skip dispatch.withheld_for_team = _resolve_withheld_skills(team.id, team_configs, default_team_config)- # 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- # leaves prune off). The sync also propagates updates to canonical content for any- # harness-seeded row the team hasn't edited, so a merged SKILL.md change rolls out- # within one coordinator tick. Idempotent; a failure here doesn't abort the tick.- try:- sync_canonical_skills(team, prune=True, withheld_skill_names=withheld_for_team)- except Exception:- logger.exception(- "signals_scout coordinator: canonical skill sync failed for team; continuing",- team_id=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]- # `register_missing_configs` drops withheld skills from its return, so they're already- # excluded from `live_skills` (and thus from dispatch below) as well as from seeding.- live_skills = register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld_for_team)+ if needs_seed:+ # Explicitly enrolled (a pinned / force-provisioned id): seed from nothing. The periodic+ # tick is the reconciliation path. `sync_canonical_skills(prune=True)` tombstones rows+ # whose canonical was removed from disk and propagates merged SKILL.md updates to+ # harness-seeded rows the team hasn't edited, so a content change rolls out within one+ # tick. Idempotent; a failure here doesn't abort the tick.+ try:+ sync_canonical_skills(team, prune=True, withheld_skill_names=withheld_for_team)+ except Exception:+ logger.exception(+ "signals_scout coordinator: canonical skill sync failed for team; continuing",+ team_id=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]+ # `register_missing_configs` drops withheld skills from its return, so they're already+ # excluded from `live_skills` (and thus from dispatch below) as well as from seeding.+ live_skills = register_missing_configs(team.id, seed_config_layers, withheld_skill_names=withheld_for_team)+ else:+ # Wildcard-discovered (`"*"`): the team already self-seeded its configs through the+ # product-autonomy-gated UI / `sync` materialization, so skip the per-tick seed ++ # reconcile — that's what keeps the hot path cheap as self-enrollment scales to thousands+ # of teams. Read only the live scout skill names (cheap) so a config whose skill was+ # deleted/superseded isn't dispatched, and honor the holdback denylist. Central canonical+ # SKILL.md updates still reach these teams: the runner cold-starts with its own+ # `sync_canonical_skills` before loading the skill (runner.py), so a merged change lands+ # on the scout's NEXT RUN for any harness-seeded row the team hasn't forked. What the+ # per-tick skip drops is only the eager refresh on ticks where nothing dispatches, plus+ # the `prune=True` tombstoning of disk-deleted canonicals and first-appearance of+ # brand-new canonical scouts as rows — both rare, and both catch up on the team's next+ # `sync` (follow-up if needed: a slow fleet-wide prune/seed sweep off the dispatch path).+ live_skills = live_scout_skill_names(team.id, withheld_skill_names=withheld_for_team)# 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.@@ -216,7 +238,7 @@ def _collect_planned_runs(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)+ selected = _allocate_tick_budget(due, team_configs, default_team_config, runs_today, max_runs_per_tick)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))@@ -228,14 +250,17 @@ def _allocate_tick_budget(team_configs: dict[int, dict] | None = None,default_team_config: dict | None = None,runs_today: dict[int, int] | None = None,+ max_runs_per_tick: int | None = None,) -> 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 its effective per-team- cap, then the global `MAX_RUNS_PER_TICK` budget is 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.+ cap, then the global budget is 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.++ The global budget is `max_runs_per_tick` (the flag-resolved ceiling the activity passes in),+ falling back to the `MAX_RUNS_PER_TICK` code constant for direct callers that don't supply one.The effective per-team cap is the tighter of two bounds: the per-tick cap(`_resolve_max_runs_per_tick`) and the day's remaining headroom under the per-team daily@@ -246,6 +271,7 @@ def _allocate_tick_budget(team_configs = team_configs or {}default_team_config = default_team_config or {}runs_today = runs_today or {}+ global_cap = max_runs_per_tick if max_runs_per_tick is not None else MAX_RUNS_PER_TICKdef _team_cap(team_id: int) -> int:per_tick = _resolve_max_runs_per_tick(team_id, team_configs, default_team_config)@@ -290,11 +316,11 @@ def _allocate_tick_budget(# 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:+ if total_after_team_caps > global_cap:logger.warning("signals_scout coordinator: more due than cap, deferring overflow",due=total_after_team_caps,- cap=MAX_RUNS_PER_TICK,+ cap=global_cap,)# Most-overdue team first, team id as the deterministic tiebreak.@@ -304,33 +330,64 @@ def _allocate_tick_budget(# of rounds needed — this naturally covers a team with a raised override too.max_rounds = max((len(runs) for runs in by_team.values()), default=0)for round_idx in range(max_rounds):- if len(selected) >= MAX_RUNS_PER_TICK:+ if len(selected) >= global_cap:breakfor team_id in team_order:runs = by_team[team_id]if round_idx >= len(runs):continueselected.append(runs[round_idx])- if len(selected) >= MAX_RUNS_PER_TICK:+ if len(selected) >= global_cap:breakreturn selected-def _participating_teams(enrolled: set[int]) -> list[Team]:- """Resolve enrolled team ids to canonical `Team`s to run scouts on.+def _canonicalize_team_ids(ids: set[int]) -> set[int]:+ """Map team ids to their canonical parent project id (child env → parent), dropping ids with no+ `Team` row. Mirrors `_canonicalize_team_config_keys` / `_is_team_enrolled` so enrollment,+ configs, and dispatch all key on the same project id."""+ if not ids:+ return set()+ return {+ (parent_id or team_id)+ for team_id, parent_id in Team.objects.filter(id__in=ids).values_list("id", "parent_team_id")+ }+- 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.+def _participating_teams(enrollment: Enrollment) -> list[tuple[Team, bool]]:+ """Resolve enrollment to canonical `Team`s to run scouts on, each tagged `needs_seed`.++ Two ways a team participates:+ - explicit `guaranteed_team_ids` (skip removed) → force-provisioned: `needs_seed=True`, so the+ tick seeds canonical skills + registers configs from nothing (the pinned internal projects).+ Adding an id in the flag UI enrolls it on the next tick with no manual seed; removing it (or+ listing it in `skip_team_ids`) drains it.+ - the `"*"` wildcard → every team that already has an enabled `SignalScoutConfig`+ (`needs_seed=False`): it self-enrolled through the product-autonomy-gated UI, so it already+ has configs and the tick skips the expensive seed/reconcile for it. If a team is in both, the+ explicit tag wins (it gets the seed pass).+ Child envs canonicalize to their parent project; `skip_team_ids` is removed from both sets.+ Skip is subtracted AFTER canonicalizing both sides, so listing a child env in `guaranteed_team_ids`+ and its parent project in `skip_team_ids` (or the reverse) still hard-excludes the project — the+ raw ids differ but their canonical parent matches."""- if not enrolled:+ skip_canonical = _canonicalize_team_ids(enrollment.skip)+ explicit = _canonicalize_team_ids(enrollment.explicit) - skip_canonical++ wildcard_ids: set[int] = set()+ if enrollment.wildcard:+ # Config rows persist under the canonical parent team, so these ids are already canonical.+ wildcard_ids = set(+ SignalScoutConfig.all_teams.filter(enabled=True).values_list("team_id", flat=True).distinct()+ )+ wildcard_ids -= skip_canonical+ wildcard_ids -= explicit # explicit wins the tag — it gets the seed pass below++ all_ids = explicit | wildcard_ids+ if not all_ids:return []- candidates = Team.objects.filter(id__in=enrolled)- canonical_ids = {team.parent_team_id or team.id for team in candidates}- return list(Team.objects.filter(id__in=canonical_ids).order_by("id"))+ teams = {team.id: team for team in Team.objects.filter(id__in=all_ids)}+ return [(teams[team_id], team_id in explicit) for team_id in sorted(all_ids) if team_id in teams]def _overdue_seconds(config: SignalScoutConfig, now: datetime) -> float | None:diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex ff37e32323e6..58edbb9dbd2c 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -28,14 +28,19 @@ from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY,from products.signals.backend.scout_harness.team_limits import (DEFAULT_ENROLLED_TEAM_IDS,SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,+ Enrollment,_default_team_config,_enrolled_team_ids,+ _parse_enrollment,_read_flag_payload,+ _resolve_enrolled,+ _resolve_global_max_runs_per_tick,_resolve_max_runs_per_day,_resolve_withheld_skills,_team_configs,)from products.signals.backend.temporal.agentic.scout_coordinator import (+ MAX_RUNS_PER_TICK,CoordinatorWorkflowInput,CoordinatorWorkflowOutput,FetchEnabledRunsInput,@@ -229,6 +234,168 @@ async def test_skip_team_ids_drains_an_enrolled_team(ateam):assert all(p.team_id != ateam.id for p in planned)+# ── Wildcard enrollment: "*" enrolls every team that has enabled scout configs ──────+++ "guaranteed,skip,expected_wildcard,expected_explicit",+ [+ (["*"], None, True, set()), # pure wildcard, no explicit ids+ (["*", 5], None, True, {5}), # wildcard + a force-provisioned id+ ([5, 6], None, False, {5, 6}), # no wildcard → today's allowlist behaviour+ (["*"], [5], True, set()), # wildcard with a skip override+ ([], None, False, set()), # empty list → intentional drain-all, NOT the fallback (cf. None)+ (["*", "nope"], None, False, set(DEFAULT_ENROLLED_TEAM_IDS)), # bad entry → whole list malformed → fallback+ ],+)+def test_parse_enrollment_wildcard(guaranteed, skip, expected_wildcard, expected_explicit):+ payload: dict[str, Any] = {"guaranteed_team_ids": guaranteed}+ if skip is not None:+ payload["skip_team_ids"] = skip+ with patch(_PAYLOAD_PATH, return_value=payload), patch(_IS_CLOUD_PATH, return_value=True):+ enrollment = _parse_enrollment(_read_flag_payload())+ assert enrollment.wildcard is expected_wildcard+ assert enrollment.explicit == expected_explicit+ assert enrollment.skip == (set(skip) if skip else set())+++async def test_wildcard_dispatches_team_with_enabled_config(ateam):+ # A team NOT in any explicit allowlist still runs under "*" purely because it has an enabled+ # scout config (the self-serve gate). Membership assertion: the global wildcard scan can also+ # pick up configs leaked by other committing async tests, so we assert ateam is present, not+ # that it is the only one.+ 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(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": ["*"]}):+ planned = await _run_activity()++ assert any(p.team_id == ateam.id and p.skill_name == "signals-scout-errors" for p in planned)+++async def test_wildcard_does_not_auto_seed_a_config_less_team(ateam):+ # Under "*" a team participates only if it ALREADY has configs — the wildcard never seeds from+ # nothing (that's the explicit-id path). A team with a scout skill but no config row is left+ # untouched: no run, and no config is auto-created for it.+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")++ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": ["*"]}):+ planned = await _run_activity()++ assert all(p.team_id != ateam.id for p in planned)+ config_count = await database_sync_to_async(SignalScoutConfig.all_teams.filter(team_id=ateam.id).count)()+ assert config_count == 0+++async def test_explicit_id_still_seeds_a_config_less_team(ateam):+ # The contrast to the wildcard case: an explicitly-listed id IS force-provisioned — the tick+ # seeds a config for its scout skill and dispatches it, even with no pre-existing config row.+ # (Canonical sync is stubbed to a no-op, so only the hand-authored skill exists → exactly one+ # config is seeded.)+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")++ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [ateam.id]}):+ planned = await _run_activity()++ assert any(p.team_id == ateam.id and p.skill_name == "signals-scout-errors" for p in planned)+ config_count = await database_sync_to_async(SignalScoutConfig.all_teams.filter(team_id=ateam.id).count)()+ assert config_count == 1+++async def test_wildcard_honors_skip_team_ids(ateam):+ # The kill switch still bites under "*": a skipped team with an enabled config is drained.+ 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(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": ["*"], "skip_team_ids": [ateam.id]}):+ planned = await _run_activity()++ assert all(p.team_id != ateam.id for p in planned)++[email protected]("guaranteed_child,skip_child", [(True, False), (False, True)])+async def test_skip_canonicalizes_across_parent_child(ateam, aorganization, guaranteed_child, skip_child):+ # The kill switch must bite even when guaranteed_team_ids and skip_team_ids reference the same+ # project via DIFFERENT ids — one the child env, one the parent. Skip is applied after both sides+ # canonicalize to the parent, so a raw `explicit - skip` (which would miss the cross-id case)+ # can't let a hard-excluded project slip through and run.+ child = await sync_to_async(Team.objects.create)(+ organization=aorganization,+ name=f"SignalsCoordinatorSkipChild-{random.randint(1, 99999)}",+ parent_team=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)++ guaranteed_id = child.id if guaranteed_child else ateam.id+ skip_id = child.id if skip_child else ateam.id+ with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [guaranteed_id], "skip_team_ids": [skip_id]}):+ planned = await _run_activity()++ assert all(p.team_id != ateam.id for p in planned)+ await sync_to_async(child.delete)()+++# ── Enrollment metadata reflects the wildcard ──────+++ "wildcard,in_explicit,in_skip,expected",+ [+ (True, False, False, True), # wildcard → everyone enrolled+ (True, False, True, False), # skip overrides the wildcard+ (False, True, False, True), # explicit allowlist+ (False, False, False, False), # not wildcard, not listed → not enrolled+ ],+)+def test_resolve_enrolled_wildcard(wildcard, in_explicit, in_skip, expected):+ # `_resolve_enrolled` short-circuits on direct set membership before any Team lookup, so a fake+ # id exercises every branch without needing a committed row.+ team_id = 999_999+ enrollment = Enrollment(+ wildcard=wildcard,+ explicit={team_id} if in_explicit else set(),+ skip={team_id} if in_skip else set(),+ )+ assert _resolve_enrolled(team_id, enrollment) is expected+++# ── Global per-tick ceiling is flag-tunable ──────+++ "payload,expected",+ [+ (None, MAX_RUNS_PER_TICK), # no payload → code default+ ({}, MAX_RUNS_PER_TICK), # absent key → code default+ ({"max_runs_per_tick_global": 5000}, 5000), # raise the ceiling for a launch blast+ ({"max_runs_per_tick_global": 100}, 100), # lower it to throttle+ ({"max_runs_per_tick_global": 0}, MAX_RUNS_PER_TICK), # non-positive → default+ ({"max_runs_per_tick_global": "x"}, MAX_RUNS_PER_TICK), # wrong type → default+ ({"max_runs_per_tick_global": True}, MAX_RUNS_PER_TICK), # bool is not a valid int here+ ],+)+def test_resolve_global_max_runs_per_tick(payload, expected):+ assert _resolve_global_max_runs_per_tick(payload, MAX_RUNS_PER_TICK) == expected++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_disabled_config_is_skipped(ateam):diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 9ad7a03cfe2c..87727d6611d3 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -492,7 +492,7 @@ export interface ScoutLimitsApi {* change without a deploy to either app.*/export interface ScoutMetadataApi {- /** Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist). */+ /** Whether this project runs scouts. True when the project is in the signals-scout flag's enrollment set — either listed explicitly in guaranteed_team_ids or covered by the "*" wildcard (every project that turns scouts on) — and not in skip_team_ids. */enrolled: boolean/*** Free-form announcement banner to show above the scout UI (e.g. alpha run-limit notice), or null when unset.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ebe84561100f..61d7c3ed6dce 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -45271,7 +45271,7 @@ export namespace Schemas {* change without a deploy to either app.*/export interface ScoutMetadata {- /** Whether this project is enrolled to run scouts (set via the signals-scout flag allowlist). */+ /** Whether this project runs scouts. True when the project is in the signals-scout flag's enrollment set — either listed explicitly in guaranteed_team_ids or covered by the "*" wildcard (every project that turns scouts on) — and not in skip_team_ids. */enrolled: boolean;/*** Free-form announcement banner to show above the scout UI (e.g. alpha run-limit notice), or null when unset.