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 on low-activity projects (#104535)

posthog[bot]bc6bd576459f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 141069c8c25d..c784d497e688 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9212,6 +9212,10 @@ snapshots:
hash: v1.k794b7964.de465356e1d0c3d5df4e27a38f222f1272cd482864e94f5c0926496b21585156.JrxNWbA8ll95SmETdYceyyUM7OXvaVFv4m2ZNqLTEc0
scenes-app-inbox-scoutsuggestionsstrip--last-scan-failed--light:
hash: v1.k794b7964.862bc68a11983494741c4d1522c7a0b5a9dbc62fa096994e7ca39fcee696dc45.Gqy-Dr8yrhe7v2EdrEZFwjferFE9JMtvLBRegJF3Ebw
+ scenes-app-inbox-scoutsuggestionsstrip--low-activity--dark:
+ hash: v1.k794b7964.732c41df9211ce01adee553f66133484b9e5ea18986cf871c44f27fa88846754.DoN92tzMp60OUzfZtXPqKJ9UiDTVJC9sLc5nQVmjHzU
+ scenes-app-inbox-scoutsuggestionsstrip--low-activity--light:
+ hash: v1.k794b7964.9073f092aa4a347930e8468bb2f212bbdbe96a636a9fbce691cffa6caa493b07.YTmjGLtgppZg6VzdbUe-5cMUkxvsWUPRELqQMczJIc8
scenes-app-inbox-scoutsuggestionsstrip--narrow--dark:
hash: v1.k794b7964.d16cb21c4d654c63d5f8b6047b3291b636b25e21b00a91b06bd8384967f8a4ef.h9itg-CPeBGLngbSfw7_TIYGEJHnd_Z_sQ4VYIS5u0k
scenes-app-inbox-scoutsuggestionsstrip--narrow--light:
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index e7dd969fe951..76948bd88aea 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -148,7 +148,7 @@ Output buckets per team: `created`, `updated`, `diverged` (team-edited or hand-a
### Pre-computed scout suggestions
-`run_scout_suggestions` drives the headless "Suggested for this project" scan (`../scout_harness/suggestions.py`) without waiting for its Temporal coordinator. `--team-id` runs the scan inline for one team (bypassing the planner and its cap; the org still needs AI data processing approved) and prints the stored batch; `--show` prints the stored batch without running; `--plan` prints what the coordinator would dispatch on the next tick under the current `signals-scout-suggestions` flag payload.
+`run_scout_suggestions` drives the headless "Suggested for this project" scan (`../scout_harness/suggestions.py`) without waiting for its Temporal coordinator. `--team-id` runs the scan inline for one team (bypassing the planner and its cap; the org still needs AI data processing approved) and prints the stored batch; `--show` prints the stored batch without running; `--plan` prints what the coordinator would dispatch on the next tick under the current `signals-scout-suggestions` flag payload, and runs the dispatch-time activity check too, so it stamps `low_activity` on the projects it rules out exactly as the tick would.
```bash
# Generate (or regenerate) the batch for one team now, then print it
diff --git a/products/signals/backend/management/commands/run_scout_suggestions.py b/products/signals/backend/management/commands/run_scout_suggestions.py
index 6637dd423ced..807052a2d23c 100644
--- a/products/signals/backend/management/commands/run_scout_suggestions.py
+++ b/products/signals/backend/management/commands/run_scout_suggestions.py
@@ -2,7 +2,9 @@
`--team-id` runs the headless scan inline (bypassing the planner and its cap) and prints the
stored batch. `--plan` prints what the coordinator would dispatch on the next tick under the
-current `signals-scout-suggestions` flag payload, without dispatching anything.
+current `signals-scout-suggestions` flag payload, without dispatching anything. `--plan` runs
+the dispatch-time activity check too, so it stamps `low_activity` on the projects it rules out,
+exactly as the tick would.
"""
from __future__ import annotations
@@ -21,10 +23,12 @@ from products.signals.backend.scout_harness.suggestions import (
plan_suggestion_runs,
read_suggestion_settings,
reserved_scout_names,
+ select_teams_to_scan,
stamp_requested,
visible_items,
)
from products.signals.backend.scout_harness.suggestions_runner import arun_scout_suggestions
+from products.signals.backend.temporal.agentic.scout_suggestions import SUGGESTIONS_OVERSELECT_FACTOR
class Command(BaseCommand):
@@ -38,11 +42,16 @@ class Command(BaseCommand):
def handle(self, *args, **options):
settings = read_suggestion_settings()
if options["plan"]:
- planned = plan_suggestion_runs(settings)
+ cap = settings.max_children_per_tick
+ planned = plan_suggestion_runs(settings, limit=cap * SUGGESTIONS_OVERSELECT_FACTOR)
+ selection = select_teams_to_scan(planned, settings, limit=cap)
self.stdout.write(f"settings: {settings}")
- self.stdout.write(f"planned {len(planned)} team(s):")
- for run in planned:
+ self.stdout.write(f"planned {len(selection.dispatch)} team(s):")
+ for run in selection.dispatch:
self.stdout.write(f" team {run.team_id} (tier {run.tier})")
+ self.stdout.write(f"skipped {len(selection.skipped_team_ids)} team(s) as low_activity:")
+ for team_id in selection.skipped_team_ids:
+ self.stdout.write(f" team {team_id}")
return
if options["team_id"] is None:
diff --git a/products/signals/backend/migrations/0152_alter_signalscoutsuggestionset_status.py b/products/signals/backend/migrations/0152_alter_signalscoutsuggestionset_status.py
new file mode 100644
index 000000000000..0ac543c5d9d8
--- /dev/null
+++ b/products/signals/backend/migrations/0152_alter_signalscoutsuggestionset_status.py
@@ -0,0 +1,25 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("signals", "0151_scout_config_retired_pause_reason")]
+
+ operations = [
+ # Choices only: `status` stays a CharField of the same length, so this emits no SQL.
+ migrations.AlterField(
+ model_name="signalscoutsuggestionset",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("fresh", "Fresh"),
+ ("stale", "Stale"),
+ ("failed", "Failed"),
+ ("empty", "Empty"),
+ ("low_activity", "Low activity"),
+ ],
+ db_default="empty",
+ default="empty",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index ba5b91931485..5b086500b494 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0151_scout_config_retired_pause_reason
+0152_alter_signalscoutsuggestionset_status
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 520c020702e6..271e60d38160 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -3128,6 +3128,8 @@ class SignalScoutSuggestionSet(TeamScopedRootMixin, UUIDModel):
FAILED = "failed", "Failed"
# The last generation completed and found nothing worth suggesting.
EMPTY = "empty", "Empty"
+ # The project was too quiet in the activity window to be worth a scan, so none ran.
+ LOW_ACTIVITY = "low_activity", "Low activity"
# See SignalScoutConfig.all_teams for rationale.
all_teams = models.Manager() # noqa: DJ012
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 04a8bea78fe5..54907625ab4a 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -36,7 +36,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; 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.
+ Pre-computed scout suggestions: the push-side twin of the "Suggest a scout" chat button. `suggestions.py` (temporalio-free, cheap to import) holds the structured-output contract the headless run returns (`ScoutSuggestionBatch`: 3-5 items, each a `canonical` "turn this on" pick or a `custom` draft with a ready-to-create `draft_body`), the `signals-scout-suggestions` flag-payload settings (`enabled`, `eligibility_tier` 0-4 (0 = allowlist only), `refresh_days`, `max_children_per_tick`, allow/blocklist, failure breaker), the planner (`plan_suggestion_runs`: recomputes the priority queue from Postgres every tick; a project that has never ingested an event is no candidate at any tier, because the scan could only refuse it, and the gate is read from `Team.ingested_event` on the project or any of its environments at plan time rather than stamped on the row, so the project re-enters the queue on its first event and an allowlisted project is scanned either way; tier, then never-generated, then most overdue, then most recently engaged; engagement is a report view or rating, a scout a person turned on or off (`status_changed_by`), or a scout a person created (`created_by`), never a plain edit or a system touch; nothing is stored as a queue; engagement is read only for the teams already in the tier map, since `SignalReportAction.last_at` is deliberately unindexed and an unbounded filter on it scans the whole action history; a team past the failure breaker doubles its refresh interval per further failure, because the cooldown is shorter than the refresh window and so could never hold a scheduled retry back), the dispatch-time activity check (`select_teams_to_scan`: after the plan is made and before a child is dispatched, one bounded ClickHouse read per picked candidate over the project and its child environments together, counting events and distinct active days in `activity_window_days`, on the offline cluster, since a scheduled fleet scan must not compete with interactive queries (a Temporal activity keeps `Workload.ONLINE` unless it says otherwise, and `readonly=True` would return before the offline routing rather than add to it); a project under `min_events_in_window` or under `min_active_days_in_window` is stamped `low_activity` instead of scanned, because the scan could only refuse it, and either knob at 0 turns that half of the check off; the read is capped at `ACTIVITY_READ_MAX_ROWS` rows and refuses at the cap rather than truncating, because the cap counts rows read while the query counts the rows inside the window, so a truncated read would answer with a small count that reads like a quiet project; a refused read counts as active, since a project whose window does not fit the cap is active whatever the refusal hid; it carries a wall-clock cap too (`ACTIVITY_READ_MAX_EXECUTION_S`), because `sync_execute` sets none and the pooled client's socket timeout is effectively infinite in production, so a stalled read would hold a worker thread past the planning activity's deadline; a read that fails dispatches anyway, since the coordinator stamps `last_requested_at` either way and a quiet minute of ClickHouse must not cost a project its refresh window; allowlisted projects are scanned whatever the read says, and the manual refresh endpoint never runs the check, because a person who pressed the button asked for the scan; the coordinator therefore overselects the plan by `SUGGESTIONS_OVERSELECT_FACTOR` so a tick still fills when several candidates are skipped, and the skipped ones are stamped `last_requested_at` alongside the dispatched ones so the planner leaves them for a full refresh window rather than re-reading them every tick), draft validation (`validate_suggestion_items` drops anything the one-click Create could not apply as-is), and persistence on `SignalScoutSuggestionSet` (one row per team, items as JSON, every write under a row lock since each is a read-modify-write of the column; dismissals carry forward by `skill_name` and survive as hidden tombstones when a batch omits the name, compacted to the dismissal fields so a dropped draft body does not sit in the row forever; a batch persisted after the fleet moved is stored `stale`, and a batch that merely aged past `refresh_days`, whether it held items or concluded there was nothing to suggest, reads as `stale` through `effective_status`, since nothing writes that status on expiry; a failed generation anywhere after the gates keeps the prior items and counts toward the breaker; a `low_activity` stamp keeps the prior items the same way but leaves the breaker alone, since a quiet project is not a broken one: the count is preserved but ignored for scheduling while the status holds, so the backoff cannot push the next activity check out past one refresh window, and it counts again as soon as a scan runs; a quiet row also does not expire to `stale`, so the project waits a full refresh window and is then re-checked; `mark_stale_if_fleet_changed` is wired to `SignalScoutConfig` saves in `../receivers.py`). Reads hide dismissed, created, and already-enabled items, plus custom drafts whose name a stored skill or config has since taken; the manual refresh endpoint honors the same kill switch and blocklist as the planner, runs the scan as its authenticated caller rather than the resolved team member, and a manual dispatch stamps `last_requested_at` so the coordinator does not double up. `suggestions_runner.py` is the one piece that needs the tasks agent facade: `arun_scout_suggestions` gates (AI-processing consent, an acting user; deliberately no self-driving credits gate, since a scan opens no pull request and so bills nothing, while a skip would still burn the team's whole refresh window), mints a `read_only` headless task with the reserved `SIGNALS_SCOUT_SUGGESTIONS` origin, no GitHub token and no MCP Store servers, because the scan reads project text any member can write, parses the batch with no prose salvage (an unparseable close-out is a failed generation), validates, and persists. Both it and the activity check emit `$scout_suggestions_generated` through the one emitter in `suggestions.py` (`capture_suggestions_generated`), so a skipped project reads as `status=skipped`, `skip_reason=low_activity` plus the two measured numbers on the same event the completed runs use, and the daily roll-up needs no new column. The skip carries a stable event id, keyed on the project and the refresh stamp the decision was made against, because the planning activity retries and would otherwise count one skipped scan several times; a completed run needs none, since its activity runs at most once. Driven by `temporal/agentic/scout_suggestions.py` (coordinator + child, same shape as the scout coordinator, own schedule) and exposed read/dismiss/refresh at `signals/scout/suggestions/` (`../scout_suggestions_api.py`), where membership, token scope, and resource-level RBAC all anchor to the canonical parent team. The prompt shares `SCOUT_PROJECT_SCAN_GUIDANCE` (in `prompt.py`) with the chat template so the two voices never drift.
- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`
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 a39b928b1c1b..4be8372a578c 100644
--- a/products/signals/backend/scout_harness/suggestions.py
+++ b/products/signals/backend/scout_harness/suggestions.py
@@ -3,10 +3,11 @@
The chat button mints a `SIGNALS_CHAT` task the user then waits on while the agent scans the
project. This module runs the same scan ahead of time, headless, for every eligible project and
stores 3-5 structured suggestions on `SignalScoutSuggestionSet`, so the scouts tab can offer them
-with zero wait. Three pieces live here, all temporalio-free and cheap to import:
+with zero wait. Four pieces live here, all temporalio-free and cheap to import:
- the structured-output contract the headless run returns (`ScoutSuggestionBatch`)
- the planner: which teams to refresh this tick, in priority order (`plan_suggestion_runs`)
+- the dispatch-time activity check on the picked candidates (`select_teams_to_scan`)
- persistence: write a batch, carry dismissals forward, dismiss / mark created
The runner that mints the headless task for one team lives in `suggestions_runner.py`, because it
@@ -24,16 +25,22 @@ import json
from collections.abc import Collection, Iterable
from datetime import datetime, timedelta
from typing import Any, Literal
-from uuid import UUID
+from uuid import NAMESPACE_URL, UUID, uuid5
from django.db import transaction
from django.db.models import F, Max, Q
from django.utils import timezone
import structlog
+import posthoganalytics
from pydantic import BaseModel, Field
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.clickhouse.workload import Workload
from posthog.dataclasses import frozen
+from posthog.errors import InternalCHQueryError
+from posthog.event_usage import groups
from posthog.models.scoping.manager import resolve_effective_team_id
from posthog.models.team.team import Team
from posthog.models.utils import uuid7
@@ -69,6 +76,21 @@ MAX_DESCRIPTION_CHARS = SPEC_DESCRIPTION_MAX_LENGTH
# Resolves a suggestion run to the `signals_scout_suggestions` gateway product.
SUGGESTIONS_AI_STAGE = "scout_suggestions"
+# Row cap on the per-candidate activity read, so the check stays cheap on a large project. The
+# read refuses at the cap rather than truncating: the cap counts rows read while the query counts
+# the rows that pass the window filter, so a truncated read would come back as a small count that
+# reads like a quiet project. A project whose window does not fit the cap is active whatever the
+# refusal hid, and only a read that finishes has numbers — the small projects the check is about.
+ACTIVITY_READ_MAX_ROWS = 100_000
+
+# Wall-clock cap on the same read. `sync_execute` adds none of its own and the pooled client's
+# socket timeout is effectively infinite in production, so a stalled read would hold its worker
+# thread past the planning activity's own deadline, which Temporal cannot reclaim. A capped read
+# over the events primary-key prefix takes milliseconds, and the planner reads its candidates one
+# after another inside a five-minute activity, so this leaves room for every candidate a tick
+# picks at the default cap.
+ACTIVITY_READ_MAX_EXECUTION_S = 10
+
SuggestionKind = Literal["canonical", "custom"]
SuggestionConfidence = Literal["low", "medium", "high"]
@@ -170,6 +192,12 @@ class SuggestionSettings:
failure_breaker_threshold: int = 3
failure_cooldown_hours: int = 24
max_runtime_s: int = SUGGESTIONS_MAX_RUNTIME_S
+ # The dispatch-time activity check. A project under either line is stamped `low_activity`
+ # instead of scanned, because the scan could only refuse it. Either threshold at 0 turns
+ # that half of the check off; both at 0 turns the check off.
+ activity_window_days: int = 14
+ min_events_in_window: int = 100
+ min_active_days_in_window: int = 3
def _int_in(payload: dict[str, Any], key: str, default: int, *, low: int, high: int) -> int:
@@ -202,6 +230,9 @@ def parse_suggestion_settings(payload: dict[str, Any] | None) -> SuggestionSetti
failure_breaker_threshold=_int_in(payload, "failure_breaker_threshold", 3, low=1, high=100),
failure_cooldown_hours=_int_in(payload, "failure_cooldown_hours", 24, low=1, high=24 * 30),
max_runtime_s=_int_in(payload, "max_runtime_s", SUGGESTIONS_MAX_RUNTIME_S, low=60, high=30 * 60),
+ activity_window_days=_int_in(payload, "activity_window_days", 14, low=1, high=90),
+ min_events_in_window=_int_in(payload, "min_events_in_window", 100, low=0, high=ACTIVITY_READ_MAX_ROWS),
+ min_active_days_in_window=_int_in(payload, "min_active_days_in_window", 3, low=0, high=90),
)
@@ -378,8 +409,13 @@ def _wait_s(consecutive_failures: int, settings: SuggestionSettings, *, refresh_
return refresh_s * (2**doublings)
-def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = None) -> list[PlannedSuggestionRun]:
- """The teams to refresh this tick, best first, capped at `max_children_per_tick`.
+def plan_suggestion_runs(
+ settings: SuggestionSettings, now: datetime | None = None, *, limit: int | None = None
+) -> list[PlannedSuggestionRun]:
+ """The teams to refresh this tick, best first, capped at `limit` (`max_children_per_tick`).
+
+ The coordinator overselects, because the dispatch-time activity check drops candidates after
+ the plan is made and a tick should still fill when several are skipped.
The queue is recomputed from DB state every tick (no stored queue), so changing eligibility is a
payload edit, never a migration of queued work. Allowlisted teams are always candidates
@@ -387,7 +423,8 @@ def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = No
geometrically so a broken project cannot hold a slot every refresh period.
"""
now = now or timezone.now()
- if not settings.enabled or settings.max_children_per_tick == 0:
+ limit = settings.max_children_per_tick if limit is None else limit
+ if not settings.enabled or limit <= 0:
return []
tiers, engagement = _candidate_teams_by_tier(settings, now)
for team_id in canonical_team_ids(settings.team_allowlist):
@@ -410,18 +447,28 @@ def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = No
candidates: list[_Candidate] = []
for team_id, tier in tiers.items():
state = state_by_team.get(team_id)
+ # The failure backoff does not apply to a quiet project. A `low_activity` stamp runs no
+ # scan and resets no count, so a project that tripped the breaker before it went quiet
+ # would wait up to 16 refresh windows for its next activity check, and nothing that can
+ # happen while it stays quiet would shorten that. The count stays on the row and holds
+ # the next scan back again as soon as one runs.
+ failures = (
+ 0
+ if state is None or state.status == SignalScoutSuggestionSet.Status.LOW_ACTIVITY
+ else state.consecutive_failures
+ )
if state is None or state.last_requested_at is None:
never_generated, overdue_s = True, float("inf")
else:
never_generated = False
- wait_s = _wait_s(state.consecutive_failures, settings, refresh_s=refresh_s)
+ wait_s = _wait_s(failures, settings, refresh_s=refresh_s)
# A stale batch is due on the shorter window, and so is a failed one, since a failure
# on a stale row replaces its status and would otherwise push the retry out to the full
# window. Both only while the project is picking up batches at all — pulling a
# repeatedly failing one forward would undo the breaker.
if (
state.status in (SignalScoutSuggestionSet.Status.STALE, SignalScoutSuggestionSet.Status.FAILED)
- and state.consecutive_failures < settings.failure_breaker_threshold
+ and failures < settings.failure_breaker_threshold
):
wait_s = min(wait_s, stale_refresh_s)
overdue_s = (now - state.last_requested_at).total_seconds() - wait_s
@@ -433,7 +480,7 @@ def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = No
# cooldown is shorter than the refresh window it would have to outlast.
if (
state is not None
- and state.consecutive_failures >= settings.failure_breaker_threshold
+ and failures >= settings.failure_breaker_threshold
and state.last_completed_at is not None
and state.last_completed_at >= now - cooldown
):
@@ -450,10 +497,7 @@ def plan_suggestion_runs(settings: SuggestionSettings, now: datetime | None = No
)
)
candidates.sort(key=lambda candidate: candidate.sort_key)
- return [
- PlannedSuggestionRun(team_id=candidate.team_id, tier=candidate.tier)
- for candidate in candidates[: settings.max_children_per_tick]
- ]
+ return [PlannedSuggestionRun(team_id=candidate.team_id, tier=candidate.tier) for candidate in candidates[:limit]]
def stamp_requested(team_ids: list[int], now: datetime | None = None) -> None:
@@ -470,6 +514,207 @@ def stamp_requested(team_ids: list[int], now: datetime | None = None) -> None:
SignalScoutSuggestionSet.all_teams.filter(team_id__in=team_ids).update(last_requested_at=now)
+# ---------------------------------------------------------------------------
+# Dispatch-time activity check
+# ---------------------------------------------------------------------------
+
+
+LOW_ACTIVITY_SKIP_REASON = "low_activity"
+
+# TOO_MANY_ROWS / TOO_MANY_ROWS_OR_BYTES: what `read_overflow_mode: throw` raises at
+# `ACTIVITY_READ_MAX_ROWS`. Any other failure belongs to the caller's dispatch-anyway path.
+_READ_CAP_ERROR_CODES = (158, 396)
+
+
+@frozen
+class TeamActivity:
+ """What the bounded read saw for one project inside the activity window."""
+
+ event_count: int
+ active_days: int
+ # The read refused at `ACTIVITY_READ_MAX_ROWS` rather than answer with a truncated count, so
+ # the two fields above hold nothing the check may read.
+ capped: bool
+
+
+@frozen
+class ActivitySelection:
+ dispatch: tuple[PlannedSuggestionRun, ...]
+ skipped_team_ids: tuple[int, ...]
+
+
+def activity_check_enabled(settings: SuggestionSettings) -> bool:
+ return settings.min_events_in_window > 0 or settings.min_active_days_in_window > 0
+
+
+def read_team_activity(team_id: int, *, window_days: int) -> TeamActivity:
+ """Events and distinct active days for a project and its child environments in the window.
+
+ Ingestion is environment-scoped while the batch is per canonical project, so the two are
+ counted together. A read that hits the row cap refuses instead of answering, because a
+ truncated aggregate is indistinguishable from a quiet project: the events table sorts on
+ `toDate(timestamp)`, so the window bound drops rows the cap has already counted, and the
+ spread is then a floor with nothing to mark it as one.
+ """
+ team_ids = list(Team.objects.filter(Q(id=team_id) | Q(parent_team_id=team_id)).values_list("id", flat=True))
+ tag_queries(
+ product=Product.SIGNALS,
+ feature=Feature.DATA_FRESHNESS,
+ query_type="SignalsScoutSuggestionsActivityCheck",
+ trigger="signals_scout_suggestions_activity_check",
+ )
+ try:
+ rows = sync_execute(
+ """
+ SELECT count(), uniqExact(toDate(timestamp))
+ FROM events
+ WHERE team_id IN %(team_ids)s
+ AND timestamp >= now() - toIntervalDay(%(window_days)s)
+ """,
+ {"team_ids": team_ids, "window_days": window_days},
+ # A scheduled fleet scan belongs off the interactive cluster: a tick reads one
+ # candidate after another, and the per-tick cap is flag-tunable.
+ workload=Workload.OFFLINE,
+ settings={
+ "max_rows_to_read": ACTIVITY_READ_MAX_ROWS,
+ "read_overflow_mode": "throw",
+ "max_execution_time": ACTIVITY_READ_MAX_EXECUTION_S,
+ # Both overflow modes throw for the same reason: a partial aggregate reads as a
+ # quiet project. A timed-out read raises instead, and the caller dispatches.
+ "timeout_overflow_mode": "throw",
+ },
+ team_id=team_id,
+ )
+ except InternalCHQueryError as error:
+ if error.code not in _READ_CAP_ERROR_CODES:
+ raise
+ return TeamActivity(event_count=ACTIVITY_READ_MAX_ROWS, active_days=0, capped=True)
+ event_count = int(rows[0][0]) if rows else 0
+ active_days = int(rows[0][1]) if rows else 0
+ return TeamActivity(event_count=event_count, active_days=active_days, capped=False)
+
+
+def team_is_active_enough(activity: TeamActivity, settings: SuggestionSettings) -> bool:
+ if activity.capped:
+ return True
+ if settings.min_events_in_window and activity.event_count < settings.min_events_in_window:
+ return False
+ if settings.min_active_days_in_window and activity.active_days < settings.min_active_days_in_window:
+ return False
+ return True
+
+
+def select_teams_to_scan(
+ planned: Iterable[PlannedSuggestionRun], settings: SuggestionSettings, *, limit: int
+) -> ActivitySelection:
+ """The planned candidates worth a scan, in order, up to `limit`.
+
+ One bounded read per candidate, over the picked set only, never over the pool. A project
+ under either activity line is stamped `low_activity` and reported as a skipped run rather
+ than dispatched, because the scan could only refuse it. Candidates past `limit` are left
+ untouched, so a tick that fills early re-plans them next tick. Allowlisted projects are
+ scanned whatever the read says, for dogfood and support.
+ """
+ candidates = list(planned)
+ if not activity_check_enabled(settings):
+ return ActivitySelection(dispatch=tuple(candidates[:limit]), skipped_team_ids=())
+ exempt = canonical_team_ids(settings.team_allowlist)
+ dispatch: list[PlannedSuggestionRun] = []
+ skipped: list[int] = []
+ for run in candidates:
+ if len(dispatch) >= limit:
+ break
+ if run.team_id in exempt:
+ dispatch.append(run)
+ continue
+ try:
+ activity = read_team_activity(run.team_id, window_days=settings.activity_window_days)
+ except Exception:
+ # A read that cannot answer must not cost the project its refresh window.
+ logger.warning("scout_suggestions: activity read failed", team_id=run.team_id, exc_info=True)
+ dispatch.append(run)
+ continue
+ if team_is_active_enough(activity, settings):
+ dispatch.append(run)
+ continue
+ skipped.append(run.team_id)
+ _record_low_activity(run.team_id, activity=activity, settings=settings, tier=run.tier)
+ return ActivitySelection(dispatch=tuple(dispatch), skipped_team_ids=tuple(skipped))
+
+
+def _skip_event_uuid(team_id: int, *, requested_at: datetime | None) -> str:
+ """One id per skip decision, so a retry of the planning activity does not count it twice.
+
+ `last_requested_at` is stamped after fan-out, so it reads the same on every attempt of one
+ tick and a different value by the time the project is due again.
+ """
+ return str(uuid5(NAMESPACE_URL, f"{LOW_ACTIVITY_SKIP_REASON}:{team_id}:{requested_at}"))
+
+
+def _record_low_activity(
+ team_id: int, *, activity: TeamActivity, settings: SuggestionSettings, tier: int | None
+) -> None:
+ row = mark_low_activity(team_id)
+ team = Team.objects.select_related("organization").filter(id=team_id).first()
+ if team is None:
+ return
+ capture_suggestions_generated(
+ team,
+ status="skipped",
+ skip_reason=LOW_ACTIVITY_SKIP_REASON,
+ tier=tier,
+ event_uuid=_skip_event_uuid(team_id, requested_at=row.last_requested_at),
+ extra_properties={
+ "activity_window_days": settings.activity_window_days,
+ "activity_event_count": activity.event_count,
+ "activity_active_days": activity.active_days,
+ },
+ )
+
+
+def capture_suggestions_generated(
+ team: Team,
+ *,
+ status: str,
+ skip_reason: str | None = None,
+ suggestion_count: int = 0,
+ runtime_s: float = 0.0,
+ task_run_id: str | None = None,
+ tier: int | None = None,
+ model: str | None = None,
+ triggered_by: str = "schedule",
+ event_uuid: str | None = None,
+ extra_properties: dict[str, Any] | None = None,
+) -> None:
+ """The one emitter of `$scout_suggestions_generated`, so a completed run and a skipped one
+ are read from the same event and the daily roll-up needs no new column.
+
+ `event_uuid` dedupes the emitters that can run twice for one decision. A completed run needs
+ none: its activity runs at most once.
+ """
+ try:
+ posthoganalytics.capture(
+ event="$scout_suggestions_generated",
+ distinct_id=str(team.uuid),
+ uuid=event_uuid,
+ properties={
+ "team_id": team.id,
+ "status": status,
+ "skip_reason": skip_reason,
+ "suggestion_count": suggestion_count,
+ "runtime_s": round(runtime_s, 1),
+ "task_run_id": task_run_id,
+ "tier": tier,
+ "model": model,
+ "triggered_by": triggered_by,
+ **(extra_properties or {}),
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.warning("scout_suggestions: failed to capture generated event", team_id=team.id)
+
+
# ---------------------------------------------------------------------------
# Prompt
# ---------------------------------------------------------------------------
@@ -673,6 +918,20 @@ def mark_generation_failed(team_id: int, *, task_run_id: str | None) -> SignalSc
return row
+def mark_low_activity(team_id: int) -> SignalScoutSuggestionSet:
+ """A project too quiet to scan. The prior items stay readable, the same as a failed
+ generation, and the failure breaker is left alone: a quiet project is not a broken one. The
+ planner re-checks it once the refresh window passes, so traffic picked up in the meantime
+ costs at most one window."""
+ with transaction.atomic():
+ row = _lock_row(team_id, create=True)
+ assert row is not None
+ row.status = SignalScoutSuggestionSet.Status.LOW_ACTIVITY
+ row.last_completed_at = timezone.now()
+ row.save(update_fields=["status", "last_completed_at", "updated_at"])
+ return row
+
+
# A generated conclusion, with or without items; `failed` and `stale` already say what they are.
_EXPIRING_STATUSES = (SignalScoutSuggestionSet.Status.FRESH, SignalScoutSuggestionSet.Status.EMPTY)
@@ -778,30 +1037,40 @@ def mark_stale_if_fleet_changed(team_id: int) -> None:
__all__ = [
+ "ACTIVITY_READ_MAX_ROWS",
+ "LOW_ACTIVITY_SKIP_REASON",
"MAX_SUGGESTIONS_PER_BATCH",
"SIGNALS_SCOUT_SUGGESTIONS_FLAG",
"SUGGESTIONS_ACTIVITY_SLACK_S",
"SUGGESTIONS_AI_STAGE",
"SUGGESTIONS_MAX_RUNTIME_S",
+ "ActivitySelection",
"PlannedSuggestionRun",
"ScoutSuggestionBatch",
"ScoutSuggestionItem",
"SuggestionSettings",
+ "TeamActivity",
+ "activity_check_enabled",
"build_suggestions_prompt",
"canonical_team_ids",
+ "capture_suggestions_generated",
"dismiss_suggestion",
"enabled_skill_names",
"find_suggestion",
"fleet_context",
"mark_generation_failed",
+ "mark_low_activity",
"mark_stale_if_fleet_changed",
"mark_suggestion_created",
"parse_suggestion_settings",
"persist_suggestion_batch",
"plan_suggestion_runs",
"read_suggestion_settings",
+ "read_team_activity",
"reserved_scout_names",
+ "select_teams_to_scan",
"stamp_requested",
"suggestions_allowed_for_team",
+ "team_is_active_enough",
"visible_items",
]
diff --git a/products/signals/backend/scout_harness/suggestions_runner.py b/products/signals/backend/scout_harness/suggestions_runner.py
index 1e6c0d755b9a..f3b641526639 100644
--- a/products/signals/backend/scout_harness/suggestions_runner.py
+++ b/products/signals/backend/scout_harness/suggestions_runner.py
@@ -13,11 +13,9 @@ from collections.abc import Collection
from typing import Literal
import structlog
-import posthoganalytics
from rest_framework import serializers
from posthog.dataclasses import frozen
-from posthog.event_usage import groups
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
@@ -37,6 +35,7 @@ from products.signals.backend.scout_harness.suggestions import (
ScoutSuggestionItem,
SuggestionSettings,
build_suggestions_prompt,
+ capture_suggestions_generated,
fleet_context,
mark_generation_failed,
persist_suggestion_batch,
@@ -147,25 +146,17 @@ def _gate_skip_reason(team: Team) -> str | None:
def _capture_generated(
team: Team, *, result: SuggestionRunResult, tier: int | None, model: str | None, triggered_by: str
) -> None:
- try:
- posthoganalytics.capture(
- event="$scout_suggestions_generated",
- distinct_id=str(team.uuid),
- properties={
- "team_id": team.id,
- "status": result.status,
- "skip_reason": result.skip_reason,
- "suggestion_count": result.suggestion_count,
- "runtime_s": round(result.runtime_s, 1),
- "task_run_id": result.task_run_id,
- "tier": tier,
- "model": model,
- "triggered_by": triggered_by,
- },
- groups=groups(team.organization, team),
- )
- except Exception:
- logger.warning("scout_suggestions: failed to capture generated event", team_id=team.id)
+ capture_suggestions_generated(
+ team,
+ status=result.status,
+ skip_reason=result.skip_reason,
+ suggestion_count=result.suggestion_count,
+ runtime_s=result.runtime_s,
+ task_run_id=result.task_run_id,
+ tier=tier,
+ model=model,
+ triggered_by=triggered_by,
+ )
async def arun_scout_suggestions(
diff --git a/products/signals/backend/scout_suggestions_api.py b/products/signals/backend/scout_suggestions_api.py
index b7d262926811..e06fc8293aed 100644
--- a/products/signals/backend/scout_suggestions_api.py
+++ b/products/signals/backend/scout_suggestions_api.py
@@ -95,7 +95,8 @@ class ScoutSuggestionSetSerializer(serializers.Serializer):
help_text=(
"`fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past "
"the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). "
- "`empty`: nothing to suggest yet."
+ "`empty`: nothing to suggest yet. `low_activity`: the project was too quiet to scan, so nothing "
+ "was generated."
),
)
generated_at = serializers.DateTimeField(
diff --git a/products/signals/backend/temporal/agentic/scout_suggestions.py b/products/signals/backend/temporal/agentic/scout_suggestions.py
index ffa69a9164fb..41660c45ec4f 100644
--- a/products/signals/backend/temporal/agentic/scout_suggestions.py
+++ b/products/signals/backend/temporal/agentic/scout_suggestions.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import json
import asyncio
-from dataclasses import asdict, dataclass
+from dataclasses import asdict, dataclass, field
from datetime import timedelta
from django.conf import settings as django_settings
@@ -36,6 +36,7 @@ from products.signals.backend.scout_harness.suggestions import (
parse_suggestion_settings,
plan_suggestion_runs,
read_suggestion_settings,
+ select_teams_to_scan,
stamp_requested,
)
@@ -48,6 +49,9 @@ SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES = 30
SUGGESTIONS_ACTIVITY_QUEUE_WAIT = timedelta(minutes=SUGGESTIONS_COORDINATOR_INTERVAL_MINUTES)
SUGGESTIONS_COORDINATOR_WORKFLOW_NAME = "run-signals-scout-suggestions-coordinator"
SUGGESTIONS_COORDINATOR_SCHEDULE_ID = "signals-scout-suggestions-coordinator-schedule"
+# How far past the per-tick cap the planner selects, so a tick still fills when the activity
+# check drops several of the picked candidates.
+SUGGESTIONS_OVERSELECT_FACTOR = 2
@dataclass(frozen=True)
@@ -67,6 +71,10 @@ class PlanSuggestionsOutput:
# The settings snapshot the plan was made under, passed to every child so one tick uses one
# max-runtime / model posture even if the flag changes mid-fan-out.
settings_json: str
+ # Candidates the activity check stamped `low_activity`. Nothing is dispatched for them, but
+ # they are stamped with the run so the planner leaves them alone for a refresh window.
+ # Defaulted so a plan serialized before the check existed still deserializes across a deploy.
+ skipped_team_ids: list[int] = field(default_factory=list)
@dataclass(frozen=True)
@@ -84,6 +92,7 @@ class SuggestionsCoordinatorOutput:
planned_count: int
started_count: int
skipped_count: int
+ low_activity_count: int = 0
@dataclass(frozen=True)
@@ -124,15 +133,31 @@ def _settings_from_json(raw: str | None) -> SuggestionSettings:
@activity.defn
async def plan_scout_suggestion_runs_activity(_input: PlanSuggestionsInput) -> PlanSuggestionsOutput:
- """Select the teams to refresh this tick, best first, capped by the flag payload."""
+ """Select the teams to refresh this tick, best first, capped by the flag payload.
+
+ The plan is overselected and then filtered by the dispatch-time activity check, which is one
+ bounded ClickHouse read per picked candidate.
+ """
async with Heartbeater():
# Flag read off the DB thread pool, like the scout coordinator: the SDK call can block on
# a cold cache and the DB pool is sized for DB-bound work.
settings = await asyncio.to_thread(read_suggestion_settings)
- planned = await database_sync_to_async(plan_suggestion_runs, thread_sensitive=False)(settings)
- logger.info("scout_suggestions coordinator: planned", count=len(planned), enabled=settings.enabled)
+ cap = settings.max_children_per_tick
+ planned = await database_sync_to_async(plan_suggestion_runs, thread_sensitive=False)(
+ settings, limit=cap * SUGGESTIONS_OVERSELECT_FACTOR
+ )
+ selection = await database_sync_to_async(select_teams_to_scan, thread_sensitive=False)(
+ planned, settings, limit=cap
+ )
+ logger.info(
+ "scout_suggestions coordinator: planned",
+ count=len(selection.dispatch),
+ low_activity=len(selection.skipped_team_ids),
+ enabled=settings.enabled,
+ )
return PlanSuggestionsOutput(
- planned=[PlannedSuggestion(team_id=run.team_id, tier=run.tier) for run in planned],
+ planned=[PlannedSuggestion(team_id=run.team_id, tier=run.tier) for run in selection.dispatch],
+ skipped_team_ids=list(selection.skipped_team_ids),
settings_json=_settings_to_json(settings),
)
@@ -243,10 +268,12 @@ class ScoutSuggestionsCoordinatorWorkflow:
plan = await workflow.execute_activity(
plan_scout_suggestion_runs_activity,
PlanSuggestionsInput(),
- start_to_close_timeout=timedelta(minutes=2),
+ # The activity check reads ClickHouse once per picked candidate, so this runs longer
+ # than a pure Postgres plan did.
+ start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
- if not plan.planned:
+ if not plan.planned and not plan.skipped_team_ids:
return SuggestionsCoordinatorOutput(0, 0, 0)
# `workflow_id` is per tick (the schedule appends the scheduled time) and stable across a
@@ -254,7 +281,9 @@ class ScoutSuggestionsCoordinatorWorkflow:
tick_id = workflow.info().workflow_id
started = 0
skipped = 0
- dispatched: list[int] = []
+ # A skipped project is stamped too: it was reached this tick, and without the stamp the
+ # planner would re-pick it on the very next one and pay for the read again.
+ dispatched: list[int] = list(plan.skipped_team_ids)
for idx, planned in enumerate(plan.planned):
child_id = f"scout-suggestions-run-{planned.team_id}-{tick_id}-{idx}"
try:
@@ -279,7 +308,10 @@ class ScoutSuggestionsCoordinatorWorkflow:
retry_policy=RetryPolicy(maximum_attempts=5),
)
return SuggestionsCoordinatorOutput(
- planned_count=len(plan.planned), started_count=started, skipped_count=skipped
+ planned_count=len(plan.planned),
+ started_count=started,
+ skipped_count=skipped,
+ low_activity_count=len(plan.skipped_team_ids),
)
diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.py
index b602b1c1e683..0c9b09b773ea 100644
--- a/products/signals/backend/test/test_scout_suggestions.py
+++ b/products/signals/backend/test/test_scout_suggestions.py
@@ -3,7 +3,7 @@ import asyncio
from datetime import timedelta
import pytest
-from posthog.test.base import APIBaseTest, BaseTest
+from posthog.test.base import APIBaseTest, BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest.mock import AsyncMock, MagicMock, patch
from django.db import DatabaseError
@@ -16,7 +16,10 @@ from parameterized import parameterized
from rest_framework import status
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.clickhouse.query_tagging import Feature, Product, QueryTags, get_query_tags
+from posthog.clickhouse.workload import Workload
from posthog.constants import AvailableFeature
+from posthog.errors import InternalCHQueryError
from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.integration import Integration
from posthog.models.scoping import team_scope
@@ -26,16 +29,22 @@ from products.access_control.backend.models.access_control import AccessControl
from products.signals.backend.models import SignalScoutConfig, SignalScoutSuggestionSet, SignalSourceConfig
from products.signals.backend.scout_harness.suggestions import (
MAX_DESCRIPTION_CHARS,
+ PlannedSuggestionRun,
ScoutSuggestionBatch,
ScoutSuggestionItem,
SuggestionSettings,
+ TeamActivity,
dismiss_suggestion,
mark_generation_failed,
mark_suggestion_created,
parse_suggestion_settings,
persist_suggestion_batch,
plan_suggestion_runs,
+ read_team_activity,
reserved_scout_names,
+ select_teams_to_scan,
+ stamp_requested,
+ team_is_active_enough,
visible_items,
)
from products.signals.backend.scout_harness.suggestions_runner import arun_scout_suggestions, validate_suggestion_items
@@ -82,6 +91,22 @@ class TestSuggestionSettings(SimpleTestCase):
(settings.enabled, settings.eligibility_tier, settings.max_children_per_tick), (enabled, tier, cap)
)
+ @parameterized.expand(
+ [
+ ("defaults", None, 14, 100, 3),
+ ("overridden", {"activity_window_days": 7, "min_events_in_window": 50}, 7, 50, 3),
+ ("checks_off", {"min_events_in_window": 0, "min_active_days_in_window": 0}, 14, 0, 0),
+ ("clamped", {"activity_window_days": 900, "min_active_days_in_window": -1}, 90, 100, 0),
+ ]
+ )
+ def test_activity_knobs(self, _name, extra, window_days, min_events, min_days):
+ payload = None if extra is None else {"enabled": True, **extra}
+ settings = parse_suggestion_settings(payload)
+ self.assertEqual(
+ (settings.activity_window_days, settings.min_events_in_window, settings.min_active_days_in_window),
+ (window_days, min_events, min_days),
+ )
+
def test_allowlist_ignores_non_int_entries(self):
settings = parse_suggestion_settings({"enabled": True, "team_allowlist": [2, "3", True, 4]})
self.assertEqual(settings.team_allowlist, frozenset({2, 4}))
@@ -309,6 +334,41 @@ 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], [(self.team.id, 1), (registered.id, 2)])
+ def test_a_low_activity_row_is_re_checked_after_the_refresh_window(self):
+ self._enable_scout(self.team, engaged=True)
+ settings = SuggestionSettings(enabled=True, refresh_days=7, stale_refresh_days=1)
+ row = SignalScoutSuggestionSet.all_teams.create(
+ team=self.team,
+ status=SignalScoutSuggestionSet.Status.LOW_ACTIVITY,
+ last_requested_at=self.now - timedelta(days=3),
+ )
+
+ # The shorter stale window is for a batch the fleet moved past, not for a quiet project.
+ self.assertEqual(plan_suggestion_runs(settings, self.now), [])
+
+ SignalScoutSuggestionSet.all_teams.filter(pk=row.pk).update(last_requested_at=self.now - timedelta(days=8))
+ self.assertEqual([run.team_id for run in plan_suggestion_runs(settings, self.now)], [self.team.id])
+
+ # A breaker tripped before the project went quiet must not delay the activity check:
+ # no scan runs while the stamp holds, so nothing would clear the count.
+ SignalScoutSuggestionSet.all_teams.filter(pk=row.pk).update(
+ consecutive_failures=5, last_completed_at=self.now - timedelta(days=8)
+ )
+ self.assertEqual([run.team_id for run in plan_suggestion_runs(settings, self.now)], [self.team.id])
+ long_cooldown = SuggestionSettings(
+ enabled=True, refresh_days=7, stale_refresh_days=1, failure_cooldown_hours=240
+ )
+ self.assertEqual([run.team_id for run in plan_suggestion_runs(long_cooldown, self.now)], [self.team.id])
+
+ def test_the_limit_overrides_the_per_tick_cap(self):
+ self._enable_scout(self.team, engaged=True)
+ second = self._team("second")
+ self._enable_scout(second, engaged=True)
+ settings = SuggestionSettings(enabled=True, max_children_per_tick=1)
+
+ self.assertEqual(len(plan_suggestion_runs(settings, self.now)), 1)
+ self.assertEqual(len(plan_suggestion_runs(settings, self.now, limit=2)), 2)
+
def test_cap_allowlist_blocklist_and_breaker(self):
self._enable_scout(self.team, engaged=True)
second = self._team("second")
@@ -467,6 +527,199 @@ class TestPlanSuggestionRuns(BaseTest):
self.assertEqual([run.team_id for run in planned], [project.id])
+class TestTeamIsActiveEnough(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("over_both_lines", 500, 7, False, 100, 3, True),
+ ("too_few_events", 40, 7, False, 100, 3, False),
+ ("too_few_active_days", 500, 2, False, 100, 3, False),
+ ("exactly_on_both_lines", 100, 3, False, 100, 3, True),
+ ("capped_read_is_active", 0, 0, True, 100, 3, True),
+ ("volume_check_disabled", 40, 7, False, 0, 3, True),
+ ("spread_check_disabled", 500, 1, False, 100, 0, True),
+ ]
+ )
+ def test_thresholds(self, _name, events, days, capped, min_events, min_days, expected):
+ activity = TeamActivity(event_count=events, active_days=days, capped=capped)
+ settings = SuggestionSettings(min_events_in_window=min_events, min_active_days_in_window=min_days)
+ self.assertEqual(team_is_active_enough(activity, settings), expected)
+
+
+class TestSelectTeamsToScan(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.quiet = self._team("quiet-project")
+ self.busy = self._team("busy-project")
+ self.suggestion_settings = SuggestionSettings(enabled=True)
+
+ def _team(self, name: str) -> Team:
+ organization = Organization.objects.create(name=name, is_ai_data_processing_approved=True)
+ return Team.objects.create(organization=organization, name=name, ingested_event=True)
+
+ def _planned(self, *teams: Team) -> list[PlannedSuggestionRun]:
+ return [PlannedSuggestionRun(team_id=team.id, tier=1) for team in teams]
+
+ def _select(self, planned, *, settings=None, limit=10, reads=None):
+ by_team = reads or {
+ self.quiet.id: TeamActivity(event_count=12, active_days=1, capped=False),
+ self.busy.id: TeamActivity(event_count=9000, active_days=12, capped=False),
+ }
+ with patch(
+ "products.signals.backend.scout_harness.suggestions.read_team_activity",
+ side_effect=lambda team_id, **_: by_team[team_id],
+ ):
+ return select_teams_to_scan(planned, settings or self.suggestion_settings, limit=limit)
+
+ def _skip_event_uuids(self, planned) -> list[str | None]:
+ with patch("posthoganalytics.capture") as capture:
+ self._select(planned)
+ return [call.kwargs.get("uuid") for call in capture.call_args_list]
+
+ def _status(self, team: Team) -> str | None:
+ row = SignalScoutSuggestionSet.all_teams.filter(team_id=team.id).first()
+ return row.status if row else None
+
+ def test_quiet_project_is_stamped_and_not_dispatched(self):
+ selection = self._select(self._planned(self.quiet, self.busy))
+
+ self.assertEqual([run.team_id for run in selection.dispatch], [self.busy.id])
+ self.assertEqual(selection.skipped_team_ids, (self.quiet.id,))
+ self.assertEqual(self._status(self.quiet), SignalScoutSuggestionSet.Status.LOW_ACTIVITY)
+ self.assertIsNone(self._status(self.busy))
+
+ def test_a_low_activity_stamp_keeps_the_prior_batch_and_the_breaker(self):
+ SignalScoutSuggestionSet.all_teams.create(
+ team=self.quiet,
+ items=[{"id": "1", "kind": "canonical", "skill_name": "signals-scout-general"}],
+ consecutive_failures=2,
+ )
+
+ self._select(self._planned(self.quiet))
+
+ row = SignalScoutSuggestionSet.all_teams.get(team_id=self.quiet.id)
+ self.assertEqual(row.status, SignalScoutSuggestionSet.Status.LOW_ACTIVITY)
+ self.assertEqual(len(row.items), 1)
+ self.assertEqual(row.consecutive_failures, 2)
+
+ def test_allowlisted_quiet_project_is_still_scanned(self):
+ settings = SuggestionSettings(enabled=True, team_allowlist=frozenset({self.quiet.id}))
+
+ selection = self._select(self._planned(self.quiet), settings=settings)
+
+ self.assertEqual([run.team_id for run in selection.dispatch], [self.quiet.id])
+ self.assertIsNone(self._status(self.quiet))
+
+ def test_both_checks_off_dispatches_without_reading(self):
+ settings = SuggestionSettings(enabled=True, min_events_in_window=0, min_active_days_in_window=0)
+
+ with patch(
+ "products.signals.backend.scout_harness.suggestions.read_team_activity",
+ side_effect=AssertionError("the check must not read when both knobs are off"),
+ ):
+ selection = select_teams_to_scan(self._planned(self.quiet, self.busy), settings, limit=10)
+
+ self.assertEqual([run.team_id for run in selection.dispatch], [self.quiet.id, self.busy.id])
+
+ def test_a_failed_read_dispatches_rather_than_costing_the_refresh_window(self):
+ with patch(
+ "products.signals.backend.scout_harness.suggestions.read_team_activity",
+ side_effect=Exception("clickhouse is down"),
+ ):
+ selection = select_teams_to_scan(self._planned(self.quiet), self.suggestion_settings, limit=10)
+
+ self.assertEqual([run.team_id for run in selection.dispatch], [self.quiet.id])
+ self.assertEqual(selection.skipped_team_ids, ())
+
+ def test_a_replanned_tick_reports_the_skip_once(self):
+ first = self._skip_event_uuids(self._planned(self.quiet))
+ retried = self._skip_event_uuids(self._planned(self.quiet))
+ stamp_requested([self.quiet.id])
+ next_tick = self._skip_event_uuids(self._planned(self.quiet))
+
+ self.assertEqual(first, retried)
+ self.assertNotEqual(first, next_tick)
+ self.assertNotIn(None, first)
+
+ def test_overselected_candidates_past_the_limit_are_left_untouched(self):
+ second_busy = self._team("second-busy")
+ reads = {
+ self.busy.id: TeamActivity(event_count=9000, active_days=12, capped=False),
+ self.quiet.id: TeamActivity(event_count=12, active_days=1, capped=False),
+ second_busy.id: TeamActivity(event_count=9000, active_days=12, capped=False),
+ }
+
+ selection = self._select(self._planned(self.busy, self.quiet, second_busy), limit=1, reads=reads)
+
+ self.assertEqual([run.team_id for run in selection.dispatch], [self.busy.id])
+ self.assertEqual(selection.skipped_team_ids, ())
+ self.assertIsNone(self._status(self.quiet))
+
+
+class TestReadTeamActivity(ClickhouseTestMixin, BaseTest):
+ def test_counts_the_project_and_its_environments_inside_the_window(self):
+ environment = Team.objects.create(organization=self.organization, name="environment", parent_team=self.team)
+ other = Team.objects.create(organization=self.organization, name="other")
+ now = timezone.now()
+ for team, timestamp in (
+ (self.team, now - timedelta(days=1)),
+ (self.team, now - timedelta(days=1)),
+ (environment, now - timedelta(days=3)),
+ (self.team, now - timedelta(days=20)),
+ (other, now - timedelta(days=1)),
+ ):
+ _create_event(team=team, event="$pageview", distinct_id="a", timestamp=timestamp)
+ flush_persons_and_events()
+
+ activity = read_team_activity(self.team.id, window_days=14)
+
+ self.assertEqual((activity.event_count, activity.active_days, activity.capped), (3, 2, False))
+
+ def test_an_empty_project_reads_as_no_activity(self):
+ activity = read_team_activity(self.team.id, window_days=14)
+
+ self.assertEqual((activity.event_count, activity.active_days, activity.capped), (0, 0, False))
+
+ def test_the_read_is_bounded_and_kept_off_the_interactive_cluster(self):
+ with patch("products.signals.backend.scout_harness.suggestions.sync_execute", return_value=[(0, 0)]) as execute:
+ read_team_activity(self.team.id, window_days=14)
+
+ kwargs = execute.call_args.kwargs
+ self.assertEqual(kwargs["workload"], Workload.OFFLINE)
+ self.assertGreater(kwargs["settings"]["max_execution_time"], 0)
+ self.assertEqual(kwargs["settings"]["timeout_overflow_mode"], "throw")
+
+ def test_the_read_is_attributed_to_the_product(self):
+ seen: list[QueryTags] = []
+
+ def _record(*_args, **_kwargs):
+ seen.append(get_query_tags())
+ return [(0, 0)]
+
+ with patch("products.signals.backend.scout_harness.suggestions.sync_execute", side_effect=_record):
+ read_team_activity(self.team.id, window_days=14)
+
+ self.assertEqual((seen[0].product, seen[0].feature), (Product.SIGNALS, Feature.DATA_FRESHNESS))
+
+ @parameterized.expand([("too_many_rows", 158), ("too_many_rows_or_bytes", 396)])
+ def test_a_read_that_hits_the_row_cap_reads_as_capped(self, _name, code):
+ with patch(
+ "products.signals.backend.scout_harness.suggestions.sync_execute",
+ side_effect=InternalCHQueryError("limit for rows exceeded", code=code),
+ ):
+ activity = read_team_activity(self.team.id, window_days=14)
+
+ self.assertTrue(activity.capped)
+ self.assertTrue(team_is_active_enough(activity, SuggestionSettings()))
+
+ def test_any_other_read_failure_is_raised_rather_than_read_as_quiet(self):
+ with patch(
+ "products.signals.backend.scout_harness.suggestions.sync_execute",
+ side_effect=InternalCHQueryError("memory limit exceeded", code=241),
+ ):
+ with self.assertRaises(InternalCHQueryError):
+ read_team_activity(self.team.id, window_days=14)
+
+
class TestManualSuggestionsDispatch(BaseTest):
def test_manual_dispatch_stamps_planner_state(self):
from products.signals.backend.temporal.agentic.scout_suggestions import start_manual_scout_suggestions_run
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index e1479209f336..e2eabe506828 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -5698,6 +5698,7 @@ export interface ForgetResponseApi {
* * `stale` - Stale
* * `failed` - Failed
* * `empty` - Empty
+ * * `low_activity` - Low activity
*/
export type SignalScoutSuggestionSetStatusEnumApi =
(typeof SignalScoutSuggestionSetStatusEnumApi)[keyof typeof SignalScoutSuggestionSetStatusEnumApi]
@@ -5707,6 +5708,7 @@ export const SignalScoutSuggestionSetStatusEnumApi = {
Stale: 'stale',
Failed: 'failed',
Empty: 'empty',
+ LowActivity: 'low_activity',
} as const
export interface ScoutSuggestionProposedConfigApi {
@@ -5768,12 +5770,13 @@ export interface ScoutSuggestionItemApi {
}
export interface ScoutSuggestionSetApi {
- /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet.
+ /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet. `low_activity`: the project was too quiet to scan, so nothing was generated.
*
* * `fresh` - Fresh
* * `stale` - Stale
* * `failed` - Failed
- * * `empty` - Empty */
+ * * `empty` - Empty
+ * * `low_activity` - Low activity */
status: SignalScoutSuggestionSetStatusEnumApi
/**
* When the current batch was generated; null before the first run.
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
index 2d5dd8678b5a..477c2a50bc8f 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.stories.tsx
@@ -146,6 +146,16 @@ export const LastScanFailed: Story = {
],
}
+// A project too quiet for a scheduled scan keeps its prior picks, so the footer is what says the
+// scan was skipped rather than run.
+export const LowActivity: Story = {
+ decorators: [
+ mswDecorator({
+ get: { [SUGGESTIONS_URL]: () => [200, mockScoutSuggestionSet({ status: 'low_activity' })] },
+ }),
+ ],
+}
+
// Every pick acted on or dismissed. No strip at all: an empty box helps nobody, and the scene
// header's "Suggest a scout" button is what asks for a new batch.
export const NothingLeft: Story = {
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
index 25bb2b83db7d..96535b467d25 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSuggestionsStrip.tsx
@@ -126,6 +126,12 @@ function StripBody(): JSX.Element {
{batchStatus === 'failed' && (
<span>The last scan didn't finish, so these are the picks from before it.</span>
)}
+ {batchStatus === 'low_activity' && (
+ <span>
+ This project has been quiet, so the last scan was skipped and these are the picks from before
+ it.
+ </span>
+ )}
<span>
Want something else? <SuggestWithAiLink />.
</span>
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 116ee7203552..5fba69901701 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -87340,6 +87340,7 @@ export namespace Schemas {
* * `stale` - Stale
* * `failed` - Failed
* * `empty` - Empty
+ * * `low_activity` - Low activity
*/
export type SignalScoutSuggestionSetStatusEnum = typeof SignalScoutSuggestionSetStatusEnum[keyof typeof SignalScoutSuggestionSetStatusEnum];
@@ -87349,15 +87350,17 @@ export namespace Schemas {
Stale: 'stale',
Failed: 'failed',
Empty: 'empty',
+ LowActivity: 'low_activity',
} as const;
export interface ScoutSuggestionSet {
- /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet.
+ /** `fresh`: current batch. `stale`: the fleet changed since it was generated, or the batch aged past the refresh window. `failed`: the last refresh failed (items are the prior batch, if any). `empty`: nothing to suggest yet. `low_activity`: the project was too quiet to scan, so nothing was generated.
*
* * `fresh` - Fresh
* * `stale` - Stale
* * `failed` - Failed
- * * `empty` - Empty */
+ * * `empty` - Empty
+ * * `low_activity` - Low activity */
status: SignalScoutSuggestionSetStatusEnum;
/**
* When the current batch was generated; null before the first run.