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): configure the enabled-scout cap per project (#105682)

posthog[bot]584d0d00dd1f
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 463a0268a3fe..6e900d3b0cf8 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2593,6 +2593,7 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
*,
pause_reason: "SignalScoutConfig.PauseReason",
evaluated_at: datetime | None = None,
+ max_enabled_scouts: int | None = None,
) -> bool:
"""Apply a system-driven status transition under the reason-scoped ownership rule.
@@ -2605,11 +2606,26 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
after the caller read the row cannot be overwritten. Pass `evaluated_at` (when the
caller read the state its decision is based on) to also refuse the transition if the
status moved after that moment, e.g. a human re-enable racing a sweep's pause.
+ `max_enabled_scouts` is the project's already-resolved enabled-scout ceiling, for a
+ caller that is inside a locked section. Left `None`, a resume resolves it here — before
+ the transaction opens, so the flag read never happens while row locks are held.
Saves and returns True when the transition applies; returns False without writing
when it is refused or a no-op.
"""
if new_status == self.Status.PAUSED_BY_USER:
raise ValueError("Only a user write may set paused_by_user.")
+ # A resume must not carry the team past the enabled-scout cap: the pause freed a slot the
+ # config API may have legitimately given to another scout since. Only a resume needs the
+ # ceiling, so a pause pays for no flag read.
+ resume_cap: int | None = None
+ if new_status in self.RUNNABLE_STATUSES:
+ from products.signals.backend.scout_harness.team_limits import ( # noqa: PLC0415 — importing via the scout_harness package init would put lazy_seed/skill_loader on the django.setup() path that loads this module
+ max_enabled_scouts_for_team,
+ )
+
+ resume_cap = (
+ max_enabled_scouts if max_enabled_scouts is not None else max_enabled_scouts_for_team(self.team_id)
+ )
with transaction.atomic():
# One ordered query locks the whole team's rows, not just ours: the cap check below
# counts sibling rows, so two concurrent resumes locking only their own rows would
@@ -2639,15 +2655,9 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
and locked.status_changed_at > evaluated_at
):
return False
- # A resume must not carry the team past the enabled-scout cap: the pause freed a
- # slot the config API may have legitimately given to another scout since.
- from products.signals.backend.scout_harness.limits import ( # noqa: PLC0415 — importing via the scout_harness package init would put lazy_seed/skill_loader on the django.setup() path that loads this module
- MAX_ENABLED_SCOUTS_PER_TEAM,
- )
-
- if new_status in self.RUNNABLE_STATUSES and locked.status not in self.RUNNABLE_STATUSES:
+ if resume_cap is not None and locked.status not in self.RUNNABLE_STATUSES:
peers = sum(1 for row in team_rows.values() if row.enabled and row.pk != locked.pk)
- if peers >= MAX_ENABLED_SCOUTS_PER_TEAM:
+ if peers >= resume_cap:
return False
recorded_reason = None if new_status == self.Status.ACTIVE else pause_reason
if new_status == locked.status and recorded_reason == locked.pause_reason:
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index dcda3e5296e2..1633ba870b68 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -34,7 +34,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- `config_registry.py`
`register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.
The scout's `scout-display-name` is stamped the same way, and additionally backfilled onto existing rows by `reconcile_canonical_display_names` — every canonical config predates the key, so nothing else would ever give them a label. That pass writes only where `display_name` is blank, so it can run on every tick without ever undoing a rename.
- An **operational** scout (`scout-role: operational`) is the one exception to all of that: it seeds enabled and `auto_pause_exempt`, past the `enabled_skills` allowlist and past `MAX_ENABLED_SCOUTS_PER_TEAM` (it still counts toward the cap, so its slot is visible), and `reconcile_operational_configs` runs on every tick to put rows seeded before the role existed back on those terms. The reconcile undoes only the harness's own silencing — a sweep warning or pause via `transition_status_by_system`, and a row the seed created disabled, which the model stores as `paused_by_user` and the reconcile tells apart by its null `status_changed_at`. A person's pause and a `repeated_failures` pause are both left standing. The holdback still gates the scout, whatever its role, and the config API refuses to delete it (`views.destroy`).
+ An **operational** scout (`scout-role: operational`) is the one exception to all of that: it seeds enabled and `auto_pause_exempt`, past the `enabled_skills` allowlist and past the enabled-scout cap (it still counts toward the cap, so its slot is visible), and `reconcile_operational_configs` runs on every tick to put rows seeded before the role existed back on those terms. The reconcile undoes only the harness's own silencing — a sweep warning or pause via `transition_status_by_system`, and a row the seed created disabled, which the model stores as `paused_by_user` and the reconcile tells apart by its null `status_changed_at`. A person's pause and a `repeated_failures` pause are both left standing. The holdback still gates the scout, whatever its role, and the config API refuses to delete it (`views.destroy`).
- `suggestions.py` / `suggestions_runner.py`
Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat button. `suggestions.py` (temporalio-free, cheap to import) holds the structured-output contract the headless run returns (`ScoutSuggestionBatch`: 3-5 items, each a `canonical` "turn this on" pick or a `custom` draft with a ready-to-create `draft_body`), the `signals-scout-suggestions` flag-payload settings (`enabled`, `eligibility_tier` 0-4 (0 = allowlist only), `refresh_days`, `max_children_per_tick`, allow/blocklist, failure breaker), the planner (`plan_suggestion_runs`: recomputes the priority queue from Postgres every tick; a project that has never ingested an event is no candidate at any tier, because the scan could only refuse it, and the gate is read from `Team.ingested_event` on the project or any of its environments at plan time rather than stamped on the row, so the project re-enters the queue on its first event and an allowlisted project is scanned either way; tier, then never-generated, then most overdue, then most recently engaged; engagement is a report view or rating, a scout a person turned on or off (`status_changed_by`), or a scout a person created (`created_by`), never a plain edit or a system touch; nothing is stored as a queue; engagement is read only for the teams already in the tier map, since `SignalReportAction.last_at` is deliberately unindexed and an unbounded filter on it scans the whole action history; a team past the failure breaker doubles its refresh interval per further failure, because the cooldown is shorter than the refresh window and so could never hold a scheduled retry back), the dispatch-time activity check (`select_teams_to_scan`: after the plan is made and before a child is dispatched, one bounded ClickHouse read per picked candidate over the project and its child environments together, counting events and distinct active days in `activity_window_days`, on the offline cluster, since a scheduled fleet scan must not compete with interactive queries (a Temporal activity keeps `Workload.ONLINE` unless it says otherwise, and `readonly=True` would return before the offline routing rather than add to it); a project under `min_events_in_window` or under `min_active_days_in_window` is stamped `low_activity` instead of scanned, because the scan could only refuse it, and either knob at 0 turns that half of the check off; the read is capped at `ACTIVITY_READ_MAX_ROWS` rows and refuses at the cap rather than truncating, because the cap counts rows read while the query counts the rows inside the window, so a truncated read would answer with a small count that reads like a quiet project; a refused read counts as active, since a project whose window does not fit the cap is active whatever the refusal hid; it carries a wall-clock cap too (`ACTIVITY_READ_MAX_EXECUTION_S`), because `sync_execute` sets none and the pooled client's socket timeout is effectively infinite in production, so a stalled read would hold a worker thread past the planning activity's deadline; a read that fails dispatches anyway, since the coordinator stamps `last_requested_at` either way and a quiet minute of ClickHouse must not cost a project its refresh window; allowlisted projects are scanned whatever the read says, and the manual refresh endpoint never runs the check, because a person who pressed the button asked for the scan; the coordinator therefore overselects the plan by `SUGGESTIONS_OVERSELECT_FACTOR` so a tick still fills when several candidates are skipped, and the skipped ones are stamped `last_requested_at` alongside the dispatched ones so the planner leaves them for a full refresh window rather than re-reading them every tick), draft validation (`validate_suggestion_items` drops anything the one-click Create could not apply as-is), and persistence on `SignalScoutSuggestionSet` (one row per team, items as JSON, every write under a row lock since each is a read-modify-write of the column; dismissals carry forward by `skill_name` and survive as hidden tombstones when a batch omits the name, compacted to the dismissal fields so a dropped draft body does not sit in the row forever; a batch persisted after the fleet moved is stored `stale`, and a batch that merely aged past `refresh_days`, whether it held items or concluded there was nothing to suggest, reads as `stale` through `effective_status`, since nothing writes that status on expiry; a failed generation anywhere after the gates keeps the prior items and counts toward the breaker; a `low_activity` stamp keeps the prior items the same way but leaves the breaker alone, since a quiet project is not a broken one: the count is preserved but ignored for scheduling while the status holds, so the backoff cannot push the next activity check out past one refresh window, and it counts again as soon as a scan runs; a quiet row also does not expire to `stale`, so the project waits a full refresh window and is then re-checked; `mark_stale_if_fleet_changed` is wired to `SignalScoutConfig` saves in `../receivers.py`). Reads hide dismissed, created, and already-enabled items, plus custom drafts whose name a stored skill or config has since taken; the manual refresh endpoint honors the same kill switch and blocklist as the planner, runs the scan as its authenticated caller rather than the resolved team member, and a manual dispatch stamps `last_requested_at` so the coordinator does not double up. `suggestions_runner.py` is the one piece that needs the tasks agent facade: `arun_scout_suggestions` gates (AI-processing consent, an acting user; deliberately no self-driving credits gate, since a scan opens no pull request and so bills nothing, while a skip would still burn the team's whole refresh window), mints a `read_only` headless task with the reserved `SIGNALS_SCOUT_SUGGESTIONS` origin, no GitHub token and no MCP Store servers, because the scan reads project text any member can write, parses the batch with no prose salvage (an unparseable close-out is a failed generation), validates, and persists. Both it and the activity check emit `$scout_suggestions_generated` through the one emitter in `suggestions.py` (`capture_suggestions_generated`), so a skipped project reads as `status=skipped`, `skip_reason=low_activity` plus the two measured numbers on the same event the completed runs use, and the daily roll-up needs no new column. The skip carries a stable event id, keyed on the project and the refresh stamp the decision was made against, because the planning activity retries and would otherwise count one skipped scan several times; a completed run needs none, since its activity runs at most once. Driven by `temporal/agentic/scout_suggestions.py` (coordinator + child, same shape as the scout coordinator, own schedule) and exposed read/dismiss/refresh at `signals/scout/suggestions/` (`../scout_suggestions_api.py`), where membership, token scope, and resource-level RBAC all anchor to the canonical parent team. The prompt shares `SCOUT_PROJECT_SCAN_GUIDANCE` (in `prompt.py`) with the chat template so the two voices never drift.
- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`
@@ -77,7 +77,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
Runtime ceilings as module constants: `DEFAULT_MAX_RUNTIME_S` (per-run budget), `ACTIVITY_SLACK_S`, and `WORKFLOW_HARD_CEILING_S` (`= DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's `start_to_close_timeout`).
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, 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`).
+ 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`).
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/config_registry.py b/products/signals/backend/scout_harness/config_registry.py
index 63471d5a82b5..f0218d88b8b8 100644
--- a/products/signals/backend/scout_harness/config_registry.py
+++ b/products/signals/backend/scout_harness/config_registry.py
@@ -35,8 +35,8 @@ from products.signals.backend.scout_harness.lazy_seed import (
canonical_skill_names,
is_operational_scout,
)
-from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
+from products.signals.backend.scout_harness.team_limits import resolve_max_enabled_scouts
from products.skills.backend.models.skills import LLMSkill
logger = structlog.get_logger(__name__)
@@ -222,8 +222,9 @@ def register_missing_configs(
so flipping the flag later doesn't disturb teams already seeded, and a user enabling a scout
won't be reverted on the next tick.
- The per-team `MAX_ENABLED_SCOUTS_PER_TEAM` cap is an independent second gate: even an
- allowlisted scout registers disabled once the team is at the cap. Both checks are best-effort
+ The per-team enabled-scout cap is an independent second gate: even an allowlisted scout
+ registers disabled once the team is at the cap. It resolves from the same `seed_config_layers`
+ (`max_enabled_scouts`), so registration and the API enforce one number. Both checks are best-effort
(count + create, no lock) — a race can briefly overshoot by one, which the coordinator's
per-tick caps still bound.
@@ -238,6 +239,7 @@ def register_missing_configs(
holdback still applies — a withheld scout is dropped above, whatever its role.
"""
enabled_skills, enabled_interval = _resolve_seed_posture(seed_config_layers)
+ max_enabled_scouts = resolve_max_enabled_scouts(seed_config_layers)
rows = list(
LLMSkill.objects.filter(
team_id=team_id,
@@ -280,7 +282,7 @@ def register_missing_configs(
missing = sorted(skill_names - existing - deprecated_names)
enabled = enabled_scout_count(team_id) if missing else 0
for name in missing:
- at_cap = enabled >= MAX_ENABLED_SCOUTS_PER_TEAM
+ at_cap = enabled >= max_enabled_scouts
operational = name in operational_names
# A canonical scout is gated by the allowlist (when one is set); a custom scout never is,
# and neither is an operational one. The explicit `is not None` keeps the membership check
@@ -329,12 +331,14 @@ def register_missing_configs(
"signals_scout: enabled-scout cap reached, auto-registered config disabled",
team_id=team_id,
skill_name=name,
- cap=MAX_ENABLED_SCOUTS_PER_TEAM,
+ cap=max_enabled_scouts,
)
reconcile_canonical_display_names(team_id, canonical_names & skill_names)
- reconcile_operational_configs(team_id, operational_names & skill_names, withheld_skill_names)
+ reconcile_operational_configs(
+ team_id, operational_names & skill_names, withheld_skill_names, max_enabled_scouts=max_enabled_scouts
+ )
# Keep the skills UI's Scouts tab in sync: stamp `category="scout"` on any scout skill rows
# not yet categorized (custom scouts authored via the skills API). Runs every reconcile tick,
@@ -375,6 +379,8 @@ def reconcile_operational_configs(
team_id: int,
skill_names: set[str],
withheld_skill_names: frozenset[str] | set[str] | None = None,
+ *,
+ max_enabled_scouts: int | None = None,
) -> None:
"""Put already-seeded operational scouts back on the posture their role asks for.
@@ -422,15 +428,20 @@ def reconcile_operational_configs(
team_id=team_id,
skill_name=config.skill_name,
)
- _resume_operational_config(config)
+ _resume_operational_config(config, max_enabled_scouts=max_enabled_scouts)
+
+def _resume_operational_config(config: SignalScoutConfig, *, max_enabled_scouts: int | None = None) -> None:
+ """Undo the harness's own silencing of one operational scout, and nothing else.
-def _resume_operational_config(config: SignalScoutConfig) -> None:
- """Undo the harness's own silencing of one operational scout, and nothing else."""
+ `max_enabled_scouts` is the caller's already-resolved cap. This runs inside the reconcile
+ transaction, which holds row locks, so the resolved value is passed in rather than read from
+ the flag here — a network read must not happen while those locks are held."""
if config.pause_reason in SignalScoutConfig.INACTIVITY_PAUSE_REASONS:
resumed = config.transition_status_by_system(
SignalScoutConfig.Status.ACTIVE,
pause_reason=SignalScoutConfig.PauseReason(config.pause_reason),
+ max_enabled_scouts=max_enabled_scouts,
)
elif config.status == SignalScoutConfig.Status.PAUSED_BY_USER and config.status_changed_at is None:
# `save` stores an `enabled=False` create as `paused_by_user`, so a row the seed disabled
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index dd1ecddb7842..8df4c4a3e179 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -170,4 +170,10 @@ WORKFLOW_RUN_COOLDOWN_S = 30 * 60
# spend, not a routine limit (the canonical fleet is ~16 scouts). Enforced at the write
# surfaces (config create/update) and in auto-registration, which falls back to registering
# new scouts disabled once the team is at the cap.
+#
+# This is the LAST-RESORT default, like the run budgets beside it. The effective ceiling
+# resolves most-specific-first through `team_limits.resolve_max_enabled_scouts`: a project's
+# `team_configs` entry → the fleet-wide `default_team_config` → this constant, all under the
+# `max_enabled_scouts` key of the `signals-scout` flag payload. A project that needs more
+# capacity gets it in the flag UI, with no deploy.
MAX_ENABLED_SCOUTS_PER_TEAM = 250
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 7bdcafb62ef9..614da9e0731c 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -3955,7 +3955,7 @@ class SignalScoutManualRunSerializer(serializers.Serializer):
class ScoutLimitsSerializer(serializers.Serializer):
- """A team's enforced scout run caps and current usage.
+ """A team's enforced scout caps and current usage.
These are the values the coordinator actually applies at dispatch (resolved per-team override →
fleet-wide default → code constant), so the UI can show the real throttle rather than what a
@@ -3976,6 +3976,9 @@ class ScoutLimitsSerializer(serializers.Serializer):
allow_null=True,
help_text="Runs still allowed in the trailing 24h window (max_runs_per_day − runs_today), or null when uncapped.",
)
+ max_enabled_scouts = serializers.IntegerField(
+ help_text="Most scouts the project can have switched on at once. Enabling another past this is rejected.",
+ )
class ScoutMetadataSerializer(serializers.Serializer):
diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.py
index 225588febdc6..411efdef7c27 100644
--- a/products/signals/backend/scout_harness/team_limits.py
+++ b/products/signals/backend/scout_harness/team_limits.py
@@ -10,6 +10,7 @@ path; both sides import from here so the reported caps never drift from what dis
from __future__ import annotations
import json
+from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
@@ -25,6 +26,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from products.signals.backend.models import SignalScoutRun
+from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM
logger = structlog.get_logger(__name__)
@@ -76,6 +78,12 @@ 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"
+# Key inside `team_configs` / `default_team_config` that overrides `MAX_ENABLED_SCOUTS_PER_TEAM`,
+# the ceiling on how many scouts one project may have switched on at once. A project that needs
+# more capacity than the fleet default gets it in the flag UI, with no deploy and without raising
+# the allowance for every other project.
+TEAM_CONFIG_MAX_ENABLED_SCOUTS = "max_enabled_scouts"
+
# Key inside `team_configs` / `default_team_config` controlling whether report-channel scouts get
# the `gh` evidence-gathering prompt guidance (reviewer routing from commit history by path, PR
# metadata — backed by the read-only token every scout sandbox gets regardless). Default ON so it
@@ -307,6 +315,39 @@ def _resolve_max_runs_per_day(team_id: int, team_configs: dict[int, dict], defau
return MAX_RUNS_PER_TEAM_PER_DAY
+def resolve_max_enabled_scouts(config_layers: Sequence[dict] | None) -> int:
+ """Effective enabled-scout ceiling for one project, most-specific layer first.
+
+ `config_layers` are the project's flag config layers in precedence order — its `team_configs`
+ entry, then the fleet `default_team_config`. The first layer carrying a positive int wins; an
+ absent or malformed value (null, zero, negative, fractional, string, bool) falls through to the
+ next layer and finally to `MAX_ENABLED_SCOUTS_PER_TEAM`, so a typo cannot silently widen or
+ narrow a project's allowance.
+
+ The single resolver every enforcement point reads, so the cap the API reports is the cap
+ registration and resume apply. Callers that already hold the layers (the coordinator, the
+ on-demand sync) pass them and pay no extra flag read; request-context callers use
+ `max_enabled_scouts_for_team`.
+ """
+ for source in config_layers or ():
+ override = source.get(TEAM_CONFIG_MAX_ENABLED_SCOUTS)
+ if isinstance(override, int) and not isinstance(override, bool) and override > 0:
+ return override
+ return MAX_ENABLED_SCOUTS_PER_TEAM
+
+
+def max_enabled_scouts_for_team(canonical_team_id: int) -> int:
+ """One flag-payload read → this project's enabled-scout ceiling.
+
+ `canonical_team_id` must be the parent/project id; `team_configs` keys are canonicalized so a
+ child-environment override still resolves, and an explicit parent-keyed entry wins over one
+ keyed on a child. A missing or unreadable payload yields `MAX_ENABLED_SCOUTS_PER_TEAM`.
+ """
+ payload = _read_flag_payload()
+ team_configs = _canonicalize_team_config_keys(_team_configs(payload))
+ return resolve_max_enabled_scouts([team_configs.get(canonical_team_id) or {}, _default_team_config(payload)])
+
+
# 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
@@ -527,6 +568,7 @@ class ScoutTeamLimits:
max_runs_per_day: int | None
runs_today: int
runs_remaining_today: int | None
+ max_enabled_scouts: int
@dataclass(frozen=True)
@@ -547,6 +589,7 @@ class ScoutTeamMetadata:
"max_runs_per_day": self.limits.max_runs_per_day,
"runs_today": self.limits.runs_today,
"runs_remaining_today": self.limits.runs_remaining_today,
+ "max_enabled_scouts": self.limits.max_enabled_scouts,
},
}
@@ -581,5 +624,8 @@ def resolve_team_metadata(canonical_team_id: int) -> ScoutTeamMetadata:
max_runs_per_day=max_runs_per_day,
runs_today=runs_today,
runs_remaining_today=runs_remaining_today,
+ max_enabled_scouts=resolve_max_enabled_scouts(
+ [team_configs.get(canonical_team_id) or {}, default_team_config]
+ ),
),
)
diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.py
index 55bf0b3e7e24..2b68d0c9df32 100644
--- a/products/signals/backend/scout_harness/tools/runs.py
+++ b/products/signals/backend/scout_harness/tools/runs.py
@@ -70,6 +70,9 @@ CRON_GAP_SAMPLES = 4
# yet" beside a cost line proving they had run. Rows stay bounded by the enabled cap in practice:
# only an enabled scout produces new runs, and a paused scout's last ones age out of the staleness
# guard.
+# A project may also raise its own enabled cap through the `signals-scout` flag, so this stays a
+# fixed guard rather than tracking that per-project value: the roster must not start truncating
+# because a flag edit moved a number, and a truncation is logged with the names it dropped.
MAX_SCOUTS_PER_RUNS_QUERY = 10 * MAX_ENABLED_SCOUTS_PER_TEAM
# How many scouts one probe statement covers. A large fleet costs more statements rather than one
diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.py
index e4fe3af151d4..7f3223b02bbd 100644
--- a/products/signals/backend/scout_harness/views.py
+++ b/products/signals/backend/scout_harness/views.py
@@ -82,7 +82,6 @@ from products.signals.backend.scout_harness.lazy_seed import (
is_operational_scout,
scout_skill_origin,
)
-from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM
from products.signals.backend.scout_harness.run_costs import scout_run_token_costs
from products.signals.backend.scout_harness.run_gates import (
ScoutRunRejection,
@@ -157,7 +156,11 @@ from products.signals.backend.scout_harness.skill_loader import (
resolve_scout_acting_user_id,
)
from products.signals.backend.scout_harness.suggestions import find_suggestion, mark_suggestion_created
-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 (
+ max_enabled_scouts_for_team,
+ resolve_team_metadata,
+ withheld_skills_for_team,
+)
from products.signals.backend.scout_harness.tools.checks import (
InvalidCheckResultError,
InvalidCheckWriteError,
@@ -2391,20 +2394,26 @@ class SignalScoutMembersViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
)
-def _reject_if_enabled_cap_reached(team_id: int, skill_name: str) -> None:
+def _reject_if_enabled_cap_reached(team_id: int, skill_name: str, *, cap: int) -> None:
"""Raise when enabling this scout would push the team past the per-team enabled cap.
Counts every enabled config except this skill's own row, so re-asserting
- `enabled=True` on an already-enabled scout is always allowed. Best-effort
- (count + write, no lock): a concurrent enable can overshoot by one, which the
- coordinator's per-tick caps still bound.
+ `enabled=True` on an already-enabled scout is always allowed. `cap` is the project's
+ effective ceiling, so the number in the error is the number enforcement uses; the
+ caller resolves it before opening its transaction, since resolving it reads the flag
+ and every write path here holds a row lock. The error names the count apart from the
+ cap, because a lowered cap pauses nothing and can leave the count above it.
+ Best-effort (count + write, no lock): a concurrent enable can overshoot by one, which
+ the coordinator's per-tick caps still bound.
"""
- if enabled_scout_count(team_id, exclude_skill=skill_name) >= MAX_ENABLED_SCOUTS_PER_TEAM:
+ enabled = enabled_scout_count(team_id, exclude_skill=skill_name)
+ if enabled >= cap:
+ to_disable = enabled - cap + 1
raise exceptions.ValidationError(
{
"enabled": (
- f"This project already has {MAX_ENABLED_SCOUTS_PER_TEAM} enabled scouts (the maximum). "
- "Disable one before enabling another."
+ f"This project already has {enabled} enabled scouts, and its limit is {cap}. "
+ f"Disable {to_disable} {'scout' if to_disable == 1 else 'scouts'} before you enable another."
)
}
)
@@ -2417,6 +2426,7 @@ def _upsert_scout_config(
tunables: dict,
request: Request,
serializer_context: dict,
+ max_enabled_scouts: int,
) -> tuple[SignalScoutConfig, bool]:
"""Create or tune one config while preserving the existing config endpoint's upsert semantics."""
@@ -2429,7 +2439,7 @@ def _upsert_scout_config(
else (not existing.enabled and tunables.get("enabled") is True)
)
if will_enable:
- _reject_if_enabled_cap_reached(team_id, skill_name)
+ _reject_if_enabled_cap_reached(team_id, skill_name, cap=max_enabled_scouts)
# `team_id` stays in the kwargs because queryset filters do not propagate into
# the row Django builds for `get_or_create`.
@@ -2536,6 +2546,10 @@ def create_scout_for_source(
if not UserAccessControl(user=user, team=team).check_access_level_for_resource("llm_skill", "editor"):
raise exceptions.PermissionDenied("Creating a scout requires editor access to skills.")
+ # Resolved before the transaction: it reads the `signals-scout` flag, and the block below
+ # holds row locks on the skill and its config.
+ max_enabled_scouts = max_enabled_scouts_for_team(team.id)
+
with transaction.atomic():
try:
skill = create_skill(
@@ -2605,6 +2619,7 @@ def create_scout_for_source(
skill_name=name,
tunables=tunables,
request=request,
+ max_enabled_scouts=max_enabled_scouts,
serializer_context=serializer_context,
)
# `create_skill` derives the server-owned `category` from the name prefix, so a scout under
@@ -3180,6 +3195,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
serializer.is_valid(raise_exception=True)
skill_name = serializer.validated_data["skill_name"]
+ max_enabled_scouts = max_enabled_scouts_for_team(team_id)
# Upsert, so the grant is compared against whatever row already exists — registering a
# config for an existing scout is the same widening as patching one. The row stays locked
# from the comparison to the save, so a grant revoked in between cannot be written back by
@@ -3214,6 +3230,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
tunables=tunables,
request=request,
serializer_context={**self.get_serializer_context(), "project_id": self.team.project_id},
+ max_enabled_scouts=max_enabled_scouts,
)
context = scout_config_context(team, [config.skill_name], request)
return Response(
@@ -3247,6 +3264,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
self._assert_can_author_structured_output_schema()
config_id = _parse_run_id_or_404(kwargs)
repositories_checked = _precheck_scout_repositories(request, team=team, config_id=config_id)
+ max_enabled_scouts = max_enabled_scouts_for_team(team_id)
# The row stays locked from the grant comparison to the save. A whole-config resend that
# compared against the grant before a concurrent revoke would otherwise write it back,
# because a model save writes every column off the instance it loaded.
@@ -3278,7 +3296,7 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
serializer.is_valid(raise_exception=True)
enabling = not config.enabled and serializer.validated_data.get("enabled")
if enabling:
- _reject_if_enabled_cap_reached(team_id, config.skill_name)
+ _reject_if_enabled_cap_reached(team_id, config.skill_name, cap=max_enabled_scouts)
# Fold `enabled_by` into the same save so enabling logs one activity entry, not two.
save_kwargs: dict[str, Any] = {}
if enabling:
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 3fabadf8dce5..9b46cec66fe8 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -31,6 +31,7 @@ from products.signals.backend.scout_harness.limits import (
AUTO_PAUSE_PROBE_INTERVAL_S,
DISPATCH_BATCH_INTERVAL_SECONDS,
DISPATCH_SMEAR_SECONDS,
+ MAX_ENABLED_SCOUTS_PER_TEAM,
)
# The flag-payload read + per-team cap resolution live in `scout_harness/team_limits.py`; helpers
@@ -52,6 +53,8 @@ from products.signals.backend.scout_harness.team_limits import (
_resolve_slot_aligned_dispatch,
_resolve_withheld_skills,
_team_configs,
+ max_enabled_scouts_for_team,
+ resolve_max_enabled_scouts,
)
from products.signals.backend.temporal.agentic.scout_coordinator import (
COORDINATOR_INTERVAL_MINUTES,
@@ -1282,6 +1285,78 @@ async def test_per_team_config_override_keyed_by_child_env_applies_to_parent(ate
await sync_to_async(child.delete)()
+# ── Enabled-scout ceiling via the flag payload (max_enabled_scouts) ──────────────
+
+
+ "layers,expected",
+ [
+ ([{"max_enabled_scouts": 500}, {"max_enabled_scouts": 300}], 500), # project override wins
+ ([{}, {"max_enabled_scouts": 300}], 300), # fleet default when the project sets none
+ ([{}, {}], MAX_ENABLED_SCOUTS_PER_TEAM), # neither layer → the code fallback
+ ([], MAX_ENABLED_SCOUTS_PER_TEAM), # no layers at all → the code fallback
+ (None, MAX_ENABLED_SCOUTS_PER_TEAM),
+ # Every invalid shape falls through to the next layer rather than binding, so a typo can
+ # neither widen nor narrow what a project may switch on.
+ ([{"max_enabled_scouts": None}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": 0}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": -5}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": 1.5}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": "500"}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": True}, {"max_enabled_scouts": 300}], 300),
+ ([{"max_enabled_scouts": 0}, {"max_enabled_scouts": "nope"}], MAX_ENABLED_SCOUTS_PER_TEAM),
+ ],
+)
+def test_resolve_max_enabled_scouts(layers, expected):
+ assert resolve_max_enabled_scouts(layers) == expected
+
+
+def test_max_enabled_scouts_for_team_falls_back_when_the_flag_read_fails(team):
+ # A flag outage must leave the ceiling at the code fallback rather than at zero, or every
+ # enable on every project would start failing.
+ with patch(_PAYLOAD_PATH, side_effect=Exception("flag service down")):
+ assert max_enabled_scouts_for_team(team.id) == MAX_ENABLED_SCOUTS_PER_TEAM
+
+
+def test_max_enabled_scouts_for_team_is_per_project(team):
+ # Two projects, one override: the listed project gets the raised ceiling and the other keeps
+ # the fleet default, which is the whole point of moving this off a global constant.
+ other = Team.objects.create(organization=team.organization, name="SignalsCapOtherProject")
+ payload = {
+ "default_team_config": {"max_enabled_scouts": 300},
+ "team_configs": {str(team.id): {"max_enabled_scouts": 500}},
+ }
+
+ with patch(_PAYLOAD_PATH, return_value=payload):
+ assert max_enabled_scouts_for_team(team.id) == 500
+ assert max_enabled_scouts_for_team(other.id) == 300
+
+ other.delete()
+
+
[email protected]("key_parent_too", [False, True])
+def test_max_enabled_scouts_for_team_resolves_child_environment_keys(team, key_parent_too):
+ # Scout rows live on the parent project, so an override keyed on a child environment has to
+ # canonicalize onto it. An explicit parent-keyed entry still wins over the child's.
+ child = Team.objects.create(organization=team.organization, name="SignalsCapChildEnv", parent_team=team)
+ team_configs: dict[str, dict] = {str(child.id): {"max_enabled_scouts": 400}}
+ if key_parent_too:
+ team_configs[str(team.id)] = {"max_enabled_scouts": 700}
+
+ with patch(_PAYLOAD_PATH, return_value={"team_configs": team_configs}):
+ resolved = max_enabled_scouts_for_team(team.id)
+
+ assert resolved == (700 if key_parent_too else 400)
+
+ child.delete()
+
+
# ── Fleet-wide default config via the flag payload (default_team_config) ──────────
@@ -1340,6 +1415,48 @@ async def test_default_team_config_resolution(ateam, team_override_cap, expected
assert sorted(p.skill_name for p in planned) == sorted(expected_names)
+ "payload_caps,expect_fresh_enabled",
+ [
+ # The fleet default caps the project at one enabled scout, so the fresh one registers paused.
+ ({"default_team_config": {"max_enabled_scouts": 1}}, False),
+ # A per-project override raises the ceiling above the fleet default, so it registers enabled.
+ (
+ {"default_team_config": {"max_enabled_scouts": 1}, "team_configs": {"max_enabled_scouts": 5}},
+ True,
+ ),
+ # An invalid per-project override falls through to the fleet default rather than widening.
+ (
+ {"default_team_config": {"max_enabled_scouts": 1}, "team_configs": {"max_enabled_scouts": 0}},
+ False,
+ ),
+ ],
+)
+async def test_auto_register_honours_the_flag_configured_enabled_cap(ateam, payload_caps, expect_fresh_enabled):
+ # Registration reads the same `max_enabled_scouts` layers the API enforces, so a project given
+ # more capacity in the flag gets its next scout enabled instead of parked.
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-existing")
+ await database_sync_to_async(_create_config)(ateam, "signals-scout-existing", enabled=True)
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-fresh")
+
+ def _payload(*_a, **_k):
+ payload: dict[str, Any] = {"guaranteed_team_ids": [int(t) for t in _FLAGGED_TEAM_IDS]}
+ payload["default_team_config"] = payload_caps["default_team_config"]
+ if "team_configs" in payload_caps:
+ payload["team_configs"] = {str(ateam.id): payload_caps["team_configs"]}
+ return payload
+
+ with patch(_PAYLOAD_PATH, side_effect=_payload):
+ await _run_activity()
+
+ fresh = await database_sync_to_async(
+ lambda: SignalScoutConfig.all_teams.get(team_id=ateam.id, skill_name="signals-scout-fresh")
+ )()
+ assert fresh.enabled is expect_fresh_enabled
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_auto_register_past_enabled_cap_creates_disabled_config(ateam):
@@ -1349,7 +1466,7 @@ async def test_auto_register_past_enabled_cap_creates_disabled_config(ateam):
await database_sync_to_async(_create_config)(ateam, "signals-scout-existing", enabled=True)
await database_sync_to_async(_create_skill)(ateam, "signals-scout-fresh")
- with patch("products.signals.backend.scout_harness.config_registry.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
+ with patch("products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
planned = await _run_activity()
fresh = await database_sync_to_async(
@@ -1550,7 +1667,7 @@ async def test_operational_scout_seeds_enabled_past_the_enabled_cap(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-fresh")
await database_sync_to_async(_create_skill)(ateam, _OPERATIONAL_SCOUT)
- with patch("products.signals.backend.scout_harness.config_registry.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
+ with patch("products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
await _run_activity()
rows = await database_sync_to_async(
diff --git a/products/signals/backend/test/test_scout_create_api.py b/products/signals/backend/test/test_scout_create_api.py
index 1f7681fdf881..361f69434889 100644
--- a/products/signals/backend/test/test_scout_create_api.py
+++ b/products/signals/backend/test/test_scout_create_api.py
@@ -251,7 +251,7 @@ class TestSignalScoutCreateAPI(APIBaseTest):
)
payload = self._payload()
- with patch("products.signals.backend.scout_harness.views.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
+ with patch("products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
response = self.client.post(self._url(), data=payload, format="json")
assert response.status_code == status.HTTP_400_BAD_REQUEST
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 37d7ab85b167..3ab8273cf7a3 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -58,7 +58,11 @@ from products.signals.backend.scout_harness.lazy_seed import (
canonical_skill_names,
discover_canonical_skills,
)
-from products.signals.backend.scout_harness.limits import MAX_RUN_NOTE_CHARS, STALE_RUN_CUTOFF_S
+from products.signals.backend.scout_harness.limits import (
+ MAX_ENABLED_SCOUTS_PER_TEAM,
+ MAX_RUN_NOTE_CHARS,
+ STALE_RUN_CUTOFF_S,
+)
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCE_REPORT_RESEARCH as PIPELINE_AUDIENCE
from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX
from products.signals.backend.scout_harness.serializers import (
@@ -3847,7 +3851,7 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
config = SignalScoutConfig.objects.get(team=self.team, skill_name="signals-scout-fresh")
assert config.output_destinations["slack"]["thread_reports"] is False
- _CAP_PATCH = "products.signals.backend.scout_harness.views.MAX_ENABLED_SCOUTS_PER_TEAM"
+ _CAP_PATCH = "products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM"
def test_create_disabled_config_is_allowed_at_team_cap(self) -> None:
self._make_skill("signals-scout-first")
@@ -3885,6 +3889,84 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
second.refresh_from_db()
assert second.enabled is False
+ @parameterized.expand(
+ [
+ # A project given more capacity in the flag may enable past the code fallback.
+ ("raised", {"max_enabled_scouts": 2}, status.HTTP_200_OK, True),
+ # Lowering it below current usage blocks the next enable without touching what runs.
+ ("lowered", {"max_enabled_scouts": 1}, status.HTTP_400_BAD_REQUEST, False),
+ ]
+ )
+ def test_enable_is_gated_by_the_flag_configured_cap(
+ self, _name: str, team_config: dict, expected_status: int, expected_enabled: bool
+ ) -> None:
+ self._make_skill("signals-scout-first")
+ first = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)
+ self._make_skill("signals-scout-second")
+ second = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-second", enabled=False)
+
+ with patch(_METADATA_PAYLOAD_PATH, return_value={"team_configs": {str(self.team.id): team_config}}):
+ response = self.client.patch(self._detail_url(str(second.id)), data={"enabled": True}, format="json")
+
+ assert response.status_code == expected_status
+ second.refresh_from_db()
+ assert second.enabled is expected_enabled
+ # A lowered cap never pauses what is already running.
+ first.refresh_from_db()
+ assert first.enabled is True
+
+ def test_cap_rejection_names_the_resolved_cap(self) -> None:
+ # The number a person reads must be the number enforcement used, or the message sends
+ # them looking for scouts that are not there.
+ self._make_skill("signals-scout-first")
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)
+ self._make_skill("signals-scout-second")
+
+ with patch(_METADATA_PAYLOAD_PATH, return_value={"default_team_config": {"max_enabled_scouts": 1}}):
+ response = self.client.post(
+ self._list_url(), data={"skill_name": "signals-scout-second", "enabled": True}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "already has 1 enabled scouts" in response.json()["detail"]
+
+ def test_cap_rejection_above_a_lowered_cap_names_the_count_and_the_scouts_to_disable(self) -> None:
+ # A lowered cap leaves every running scout enabled, so the count can sit above the cap.
+ # Reporting the cap as the count, or asking for one disable, leaves the next enable refused.
+ for name in ("signals-scout-first", "signals-scout-second", "signals-scout-third"):
+ self._make_skill(name)
+ SignalScoutConfig.objects.create(team=self.team, skill_name=name, enabled=True)
+ self._make_skill("signals-scout-fourth")
+
+ with patch(_METADATA_PAYLOAD_PATH, return_value={"default_team_config": {"max_enabled_scouts": 1}}):
+ response = self.client.post(
+ self._list_url(), data={"skill_name": "signals-scout-fourth", "enabled": True}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == (
+ "This project already has 3 enabled scouts, and its limit is 1. Disable 3 scouts before you enable another."
+ )
+
+ def test_disabling_and_editing_stay_allowed_below_a_lowered_cap(self) -> None:
+ # Lowering the cap must leave a project able to dig itself out: disabling frees a slot,
+ # and tuning an enabled scout is not a net-new enable.
+ self._make_skill("signals-scout-first")
+ first = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-first", enabled=True)
+ self._make_skill("signals-scout-second")
+ second = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-second", enabled=True)
+
+ with patch(_METADATA_PAYLOAD_PATH, return_value={"default_team_config": {"max_enabled_scouts": 1}}):
+ tuned = self.client.patch(
+ self._detail_url(str(first.id)), data={"run_interval_minutes": 120}, format="json"
+ )
+ disabled = self.client.patch(self._detail_url(str(second.id)), data={"enabled": False}, format="json")
+
+ assert tuned.status_code == status.HTTP_200_OK
+ assert disabled.status_code == status.HTTP_200_OK
+ second.refresh_from_db()
+ assert second.enabled is False
+
@parameterized.expand(
[
# Re-asserting `enabled=True` on the already-enabled scout: it's excluded from
@@ -4029,8 +4111,34 @@ class TestScoutHarnessMetadataAPI(APIBaseTest):
"max_runs_per_day",
"runs_today",
"runs_remaining_today",
+ "max_enabled_scouts",
}
+ @parameterized.expand(
+ [
+ ("no_override", {}, MAX_ENABLED_SCOUTS_PER_TEAM),
+ ("fleet_default", {"default_team_config": {"max_enabled_scouts": 400}}, 400),
+ (
+ "project_override_wins",
+ {
+ "default_team_config": {"max_enabled_scouts": 400},
+ "team_configs": {"__team__": {"max_enabled_scouts": 500}},
+ },
+ 500,
+ ),
+ ]
+ )
+ def test_metadata_reports_the_enforced_enabled_cap(self, _name: str, extra: dict, expected: int) -> None:
+ # The endpoint exists to show the enforced number, so the cap it reports must be the one
+ # the write surfaces apply — the same three layers, resolved the same way.
+ payload = {"guaranteed_team_ids": [self.team.id], **extra}
+ if "team_configs" in payload:
+ payload["team_configs"] = {str(self.team.id): payload["team_configs"]["__team__"]}
+
+ body = self._get(payload).json()
+
+ assert body["limits"]["max_enabled_scouts"] == expected
+
@parameterized.expand([("listed", True), ("not_listed", False)])
def test_enrolled_reflects_guaranteed_team_ids(self, _name: str, listed: bool) -> None:
team_id = self.team.id if listed else self.team.id + 1
diff --git a/products/signals/backend/test/test_scout_status.py b/products/signals/backend/test/test_scout_status.py
index 586fefc053d8..3b1caa2b1a84 100644
--- a/products/signals/backend/test/test_scout_status.py
+++ b/products/signals/backend/test/test_scout_status.py
@@ -169,13 +169,32 @@ class TestScoutStatusTransitions(BaseTest):
paused = self._config(status=Status.PAUSED_BY_SYSTEM, pause_reason=Reason.REPEATED_FAILURES)
SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-other")
- with patch("products.signals.backend.scout_harness.limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
+ with patch("products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1):
applied = paused.transition_status_by_system(Status.ACTIVE, pause_reason=Reason.REPEATED_FAILURES)
assert applied is False
paused.refresh_from_db()
assert paused.enabled is False
+ def test_system_resume_uses_the_flag_configured_enabled_cap(self) -> None:
+ # The resume re-checks the ceiling the API enforces, so a project given more capacity in
+ # the flag gets its breaker-paused scout back instead of staying silenced at 250.
+ paused = self._config(status=Status.PAUSED_BY_SYSTEM, pause_reason=Reason.REPEATED_FAILURES)
+ SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-other")
+
+ with (
+ patch("products.signals.backend.scout_harness.team_limits.MAX_ENABLED_SCOUTS_PER_TEAM", 1),
+ patch(
+ "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload",
+ return_value={"team_configs": {str(self.team.id): {"max_enabled_scouts": 5}}},
+ ),
+ ):
+ applied = paused.transition_status_by_system(Status.ACTIVE, pause_reason=Reason.REPEATED_FAILURES)
+
+ assert applied is True
+ paused.refresh_from_db()
+ assert paused.enabled is True
+
def test_system_resume_starts_with_a_clean_failure_streak(self) -> None:
# Without the reset, the first failed run after a resume would re-trip the breaker
# off the stale pre-pause streak instead of five fresh failures.
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 7121c9a02c0f..cbee06b42550 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3712,7 +3712,7 @@ export interface ScoutMemberApi {
}
/**
- * A team's enforced scout run caps and current usage.
+ * A team's enforced scout caps and current usage.
*
* These are the values the coordinator actually applies at dispatch (resolved per-team override →
* fleet-wide default → code constant), so the UI can show the real throttle rather than what a
@@ -3733,6 +3733,8 @@ export interface ScoutLimitsApi {
* @nullable
*/
runs_remaining_today: number | null
+ /** Most scouts the project can have switched on at once. Enabling another past this is rejected. */
+ max_enabled_scouts: number
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2bce3f5e52ff..581fefac95ab 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -87345,7 +87345,7 @@ export namespace Schemas {
}
/**
- * A team's enforced scout run caps and current usage.
+ * A team's enforced scout caps and current usage.
*
* These are the values the coordinator actually applies at dispatch (resolved per-team override →
* fleet-wide default → code constant), so the UI can show the real throttle rather than what a
@@ -87366,6 +87366,8 @@ export namespace Schemas {
* @nullable
*/
runs_remaining_today: number | null;
+ /** Most scouts the project can have switched on at once. Enabling another past this is rejected. */
+ max_enabled_scouts: number;
}
/**