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): sample background scouts by activity band (#109497)

posthog[bot]4ab81507db44
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 37f3d1516a60..6796f5c3ee1b 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -374,6 +374,7 @@ rules:
|SignalScoutNote
|SignalScoutStructuredOutput
|SignalScoutSuggestionSet
+ |SignalScoutBackgroundBand
|SignalScratchpad
|SignalProjectProfile
|SingleSessionSummary
@@ -805,6 +806,7 @@ rules:
|SignalScoutNote
|SignalScoutStructuredOutput
|SignalScoutSuggestionSet
+ |SignalScoutBackgroundBand
|SignalScratchpad
|SignalProjectProfile
|SingleSessionSummary
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 1775f583672f..daefce47d05f 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -117,6 +117,7 @@ from products.signals.backend.tasks import (
pause_inactive_signal_scouts,
prune_expired_scratchpad_entries_task,
refresh_signal_repository_activity,
+ refresh_signal_scout_background_bands,
sweep_implementation_dispatches,
sync_pending_signals_refund_credits,
)
@@ -438,6 +439,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="sync pending signals refund credits",
)
+ # Recompute the activity bands the background scout lane samples from - daily at 5:50 AM
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(hour="5", minute="50"),
+ refresh_signal_scout_background_bands.s(),
+ name="refresh signals scout background bands",
+ )
+
# Warn, then pause signals scouts that produce nothing anyone uses - daily at 6:15 AM
sender.add_periodic_task(
crontab(hour="6", minute="15"),
diff --git a/products/signals/backend/migrations/0159_signalscoutbackgroundband.py b/products/signals/backend/migrations/0159_signalscoutbackgroundband.py
new file mode 100644
index 000000000000..3a6d5ba171b2
--- /dev/null
+++ b/products/signals/backend/migrations/0159_signalscoutbackgroundband.py
@@ -0,0 +1,55 @@
+# Generated by Django 5.2.17 on 2026-09-30 20:53
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1390_rename_desktop_canvas_comment_scope"),
+ ("signals", "0158_signalscoutconfig_managed_by"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="background_band",
+ field=models.PositiveSmallIntegerField(blank=True, null=True),
+ ),
+ migrations.CreateModel(
+ name="SignalScoutBackgroundBand",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("band", models.PositiveSmallIntegerField()),
+ ("computed_at", models.DateTimeField()),
+ (
+ "team",
+ models.OneToOneField(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Signal scout background band",
+ "verbose_name_plural": "Signal scout background bands",
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 9a8871f0822c..aca9ad3c81d0 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0158_signalscoutconfig_managed_by
+0159_signalscoutbackgroundband
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index eecfa9c4b82d..76a127fb2736 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2466,6 +2466,9 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
default=ManagedBy.TEAM,
db_default=ManagedBy.TEAM,
)
+ # The activity band that sampled this project into the background lane. `None` for a
+ # hand-picked `team_ids` project and for every `team`-managed row that the band lane never made.
+ background_band = models.PositiveSmallIntegerField(null=True, blank=True)
# Set only alongside `pending_pause` / `paused_by_system`; see `PauseReason`.
pause_reason = models.CharField(
max_length=20,
@@ -3397,3 +3400,31 @@ class SignalScoutSuggestionSet(TeamScopedRootMixin, UUIDModel):
verbose_name = "Signal scout suggestion set"
verbose_name_plural = "Signal scout suggestion sets"
default_manager_name = "all_teams"
+
+
+class SignalScoutBackgroundBand(TeamScopedRootMixin, UUIDModel):
+ """The activity band of one project that can get a background scout, one row per team.
+
+ A nightly job (`scout_harness/background_bands.py`) writes the full set and deletes every row
+ for a project that is no longer eligible. The coordinator samples a percentage of each band
+ from the `background.bands` block of the `signals-scout` flag payload.
+ """
+
+ # See SignalScoutConfig.all_teams for rationale.
+ all_teams = models.Manager() # noqa: DJ012
+
+ # db_constraint=False: creating an FK constraint locks the hot posthog_team table and has
+ # blocked deploys (same as SignalScoutSuggestionSet); app-level enforcement only.
+ team = models.OneToOneField(
+ "posthog.Team",
+ on_delete=models.CASCADE,
+ db_constraint=False,
+ related_name="+",
+ )
+ band = models.PositiveSmallIntegerField()
+ computed_at = models.DateTimeField()
+
+ class Meta:
+ verbose_name = "Signal scout background band"
+ verbose_name_plural = "Signal scout background bands"
+ default_manager_name = "all_teams"
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 33a9c81dd35e..aa80ba2e3a4c 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -86,7 +86,8 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
Also the failure-streak circuit breaker's knobs: `failure_streak_pause_threshold(runs_in_tolerance_window)` — consecutive failed runs before the breaker pauses the lane, derived per-lane so the same wall-clock tolerance holds at every cadence (one failure past the runs the schedule fits into `FAILURE_STREAK_MIN_SPAN_MINUTES` of continuous failure, `FAILURE_STREAK_MIN_RUNS` floor, capped at `FAILURE_STREAK_MAX_RUNS` + 1), with `interval_runs_in_tolerance_window` sizing the evenly spaced case — and `AUTO_PAUSE_PROBE_INTERVAL_S` (how long a paused lane holds before the coordinator dispatches one probe).
- `team_limits.py`
Single source of truth for a team's effective scout caps + metadata, resolved from the `signals-scout` flag payload in one read. The same three-layer cap resolution (`team_configs[team]` → `default_team_config` → code constant) the coordinator enforces at dispatch — for the run budgets and for `max_enabled_scouts`, the ceiling on how many scouts a project may have switched on, which `resolve_max_enabled_scouts` / `max_enabled_scouts_for_team` serve to the config write surfaces, auto-registration and the system resume alike, plus enrollment (`_parse_enrollment` → `guaranteed_team_ids` / `skip_team_ids`, with a cloud/dev-gated fallback) and the editorial banner string. `guaranteed_team_ids` may contain the `"*"` wildcard (`ENROLL_ALL_TOKEN`): with it, enrollment inverts from an explicit allowlist to "every team that has enabled scout configs" — the self-serve gate, where the product-autonomy- gated UI creates the configs; explicit ids alongside `"*"` are still force-provisioned and `skip_team_ids` still hard-excludes. The global per-tick ceiling is flag-tunable too (`_resolve_global_max_runs_per_tick` ← `max_runs_per_tick_global`, default `MAX_RUNS_PER_TICK`).
- The `background` block (`_parse_background` → `BackgroundEnrollment`: `enabled`, `skill_name`, `team_ids`, `interval_minutes`, `max_new_teams_per_tick`) is the pilot cohort that runs one scout without a person asking. The coordinator creates one `managed_by=background` config per listed team whose organization approved AI data processing, seeding only that skill, and pauses a background config with `background_removed` when its team leaves the list. Background configs dispatch only through `_collect_background_runs`, which checks consent again, so the kill switch (`enabled: false`) and the consent check gate every background run. A malformed block parses to `None`, and the coordinator then does nothing, so a typo in `team_ids` cannot pause the whole cohort.
+ The `background` block (`_parse_background` → `BackgroundEnrollment`: `enabled`, `skill_name`, `team_ids`, `interval_minutes`, `max_new_teams_per_tick`, `bands`) is the pilot cohort that runs one scout without a person asking. The coordinator creates one `managed_by=background` config per listed team whose organization approved AI data processing, seeding only that skill, and pauses a background config with `background_removed` when its team leaves the list. Background configs dispatch only through `_collect_background_runs`, which checks consent again, so the kill switch (`enabled: false`) and the consent check gate every background run. A malformed block parses to `None`, and the coordinator then does nothing, so a typo in `team_ids` cannot pause the whole cohort.
+ `background.bands` samples a percentage of each activity band on top of the hand-picked `team_ids`. `background_bands.py` writes the bands once a day to `SignalScoutBackgroundBand` (the `refresh_signal_scout_background_bands` Celery task). Eligibility, the band rules, and the one fleet-wide ClickHouse read are in its module docstring. A project in band `n` is sampled when `background_sample_bucket(team_id) < bands[n].percent`. The bucket is a stable digest, so a higher percent keeps every project a lower one sampled. A sampled project gets its config through the same creation path and `max_new_teams_per_tick` cap, with the band's `interval_minutes`, and `SignalScoutConfig.background_band` records the band. A lower percent, a band at 0, or a project that leaves its band removes the team from the listed set, so the existing `background_removed` pause applies, and a `managed_by=team` config never pauses. A malformed band entry counts as 0 percent for that band alone. A hand-picked team keeps no band. The runner stamps `background_band` on the run metadata and on both lifecycle events, next to `managed_by`.
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/background_bands.py b/products/signals/backend/scout_harness/background_bands.py
new file mode 100644
index 000000000000..19dc670451a7
--- /dev/null
+++ b/products/signals/backend/scout_harness/background_bands.py
@@ -0,0 +1,202 @@
+"""Nightly activity bands for the background scout lane.
+
+The coordinator samples a percentage of each band from the `background.bands` block of the
+`signals-scout` flag payload (see `team_limits._parse_background`). This module decides which
+projects are eligible and which band each one is in, once a day, so the 30-minute coordinator tick
+reads one small table instead of ClickHouse.
+
+A project is eligible only when all of these hold:
+
+- it did not set Signals up (`suggestions.set_up_team_q`)
+- its organization approved AI data processing
+- it is a root project, not a demo, and its organization is not the internal-metrics one
+- it is the project where the most recently active member of its organization last worked
+
+Bands, first match wins. "Paying" is `Organization.has_active_subscription is True`, so an
+organization that billing never synced counts as not paying.
+
+| Band | Rule |
+|---|---|
+| 1 | paying, 5,000 or more events a day, a member logged in within 14 days |
+| 2 | paying, 500 to 5,000 events a day, a member logged in within 14 days |
+| 3 | not paying, 500 or more events a day, a member logged in within 14 days |
+| 4 | 500 or more events a day, last member login 15 to 30 days ago |
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Collection, Iterator
+from datetime import datetime, timedelta
+from itertools import batched
+
+from django.db import transaction
+from django.db.models import F, Q
+from django.utils import timezone
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.models import Team, User
+from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
+
+from products.signals.backend.models import SignalScoutBackgroundBand
+from products.signals.backend.scout_harness.suggestions import set_up_team_q
+
+HIGH_VOLUME_EVENTS_PER_DAY = 5_000
+MIN_EVENTS_PER_DAY = 500
+RECENT_LOGIN_DAYS = 14
+MAX_LOGIN_DAYS = 30
+# A week evens out the weekday and weekend traffic of one project.
+EVENT_WINDOW_DAYS = 7
+# `sync_execute` sets no wall-clock cap, so a stalled read would otherwise hold a Celery worker.
+EVENT_READ_MAX_EXECUTION_S = 600
+# Keeps each `IN (...)` list far below the Postgres bind-parameter limit.
+ID_BATCH_SIZE = 5_000
+
+
+@frozen
+class BandOutcome:
+ written: int
+ removed: int
+
+
+@frozen
+class _OrgActivity:
+ team_id: int
+ last_login: datetime
+
+
+def _id_batches(ids: Collection[int]) -> Iterator[tuple[int, ...]]:
+ return batched(sorted(ids), ID_BATCH_SIZE, strict=False)
+
+
+def _root_team_id(team_id: int, parent_team_id: int | None) -> int:
+ return parent_team_id or team_id
+
+
+def _most_active_project_by_org(login_cutoff: datetime) -> dict[int, _OrgActivity]:
+ """Per organization: the root project of the member who logged in last, and when that was.
+
+ `current_team` is the project that member last had open. A child environment counts as its
+ parent project, because background configs live on the root project.
+ """
+ rows = (
+ User.objects.filter(is_active=True, last_login__gte=login_cutoff, current_team__isnull=False)
+ .order_by("-last_login")
+ .values_list("current_team_id", "current_team__parent_team_id", "current_team__organization_id", "last_login")
+ )
+ by_org: dict[int, _OrgActivity] = {}
+ for team_id, parent_team_id, organization_id, last_login in rows.iterator():
+ if organization_id not in by_org:
+ by_org[organization_id] = _OrgActivity(
+ team_id=_root_team_id(team_id, parent_team_id), last_login=last_login
+ )
+ return by_org
+
+
+def _eligible_teams(team_ids: set[int]) -> dict[int, bool]:
+ """`team_id -> paying` for each project in `team_ids` that can get a background scout."""
+ eligible: dict[int, bool] = {}
+ for batch in _id_batches(team_ids):
+ rows = (
+ Team.objects.filter(
+ Q(parent_team_id__isnull=True) | Q(parent_team_id=F("id")),
+ id__in=batch,
+ is_demo=False,
+ organization__is_ai_data_processing_approved=True,
+ organization__for_internal_metrics=False,
+ )
+ .exclude(set_up_team_q())
+ .values_list("id", "organization__has_active_subscription")
+ )
+ eligible.update((team_id, paying is True) for team_id, paying in rows)
+ return eligible
+
+
+def _events_per_day_by_org(organization_ids: Collection[int], begin: datetime, end: datetime) -> dict[int, float]:
+ """Average daily events of each organization in `organization_ids` over `[begin, end)`, from one fleet-wide query.
+
+ Organization-level volume is enough to band a project, and it counts child environments too.
+ """
+ tag_queries(product=Product.SIGNALS, query_type="SignalsScoutBackgroundBands")
+ rows = sync_execute( # nosemgrep: clickhouse-fstring-param-audit - the table is events_read_table() output; every value is parameterized
+ f"""
+ SELECT team_id, count() AS events
+ FROM {events_read_table(use_new_events_schema())}
+ WHERE timestamp >= %(begin)s AND timestamp < %(end)s
+ GROUP BY team_id
+ """,
+ {"begin": begin, "end": end},
+ workload=Workload.OFFLINE,
+ settings={"max_execution_time": EVENT_READ_MAX_EXECUTION_S},
+ )
+ events_by_team = dict(rows)
+ days = (end - begin).total_seconds() / 86_400
+ by_org: dict[int, float] = defaultdict(float)
+ for batch in _id_batches(organization_ids):
+ for team_id, organization_id in Team.objects.filter(organization_id__in=batch).values_list(
+ "id", "organization_id"
+ ):
+ by_org[organization_id] += events_by_team.get(team_id, 0) / days
+ return by_org
+
+
+def band_for(*, paying: bool, events_per_day: float, last_login: datetime, now: datetime) -> int | None:
+ if events_per_day < MIN_EVENTS_PER_DAY or last_login < now - timedelta(days=MAX_LOGIN_DAYS):
+ return None
+ if last_login < now - timedelta(days=RECENT_LOGIN_DAYS):
+ return 4
+ if not paying:
+ return 3
+ return 1 if events_per_day >= HIGH_VOLUME_EVENTS_PER_DAY else 2
+
+
+def compute_background_bands(now: datetime | None = None) -> dict[int, int]:
+ """`team_id -> band` for every eligible project."""
+ now = now or timezone.now()
+ activity_by_org = _most_active_project_by_org(now - timedelta(days=MAX_LOGIN_DAYS))
+ eligible = _eligible_teams({activity.team_id for activity in activity_by_org.values()})
+ # The org's most active project must itself be eligible. The org never falls back to a
+ # quieter project, so a set-up org does not get a background scout next to its own setup.
+ activity_by_org = {
+ organization_id: activity
+ for organization_id, activity in activity_by_org.items()
+ if activity.team_id in eligible
+ }
+ if not activity_by_org:
+ return {}
+ day_end = now.replace(hour=0, minute=0, second=0, microsecond=0)
+ events_by_org = _events_per_day_by_org(activity_by_org.keys(), day_end - timedelta(days=EVENT_WINDOW_DAYS), day_end)
+ bands: dict[int, int] = {}
+ for organization_id, activity in activity_by_org.items():
+ band = band_for(
+ paying=eligible[activity.team_id],
+ events_per_day=events_by_org.get(organization_id, 0.0),
+ last_login=activity.last_login,
+ now=now,
+ )
+ if band is not None:
+ bands[activity.team_id] = band
+ return bands
+
+
+def refresh_background_bands(now: datetime | None = None) -> BandOutcome:
+ """Recompute the bands and replace the table. A project that stopped being eligible loses its row."""
+ now = now or timezone.now()
+ bands = compute_background_bands(now)
+ departed = set(SignalScoutBackgroundBand.all_teams.values_list("team_id", flat=True)) - bands.keys()
+ with transaction.atomic():
+ removed = 0
+ for batch in _id_batches(departed):
+ deleted, _ = SignalScoutBackgroundBand.all_teams.filter(team_id__in=batch).delete()
+ removed += deleted
+ SignalScoutBackgroundBand.all_teams.bulk_create(
+ [SignalScoutBackgroundBand(team_id=team_id, band=band, computed_at=now) for team_id, band in bands.items()],
+ update_conflicts=True,
+ unique_fields=["team"],
+ update_fields=["band", "computed_at"],
+ batch_size=1000,
+ )
+ return BandOutcome(written=len(bands), removed=removed)
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index ac6ab0e00bae..5179d15d41dd 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -1101,6 +1101,10 @@ def _create_run_row(
# and deleting it nulls `scout_config`. Reports this run authors keep their background origin.
if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND:
metadata["managed_by"] = config.managed_by
+ # The band that sampled the project, so each band's pilot reads on its own. Absent for a
+ # hand-picked `team_ids` project.
+ if config.background_band is not None:
+ metadata["background_band"] = config.background_band
# Dispatch-time snapshot of the structured-output contract. The prompt renders this exact
# schema, so the record endpoint validates against the snapshot rather than the live config
# value — a mid-run schema edit must not reject records that match what the run was shown.
@@ -1504,6 +1508,8 @@ def _attach_run_shape_props(
properties["github_guidance"] = github_guidance
properties["business_knowledge_maintained"] = business_knowledge_maintained
properties["managed_by"] = config.managed_by
+ if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND and config.background_band is not None:
+ properties["background_band"] = config.background_band
if config.network_access == SignalScoutConfig.NetworkAccess.FULL:
properties["network_access"] = config.network_access
if granted_write_scopes := _granted_write_scopes(config):
diff --git a/products/signals/backend/scout_harness/suggestions.py b/products/signals/backend/scout_harness/suggestions.py
index 5b3e5df00233..89b4ac00b27a 100644
--- a/products/signals/backend/scout_harness/suggestions.py
+++ b/products/signals/backend/scout_harness/suggestions.py
@@ -287,6 +287,26 @@ def _root_team_q() -> Q:
return Q(parent_team_id__isnull=True) | Q(parent_team_id=F("id"))
+def set_up_team_q() -> Q:
+ """Projects that set Signals up: an enabled signal source, or an enabled scout a person turned on.
+
+ Source configs are environment-scoped, so a project whose Signals setup lives in a child
+ environment counts through that child's parent; scout configs already canonicalize.
+ A background-managed scout is not set up: nobody on the project turned it on.
+ """
+ source_teams = SignalSourceConfig.objects.filter(enabled=True).values("team_id")
+ user_scout_teams = (
+ SignalScoutConfig.all_teams.filter(enabled=True)
+ .exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
+ .values("team_id")
+ )
+ return (
+ Q(id__in=source_teams)
+ | Q(id__in=Team.objects.filter(id__in=source_teams, parent_team_id__isnull=False).values("parent_team_id"))
+ | Q(id__in=user_scout_teams)
+ )
+
+
def _engagement_by_team(cutoff: datetime, team_ids: Collection[int]) -> dict[int, datetime]:
"""Most recent inbox engagement per team inside the window: report views/ratings, a scout
someone turned on or off, or a scout someone created. Aggregated in Postgres so the transfer
@@ -342,20 +362,7 @@ def _candidate_teams_by_tier(settings: SuggestionSettings, now: datetime) -> tup
Q(ingested_event=True) | Q(id__in=ingested_child_teams.values("parent_team_id")),
organization__is_ai_data_processing_approved=True,
)
- # Source configs are environment-scoped, so a project whose Signals setup lives in a child
- # environment counts through that child's parent; scout configs already canonicalize.
- # A background-managed scout is not set up: nobody on the project turned it on.
- source_teams = SignalSourceConfig.objects.filter(enabled=True).values("team_id")
- user_scout_teams = (
- SignalScoutConfig.all_teams.filter(enabled=True)
- .exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)
- .values("team_id")
- )
- set_up = (
- Q(id__in=source_teams)
- | Q(id__in=Team.objects.filter(id__in=source_teams, parent_team_id__isnull=False).values("parent_team_id"))
- | Q(id__in=user_scout_teams)
- )
+ set_up = set_up_team_q()
tiers: dict[int, int] = {}
set_up_team_ids = list(approved_root_teams.filter(set_up).values_list("id", flat=True))
diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.py
index 05672a4d0e10..d05b812ec7bd 100644
--- a/products/signals/backend/scout_harness/team_limits.py
+++ b/products/signals/backend/scout_harness/team_limits.py
@@ -10,8 +10,9 @@ 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
+import hashlib
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass, field
from datetime import datetime, timedelta
from django.conf import settings
@@ -230,6 +231,18 @@ DEFAULT_BACKGROUND_SKILL_NAME = "signals-scout-general"
DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK = 5
+@dataclass(frozen=True)
+class BackgroundBand:
+ """One entry of `background.bands`. `interval_minutes` is `None` when unset, so the block value applies."""
+
+ percent: int
+ interval_minutes: int | None
+
+
+# The activity bands that the nightly job writes to `SignalScoutBackgroundBand`, most active first.
+BACKGROUND_BANDS = (1, 2, 3, 4)
+
+
@dataclass(frozen=True)
class BackgroundEnrollment:
"""Parsed `background` block from the `signals-scout` flag payload.
@@ -244,20 +257,59 @@ class BackgroundEnrollment:
team_ids: frozenset[int]
interval_minutes: int | None
max_new_teams_per_tick: int
+ # Only the bands with a valid entry. A missing band samples no project.
+ bands: Mapping[int, BackgroundBand] = field(default_factory=dict)
+
+ def band_interval_minutes(self, band: int | None) -> int | None:
+ entry = self.bands.get(band) if band is not None else None
+ if entry is not None and entry.interval_minutes is not None:
+ return entry.interval_minutes
+ return self.interval_minutes
def _positive_int_or_none(value: object) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else None
+def _parse_background_bands(raw: object) -> dict[int, BackgroundBand]:
+ """Parse `background.bands`. A malformed entry drops out, so that band samples 0 percent.
+
+ A malformed entry never invalidates the block, because the block also carries `team_ids`.
+ """
+ if not isinstance(raw, dict):
+ return {}
+ bands: dict[int, BackgroundBand] = {}
+ for band in BACKGROUND_BANDS:
+ entry = raw.get(str(band))
+ if not isinstance(entry, dict):
+ continue
+ percent = entry.get("percent")
+ if not isinstance(percent, int) or isinstance(percent, bool) or not 0 <= percent <= 100:
+ continue
+ bands[band] = BackgroundBand(
+ percent=percent, interval_minutes=_positive_int_or_none(entry.get("interval_minutes"))
+ )
+ return bands
+
+
+def background_sample_bucket(team_id: int) -> int:
+ """The stable 0-99 bucket of a project. Python's `hash()` is salted per process, so it cannot be used.
+
+ A project is sampled when its bucket is below its band percent, so a higher percent keeps every
+ project that a lower percent sampled.
+ """
+ digest = hashlib.sha256(f"signals-scout-background:{team_id}".encode()).digest()
+ return int.from_bytes(digest[:8], "big") % 100
+
+
def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:
"""Parse the `background` block, or return `None` when the coordinator must not act on it.
`None` for a missing payload, a missing block, a block that is not an object, a `skill_name`
that is not a non-empty string, or a `team_ids` that is not a list of integer ids. A malformed
`team_ids` must not read as an empty list, because an empty list pauses every background
- config. `enabled` is on only for a literal `true`. An absent or malformed `interval_minutes` or
- `max_new_teams_per_tick` falls back to its default and does not invalidate the block.
+ config. `enabled` is on only for a literal `true`. An absent or malformed `interval_minutes`,
+ `max_new_teams_per_tick`, or `bands` entry falls back to its default and does not invalidate the block.
"""
if payload is None:
return None
@@ -282,6 +334,7 @@ def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:
team_ids=frozenset(raw_team_ids),
interval_minutes=_positive_int_or_none(raw.get("interval_minutes")),
max_new_teams_per_tick=max_new if max_new is not None else DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
+ bands=_parse_background_bands(raw.get("bands")),
)
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 8ca9be32ddd3..6732e511aaec 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -51,6 +51,7 @@ from products.signals.backend.report_generation.repo_activity import (
)
from products.signals.backend.reviewer_pr_assignment import assign_reviewers_to_pull_request
from products.signals.backend.reviewer_pr_ready import open_pull_request_ready_for_review
+from products.signals.backend.scout_harness.background_bands import refresh_background_bands
from products.signals.backend.scout_harness.inactivity import sweep_inactive_scouts
from products.signals.backend.scout_harness.slack_delivery import (
DELIVERABLE_REPORT_STATUSES,
@@ -990,6 +991,22 @@ def rebuild_signal_repository_activity(team_id: int, repository: str, force: boo
cache.delete(lock_key)
+@shared_task(
+ name="products.signals.backend.tasks.refresh_signal_scout_background_bands",
+ ignore_result=True,
+ max_retries=0,
+)
+@skip_team_scope_audit
+def refresh_signal_scout_background_bands() -> None:
+ """Daily: recompute which projects can get a background scout, and their activity band.
+
+ Runs here rather than on the coordinator tick, because it reads a week of fleet-wide event
+ volume and activity bands do not change by the half hour.
+ """
+ outcome = refresh_background_bands()
+ logger.info("signals_scout background bands refreshed", written=outcome.written, removed=outcome.removed)
+
+
@shared_task(
name="products.signals.backend.tasks.pause_inactive_signal_scouts",
ignore_result=True,
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index bf3674b03619..e6ffdfbd648d 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -21,7 +21,7 @@ from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
-from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.models import SignalScoutBackgroundBand, SignalScoutConfig
from products.signals.backend.report_check_execution import run_due_report_checks
from products.signals.backend.scout_harness.config_registry import (
MAX_RUN_INTERVAL_MINUTES,
@@ -69,6 +69,7 @@ from products.signals.backend.scout_harness.team_limits import (
_resolve_withheld_skills,
_runs_today_by_team,
_team_configs,
+ background_sample_bucket,
resolve_max_enabled_scouts,
)
from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflow
@@ -366,9 +367,19 @@ def _collect_planned_runs(
due: list[_DueRun] = []
background_team_ids: set[int] = set()
if background is not None:
- background_team_ids = _canonicalize_team_ids(set(background.team_ids)) - _canonicalize_team_ids(enrollment.skip)
+ skipped_team_ids = _canonicalize_team_ids(enrollment.skip)
+ background_team_ids = _canonicalize_team_ids(set(background.team_ids)) - skipped_team_ids
try:
- _reconcile_background_configs(background, background_team_ids, team_configs, default_team_config)
+ # A hand-picked team keeps no band, so `team_ids` stays an override that bands never change.
+ band_by_team = {
+ team_id: band
+ for team_id, band in _sampled_band_teams(background).items()
+ if team_id not in background_team_ids and team_id not in skipped_team_ids
+ }
+ background_team_ids |= band_by_team.keys()
+ _reconcile_background_configs(
+ background, background_team_ids, band_by_team, team_configs, default_team_config
+ )
except Exception:
logger.exception("signals_scout coordinator: background reconcile failed; continuing")
paused_by_team = _breaker_paused_configs_by_team()
@@ -700,17 +711,37 @@ def _ai_data_processing_approved(team: Team) -> bool:
return team.organization.is_ai_data_processing_approved is True
+def _sampled_band_teams(background: BackgroundEnrollment) -> dict[int, int]:
+ """`team_id -> band` for each project that its band percent samples into the background lane.
+
+ Reads nothing when every band is at 0 percent, which is the rollout default.
+ """
+ percents = {band: entry.percent for band, entry in background.bands.items() if entry.percent > 0}
+ if not percents:
+ return {}
+ return {
+ team_id: band
+ for team_id, band in SignalScoutBackgroundBand.all_teams.filter(band__in=percents).values_list(
+ "team_id", "band"
+ )
+ if background_sample_bucket(team_id) < percents[band]
+ }
+
+
def _reconcile_background_configs(
background: BackgroundEnrollment,
listed_team_ids: set[int],
+ band_by_team: dict[int, int],
team_configs: dict[int, dict],
default_team_config: dict,
) -> None:
"""Move background configs toward the `background` block of the flag payload.
+ `listed_team_ids` holds the hand-picked `team_ids` and the band-sampled teams in `band_by_team`.
Runs on a valid block only, because an unreadable block must never read as an empty list. The
pause of departed teams runs even with `enabled` off, so an operator can drain one team without
- stopping the pilot. Creation and resume run only with `enabled` on.
+ stopping the pilot. A lower band percent pauses through the same path, because the team leaves
+ the listed set. Creation, resume, and band updates run only with `enabled` on.
"""
_pause_departed_background_configs(listed_team_ids)
if not background.enabled:
@@ -728,7 +759,8 @@ def _reconcile_background_configs(
and background.skill_name not in _resolve_withheld_skills(team.id, team_configs, default_team_config)
]
_resume_background_configs(background, eligible, team_configs, default_team_config)
- _create_background_configs(background, eligible, team_configs, default_team_config)
+ _sync_background_bands(background, eligible, band_by_team)
+ _create_background_configs(background, eligible, band_by_team, team_configs, default_team_config)
def _pause_departed_background_configs(listed_team_ids: set[int]) -> None:
@@ -777,9 +809,49 @@ def _resume_background_configs(
)
+def _background_interval(background: BackgroundEnrollment, band: int | None) -> int | None:
+ """The interval a background config gets, or `None` to keep the model default."""
+ interval = background.band_interval_minutes(band)
+ if interval is not None and MIN_RUN_INTERVAL_MINUTES <= interval <= MAX_RUN_INTERVAL_MINUTES:
+ return interval
+ return None
+
+
+def _sync_background_bands(
+ background: BackgroundEnrollment,
+ eligible_teams: list[Team],
+ band_by_team: dict[int, int],
+) -> None:
+ """Keep the band of each background config current, and give a config its new band's interval.
+
+ Only `managed_by=background` rows change, so a person who took a config over keeps their schedule.
+ """
+ stale = SignalScoutConfig.all_teams.filter(
+ team_id__in=[team.id for team in eligible_teams],
+ skill_name=background.skill_name,
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ ).only("id", "team_id", "background_band")
+ for config in stale:
+ band = band_by_team.get(config.team_id)
+ if config.background_band == band:
+ continue
+ # Without a configured interval, fall back to the model default rather than keep the old band's.
+ interval = _background_interval(background, band)
+ changes: dict = {
+ "background_band": band,
+ "run_interval_minutes": interval
+ if interval is not None
+ else SignalScoutConfig._meta.get_field("run_interval_minutes").default,
+ }
+ SignalScoutConfig.all_teams.filter(pk=config.pk, managed_by=SignalScoutConfig.ManagedBy.BACKGROUND).update(
+ **changes
+ )
+
+
def _create_background_configs(
background: BackgroundEnrollment,
eligible_teams: list[Team],
+ band_by_team: dict[int, int],
team_configs: dict[int, dict],
default_team_config: dict,
) -> None:
@@ -797,10 +869,7 @@ def _create_background_configs(
pending = [team for team in eligible_teams if team.id not in has_config]
if not pending:
return
- interval = background.interval_minutes
defaults: dict = {"managed_by": SignalScoutConfig.ManagedBy.BACKGROUND}
- if interval is not None and MIN_RUN_INTERVAL_MINUTES <= interval <= MAX_RUN_INTERVAL_MINUTES:
- defaults["run_interval_minutes"] = interval
if tags := canonical_config_tags_for(background.skill_name):
defaults["tags"] = list(tags)
if display_name := canonical_display_name_for(background.skill_name):
@@ -827,8 +896,12 @@ def _create_background_configs(
team_id=team.id,
)
continue
+ band = band_by_team.get(team.id)
+ team_defaults = {**defaults, "background_band": band}
+ if (interval := _background_interval(background, band)) is not None:
+ team_defaults["run_interval_minutes"] = interval
_, was_created = SignalScoutConfig.objects.for_team(team.id).get_or_create(
- team_id=team.id, skill_name=background.skill_name, defaults=defaults
+ team_id=team.id, skill_name=background.skill_name, defaults=team_defaults
)
if was_created:
created += 1
@@ -836,6 +909,7 @@ def _create_background_configs(
"signals_scout coordinator: created background scout config",
team_id=team.id,
skill_name=background.skill_name,
+ background_band=band,
)
diff --git a/products/signals/backend/test/test_scout_background_bands.py b/products/signals/backend/test/test_scout_background_bands.py
new file mode 100644
index 000000000000..329d5fc28004
--- /dev/null
+++ b/products/signals/backend/test/test_scout_background_bands.py
@@ -0,0 +1,75 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models import Organization, Team, User
+
+from products.signals.backend.models import SignalScoutBackgroundBand, SignalScoutConfig
+from products.signals.backend.scout_harness.background_bands import band_for, refresh_background_bands
+
+_NOW = datetime(2026, 9, 30, 12, tzinfo=UTC)
+_SYNC_EXECUTE = "products.signals.backend.scout_harness.background_bands.sync_execute"
+
+
+ [
+ ("paying_high_volume", True, 5_000, 3, 1),
+ ("paying_mid_volume", True, 4_999, 3, 2),
+ ("not_paying", False, 50_000, 3, 3),
+ ("stale_login", True, 50_000, 20, 4),
+ ("quiet", True, 499, 3, None),
+ ("login_too_old", True, 50_000, 31, None),
+ ]
+)
+def test_band_for(_name: str, paying: bool, events_per_day: float, login_days_ago: int, expected: int | None) -> None:
+ last_login = _NOW - timedelta(days=login_days_ago)
+ assert band_for(paying=paying, events_per_day=events_per_day, last_login=last_login, now=_NOW) == expected
+
+
+class TestRefreshBackgroundBands:
+ def _org_with_member(self, *, paying: bool = True, login_days_ago: int = 1, **org_kwargs) -> tuple[Team, User]:
+ org = Organization.objects.create(
+ name="band-org", is_ai_data_processing_approved=True, has_active_subscription=paying, **org_kwargs
+ )
+ team = Team.objects.create(organization=org, name="band-team")
+ user = User.objects.create(
+ email=f"member-{team.id}@example.com",
+ current_team=team,
+ current_organization=org,
+ last_login=_NOW - timedelta(days=login_days_ago),
+ )
+ return team, user
+
+ def test_bands_each_org_by_its_most_active_eligible_project(self) -> None:
+ paying, _ = self._org_with_member()
+ free, _ = self._org_with_member(paying=False)
+ # The most active member of this org works in a quieter second project, which holds the band.
+ busy_org_team, _ = self._org_with_member()
+ second_project = Team.objects.create(organization=busy_org_team.organization, name="second")
+ User.objects.create(
+ current_team=second_project,
+ current_organization=busy_org_team.organization,
+ last_login=_NOW,
+ )
+ set_up, _ = self._org_with_member()
+ SignalScoutConfig.objects.for_team(set_up.id).create(team=set_up, skill_name="signals-scout-general")
+ demo, _ = self._org_with_member()
+ Team.objects.filter(id=demo.id).update(is_demo=True)
+ internal, _ = self._org_with_member(for_internal_metrics=True)
+ stale = SignalScoutBackgroundBand.all_teams.create(
+ team=Team.objects.create(organization=paying.organization, name="old"), band=1, computed_at=_NOW
+ )
+
+ rows = [(team.id, 7 * 10_000) for team in (paying, free, busy_org_team, set_up, demo, internal)]
+ with patch(_SYNC_EXECUTE, return_value=rows):
+ outcome = refresh_background_bands(_NOW)
+
+ bands = dict(SignalScoutBackgroundBand.all_teams.values_list("team_id", "band"))
+ assert bands == {paying.id: 1, free.id: 3, second_project.id: 1}
+ assert not SignalScoutBackgroundBand.all_teams.filter(pk=stale.pk).exists()
+ assert outcome.written == 3
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index f4e5f4b1b7b0..5821a22de4f7 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -23,7 +23,7 @@ from posthog.models import Organization, Team
from posthog.models.scoping import team_scope
from posthog.sync import database_sync_to_async
-from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.models import SignalScoutBackgroundBand, SignalScoutConfig
from products.signals.backend.scout_harness import lazy_seed
from products.signals.backend.scout_harness.config_registry import register_missing_configs
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, sync_canonical_skills
@@ -41,6 +41,7 @@ from products.signals.backend.scout_harness.team_limits import (
DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
DEFAULT_ENROLLED_TEAM_IDS,
SIGNALS_SCOUT_DISCOVERY_DISTINCT_ID,
+ BackgroundBand,
BackgroundEnrollment,
Enrollment,
_default_team_config,
@@ -56,6 +57,7 @@ from products.signals.backend.scout_harness.team_limits import (
_resolve_slot_aligned_dispatch,
_resolve_withheld_skills,
_team_configs,
+ background_sample_bucket,
max_enabled_scouts_for_team,
resolve_max_enabled_scouts,
)
@@ -662,14 +664,43 @@ _GENERAL = "signals-scout-general"
{"background": {"enabled": True, "team_ids": [3], "interval_minutes": 720, "max_new_teams_per_tick": 2}},
BackgroundEnrollment(True, _GENERAL, frozenset({3}), 720, 2),
),
+ (
+ # A malformed band drops out alone and never costs the block its `team_ids`.
+ {
+ "background": {
+ "enabled": True,
+ "team_ids": [3],
+ "bands": {
+ "1": {"percent": 5, "interval_minutes": 10080},
+ "2": {"percent": 101},
+ "3": {"percent": True},
+ "4": "nope",
+ },
+ }
+ },
+ BackgroundEnrollment(
+ True,
+ _GENERAL,
+ frozenset({3}),
+ None,
+ DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
+ {1: BackgroundBand(percent=5, interval_minutes=10080)},
+ ),
+ ),
+ (
+ {"background": {"enabled": True, "team_ids": [3], "bands": ["1"]}},
+ BackgroundEnrollment(True, _GENERAL, frozenset({3}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),
+ ),
],
)
def test_parse_background(payload, expected):
assert _parse_background(payload) == expected
-def _background(team_ids: set[int], *, enabled: bool = True, max_new: int = 5) -> BackgroundEnrollment:
- return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new)
+def _background(
+ team_ids: set[int], *, enabled: bool = True, max_new: int = 5, bands: dict[int, BackgroundBand] | None = None
+) -> BackgroundEnrollment:
+ return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new, bands or {})
_NO_ENROLLMENT = Enrollment(wildcard=False, explicit=set(), skip=set())
@@ -745,6 +776,59 @@ class TestBackgroundEnrollment:
assert background_config.status == SignalScoutConfig.Status.ACTIVE
assert background_config.enabled is True
+ def _banded_teams(self, band: int, count: int) -> list[Team]:
+ teams = [self._team() for _ in range(count)]
+ now = timezone.now()
+ for team in teams:
+ SignalScoutBackgroundBand.all_teams.create(team=team, band=band, computed_at=now)
+ return teams
+
+ def test_band_sampling_keeps_earlier_picks_as_the_percent_rises(self):
+ teams = self._banded_teams(2, 30)
+ buckets = {team.id: background_sample_bucket(team.id) for team in teams}
+
+ def sampled(percent: int) -> set[int]:
+ bands = {2: BackgroundBand(percent=percent, interval_minutes=20160)}
+ _collect_planned_runs(_NO_ENROLLMENT, background=_background(set(), max_new=100, bands=bands))
+ return set(
+ SignalScoutConfig.all_teams.filter(
+ team__in=teams, status=SignalScoutConfig.Status.ACTIVE, skill_name=_GENERAL
+ ).values_list("team_id", flat=True)
+ )
+
+ low, high = sampled(30), sampled(70)
+
+ assert low == {team_id for team_id, bucket in buckets.items() if bucket < 30}
+ assert high == {team_id for team_id, bucket in buckets.items() if bucket < 70}
+ assert low < high
+ assert set(
+ SignalScoutConfig.all_teams.filter(team__in=teams).values_list("background_band", "run_interval_minutes")
+ ) == {(2, 20160)}
+
+ def test_band_at_zero_pauses_band_configs_but_not_team_managed_or_hand_picked_ones(self):
+ banded, taken_over, hand_picked = self._banded_teams(1, 3)
+ with team_scope(banded.id, canonical=True):
+ banded_config = _create_config(
+ banded, _GENERAL, managed_by=SignalScoutConfig.ManagedBy.BACKGROUND, background_band=1
+ )
+ with team_scope(taken_over.id, canonical=True):
+ taken_over_config = _create_config(taken_over, _GENERAL, background_band=1)
+ with team_scope(hand_picked.id, canonical=True):
+ hand_picked_config = _create_config(
+ hand_picked, _GENERAL, managed_by=SignalScoutConfig.ManagedBy.BACKGROUND
+ )
+
+ bands = {1: BackgroundBand(percent=0, interval_minutes=None)}
+ _collect_planned_runs(_NO_ENROLLMENT, background=_background({hand_picked.id}, bands=bands))
+
+ for config in (banded_config, taken_over_config, hand_picked_config):
+ config.refresh_from_db()
+ assert banded_config.status == SignalScoutConfig.Status.PAUSED_BY_SYSTEM
+ assert banded_config.pause_reason == SignalScoutConfig.PauseReason.BACKGROUND_REMOVED
+ assert taken_over_config.status == SignalScoutConfig.Status.ACTIVE
+ assert hand_picked_config.status == SignalScoutConfig.Status.ACTIVE
+ assert hand_picked_config.background_band is None
+
# ── Schedule: deterministic due-check, no sampling ──────────────────────────────