: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): add per-team daily run budget and daily seed cadence (#64862)
Andrew Maguire9c2882178d62
diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.pyindex 2f9557308731..f18da8f5d824 100644--- a/products/signals/backend/scout_harness/config_registry.py+++ b/products/signals/backend/scout_harness/config_registry.py@@ -142,9 +142,11 @@ def register_missing_configs(team_id: int, seed_config_layers: list[dict] | Noneseed_enabled = in_allowlist and not at_capdefaults: 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:+ # The launch cadence is stamped on every canonical (gated) scout — whether it seeds+ # enabled now or stays disabled for the user to switch on later — so a specialist a user+ # toggles on runs at the daily launch cadence, not the 3h model default. Custom scouts+ # keep the model default so a user's own scout isn't forced onto the fleet's schedule.+ if 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 fromdiff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex 4ad397e63c4e..123c98621a30 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -6,7 +6,7 @@ from dataclasses import dataclassfrom datetime import datetime, timedeltafrom django.conf import settings-from django.db.models import Q+from django.db.models import Count, Qfrom django.utils import timezoneimport structlog@@ -21,7 +21,7 @@ from posthog.models import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater-from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.config_registry import register_missing_configsfrom products.signals.backend.scout_harness.lazy_seed import sync_canonical_skillsfrom products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflow@@ -66,6 +66,25 @@ MAX_RUNS_PER_TEAM_PER_TICK = 50# the key it cares about.TEAM_CONFIG_MAX_RUNS_PER_TICK = "max_runs_per_tick"+# Per-team DAILY run budget — the cost guarantee the per-tick cap can't express. The tick cap+# bounds bursts (≤ cap per 30-min tick → ≤ cap × 48/day); this bounds the day directly, so a+# launch team that enables many scouts (or cranks their intervals down) still runs at most N+# times a day. Counted over a rolling 24h window of dispatched runs and folded into the per-team+# tick cap (the tighter of the two binds each tick — see `_allocate_tick_budget`).+#+# `None` = no daily cap (the historical behaviour; the per-tick cap stays the only bound). Like+# the tick cap, the effective value resolves most-specific-first (see `_resolve_max_runs_per_day`):+# a team's `team_configs` entry → the fleet-wide `default_team_config` → this code constant. Left+# `None` so existing teams are unchanged; the launch posture sets a small N on+# `default_team_config` in the flag, no deploy.+MAX_RUNS_PER_TEAM_PER_DAY: int | None = None++# Key inside `team_configs` / `default_team_config` that overrides `MAX_RUNS_PER_TEAM_PER_DAY`.+TEAM_CONFIG_MAX_RUNS_PER_DAY = "max_runs_per_day"++# Rolling window the per-team daily budget is counted over.+DAILY_BUDGET_WINDOW = timedelta(hours=24)+# 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@@ -224,7 +243,13 @@ def _collect_planned_runs(if not due:return []- selected = _allocate_tick_budget(due, team_configs, default_team_config)+ # Only count runs for teams that actually have a resolved daily budget — for the default+ # rollout (no `max_runs_per_day` set anywhere) this skips the aggregate query entirely.+ capped_team_ids = {+ 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)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))@@ -235,21 +260,36 @@ def _allocate_tick_budget(due: list[_DueRun],team_configs: dict[int, dict] | None = None,default_team_config: dict | None = None,+ runs_today: dict[int, 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 per-team cap,- resolved per `_resolve_max_runs_per_tick` (team override → fleet default → code constant);- 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+ 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. Deferredruns stay unstamped, so they're the most overdue next tick — a poor-man's queue, samecatch-up semantics as before.++ 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+ budget (`_resolve_max_runs_per_day` minus `runs_today`). The daily budget is what bounds a+ team to N runs/day regardless of how many scouts it enables or how short their intervals —+ the per-tick cap alone can only bound bursts (≤ cap × ticks/day)."""team_configs = team_configs or {}default_team_config = default_team_config or {}+ runs_today = runs_today or {}def _team_cap(team_id: int) -> int:- return _resolve_max_runs_per_tick(team_id, team_configs, default_team_config)+ per_tick = _resolve_max_runs_per_tick(team_id, team_configs, default_team_config)+ per_day = _resolve_max_runs_per_day(team_id, team_configs, default_team_config)+ if per_day is None:+ return per_tick+ # Day's remaining headroom caps this tick too: a team that's spent its daily budget gets+ # 0 this tick, no matter how many scouts are due. Counted runs exclude this tick's+ # not-yet-started dispatches; the per-tick cap bounds that brief window.+ remaining_today = max(0, per_day - runs_today.get(team_id, 0))+ return min(per_tick, remaining_today)by_team: dict[int, list[_DueRun]] = {}for d in due:@@ -258,14 +298,28 @@ def _allocate_tick_budget(runs.sort(key=lambda d: (-d.overdue_s, d.skill_name))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=cap,- )+ if cap == 0:+ # The expected steady state once a team has spent its daily budget — info, not a+ # warning, so it doesn't read as a misconfiguration in alerting (it would otherwise+ # fire every tick for the rest of the 24h window).+ logger.info(+ "signals_scout coordinator: team daily budget spent, deferring all due scouts",+ team_id=team_id,+ deferred=len(runs),+ )+ else:+ logger.warning(+ "signals_scout coordinator: team over effective per-team cap, deferring overflow",+ team_id=team_id,+ due=len(runs),+ cap=cap,+ )del runs[cap:]+ # Drop teams trimmed to zero (e.g. daily budget spent) so the round-robin's most-overdue-team+ # sort never indexes into an empty list.+ by_team = {team_id: runs for team_id, runs in by_team.items() if runs}+# 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())@@ -310,6 +364,40 @@ def _resolve_max_runs_per_tick(team_id: int, team_configs: dict[int, dict], defareturn MAX_RUNS_PER_TEAM_PER_TICK+def _resolve_max_runs_per_day(team_id: int, team_configs: dict[int, dict], default_team_config: dict) -> int | None:+ """Effective per-team daily run budget, most-specific layer first.++ `team_configs[team_id]` (per-team override) → `default_team_config` (fleet-wide default) →+ `MAX_RUNS_PER_TEAM_PER_DAY` (code constant, `None` = unbounded). Same per-layer fallback and+ validation (positive int, not bool) as `_resolve_max_runs_per_tick`: a malformed value at one+ layer falls through to the next rather than failing the tick. `None` means no daily cap — only+ the per-tick cap binds, the historical behaviour.+ """+ for source in ((team_configs.get(team_id) or {}), default_team_config):+ override = source.get(TEAM_CONFIG_MAX_RUNS_PER_DAY)+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:+ return override+ return MAX_RUNS_PER_TEAM_PER_DAY+++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.++ Counts `SignalScoutRun` bridge rows (created at run start), so the budget tracks runs that+ actually happened — the durable, cost-relevant signal. Uses the unscoped `all_teams` manager,+ matching the coordinator's other cross-team reads. A run dispatched this tick but not yet+ started isn't counted until its row lands; the per-tick cap bounds that brief window.+ """+ if not team_ids:+ return {}+ rows = (+ SignalScoutRun.all_teams.filter(team_id__in=team_ids, created_at__gte=window_start)+ .values("team_id")+ .annotate(n=Count("id"))+ )+ return {row["team_id"]: row["n"] for row in rows}++def _participating_teams(enrolled: set[int]) -> list[Team]:"""Resolve enrolled team ids to canonical `Team`s to run scouts on.diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.pyindex dda0026bfeb3..a7011ea5938e 100644--- a/products/signals/backend/test/test_scout_coordinator.py+++ b/products/signals/backend/test/test_scout_coordinator.py@@ -30,9 +30,12 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (PlannedRun,SignalsScoutCoordinatorWorkflow,StampDispatchedRunsInput,+ _allocate_tick_budget,_default_team_config,+ _DueRun,_enrolled_team_ids,_read_flag_payload,+ _resolve_max_runs_per_day,_team_configs,fetch_enabled_signals_scout_runs_activity,stamp_dispatched_signals_scout_runs_activity,@@ -738,6 +741,116 @@ async def test_seed_enabled_interval_validates_bounds(ateam, interval, expected)assert general.run_interval_minutes != interval+async def test_seed_launch_cadence_stamped_on_disabled_canonical(ateam):+ # Option B: a canonical scout that seeds DISABLED under the allowlist still gets the launch+ # cadence stamped, so when the user later toggles it on it runs at the daily cadence, not the+ # 3h model default. general is allowlisted (enabled); error-tracking is gated (disabled).+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-general")+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-error-tracking")++ 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": 1440,+ },+ }++ with patch(_PAYLOAD_PATH, side_effect=_payload):+ await _run_activity()++ rows = await database_sync_to_async(+ lambda: {+ c.skill_name: (c.enabled, c.run_interval_minutes)+ for c in SignalScoutConfig.all_teams.filter(team_id=ateam.id)+ }+ )()+ assert rows["signals-scout-general"] == (True, 1440)+ # Disabled, but already on the daily cadence — so enabling it later doesn't run it every 3h.+ assert rows["signals-scout-error-tracking"] == (False, 1440)+++# ── Per-team daily run budget (max_runs_per_day) ──────────────────────────────────+++ "team_configs,default_cfg,expected",+ [+ ({}, {}, None), # nothing set → unbounded (only the per-tick cap binds)+ ({}, {"max_runs_per_day": 3}, 3), # fleet default binds+ ({7: {"max_runs_per_day": 10}}, {"max_runs_per_day": 3}, 10), # per-team override wins+ ({7: {"max_runs_per_day": "nope"}}, {"max_runs_per_day": 3}, 3), # malformed team → fleet default+ ({}, {"max_runs_per_day": 0}, None), # non-positive → falls through to the constant (None)+ ({}, {"max_runs_per_day": True}, None), # bool rejected+ ],+)+def test_resolve_max_runs_per_day(team_configs, default_cfg, expected):+ assert _resolve_max_runs_per_day(7, team_configs, default_cfg) == expected+++def _due_run(team_id: int, skill_name: str, overdue_s: float) -> _DueRun:+ return _DueRun(overdue_s=overdue_s, config_pk=skill_name, team_id=team_id, skill_name=skill_name)+++ "default_cfg,runs_today,due_skills,expected",+ [+ # Budget 3, 2 already run today → 1 slot left, so only the most-overdue dispatches (the+ # per-tick cap of 50 is nowhere near binding).+ (+ {"max_runs_per_day": 3},+ {7: 2},+ [("signals-scout-most", 10), ("signals-scout-mid", 5), ("signals-scout-least", 2)],+ ["signals-scout-most"],+ ),+ # Budget fully spent → 0 runs this tick; the empty team must not crash the round-robin.+ ({"max_runs_per_day": 3}, {7: 3}, [("signals-scout-most", 10)], []),+ # Pre-existing over-run (runs_today > budget) → still 0, no negative cap.+ ({"max_runs_per_day": 3}, {7: 5}, [("signals-scout-most", 10)], []),+ # No daily budget set → historical behaviour: every due run (within the per-tick cap) goes.+ ({}, {7: 999}, [("signals-scout-a", 1), ("signals-scout-b", 2)], ["signals-scout-a", "signals-scout-b"]),+ ],+)+def test_daily_budget_allocation(default_cfg, runs_today, due_skills, expected):+ due = [_due_run(7, name, hours * 3600) for name, hours in due_skills]+ selected = _allocate_tick_budget(due, {}, default_cfg, runs_today)+ assert sorted(d.skill_name for d in selected) == sorted(expected)+++async def test_daily_budget_bounds_dispatch_end_to_end(ateam):+ # End-to-end through the activity: fleet daily budget 2, team already ran once today (the+ # trailing-24h count is stubbed to 1) → only 1 slot left, so the single most-overdue scout+ # dispatches regardless of the per-tick cap.+ 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],+ "default_team_config": {"max_runs_per_day": 2},+ }++ with (+ patch(_PAYLOAD_PATH, side_effect=_payload),+ patch(+ "products.signals.backend.temporal.agentic.scout_coordinator._runs_today_by_team",+ return_value={ateam.id: 1},+ ),+ ):+ planned = await _run_activity()++ assert [p.skill_name for p in planned] == ["signals-scout-most"]++@pytest.mark.asyncio@pytest.mark.django_dbasync def test_planned_runs_sorted_by_team_then_skill(ateam, aother_team):