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): skip scout suggestion scans for projects with no data (#101698)

posthog[bot]260d4234decc
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 3f1e8f53aa24..2ea9c3b5111a 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -31,7 +31,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
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`).
- `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; 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), 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; `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, persists, and emits `$scout_suggestions_generated`. 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.
+ 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), 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; `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, persists, and emits `$scout_suggestions_generated`. 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`
Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. The destination targets a single channel or up to `MAX_SCOUT_SLACK_DM_TARGETS` members who each get an individual DM (one Celery task per recipient, so retries and permanent failures stay independent; a group DM would need the `mpim:write` scope the Slack app doesn't request). Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.
A report message renders its `charts` through the exports facade (`render_png_export`, attributed to the run's acting user, so the insight access check applies; a system render that expires with its delivery url, so it stays out of the user's export quota and does not outlive its only reference) and appends them as `image` blocks pointing at a signed delivery url; chart links in the prose still reduce to their label. A threaded report carries its charts on the lead message, since the replies only hold the summary's tail. Only `InsightVizNode` / `SavedInsightNode` charts render, capped per report and by a render-time budget (a render only starts if it can finish inside the budget), with rendered assets remembered per delivery so a Slack retry does not re-render, and every failure is skipped rather than failing the delivery — the whole chart build is best effort, not only the render. The Slack integration row is resolved again after the build, since a workspace reconnected during the render window replaces the token on the same row.
diff --git a/products/signals/backend/scout_harness/suggestions.py b/products/signals/backend/scout_harness/suggestions.py
index 0e3dfa82b60a..a39b928b1c1b 100644
--- a/products/signals/backend/scout_harness/suggestions.py
+++ b/products/signals/backend/scout_harness/suggestions.py
@@ -301,7 +301,15 @@ def _candidate_teams_by_tier(settings: SuggestionSettings, now: datetime) -> tup
return {}, {}
cutoff = now - timedelta(days=settings.engagement_window_days)
- approved_root_teams = Team.objects.filter(_root_team_q(), organization__is_ai_data_processing_approved=True)
+ # A project that has never ingested an event can only be refused by the scan, and this base
+ # set feeds every tier. Nothing is stamped on the row, so the project re-enters the queue on
+ # its first event; ingestion is environment-scoped, so traffic in a child environment counts.
+ ingested_child_teams = Team.objects.filter(ingested_event=True, parent_team_id__isnull=False)
+ approved_root_teams = Team.objects.filter(
+ _root_team_q(),
+ 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.
source_teams = SignalSourceConfig.objects.filter(enabled=True).values("team_id")
diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.py
index ad0b8244f539..b602b1c1e683 100644
--- a/products/signals/backend/test/test_scout_suggestions.py
+++ b/products/signals/backend/test/test_scout_suggestions.py
@@ -256,11 +256,13 @@ class TestPlanSuggestionRuns(BaseTest):
super().setUp()
self.organization.is_ai_data_processing_approved = True
self.organization.save()
+ self.team.ingested_event = True
+ self.team.save()
self.now = timezone.now()
- def _team(self, name: str, *, approved: bool = True) -> Team:
+ def _team(self, name: str, *, approved: bool = True, ingested: bool = True) -> Team:
organization = Organization.objects.create(name=name, is_ai_data_processing_approved=approved)
- return Team.objects.create(organization=organization, name=name)
+ return Team.objects.create(organization=organization, name=name, ingested_event=ingested)
def _enable_scout(self, team: Team, *, engaged: bool) -> None:
config = SignalScoutConfig.objects.create(team=team, skill_name="signals-scout-general", enabled=True)
@@ -440,6 +442,30 @@ class TestPlanSuggestionRuns(BaseTest):
planned = plan_suggestion_runs(SuggestionSettings(enabled=True, eligibility_tier=2), self.now)
self.assertEqual([(run.team_id, run.tier) for run in planned], [(project.id, 2)])
+ def test_a_project_that_never_ingested_an_event_is_planned_once_it_does(self):
+ empty = self._team("never-ingested", ingested=False)
+ self._enable_scout(empty, engaged=True)
+ settings = SuggestionSettings(enabled=True, eligibility_tier=2)
+
+ self.assertEqual(plan_suggestion_runs(settings, self.now), [])
+
+ Team.objects.filter(pk=empty.pk).update(ingested_event=True)
+ self.assertEqual([run.team_id for run in plan_suggestion_runs(settings, self.now)], [empty.id])
+
+ def test_an_allowlisted_project_is_planned_with_no_data(self):
+ empty = self._team("allowlisted-empty", ingested=False)
+
+ planned = plan_suggestion_runs(SuggestionSettings(enabled=True, team_allowlist=frozenset({empty.id})), self.now)
+ self.assertEqual([(run.team_id, run.tier) for run in planned], [(empty.id, 0)])
+
+ def test_ingestion_in_a_child_environment_keeps_the_project_planned(self):
+ project = self._team("child-ingestion", ingested=False)
+ Team.objects.create(organization=project.organization, name="prod", parent_team=project, ingested_event=True)
+ self._enable_scout(project, engaged=True)
+
+ planned = plan_suggestion_runs(SuggestionSettings(enabled=True), self.now)
+ self.assertEqual([run.team_id for run in planned], [project.id])
+
class TestManualSuggestionsDispatch(BaseTest):
def test_manual_dispatch_stamps_planner_state(self):