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): back off background scouts that nobody engages with (#114584)

posthog[bot]bf8671dc93aa
diff --git a/products/signals/backend/migrations/0169_signalscoutconfig_background_backoff_level.py b/products/signals/backend/migrations/0169_signalscoutconfig_background_backoff_level.py
new file mode 100644
index 000000000000..54b780462a04
--- /dev/null
+++ b/products/signals/backend/migrations/0169_signalscoutconfig_background_backoff_level.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-09 12:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0168_signalscoutconfig_mcp_tool_grants"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalscoutconfig",
+ name="background_backoff_level",
+ field=models.PositiveSmallIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index d79256cd3327..ad0064a5dee9 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0168_signalscoutconfig_mcp_tool_grants
+0169_signalscoutconfig_background_backoff_level
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 7f4b28c79377..d345e78a07b6 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -2580,6 +2580,10 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
# 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)
+ # How many background runs in a row nobody engaged with. The coordinator multiplies the band
+ # interval by `background.backoff.factor` once per level, so `run_interval_minutes` keeps the
+ # nominal cadence. `None` means level 0. Read only while the row is `managed_by=background`.
+ background_backoff_level = models.PositiveSmallIntegerField(null=True, blank=True)
# Set only alongside `pending_pause` / `paused_by_system`; see `PauseReason`.
pause_reason = models.CharField(
max_length=20,
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 3fa2bc67d6a8..9d5f6292980e 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -96,6 +96,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
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`, `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`.
+ `background.backoff` (`enabled`, `factor`, `max_interval_minutes`) slows down a background config that nobody engages with. `SignalScoutConfig.background_backoff_level` counts the runs in a row with no engagement, and the coordinator makes the config due at `min(run_interval_minutes × factor^level, max_interval_minutes)`, so `run_interval_minutes` keeps the nominal band cadence. The stamp moves the level when it dispatches a run: up by one when the previous dispatch created a `SignalScoutRun` and no member engaged since, and back to 0 when one did. A previous dispatch that the child skipped (quota, daily report limit, an active run) keeps the level. Planning reads the same engagement, so engagement makes a backed-off config due at the band interval at once. Engagement is a `SignalReportAction` row of any type or a person-attributed dismissal or log artefact on the team's reports, read for all due teams together (`_engaged_team_ids`). A login is not engagement. A config above level 0 is stamped at the tick start rather than at its slot anchor, because a slot on a changing period would dispatch it early. Without the block, nothing reads or moves the level, and a `managed_by=team` config never backs off. The runner stamps `background_backoff_level` and `background_effective_interval_minutes` next to `background_band`; both describe the cadence after the run.
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/runner.py b/products/signals/backend/scout_harness/runner.py
index b4d1ab856309..5332b197d4f1 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -63,7 +63,12 @@ from products.signals.backend.scout_harness.skill_loader import (
resolve_scout_acting_user_id,
skill_uses_report_channel,
)
-from products.signals.backend.scout_harness.team_limits import github_read_access_for_team, withheld_skills_for_team
+from products.signals.backend.scout_harness.team_limits import (
+ BackgroundBackoff,
+ github_read_access_for_team,
+ resolve_background_backoff,
+ withheld_skills_for_team,
+)
from products.signals.backend.scout_harness.trial_launch import (
TrialLaunch,
assert_trial_model_access,
@@ -491,6 +496,12 @@ async def _arun_signals_scout(
business_knowledge_maintained = await database_sync_to_async(
_business_knowledge_maintained_for_team, thread_sensitive=False
)(team)
+ # Resolved here for the same reason, so every lifecycle event reports the same cadence.
+ backoff = (
+ await asyncio.to_thread(resolve_background_backoff)
+ if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND
+ else None
+ )
trial_status = tasks_facade.TaskRunStatus.FAILED.value
try:
last_message, task_run_id = await _spawn_and_run(
@@ -504,6 +515,7 @@ async def _arun_signals_scout(
user_id=user_id,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=backoff,
model=model,
runtime_adapter=runtime_adapter,
reasoning_effort=reasoning_effort,
@@ -531,6 +543,7 @@ async def _arun_signals_scout(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=backoff,
run_id=run_id,
task_run_id=task_run_id,
status=tasks_facade.TaskRunStatus.COMPLETED.value,
@@ -615,6 +628,7 @@ async def _arun_signals_scout(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=backoff,
run_id=run_id,
task_run_id=failed_task_run_id,
status=tasks_facade.TaskRunStatus.FAILED.value,
@@ -676,6 +690,7 @@ async def _arun_signals_scout(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=backoff,
run_id=run_id,
task_run_id=None,
status=tasks_facade.TaskRunStatus.CANCELLED.value,
@@ -872,6 +887,7 @@ async def _spawn_and_run(
github_guidance: bool,
business_knowledge_maintained: bool,
model: str | None,
+ background_backoff: BackgroundBackoff | None = None,
runtime_adapter: str | None = None,
reasoning_effort: str | None = None,
service_tier: str | None = None,
@@ -1020,6 +1036,7 @@ async def _spawn_and_run(
service_tier=service_tier,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=background_backoff,
repositories=repositories,
triggered_by=triggered_by,
run_note=run_note,
@@ -1038,6 +1055,7 @@ async def _spawn_and_run(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=background_backoff,
run_id=run_id,
task_run_id=str(task_run_id),
triggered_by=triggered_by,
@@ -1291,6 +1309,7 @@ def _create_run_row(
service_tier: str | None = None,
github_guidance: bool = False,
business_knowledge_maintained: bool = False,
+ background_backoff: BackgroundBackoff | None = None,
repositories: list[str] | None = None,
triggered_by: str = TRIGGERED_BY_SCHEDULE,
run_note: str | None = None,
@@ -1345,6 +1364,7 @@ def _create_run_row(
# hand-picked `team_ids` project.
if config.background_band is not None:
metadata["background_band"] = config.background_band
+ metadata.update(_background_backoff_props(config, background_backoff))
# 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.
@@ -1589,6 +1609,7 @@ def _capture_run_started(
github_guidance: bool,
business_knowledge_maintained: bool,
run_id: Any,
+ background_backoff: BackgroundBackoff | None = None,
task_run_id: str,
triggered_by: str,
model: str | None = None,
@@ -1619,6 +1640,7 @@ def _capture_run_started(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=background_backoff,
model=model,
runtime_adapter=runtime_adapter,
service_tier=service_tier,
@@ -1721,6 +1743,21 @@ def _capture_config_auto_paused(
)
+def _background_backoff_props(config: SignalScoutConfig, backoff: BackgroundBackoff | None) -> dict[str, int]:
+ """The backoff level of a background config and the interval it sets to the next run.
+
+ Empty when the backoff is off or the config is not background-managed. The stamp before this
+ run already moved the level, so the values describe the cadence after this run.
+ """
+ if backoff is None or config.managed_by != SignalScoutConfig.ManagedBy.BACKGROUND or config.run_cron_schedule:
+ return {}
+ level = config.background_backoff_level or 0
+ return {
+ "background_backoff_level": level,
+ "background_effective_interval_minutes": backoff.effective_interval_minutes(config.run_interval_minutes, level),
+ }
+
+
def _attach_run_shape_props(
properties: dict[str, Any],
*,
@@ -1732,6 +1769,7 @@ def _attach_run_shape_props(
runtime_adapter: str | None,
service_tier: str | None,
triggered_by: str,
+ background_backoff: BackgroundBackoff | None = None,
) -> None:
"""Attach the dimensions that describe what this run was configured with, to both lifecycle
events from one place so the started and finished streams can never drift apart.
@@ -1760,6 +1798,7 @@ def _attach_run_shape_props(
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
+ properties.update(_background_backoff_props(config, background_backoff))
if config.network_access == SignalScoutConfig.NetworkAccess.FULL:
properties["network_access"] = config.network_access
if granted_write_scopes := _granted_write_scopes(config):
@@ -1782,6 +1821,7 @@ def _capture_run_finished(
github_guidance: bool,
business_knowledge_maintained: bool,
run_id: Any,
+ background_backoff: BackgroundBackoff | None = None,
task_run_id: str | None,
status: str,
runtime_s: float,
@@ -1829,6 +1869,7 @@ def _capture_run_finished(
skill=skill,
github_guidance=github_guidance,
business_knowledge_maintained=business_knowledge_maintained,
+ background_backoff=background_backoff,
model=model,
runtime_adapter=runtime_adapter,
service_tier=service_tier,
diff --git a/products/signals/backend/scout_harness/team_limits.py b/products/signals/backend/scout_harness/team_limits.py
index d05b812ec7bd..703e76903413 100644
--- a/products/signals/backend/scout_harness/team_limits.py
+++ b/products/signals/backend/scout_harness/team_limits.py
@@ -243,6 +243,25 @@ class BackgroundBand:
BACKGROUND_BANDS = (1, 2, 3, 4)
+@dataclass(frozen=True)
+class BackgroundBackoff:
+ """Parsed `background.backoff`: each background run that nobody engages with multiplies the
+ interval to the next run by `factor`, up to `max_interval_minutes`."""
+
+ factor: int
+ max_interval_minutes: int
+
+ def effective_interval_minutes(self, base_minutes: int, level: int | None) -> int:
+ return min(base_minutes * self.factor ** (level or 0), max(base_minutes, self.max_interval_minutes))
+
+ def next_level(self, base_minutes: int, level: int | None) -> int:
+ """One level up, but never past the first level that reaches the cap, so the level stays bounded."""
+ current = level or 0
+ if self.effective_interval_minutes(base_minutes, current) >= self.max_interval_minutes:
+ return current
+ return current + 1
+
+
@dataclass(frozen=True)
class BackgroundEnrollment:
"""Parsed `background` block from the `signals-scout` flag payload.
@@ -259,6 +278,8 @@ class BackgroundEnrollment:
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)
+ # `None` turns the backoff off, so every background config runs at its band interval.
+ backoff: BackgroundBackoff | None = None
def band_interval_minutes(self, band: int | None) -> int | None:
entry = self.bands.get(band) if band is not None else None
@@ -292,6 +313,23 @@ def _parse_background_bands(raw: object) -> dict[int, BackgroundBand]:
return bands
+def _parse_background_backoff(raw: object) -> BackgroundBackoff | None:
+ """Parse `background.backoff`. A missing, disabled, or malformed block turns the backoff off."""
+ if not isinstance(raw, dict) or raw.get("enabled") is not True:
+ return None
+ factor = _positive_int_or_none(raw.get("factor"))
+ max_interval_minutes = _positive_int_or_none(raw.get("max_interval_minutes"))
+ if factor is None or factor < 2 or max_interval_minutes is None:
+ return None
+ return BackgroundBackoff(factor=factor, max_interval_minutes=max_interval_minutes)
+
+
+def resolve_background_backoff() -> BackgroundBackoff | None:
+ """One flag-payload read of `background.backoff`, for callers outside the coordinator."""
+ background = _parse_background(_read_flag_payload())
+ return background.backoff if background is not None else None
+
+
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.
@@ -309,7 +347,8 @@ def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:
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`,
- `max_new_teams_per_tick`, or `bands` entry falls back to its default and does not invalidate the block.
+ `max_new_teams_per_tick`, `bands` entry, or `backoff` falls back to its default and does not
+ invalidate the block.
"""
if payload is None:
return None
@@ -335,6 +374,7 @@ def _parse_background(payload: dict | None) -> BackgroundEnrollment | None:
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")),
+ backoff=_parse_background_backoff(raw.get("backoff")),
)
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index e6ffdfbd648d..e4a7f49fc1c0 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -7,7 +7,8 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta, tzinfo
from uuid import UUID
-from django.db.models import Case, DateTimeField, Q, Value, When
+from django.db import transaction
+from django.db.models import Case, DateTimeField, Max, PositiveSmallIntegerField, Q, Value, When
from django.utils import timezone
import structlog
@@ -21,7 +22,13 @@ 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 SignalScoutBackgroundBand, SignalScoutConfig
+from products.signals.backend.models import (
+ SignalReportAction,
+ SignalReportArtefact,
+ SignalScoutBackgroundBand,
+ SignalScoutConfig,
+ SignalScoutRun,
+)
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,
@@ -54,6 +61,7 @@ from products.signals.backend.scout_harness.limits import (
# them unqualified and tests can patch them on this module.
from products.signals.backend.scout_harness.team_limits import (
DAILY_BUDGET_WINDOW,
+ BackgroundBackoff,
BackgroundEnrollment,
Enrollment,
_canonicalize_team_config_keys,
@@ -231,8 +239,12 @@ async def stamp_dispatched_signals_scout_runs_activity(
# `database_sync_to_async`'s pool is sized for DB-bound work.
payload = await asyncio.to_thread(_read_flag_payload)
slot_aligned = _resolve_slot_aligned_dispatch(payload)
+ background = _parse_background(payload)
await database_sync_to_async(_stamp_dispatched_runs, thread_sensitive=False)(
- stamp_input.dispatched_runs, slot_aligned=slot_aligned, dispatched_at=stamp_input.dispatched_at
+ stamp_input.dispatched_runs,
+ slot_aligned=slot_aligned,
+ dispatched_at=stamp_input.dispatched_at,
+ backoff=background.backoff if background is not None else None,
)
# Counted here rather than in the workflow so a replay cannot double-count it, and after the
# stamp so a retried attempt counts the batch once.
@@ -286,7 +298,11 @@ def _slot_anchor(config_pk: str, run_interval_minutes: int, dispatched_at: datet
def _stamp_dispatched_runs(
- dispatched_runs: list[PlannedRun], *, slot_aligned: bool = True, dispatched_at: datetime | None = None
+ dispatched_runs: list[PlannedRun],
+ *,
+ slot_aligned: bool = True,
+ dispatched_at: datetime | None = None,
+ backoff: BackgroundBackoff | None = None,
) -> None:
"""Sync bulk stamp. `.update()` bypasses save(), so this per-tick write never hits the
activity log.
@@ -308,6 +324,12 @@ def _stamp_dispatched_runs(
- A disabled config, which here is a lane the failure breaker paused and the coordinator is
probing. Its `last_run_at` is the probe cooldown clock rather than a schedule anchor, so
backdating it would shorten the cooldown the breaker is counting.
+ - A background config at a backoff level above 0. Its period changes with every level, and a
+ slot on a new period can sit up to that whole period back, which would dispatch it early and
+ undo the backoff. The tick start is already on the grid, so nothing drifts.
+
+ With `backoff` set, this also moves the backoff level of each dispatched background config (see
+ `_next_backoff_levels`).
"""
if not dispatched_runs:
return
@@ -316,25 +338,137 @@ def _stamp_dispatched_runs(
for run in dispatched_runs:
predicate |= Q(team_id=run.team_id, skill_name=run.skill_name)
dispatched = SignalScoutConfig.all_teams.filter(predicate)
- if not slot_aligned:
- dispatched.update(last_run_at=now)
- return
+ rows = list(
+ dispatched.values_list(
+ "pk",
+ "team_id",
+ "enabled",
+ "run_cron_schedule",
+ "run_interval_minutes",
+ "managed_by",
+ "background_backoff_level",
+ "last_run_at",
+ )
+ )
+ levels = _next_backoff_levels(rows, backoff, now) if backoff is not None else {}
+ # The level and `last_run_at` commit together. After a partial write, the retried stamp would
+ # read the old `last_run_at` and raise the level a second time.
+ with transaction.atomic():
+ if levels:
+ pks_by_level: dict[int, list[UUID]] = {}
+ for pk, level in levels.items():
+ pks_by_level.setdefault(level, []).append(pk)
+ SignalScoutConfig.all_teams.filter(pk__in=levels.keys()).update(
+ background_backoff_level=Case(
+ *(When(pk__in=pks, then=Value(level)) for level, pks in pks_by_level.items()),
+ output_field=PositiveSmallIntegerField(),
+ )
+ )
+ if not slot_aligned:
+ dispatched.update(last_run_at=now)
+ return
+
+ pks_by_anchor: dict[datetime, list[UUID]] = {}
+ for pk, _team_id, enabled, cron_schedule, interval_minutes, *_ in rows:
+ slotted = enabled and not cron_schedule and not levels.get(pk)
+ anchor = _slot_anchor(str(pk), interval_minutes, now) if slotted else now
+ pks_by_anchor.setdefault(anchor, []).append(pk)
+ if not pks_by_anchor:
+ return
+ dispatched.update(
+ last_run_at=Case(
+ *(When(pk__in=pks, then=Value(anchor)) for anchor, pks in pks_by_anchor.items()),
+ default=Value(now),
+ output_field=DateTimeField(),
+ )
+ )
- pks_by_anchor: dict[datetime, list[UUID]] = {}
- for pk, enabled, cron_schedule, interval_minutes in dispatched.values_list(
- "pk", "enabled", "run_cron_schedule", "run_interval_minutes"
- ):
- anchor = _slot_anchor(str(pk), interval_minutes, now) if enabled and not cron_schedule else now
- pks_by_anchor.setdefault(anchor, []).append(pk)
- if not pks_by_anchor:
- return
- dispatched.update(
- last_run_at=Case(
- *(When(pk__in=pks, then=Value(anchor)) for anchor, pks in pks_by_anchor.items()),
- default=Value(now),
- output_field=DateTimeField(),
+
+def _next_backoff_levels(rows: list[tuple], backoff: BackgroundBackoff, now: datetime) -> dict[UUID, int]:
+ """The backoff level to store for each enabled rolling-interval background config in `rows`.
+
+ A config that a member engaged with since its previous run goes back to level 0. A config with a
+ previous run and no engagement goes up one level. The first run of a config keeps level 0,
+ because no earlier run exists for anyone to ignore. A previous dispatch that the child skipped
+ (quota, daily report limit, an active run) left no output to ignore, so it keeps the level.
+ """
+ previous_runs: dict[UUID, tuple[int, int, int | None, datetime]] = {
+ pk: (team_id, interval_minutes, level, last_run_at)
+ for pk, team_id, enabled, cron_schedule, interval_minutes, managed_by, level, last_run_at in rows
+ if enabled
+ and not cron_schedule
+ and managed_by == SignalScoutConfig.ManagedBy.BACKGROUND
+ and last_run_at is not None
+ }
+ engaged = _engaged_team_ids({team_id: since for team_id, _, _, since in previous_runs.values()})
+ ran = _configs_with_run_between({pk: since for pk, (_, _, _, since) in previous_runs.items()}, now)
+ levels: dict[UUID, int] = {}
+ for pk, (team_id, interval_minutes, level, _) in previous_runs.items():
+ if team_id in engaged:
+ levels[pk] = 0
+ elif pk in ran:
+ levels[pk] = backoff.next_level(interval_minutes, level)
+ else:
+ levels[pk] = level or 0
+ return levels
+
+
+def _configs_with_run_between(since_by_config: dict[UUID, datetime], until: datetime) -> set[UUID]:
+ """The configs in `since_by_config` with a `SignalScoutRun` created in `[since, until)`.
+
+ `until` is the current tick start, so the run this tick dispatches does not count as the
+ previous one. One query for all configs together, on the `scout_config` index.
+ """
+ if not since_by_config:
+ return set()
+ latest = (
+ SignalScoutRun.all_teams.filter(
+ scout_config_id__in=since_by_config,
+ created_at__gte=min(since_by_config.values()),
+ created_at__lt=until,
)
+ .values("scout_config_id")
+ .annotate(latest=Max("created_at"))
)
+ return {row["scout_config_id"] for row in latest if row["latest"] >= since_by_config[row["scout_config_id"]]}
+
+
+# Artefacts a person writes when they act on a report: a dismissal (dismiss, snooze, or a resolve
+# with a note) or a log entry such as a note. Only person-attributed rows count.
+_ENGAGEMENT_ARTEFACT_TYPES: frozenset[str] = SignalReportArtefact.LOG_ARTEFACT_TYPES | frozenset(
+ {SignalReportArtefact.ArtefactType.DISMISSAL}
+)
+
+
+def _engaged_team_ids(since_by_team: dict[int, datetime]) -> set[int]:
+ """The teams in `since_by_team` where a member engaged with a report after the given time.
+
+ Engagement is a `SignalReportAction` row (view, read, feedback, Slack discussion) or a
+ person-attributed dismissal or log artefact. A login alone is not engagement. Two queries for
+ all teams together, on the `team_id` index: `SignalReportAction.last_at` has no index.
+ """
+ if not since_by_team:
+ return set()
+ earliest = min(since_by_team.values())
+ latest: dict[int, datetime] = {}
+ for queryset in (
+ SignalReportAction.all_teams.filter(team_id__in=since_by_team, last_at__gt=earliest)
+ .values("team_id")
+ .annotate(latest=Max("last_at")),
+ SignalReportArtefact.objects.filter(
+ team_id__in=since_by_team,
+ type__in=_ENGAGEMENT_ARTEFACT_TYPES,
+ created_by__isnull=False,
+ created_at__gt=earliest,
+ )
+ .values("team_id")
+ .annotate(latest=Max("created_at")),
+ ):
+ for row in queryset:
+ team_id, engaged_at = row["team_id"], row["latest"]
+ if team_id not in latest or engaged_at > latest[team_id]:
+ latest[team_id] = engaged_at
+ return {team_id for team_id, engaged_at in latest.items() if engaged_at > since_by_team[team_id]}
@dataclass
@@ -925,19 +1059,24 @@ def _collect_background_runs(
Checks consent again at dispatch, because an organization can withdraw it after its config was
created. Breaker-paused background configs get their probes here too, so no background run
skips the consent check.
+
+ With `background.backoff` set, a config is due at its backed-off interval. Engagement since its
+ previous run makes it due at the band interval again, before the stamp stores level 0.
"""
if not listed_team_ids:
return []
- configs = SignalScoutConfig.all_teams.filter(
- Q(enabled=True)
- | Q(
- status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
- pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
- ),
- team_id__in=listed_team_ids,
- skill_name=background.skill_name,
- managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
- ).select_related("team__organization")
+ configs = list(
+ SignalScoutConfig.all_teams.filter(
+ Q(enabled=True)
+ | Q(
+ status=SignalScoutConfig.Status.PAUSED_BY_SYSTEM,
+ pause_reason=SignalScoutConfig.PauseReason.REPEATED_FAILURES,
+ ),
+ team_id__in=listed_team_ids,
+ skill_name=background.skill_name,
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ ).select_related("team__organization")
+ )
live_team_ids = set(
LLMSkill.objects.filter(
team_id__in=listed_team_ids, name=background.skill_name, is_latest=True, deleted=False
@@ -945,6 +1084,17 @@ def _collect_background_runs(
)
due: list[_DueRun] = []
live_skills = {background.skill_name}
+ engaged = (
+ _engaged_team_ids(
+ {
+ config.team_id: config.last_run_at
+ for config in configs
+ if config.enabled and config.background_backoff_level and config.last_run_at is not None
+ }
+ )
+ if background.backoff is not None
+ else set()
+ )
for config in configs:
if config.team_id not in live_team_ids or not _ai_data_processing_approved(config.team):
continue
@@ -953,14 +1103,25 @@ def _collect_background_runs(
if not config.enabled:
due.extend(_collect_probe_runs([config], live_skills, now))
continue
- overdue_s = _overdue_seconds(config, now, config.team.timezone_info)
+ interval_minutes = None
+ if background.backoff is not None and config.team_id not in engaged:
+ interval_minutes = background.backoff.effective_interval_minutes(
+ config.run_interval_minutes, config.background_backoff_level
+ )
+ overdue_s = _overdue_seconds(config, now, config.team.timezone_info, interval_minutes=interval_minutes)
if overdue_s is not None:
due.append(_DueRun(overdue_s, str(config.pk), config.team_id, config.skill_name))
return due
-def _overdue_seconds(config: SignalScoutConfig, now: datetime, project_timezone: tzinfo) -> float | None:
- """Seconds past due, or None if not yet due. Never-run rolling schedules are maximally overdue."""
+def _overdue_seconds(
+ config: SignalScoutConfig, now: datetime, project_timezone: tzinfo, *, interval_minutes: int | None = None
+) -> float | None:
+ """Seconds past due, or None if not yet due. Never-run rolling schedules are maximally overdue.
+
+ `interval_minutes` replaces `run_interval_minutes` for a rolling schedule, such as a backed-off
+ background config.
+ """
if config.run_cron_schedule:
# `schedule_changed_at` (stamped only on actual schedule edits — deliberately not
# `updated_at`, which every emit/enabled save bumps) anchors a newly saved schedule so
@@ -998,7 +1159,7 @@ def _overdue_seconds(config: SignalScoutConfig, now: datetime, project_timezone:
if config.last_run_at is None:
return float("inf")
- overdue = (now - config.last_run_at).total_seconds() - config.run_interval_minutes * 60
+ overdue = (now - config.last_run_at).total_seconds() - (interval_minutes or config.run_interval_minutes) * 60
return overdue if overdue >= -DUE_GRACE_SECONDS else None
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index 5821a22de4f7..cdbb4f2cfac0 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -19,11 +19,17 @@ from parameterized import parameterized
from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.testing import ActivityEnvironment
-from posthog.models import Organization, Team
+from posthog.models import Organization, Team, User
from posthog.models.scoping import team_scope
from posthog.sync import database_sync_to_async
-from products.signals.backend.models import SignalScoutBackgroundBand, SignalScoutConfig
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportAction,
+ SignalScoutBackgroundBand,
+ SignalScoutConfig,
+ SignalScoutRun,
+)
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 +47,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,
+ BackgroundBackoff,
BackgroundBand,
BackgroundEnrollment,
Enrollment,
@@ -81,11 +88,13 @@ from products.signals.backend.temporal.agentic.scout_coordinator import (
_DueRun,
_overdue_seconds,
_slot_anchor,
+ _stamp_dispatched_runs,
fetch_enabled_signals_scout_runs_activity,
run_due_signal_report_checks_activity,
stamp_dispatched_signals_scout_runs_activity,
)
from products.skills.backend.models.skills import LLMSkill
+from products.tasks.backend.models import Task, TaskRun
_PAYLOAD_PATH = "products.signals.backend.scout_harness.team_limits.posthoganalytics.get_feature_flag_payload"
_IS_CLOUD_PATH = "products.signals.backend.scout_harness.team_limits.is_cloud"
@@ -691,6 +700,28 @@ _GENERAL = "signals-scout-general"
{"background": {"enabled": True, "team_ids": [3], "bands": ["1"]}},
BackgroundEnrollment(True, _GENERAL, frozenset({3}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),
),
+ (
+ {
+ "background": {
+ "enabled": True,
+ "team_ids": [3],
+ "backoff": {"enabled": True, "factor": 2, "max_interval_minutes": 129600},
+ }
+ },
+ BackgroundEnrollment(
+ True,
+ _GENERAL,
+ frozenset({3}),
+ None,
+ DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK,
+ backoff=BackgroundBackoff(factor=2, max_interval_minutes=129600),
+ ),
+ ),
+ (
+ # A malformed backoff turns the backoff off and never costs the block its `team_ids`.
+ {"background": {"enabled": True, "team_ids": [3], "backoff": {"enabled": True, "factor": 1}}},
+ BackgroundEnrollment(True, _GENERAL, frozenset({3}), None, DEFAULT_BACKGROUND_MAX_NEW_TEAMS_PER_TICK),
+ ),
],
)
def test_parse_background(payload, expected):
@@ -698,9 +729,18 @@ def test_parse_background(payload, expected):
def _background(
- team_ids: set[int], *, enabled: bool = True, max_new: int = 5, bands: dict[int, BackgroundBand] | None = None
+ team_ids: set[int],
+ *,
+ enabled: bool = True,
+ max_new: int = 5,
+ bands: dict[int, BackgroundBand] | None = None,
+ backoff: BackgroundBackoff | None = None,
) -> BackgroundEnrollment:
- return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new, bands or {})
+ return BackgroundEnrollment(enabled, _GENERAL, frozenset(team_ids), 720, max_new, bands or {}, backoff)
+
+
+_WEEK_MINUTES = 7 * 24 * 60
+_BACKOFF = BackgroundBackoff(factor=2, max_interval_minutes=90 * 24 * 60)
_NO_ENROLLMENT = Enrollment(wildcard=False, explicit=set(), skip=set())
@@ -829,6 +869,140 @@ class TestBackgroundEnrollment:
assert hand_picked_config.status == SignalScoutConfig.Status.ACTIVE
assert hand_picked_config.background_band is None
+ def _weekly_background_config(self, team: Team, **kwargs: Any) -> SignalScoutConfig:
+ with team_scope(team.id, canonical=True):
+ _create_skill(team, _GENERAL)
+ return _create_config(
+ team,
+ _GENERAL,
+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,
+ run_interval_minutes=_WEEK_MINUTES,
+ **kwargs,
+ )
+
+ def _tick(
+ self, team: Team, config: SignalScoutConfig, background: BackgroundEnrollment, at: datetime, *, runs: bool
+ ) -> bool:
+ with time_machine.travel(at, tick=False):
+ planned = _collect_planned_runs(_NO_ENROLLMENT, background=background)
+ _stamp_dispatched_runs(planned, dispatched_at=at, backoff=background.backoff)
+ dispatched = PlannedRun(team_id=team.id, skill_name=_GENERAL) in planned
+ if dispatched and runs:
+ self._record_run(team, config, at + timedelta(minutes=1))
+ return dispatched
+
+ def _record_run(self, team: Team, config: SignalScoutConfig, at: datetime) -> None:
+ with time_machine.travel(at, tick=False):
+ task = Task.objects.create(
+ team=team,
+ title="scout run",
+ description="scout run",
+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,
+ )
+ SignalScoutRun.all_teams.create(
+ task_run=TaskRun.objects.create(task=task, team=team),
+ team=team,
+ scout_config=config,
+ skill_name=_GENERAL,
+ skill_version=1,
+ )
+
+ @parameterized.expand(
+ [
+ ("runs_back_off_to_the_cap", True, [7, 14, 28, 56, 90, 90, 90]),
+ # A child that skips (quota, daily report limit) creates no run, so the level never rises.
+ ("skipped_runs_stay_weekly", False, [7, 7, 7, 7, 7, 7, 7]),
+ ]
+ )
+ def test_unengaged_dispatches_over_400_days(self, _name, runs, expected_gaps):
+ team = self._team()
+ config = self._weekly_background_config(team)
+ # Start on the config's own weekly slot, so the first stamp lands exactly on the start day.
+ start = _slot_anchor(str(config.pk), _WEEK_MINUTES, datetime(2026, 1, 5, tzinfo=UTC))
+ background = _background({team.id}, backoff=_BACKOFF)
+
+ dispatch_days = [
+ day for day in range(400) if self._tick(team, config, background, start + timedelta(days=day), runs=runs)
+ ]
+
+ gaps = [later - earlier for earlier, later in zip(dispatch_days, dispatch_days[1:])]
+ assert gaps[:7] == expected_gaps
+ config.refresh_from_db()
+ assert config.run_interval_minutes == _WEEK_MINUTES
+
+ @parameterized.expand(
+ [
+ ("engaged_resets_to_weekly", True, SignalScoutConfig.ManagedBy.BACKGROUND, _BACKOFF, True, 0),
+ ("unengaged_stays_backed_off", False, SignalScoutConfig.ManagedBy.BACKGROUND, _BACKOFF, False, 3),
+ ("no_backoff_block_runs_weekly", False, SignalScoutConfig.ManagedBy.BACKGROUND, None, True, 3),
+ ("team_managed_never_backs_off", False, SignalScoutConfig.ManagedBy.TEAM, _BACKOFF, True, 3),
+ ]
+ )
+ def test_backed_off_config_eight_days_after_its_last_run(
+ self, _name, engaged, managed_by, backoff, expect_dispatch, expected_level
+ ):
+ team = self._team()
+ last_run_at = datetime(2026, 3, 2, tzinfo=UTC)
+ config = self._weekly_background_config(team, last_run_at=last_run_at, background_backoff_level=3)
+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(managed_by=managed_by)
+ if engaged:
+ with time_machine.travel(last_run_at + timedelta(days=2), tick=False):
+ report = SignalReport.objects.create(team=team, title="A report", summary="Something")
+ user = User.objects.create(email=f"member-{team.id}@example.com")
+ SignalReportAction.record(
+ team_id=team.id,
+ report_id=str(report.pk),
+ user_id=user.pk,
+ action_type=SignalReportAction.ActionType.VIEW,
+ )
+ at = last_run_at + timedelta(days=8)
+ enrollment = (
+ Enrollment(wildcard=False, explicit={team.id}, skip=set())
+ if managed_by == SignalScoutConfig.ManagedBy.TEAM
+ else _NO_ENROLLMENT
+ )
+
+ with (
+ time_machine.travel(at, tick=False),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.register_missing_configs",
+ return_value={_GENERAL},
+ ),
+ ):
+ planned = _collect_planned_runs(enrollment, background=_background({team.id}, backoff=backoff))
+ _stamp_dispatched_runs(planned, dispatched_at=at, backoff=backoff)
+
+ assert (PlannedRun(team_id=team.id, skill_name=_GENERAL) in planned) is expect_dispatch
+ config.refresh_from_db()
+ assert config.background_backoff_level == expected_level
+
+ @parameterized.expand([("acknowledgement_lost", False), ("failed_between_writes", True)])
+ def test_retried_stamp_raises_the_level_once(self, _name, first_attempt_fails):
+ team = self._team()
+ last_run_at = datetime(2026, 3, 2, tzinfo=UTC)
+ config = self._weekly_background_config(team, last_run_at=last_run_at)
+ self._record_run(team, config, last_run_at + timedelta(minutes=1))
+ planned = [PlannedRun(team_id=team.id, skill_name=_GENERAL)]
+ at = last_run_at + timedelta(days=7)
+
+ with time_machine.travel(at, tick=False):
+ if first_attempt_fails:
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.DateTimeField",
+ side_effect=RuntimeError("stamp failed"),
+ ),
+ pytest.raises(RuntimeError),
+ ):
+ _stamp_dispatched_runs(planned, dispatched_at=at, backoff=_BACKOFF)
+ else:
+ _stamp_dispatched_runs(planned, dispatched_at=at, backoff=_BACKOFF)
+ _stamp_dispatched_runs(planned, dispatched_at=at, backoff=_BACKOFF)
+
+ config.refresh_from_db()
+ assert config.background_backoff_level == 1
+ assert config.last_run_at == at
+
# ── Schedule: deterministic due-check, no sampling ──────────────────────────────
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index ad0fda3cb6c3..48ae521bdfb6 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -81,6 +81,7 @@ from products.signals.backend.scout_harness.runner import (
SIGNALS_SCOUT_SANDBOX_ENV_NAME,
RunResult,
_ai_stage,
+ _background_backoff_props,
_create_run_row,
_failure_streak_runs_in_window,
arun_signals_scout,
@@ -92,6 +93,7 @@ from products.signals.backend.scout_harness.skill_loader import (
load_skill_for_run,
resolve_scout_acting_user_id,
)
+from products.signals.backend.scout_harness.team_limits import BackgroundBackoff
from products.signals.backend.scout_harness.tools.runs import _build_task_url, _to_detail, _to_summary
from products.signals.backend.scout_harness.trial_launch import (
ScoutTrialLaunchError,
@@ -1601,7 +1603,6 @@ class TestTrialDispatch(SimpleTestCase):
def _fake_start_invoking_hook(session: MagicMock, result: object):
-
async def _start(*args, before_task_dispatch=None, **kwargs):
if before_task_dispatch is not None:
await database_sync_to_async(before_task_dispatch)(session.task_run.id)
@@ -3965,3 +3966,27 @@ class TestScoutRunTokenCosts(BaseTest):
assert [cost.run_id for cost in costs.costs] == [str(mine.id)]
assert query.call_args.kwargs["task_run_ids"] == [mine.task_run_id]
+
+
+ "managed_by,backoff,level,expected",
+ [
+ (
+ SignalScoutConfig.ManagedBy.BACKGROUND,
+ BackgroundBackoff(factor=2, max_interval_minutes=129600),
+ 2,
+ {"background_backoff_level": 2, "background_effective_interval_minutes": 40320},
+ ),
+ (
+ SignalScoutConfig.ManagedBy.BACKGROUND,
+ BackgroundBackoff(factor=2, max_interval_minutes=129600),
+ 9,
+ {"background_backoff_level": 9, "background_effective_interval_minutes": 129600},
+ ),
+ (SignalScoutConfig.ManagedBy.BACKGROUND, None, 2, {}),
+ (SignalScoutConfig.ManagedBy.TEAM, BackgroundBackoff(factor=2, max_interval_minutes=129600), 2, {}),
+ ],
+)
+def test_background_backoff_props(managed_by, backoff, level, expected):
+ config = SignalScoutConfig(managed_by=managed_by, run_interval_minutes=10080, background_backoff_level=level)
+ assert _background_backoff_props(config, backoff) == expected