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): optional per-team scout config overrides via flag payload (#64370)

Andrew Maguiref9f6f9e7b54e
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 86b8fbf12713..c1eef966393c 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -50,9 +50,17 @@ MAX_RUNS_PER_TICK = 1000
# per day: cap × ticks/day), so a team registering many scouts degrades its own cadence,
# not everyone else's. Sized well above the canonical fleet (~16 scouts) so a fully-enrolled
# team is never trimmed; round-robin allocation still keeps any one team from starving the
-# others even when this is close to the global cap.
+# others even when this is close to the global cap. This is the DEFAULT — a per-team override
+# takes precedence when set in the `signals-scout` flag payload under `team_configs` (see
+# `_team_configs`), to give an important dogfooder more headroom or hold a noisy one lower,
+# no deploy.
MAX_RUNS_PER_TEAM_PER_TICK = 50
+# Key inside a team's `team_configs` entry that overrides `MAX_RUNS_PER_TEAM_PER_TICK` for that
+# team. `team_configs` is a forward-looking per-team override bag — add more keys here as other
+# settings become per-team-tunable; each consumer reads + validates the key it cares about.
+TEAM_CONFIG_MAX_RUNS_PER_TICK = "max_runs_per_tick"
+
# Coordinator tick cadence. Per-scout schedules are enforced via the due-check, so this is
# just the polling granularity — the floor on how often any scout can run.
COORDINATOR_INTERVAL_MINUTES = 30
@@ -114,11 +122,16 @@ async def fetch_enabled_signals_scout_runs_activity(
schedule is due — most-overdue first, capped at MAX_RUNS_PER_TICK.
"""
async with Heartbeater():
- # Read the flag payload off the DB thread pool — the SDK call can block on a cold
+ # Read the flag payload once, 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)
+ # 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)
+ team_configs = _team_configs(payload)
+ planned = await database_sync_to_async(_collect_planned_runs, thread_sensitive=False)(
+ enrolled_team_ids, team_configs
+ )
logger.info("signals_scout coordinator: planned runs", count=len(planned))
return FetchEnabledRunsOutput(planned_runs=planned)
@@ -159,12 +172,14 @@ class _DueRun:
skill_name: str
-def _collect_planned_runs(enrolled_team_ids: set[int]) -> list[PlannedRun]:
+def _collect_planned_runs(enrolled_team_ids: set[int], team_configs: dict[int, dict] | 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 so the flag read stays off this DB pool.
+ Takes the already-resolved enrolled team ids (and optional per-team config overrides) so
+ the flag reads stay off this DB pool.
"""
now = timezone.now()
+ team_configs = _canonicalize_team_config_keys(team_configs 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.
@@ -193,35 +208,47 @@ def _collect_planned_runs(enrolled_team_ids: set[int]) -> list[PlannedRun]:
if not due:
return []
- selected = _allocate_tick_budget(due)
+ selected = _allocate_tick_budget(due, team_configs)
planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in selected]
# Stable order for predictable child-workflow ids within the tick.
planned.sort(key=lambda p: (p.team_id, p.skill_name))
return planned
-def _allocate_tick_budget(due: list[_DueRun]) -> list[_DueRun]:
+def _allocate_tick_budget(due: list[_DueRun], team_configs: dict[int, dict] | 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
+ Each team's due runs are ordered most-overdue-first and trimmed to its per-team cap — the
+ `max_runs_per_tick` from its `team_configs` flag override if set, else
`MAX_RUNS_PER_TEAM_PER_TICK`; the global `MAX_RUNS_PER_TICK` budget is then filled
- round-robin across teams (one run per team per round) so a single team with many due
- scouts can't monopolize the tick. Deferred runs stay unstamped, so they're the most
- overdue next tick — a poor-man's queue, same catch-up semantics as before.
+ 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.
"""
+ team_configs = team_configs or {}
+
+ def _team_cap(team_id: int) -> int:
+ # Per-team override takes precedence; validate the value here (the config blob is
+ # arbitrary flag JSON) and fall back to the global default if absent or invalid.
+ override = (team_configs.get(team_id) or {}).get(TEAM_CONFIG_MAX_RUNS_PER_TICK)
+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:
+ return override
+ return MAX_RUNS_PER_TEAM_PER_TICK
+
by_team: dict[int, list[_DueRun]] = {}
for d in due:
by_team.setdefault(d.team_id, []).append(d)
for team_id, runs in by_team.items():
runs.sort(key=lambda d: (-d.overdue_s, d.skill_name))
- if len(runs) > MAX_RUNS_PER_TEAM_PER_TICK:
+ cap = _team_cap(team_id)
+ if len(runs) > cap:
logger.warning(
"signals_scout coordinator: team over per-tick cap, deferring overflow",
team_id=team_id,
due=len(runs),
- cap=MAX_RUNS_PER_TEAM_PER_TICK,
+ cap=cap,
)
- del runs[MAX_RUNS_PER_TEAM_PER_TICK:]
+ del runs[cap:]
# 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.
@@ -236,7 +263,10 @@ def _allocate_tick_budget(due: list[_DueRun]) -> list[_DueRun]:
# Most-overdue team first, team id as the deterministic tiebreak.
team_order = sorted(by_team, key=lambda t: (-by_team[t][0].overdue_s, t))
selected: list[_DueRun] = []
- for round_idx in range(MAX_RUNS_PER_TEAM_PER_TICK):
+ # Lists are already trimmed to each team's cap, so the longest list is exactly the number
+ # 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:
break
for team_id in team_order:
@@ -266,6 +296,28 @@ def _participating_teams(enrolled: set[int]) -> list[Team]:
return list(Team.objects.filter(id__in=canonical_ids).order_by("id"))
+def _canonicalize_team_config_keys(team_configs: dict[int, dict]) -> dict[int, dict]:
+ """Remap child-env config keys to their parent project id so per-team overrides line up with
+ the canonical team ids planning uses — `_participating_teams` canonicalizes enrollment the
+ same way, so an operator listing a child env id in both `guaranteed_team_ids` and
+ `team_configs` keeps its override. If both a parent and one of its child envs are keyed, the
+ explicit parent-keyed config wins regardless of dict order."""
+ if not team_configs:
+ return team_configs
+ parent_of = {
+ team_id: (parent_id or team_id)
+ for team_id, parent_id in Team.objects.filter(id__in=team_configs.keys()).values_list("id", "parent_team_id")
+ }
+ canonical: dict[int, dict] = {}
+ for team_id, config in team_configs.items():
+ canonical_id = parent_of.get(team_id, team_id)
+ # A parent/standalone key (team_id == canonical_id) always wins; a child remap only
+ # fills in when no parent-keyed config is present for that project.
+ if team_id == canonical_id or canonical_id not in canonical:
+ canonical[canonical_id] = config
+ return canonical
+
+
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)
@@ -274,41 +326,87 @@ def _fallback_team_ids() -> list[int]:
return list(DEFAULT_ENROLLED_TEAM_IDS) if (is_cloud() or settings.DEBUG) else []
-def _enrolled_team_ids() -> set[int]:
- """Project ids enrolled in scouts, read from the `signals-scout` flag's JSON payload.
+def _read_flag_payload() -> dict | None:
+ """Read + parse the `signals-scout` flag's JSON payload once.
- 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`.
+ 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. Returns the parsed dict, or `None` when the payload is absent / not an object /
+ unreadable. A read error never breaks dispatch: callers apply their own fallback to `None`.
+ Enrollment and per-team configs both derive from a single call to this so they always see
+ the same snapshot. Mirrors `posthog/temporal/ai_observability/team_discovery.py`.
"""
- fallback = _fallback_team_ids()
try:
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)
+ return payload if isinstance(payload, dict) else None
+ except Exception as error:
+ capture_exception(error)
+ return None
- # 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]:
+ """Project ids enrolled in scouts, parsed from the `signals-scout` flag payload.
- return set(guaranteed) - set(skip)
- except Exception as error:
- capture_exception(error)
+ 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`.
+ """
+ fallback = _fallback_team_ids()
+ if payload is None:
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)
+
+
+def _team_configs(payload: dict | None) -> dict[int, dict]:
+ """Optional per-team config overrides, parsed from the same `signals-scout` flag payload as
+ enrollment. Returns `{team_id: config_dict}`.
+
+ Payload key `team_configs` is a `{team_id: {…}}` map — a forward-looking per-team override
+ bag. Today the only honored key is `max_runs_per_tick` (overrides `MAX_RUNS_PER_TEAM_PER_TICK`
+ for that team — give an important dogfooder more headroom or hold a noisy one lower, no
+ deploy); add more per-team settings under the same blob later. The override takes precedence
+ over the global default for its team; teams not listed keep the global default.
+
+ Absent/malformed (`None` payload included) → `{}` (everyone on the defaults). Defensive
+ parse: JSON object keys arrive as strings so they're coerced to int; entries whose value
+ isn't a dict are dropped. Each consumer validates the specific key it reads (see
+ `_allocate_tick_budget._team_cap`). Keys are canonicalized to parent projects at planning
+ time (see `_canonicalize_team_config_keys`).
+ """
+ if payload is None:
+ return {}
+
+ raw = payload.get("team_configs", {})
+ if not isinstance(raw, dict):
+ return {}
+
+ configs: dict[int, dict] = {}
+ for key, value in raw.items():
+ if not isinstance(value, dict):
+ continue
+ try:
+ team_id = int(key)
+ except (TypeError, ValueError):
+ continue
+ configs[team_id] = value
+ return configs
+
def _overdue_seconds(config: SignalScoutConfig, now: datetime) -> float | None:
"""Seconds past due (down to `-DUE_GRACE_SECONDS`), or None if not yet due. Never-run rows are maximally overdue."""
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 6e38ac793a9e..ee528dd60bbc 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -31,6 +31,8 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
SignalsScoutCoordinatorWorkflow,
StampDispatchedRunsInput,
_enrolled_team_ids,
+ _read_flag_payload,
+ _team_configs,
fetch_enabled_signals_scout_runs_activity,
stamp_dispatched_signals_scout_runs_activity,
)
@@ -154,7 +156,7 @@ 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
+ assert _enrolled_team_ids(_read_flag_payload()) == expected
@pytest.mark.flag_off
@@ -162,7 +164,7 @@ 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()
+ _read_flag_payload()
args, kwargs = mock_payload.call_args
assert args[0] == "signals-scout"
assert args[1] == SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID
@@ -172,7 +174,7 @@ def test_enrolled_team_ids_uses_match_value_true():
@pytest.mark.flag_off
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 _enrolled_team_ids(_read_flag_payload()) == set(DEFAULT_ENROLLED_TEAM_IDS)
@pytest.mark.flag_off
@@ -182,9 +184,9 @@ def test_enrolled_team_ids_fails_closed_off_cloud():
# 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()
+ assert _enrolled_team_ids(_read_flag_payload()) == set()
with patch(_PAYLOAD_PATH, return_value={"guaranteed_team_ids": [5]}):
- assert _enrolled_team_ids() == {5}
+ assert _enrolled_team_ids(_read_flag_payload()) == {5}
@pytest.mark.asyncio
@@ -428,6 +430,120 @@ async def test_global_cap_is_split_fairly_across_teams(ateam, aother_team):
]
+# ── Per-team config overrides via the flag payload (optional, opt-in per team) ───
+
+
+ "payload,expected",
+ [
+ # String keys (JSON object keys) coerced to int; arbitrary config blob kept verbatim.
+ (
+ {"team_configs": {"5": {"max_runs_per_tick": 10}, "6": {"max_runs_per_tick": 3}}},
+ {5: {"max_runs_per_tick": 10}, 6: {"max_runs_per_tick": 3}},
+ ),
+ ('{"team_configs": {"9": {"max_runs_per_tick": 7}}}', {9: {"max_runs_per_tick": 7}}), # JSON string payload
+ ({"team_configs": {"5": "nope"}}, {}), # non-dict config value dropped
+ ({"team_configs": "nope"}, {}), # wrong type → empty
+ ({}, {}), # absent key → existing behaviour (no overrides)
+ (None, {}), # no payload → no overrides
+ ],
+)
+def test_team_configs_parses_payload(payload, expected):
+ with patch(_PAYLOAD_PATH, return_value=payload):
+ assert _team_configs(_read_flag_payload()) == expected
+
+
+def test_team_configs_falls_back_to_empty_on_error():
+ # A read error never breaks dispatch — every team falls back to the global default cap.
+ with patch(_PAYLOAD_PATH, side_effect=RuntimeError("flag service down")):
+ assert _team_configs(_read_flag_payload()) == {}
+
+
+async def test_per_team_config_cap_override_takes_precedence(ateam):
+ # Three due scouts. A `team_configs` override caps THIS team at 1/tick (below the global
+ # default of 50), so only its single most-overdue scout dispatches — proving the per-team
+ # override is read from the flag payload and takes precedence.
+ now = timezone.now()
+ for name, hours in [("signals-scout-most", 10), ("signals-scout-mid", 5), ("signals-scout-least", 2)]:
+ await database_sync_to_async(_create_skill)(ateam, name)
+ await database_sync_to_async(_create_config)(
+ ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)
+ )
+
+ def _payload(*_a, **_k):
+ return {
+ "guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS],
+ "team_configs": {str(ateam.id): {"max_runs_per_tick": 1}},
+ }
+
+ with patch(_PAYLOAD_PATH, side_effect=_payload):
+ planned = await _run_activity()
+
+ assert [p.skill_name for p in planned] == ["signals-scout-most"]
+
+
+async def test_team_without_config_override_keeps_global_default(ateam):
+ # An override set for a DIFFERENT team must not affect this one — it keeps the global
+ # default. Both this team's due scouts dispatch (global default of 50 is not exceeded).
+ now = timezone.now()
+ for name, hours in [("signals-scout-most", 10), ("signals-scout-mid", 5)]:
+ await database_sync_to_async(_create_skill)(ateam, name)
+ await database_sync_to_async(_create_config)(
+ ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)
+ )
+
+ def _payload(*_a, **_k):
+ return {
+ "guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS],
+ "team_configs": {"999999": {"max_runs_per_tick": 1}}, # some other team
+ }
+
+ with patch(_PAYLOAD_PATH, side_effect=_payload):
+ planned = await _run_activity()
+
+ assert sorted(p.skill_name for p in planned) == ["signals-scout-mid", "signals-scout-most"]
+
+
+async def test_per_team_config_override_keyed_by_child_env_applies_to_parent(ateam, aorganization):
+ # An operator enrolls a child environment id (the same id they'd list in guaranteed_team_ids).
+ # Planning canonicalizes that child to its parent project, so a team_configs override keyed by
+ # the child id must be canonicalized the same way to land on the parent. Cap at 1/tick via the
+ # child-keyed override and assert only the most-overdue scout dispatches.
+ child = await sync_to_async(Team.objects.create)(
+ organization=aorganization,
+ name=f"SignalsCoordinatorChildEnv-{random.randint(1, 99999)}",
+ parent_team=ateam,
+ )
+
+ now = timezone.now()
+ for name, hours in [("signals-scout-most", 10), ("signals-scout-mid", 5), ("signals-scout-least", 2)]:
+ await database_sync_to_async(_create_skill)(ateam, name)
+ await database_sync_to_async(_create_config)(
+ ateam, name, enabled=True, run_interval_minutes=60, last_run_at=now - timedelta(hours=hours)
+ )
+
+ def _payload(*_a, **_k):
+ return {
+ "guaranteed_team_ids": [child.id],
+ "team_configs": {str(child.id): {"max_runs_per_tick": 1}},
+ }
+
+ with patch(_PAYLOAD_PATH, side_effect=_payload):
+ planned = await _run_activity()
+
+ assert [p.skill_name for p in planned] == ["signals-scout-most"]
+
+ await sync_to_async(child.delete)()
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_auto_register_past_enabled_cap_creates_disabled_config(ateam):