: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): keep background scouts out of autostart and set-up checks (#109017)
posthog[bot]dc875ffd4e4b
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex 4e9a912d1195..6f8ec43a34e4 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -60,7 +60,7 @@ from products.signals.backend.report_generation.resolve_reviewers import ()from products.signals.backend.report_generation.select_repo import RepoSelectionResultfrom products.signals.backend.report_steering import NO_STEERING, ReportSteering, load_report_steering-from products.signals.backend.scout_authorship import resolve_touching_scout_skills+from products.signals.backend.scout_authorship import report_is_from_background_scout, resolve_touching_scout_skillsfrom products.signals.backend.scout_harness.skill_loader import resolve_skill_owner_user_uuidsfrom products.signals.backend.signal_metadata import (SignalSourceReference,@@ -1655,7 +1655,18 @@ async def maybe_autostart_from_report_artefacts(When the latest reviewers artefact was user-edited, the task runs as that editing user (not anamed colleague) — see `_latest_reviewers_content` and `triggering_user_id`.++ A report that a background-enrolled scout authored never auto-starts. Nobody on the project+ asked for that scout, so its findings must not open pull requests on their own."""+ if await database_sync_to_async(report_is_from_background_scout)(team_id, report_id):+ logger.info(+ "signals auto-start re-eval skipped",+ report_id=report_id,+ team_id=team_id,+ reason="report from background scout",+ )+ return AutostartOutcome(status="blocked", reason="Reports from background scouts do not auto-start")if dispatch is None:from products.signals.backend.implementation_dispatch import (ImplementationDispatcher, # noqa: PLC0415 - breaks the dispatcher/autostart cyclediff --git a/products/signals/backend/background_pilot.py b/products/signals/backend/background_pilot.pynew file mode 100644index 000000000000..e724ac49fe0c--- /dev/null+++ b/products/signals/backend/background_pilot.py@@ -0,0 +1,81 @@+"""Pilot telemetry for scouts that the background coordinator enrolls.++A background config (`managed_by=background`) runs for a project that did not set the scout+up, so each reaction to its output is pilot evidence. These events fire only for background+configs and their reports. The run events (`signals_scout_run_started` / `_finished`) carry+`managed_by` for run failure, and `$ai_generation` joins to them on `task_run_id` for cost.+"""++from __future__ import annotations++from typing import Any++import structlog+import posthoganalytics++from posthog.event_usage import groups+from posthog.models.team.team import Team+from posthog.models.user import User++from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_authorship import resolve_background_authoring_runs++logger = structlog.get_logger(__name__)++BACKGROUND_REPORT_VIEWED_EVENT = "signals_background_report_viewed"+BACKGROUND_REPORT_RATED_EVENT = "signals_background_report_rated"+BACKGROUND_REPORT_DISMISSED_EVENT = "signals_background_report_dismissed"+BACKGROUND_SCOUT_OPTED_OUT_EVENT = "signals_background_scout_opted_out"++OPT_OUT_DISABLED = "disabled"+OPT_OUT_DELETED = "deleted"+++def _capture(*, event: str, team: Team, user: User | None, properties: dict[str, Any]) -> None:+ try:+ posthoganalytics.capture(+ event=event,+ distinct_id=user.distinct_id if user is not None and user.distinct_id else str(team.uuid),+ properties={"team_id": team.id, **properties},+ groups=groups(team.organization, team),+ )+ except Exception:+ logger.warning("signals_background_pilot: failed to capture event", event=event, team_id=team.id)+++def capture_background_report_events(+ *, team: Team, user: User | None, event: str, report_ids: list[str], properties: dict[str, Any] | None = None+) -> None:+ """Capture `event` once for each report in `report_ids` that a background scout authored.++ Best-effort: a failed lookup or capture never fails the request that called it.+ """+ try:+ runs = resolve_background_authoring_runs(team.id, report_ids)+ except Exception:+ logger.warning("signals_background_pilot: failed to resolve report origin", event=event, team_id=team.id)+ return+ for report_id, run in runs.items():+ _capture(+ event=event,+ team=team,+ user=user,+ properties={+ "report_id": report_id,+ "scout_config_id": str(run.scout_config_id) if run.scout_config_id else None,+ "skill_name": run.skill_name,+ **(properties or {}),+ },+ )+++def capture_background_scout_opted_out(*, config: SignalScoutConfig, user: User | None, action: str) -> None:+ """Capture that a person switched off or deleted a background config. Call it before the write."""+ if config.managed_by != SignalScoutConfig.ManagedBy.BACKGROUND:+ return+ _capture(+ event=BACKGROUND_SCOUT_OPTED_OUT_EVENT,+ team=config.team,+ user=user,+ properties={"scout_config_id": str(config.id), "skill_name": config.skill_name, "action": action},+ )diff --git a/products/signals/backend/scout_authorship.py b/products/signals/backend/scout_authorship.pyindex 2ed055c5ebd7..fb88c2572605 100644--- a/products/signals/backend/scout_authorship.py+++ b/products/signals/backend/scout_authorship.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom django.db.models import Q-from products.signals.backend.models import SignalScoutRun+from products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.skills.backend.models.skills import LLMSkill@@ -100,3 +100,31 @@ def resolve_authoring_skill_names(team_id: int, report_ids: list[str]) -> dict[selse set())return {report_id: (skill_name if skill_name in live else "") for report_id, skill_name in resolved.items()}+++BACKGROUND_RUN_METADATA = {"managed_by": SignalScoutConfig.ManagedBy.BACKGROUND}+++def resolve_background_authoring_runs(team_id: int, report_ids: list[str]) -> dict[str, SignalScoutRun]:+ """Map each report a background-enrolled scout run authored to that run.++ Only authorship counts: a background scout that edited a user scout's report does not make the+ report a background one. The origin is the one stamped on the run at dispatch, so a person who+ later takes over, switches off, or deletes the config does not clear it.+ """+ if not report_ids:+ return {}+ authored = Q()+ for report_id in report_ids:+ authored |= Q(emitted_report_ids__contains=[report_id])+ runs = SignalScoutRun.objects.for_team(team_id).filter(authored, metadata__contains=BACKGROUND_RUN_METADATA)+ wanted = set(report_ids)+ resolved: dict[str, SignalScoutRun] = {}+ for run in runs:+ for report_id in wanted.intersection(run.emitted_report_ids or []):+ resolved[report_id] = run+ return resolved+++def report_is_from_background_scout(team_id: int, report_id: str) -> bool:+ return report_id in resolve_background_authoring_runs(team_id, [report_id])diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 55f7636fa7d0..ac6ab0e00bae 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -1097,6 +1097,10 @@ def _create_run_row(# Both inputs can change between runs, so like `github_guidance` this is stamped rather than# re-derived at read time, letting an eval or A/B compare only runs that got the same prompt.metadata["business_knowledge_maintained"] = business_knowledge_maintained+ # Stamped only for background-managed scouts, because a person who edits the config takes it over+ # and deleting it nulls `scout_config`. Reports this run authors keep their background origin.+ if config.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND:+ metadata["managed_by"] = config.managed_by# 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.@@ -1499,6 +1503,7 @@ def _attach_run_shape_props(properties["skill_origin"] = skill.originproperties["github_guidance"] = github_guidanceproperties["business_knowledge_maintained"] = business_knowledge_maintained+ properties["managed_by"] = config.managed_byif config.network_access == SignalScoutConfig.NetworkAccess.FULL:properties["network_access"] = config.network_accessif granted_write_scopes := _granted_write_scopes(config):diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 0f1a137d2321..d0bba0f5f698 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -29,6 +29,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import groupsfrom posthog.models.integration import Integrationfrom posthog.models.team.team import Team+from posthog.models.user import Userfrom posthog.permissions import get_authenticator_scopesfrom posthog.slack.formatting import channel_id_from_targetfrom posthog.temporal.oauth import SCOUT_GRANTABLE_WRITE_SCOPES@@ -39,6 +40,7 @@ from products.signals.backend.artefact_schemas import (ActionabilityChoice,Priority,)+from products.signals.backend.background_pilot import OPT_OUT_DISABLED, capture_background_scout_opted_outfrom products.signals.backend.enums import ReportLinkKindfrom products.signals.backend.models import SignalReportCheck, SignalScoutConfig, SignalScoutEmissionfrom products.signals.backend.report_charts import MAX_REPORT_CHARTS@@ -3766,6 +3768,12 @@ class SignalScoutConfigUpdateSerializer(_ScoutConfigCapabilityFieldsMixin, seria# A person who edits a background-managed scout takes it over, so the background coordinator# must not change or remove it after this. An empty write is not an edit.if validated_data and instance.managed_by == SignalScoutConfig.ManagedBy.BACKGROUND:+ if validated_data.get("enabled") is False and instance.enabled:+ request = self.context.get("request")+ user = getattr(request, "user", None)+ capture_background_scout_opted_out(+ config=instance, user=user if isinstance(user, User) else None, action=OPT_OUT_DISABLED+ )validated_data["managed_by"] = SignalScoutConfig.ManagedBy.TEAMif "enabled" in validated_data and validated_data["enabled"] != instance.enabled:target = (diff --git a/products/signals/backend/scout_harness/suggestions.py b/products/signals/backend/scout_harness/suggestions.pyindex eeddb9159903..5b3e5df00233 100644--- a/products/signals/backend/scout_harness/suggestions.py+++ b/products/signals/backend/scout_harness/suggestions.py@@ -344,11 +344,17 @@ def _candidate_teams_by_tier(settings: SuggestionSettings, now: datetime) -> tup)# Source configs are environment-scoped, so a project whose Signals setup lives in a child# environment counts through that child's parent; scout configs already canonicalize.+ # A background-managed scout is not set up: nobody on the project turned it on.source_teams = SignalSourceConfig.objects.filter(enabled=True).values("team_id")+ user_scout_teams = (+ SignalScoutConfig.all_teams.filter(enabled=True)+ .exclude(managed_by=SignalScoutConfig.ManagedBy.BACKGROUND)+ .values("team_id")+ )set_up = (Q(id__in=source_teams)| Q(id__in=Team.objects.filter(id__in=source_teams, parent_team_id__isnull=False).values("parent_team_id"))- | Q(id__in=SignalScoutConfig.all_teams.filter(enabled=True).values("team_id"))+ | Q(id__in=user_scout_teams))tiers: dict[int, int] = {}diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 88358fd4a609..eef65a035faa 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -62,6 +62,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControl+from products.signals.backend.background_pilot import OPT_OUT_DELETED, capture_background_scout_opted_outfrom products.signals.backend.models import (SignalProjectProfile,SignalReport,@@ -3519,6 +3520,9 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"This scout watches the self-driving system itself, so it can't be deleted. ""Switch it off in its settings if you need it to stop running.")+ capture_background_scout_opted_out(+ config=config, user=request.user if isinstance(request.user, User) else None, action=OPT_OUT_DELETED+ )# Delete on the instance (not the queryset) so ModelActivityMixin's delete hook fires —# config changes drive spend and are activity-logged, removals included.config.delete()diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pyindex ddb23bf967d6..78fd803b3c45 100644--- a/products/signals/backend/scout_report/persistence.py+++ b/products/signals/backend/scout_report/persistence.py@@ -338,6 +338,10 @@ def create_scout_report(source="scout",))+ # In-txn and before the signal emits below: the autostart gate reads authorship from this+ # tally, so a report must never commit without it, and a failed Kafka emit must not skip it.+ if run is not None:+ _record_report_emit(team_id=team_id, run_id=run.id, report_id=report_id)except IntegrityError:# A concurrent emit of the same emission won the race, so this transaction rolled back. Hand# its report back: the loser is a retry, and it wants the twin it just avoided creating.@@ -367,9 +371,6 @@ def create_scout_report(team_id=team_id, report_id=report_id, signal=signal, document_id=document_id, skill_name=skill_name)- if run is not None:- _record_report_emit(team_id=team_id, run_id=run.id, report_id=report_id)-logger.info("signals_scout.emit_report: created",extra={"team_id": team_id, "report_id": report_id, "signal_count": len(signals)},@@ -1384,22 +1385,16 @@ def _signal_metadata(*, report_id: str, source_id: str, weight: float, extra: didef _record_report_emit(*, team_id: int, run_id: uuid.UUID, report_id: str) -> None:"""Append `report_id` to the run's `emitted_report_ids` tally so "which reports did this run- author?" is a column lookup. Best-effort and observability only (mirrors `emit._record_emit`):- the report has already been created by the time this runs, so any failure here is swallowed rather- than surfaced as a false emit failure. Runs under `select_for_update` so the read-modify-write on- the JSON list is safe, and scopes the lookup to `team_id` via the fail-closed manager so the tally- write can never touch a foreign team's run even if the caller's ownership guard regresses."""- try:- with transaction.atomic():- run = SignalScoutRun.objects.for_team(team_id).select_for_update().filter(pk=run_id).first()- if run is None:- logger.warning("signals_scout.emit_report: run %s gone, skipping report tally", run_id)- return- report_ids = [*(run.emitted_report_ids or []), report_id]- run.emitted_report_ids = report_ids- run.save(update_fields=["emitted_report_ids"])- except Exception:- logger.exception("signals_scout.emit_report: failed to record report emit for run %s", run_id)+ author?" is a column lookup. Unlike `emit._record_emit` this is not best-effort: the autostart+ gate reads the tally to hold back reports a background scout authored. So the caller runs it in+ the report's transaction, and any failure here (run row gone included) rolls the report back+ instead of leaving it without its authoring run. Runs under `select_for_update` so the+ read-modify-write on the JSON list is safe, and scopes the lookup to `team_id` via the fail-closed+ manager so the tally write can never touch a foreign team's run even if the caller's ownership+ guard regresses."""+ run = SignalScoutRun.objects.for_team(team_id).select_for_update().get(pk=run_id)+ run.emitted_report_ids = [*(run.emitted_report_ids or []), report_id]+ run.save(update_fields=["emitted_report_ids"])def record_report_edit(*, team_id: int, run_id: uuid.UUID, report_id: str) -> None:diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex a46e4d90e3f8..3046485ad8fe 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -1333,6 +1333,77 @@ async def test_repo_selection_eligibility_reaches_autostart(autostart_eligible):assert mock_autostart.call_args.kwargs["repository_autostart_eligible"] is autostart_eligible[email protected]_db(transaction=True)+ ("run_origin", "config_after", "expect_autostart"),+ [+ ("background", "background", False),+ ("background", "taken_over", False),+ ("background", "deleted", False),+ ("team", "team", True),+ ],+)+async def test_background_scout_reports_never_reach_autostart(run_origin, config_after, expect_autostart):+ def _setup() -> tuple[Team, SignalReport]:+ organization = Organization.objects.create(name="background-org")+ team = Team.objects.create(organization=organization, name="background-team")+ report = SignalReport.objects.create(+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0+ )+ for artefact_type, content in (+ (+ SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,+ {+ "explanation": "Clear fix in the affected module.",+ "actionability": ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,+ "already_addressed": False,+ },+ ),+ (+ SignalReportArtefact.ArtefactType.REPO_SELECTION,+ {"repository": "owner/repo", "reason": "Linked repository.", "autostart_eligible": True},+ ),+ (+ SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,+ {"explanation": "Affects many sessions.", "priority": Priority.P2.value},+ ),+ ):+ SignalReportArtefact.objects.create(+ team=team, report=report, type=artefact_type, content=json.dumps(content)+ )+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ scout_task = Task.objects.create(team=team, title="scout", description="d")+ with team_scope(team.id):+ config = SignalScoutConfig.objects.create(team=team, skill_name=SCOUT_SKILL, managed_by=run_origin)+ SignalScoutRun.objects.create(+ team=team,+ task_run=TaskRun.objects.create(team=team, task=scout_task),+ scout_config=config,+ skill_name=SCOUT_SKILL,+ skill_version=1,+ emitted_report_ids=[str(report.id)],+ metadata={"managed_by": run_origin} if run_origin == "background" else {},+ )+ if config_after == "taken_over":+ config.managed_by = SignalScoutConfig.ManagedBy.TEAM+ config.enabled = False+ config.save()+ elif config_after == "deleted":+ config.delete()+ return team, report++ team, report = await sync_to_async(_setup)()++ with patch("products.signals.backend.auto_start.maybe_autostart_implementation_task") as mock_autostart:+ outcome = await maybe_autostart_from_report_artefacts(team_id=team.id, report_id=str(report.id))++ assert mock_autostart.called is expect_autostart+ if not expect_autostart:+ assert outcome.status == "blocked"++@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize(diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.pyindex 9a51bcc29d54..178da7322919 100644--- a/products/signals/backend/test/test_scout_report_persistence.py+++ b/products/signals/backend/test/test_scout_report_persistence.py@@ -1,5 +1,5 @@import json-from contextlib import AbstractContextManager+from contextlib import AbstractContextManager, nullcontextfrom datetime import UTC, datetimeimport pytest@@ -7,6 +7,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.apps import apps+from django.db import DatabaseErrorfrom parameterized import parameterized@@ -207,6 +208,35 @@ class TestScoutReportPersistence(BaseTest):run.refresh_from_db()assert run.emitted_report_ids == [result.report_id]+ @parameterized.expand(+ [+ ("signal_delivery_fails", RuntimeError("kafka unavailable"), None, True),+ ("run_tally_write_fails", None, DatabaseError("connection reset"), False),+ ]+ )+ def test_a_committed_report_always_carries_its_authoring_run(+ self, _name, emit_error, save_error, expect_report+ ) -> None:+ run = self._make_run()+ self.emit_mock.side_effect = emit_error+ save_patch = patch.object(SignalScoutRun, "save", side_effect=save_error) if save_error else nullcontext()+ with save_patch, pytest.raises(type(emit_error or save_error)):+ create_scout_report(+ team_id=self.team.id,+ title="Checkout API p99 latency regressed",+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],+ attribution=ArtefactAttribution.from_task(str(run.task_run.task_id)),+ run=run,+ )++ report_ids = [+ str(report_id) for report_id in SignalReport.objects.filter(team=self.team).values_list("id", flat=True)+ ]+ assert bool(report_ids) is expect_report+ run.refresh_from_db()+ assert run.emitted_report_ids == report_ids+def test_create_with_reviewers_fires_linkability_telemetry(self) -> None:# Scout-authored reports persist reviewers here, not through the custom-agent path; without# this call the scout bucket silently disappears from the reviewer-linkability metric.diff --git a/products/signals/backend/test/test_scout_suggestions.py b/products/signals/backend/test/test_scout_suggestions.pyindex 0c9b09b773ea..f2150fcf518b 100644--- a/products/signals/backend/test/test_scout_suggestions.py+++ b/products/signals/backend/test/test_scout_suggestions.py@@ -312,6 +312,13 @@ class TestPlanSuggestionRuns(BaseTest):unapproved = self._team("unapproved", approved=False)self._enable_scout(unapproved, engaged=True)self._team("no-signals-setup")+ background_only = self._team("background-only")+ SignalScoutConfig.objects.create(+ team=background_only,+ skill_name="signals-scout-general",+ enabled=True,+ managed_by=SignalScoutConfig.ManagedBy.BACKGROUND,+ )SignalScoutSuggestionSet.all_teams.create(team=engaged_fresh, last_requested_at=self.now - timedelta(days=1))SignalScoutSuggestionSet.all_teams.create(team=engaged_overdue, last_requested_at=self.now - timedelta(days=30))diff --git a/products/signals/backend/test/test_signal_report_actions.py b/products/signals/backend/test/test_signal_report_actions.pyindex d51526525f3c..463d4ae6f04e 100644--- a/products/signals/backend/test/test_signal_report_actions.py+++ b/products/signals/backend/test/test_signal_report_actions.py@@ -1,6 +1,7 @@from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.apps import appsfrom django.utils import timezonefrom parameterized import parameterized@@ -9,7 +10,7 @@ from rest_framework import statusfrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_valuefrom posthog.models.utils import generate_random_token_personal-from products.signals.backend.models import SignalReport, SignalReportAction+from products.signals.backend.models import SignalReport, SignalReportAction, SignalScoutConfig, SignalScoutRunclass TestSignalReportViewedEndpoint(APIBaseTest):@@ -114,6 +115,72 @@ class TestSignalReportViewedEndpoint(APIBaseTest):assert response.status_code == expected_statusassert not SignalReportAction.objects.for_team(self.team.id).filter(report=report).exists()+ def _author_with_scout(self, report: SignalReport, managed_by: str) -> SignalScoutConfig:+ config = SignalScoutConfig.objects.create(+ team=self.team, skill_name="signals-scout-general", managed_by=managed_by+ )+ task = apps.get_model("tasks", "Task").objects.create(team=self.team, title="scout", description="d")+ task_run = apps.get_model("tasks", "TaskRun").objects.create(team=self.team, task=task)+ SignalScoutRun.objects.create(+ team=self.team,+ task_run=task_run,+ scout_config=config,+ skill_name=config.skill_name,+ skill_version=1,+ emitted_report_ids=[str(report.id)],+ metadata={"managed_by": managed_by} if managed_by == SignalScoutConfig.ManagedBy.BACKGROUND else {},+ )+ return config++ @parameterized.expand(+ [+ (f"{path}_{origin}", path, body, event, origin)+ for path, body, event in (+ ("viewed", None, "signals_background_report_viewed"),+ ("feedback", {"sentiment": "negative"}, "signals_background_report_rated"),+ ("state", {"state": "suppressed"}, "signals_background_report_dismissed"),+ )+ for origin in (SignalScoutConfig.ManagedBy.BACKGROUND, SignalScoutConfig.ManagedBy.TEAM)+ ]+ )+ @patch("products.signals.backend.background_pilot.posthoganalytics.capture")+ def test_background_pilot_events_fire_only_for_background_reports(+ self, _name, action_path: str, body: dict | None, event: str, origin: str, mock_capture: MagicMock+ ) -> None:+ report = self._create_report()+ config = self._author_with_scout(report, origin)++ response = self.client.post(+ f"/api/projects/{self.team.pk}/signals/reports/{report.pk}/{action_path}/", body, format="json"+ )++ assert response.status_code < 300+ captured = [call.kwargs for call in mock_capture.call_args_list if call.kwargs["event"] == event]+ if origin == SignalScoutConfig.ManagedBy.BACKGROUND:+ assert len(captured) == 1+ assert captured[0]["properties"]["report_id"] == str(report.id)+ assert captured[0]["properties"]["scout_config_id"] == str(config.id)+ else:+ assert captured == []++ @patch("products.signals.backend.background_pilot.posthoganalytics.capture")+ def test_repeat_dismissal_of_a_background_report_is_not_counted_again(self, mock_capture: MagicMock) -> None:+ report = self._create_report(status=SignalReport.Status.SUPPRESSED)+ self._author_with_scout(report, SignalScoutConfig.ManagedBy.BACKGROUND)++ response = self.client.post(+ f"/api/projects/{self.team.pk}/signals/reports/{report.pk}/state/",+ {"state": "suppressed", "dismissal_reason": "report_unclear"},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK+ assert not [+ call+ for call in mock_capture.call_args_list+ if call.kwargs["event"] == "signals_background_report_dismissed"+ ]+def test_a_suppressed_report_still_records_its_view(self) -> None:# The Dismissed tab renders the same detail view, so its opens must count too instead of# 404ing like mutating-by-ID actions on suppressed reports do.diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex a2fb7ca2565e..113469792d22 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -89,6 +89,12 @@ from products.signals.backend.artefact_schemas import (TitleChange,parse_artefact_content,)+from products.signals.backend.background_pilot import (+ BACKGROUND_REPORT_DISMISSED_EVENT,+ BACKGROUND_REPORT_RATED_EVENT,+ BACKGROUND_REPORT_VIEWED_EVENT,+ capture_background_report_events,+)from products.signals.backend.billing import (REFUND_INELIGIBLE_BILLING_EXEMPT,REFUND_INELIGIBLE_NO_BILLABLE_PR,@@ -2507,7 +2513,6 @@ class SignalReportViewSet(serializer = SignalReportStateRequestSerializer(data=request.data)serializer.is_valid(raise_exception=True)data = serializer.validated_data-outcome, detail = self._transition_report_state(report,target=data["state"],@@ -2533,6 +2538,11 @@ class SignalReportViewSet(dismissal_reason=data.get("dismissal_reason"),dismissal_note=data.get("dismissal_note"),)+ self._capture_background_dismissals(+ reports=[report] if getattr(report, "_newly_suppressed", False) else [],+ target=data["state"],+ dismissal_reason=data.get("dismissal_reason"),+ )return Response(SignalReportSerializer(report, context=self._enriched_report_context(report)).data)@@ -2654,6 +2664,14 @@ class SignalReportViewSet(metadata={"sentiment": data["sentiment"]},bump_count=not note,)+ if not note:+ capture_background_report_events(+ team=self.team,+ user=request.user,+ event=BACKGROUND_REPORT_RATED_EVENT,+ report_ids=[str(report.id)],+ properties={"sentiment": data["sentiment"]},+ )if not note:return Response(SignalReportFeedbackResponseSerializer({"forwarded": False}).data)@@ -2701,6 +2719,9 @@ class SignalReportViewSet(user_id=request.user.id,action_type=SignalReportAction.ActionType.VIEW,)+ capture_background_report_events(+ team=self.team, user=request.user, event=BACKGROUND_REPORT_VIEWED_EVENT, report_ids=[str(report.id)]+ )return Response(status=status.HTTP_204_NO_CONTENT)# `list` names the viewset's own action inside the class body, so the annotations use `Sequence`.@@ -2797,6 +2818,19 @@ class SignalReportViewSet()return Response(serializer.data)+ def _capture_background_dismissals(+ self, *, reports: Sequence[SignalReport], target: str, dismissal_reason: str | None+ ) -> None:+ if target != SignalReport.Status.SUPPRESSED or not reports:+ return+ capture_background_report_events(+ team=self.team,+ user=self.request.user if isinstance(self.request.user, User) else None,+ event=BACKGROUND_REPORT_DISMISSED_EVENT,+ report_ids=[str(report.id) for report in reports],+ properties={"dismissal_reason": dismissal_reason},+ )+def _forward_dismissal_note(self,*,@@ -3042,6 +3076,8 @@ class SignalReportViewSet(# and tracker issue. An external agent keeps its user principal, so it names the# person who ran it rather than nobody.report._transition_actor_user_id = self._request_attribution().user_id # type: ignore[attr-defined]+ # Read under the row lock, so two concurrent dismissals count as one new suppression.+ report._newly_suppressed = target_status == SignalReport.Status.SUPPRESSED # type: ignore[attr-defined]report.save(update_fields=updated_fields)@@ -3147,6 +3183,7 @@ class SignalReportViewSet(results: list[dict] = []counts: dict[str, int] = {outcome.value: 0 for outcome in SignalReportBulkStateOutcome}transitioned: list[SignalReport] = []+ newly_dismissed: list[SignalReport] = []for report_id in ordered_ids:report = reports_by_id.get(report_id)if report is None:@@ -3165,6 +3202,8 @@ class SignalReportViewSet(report_status = report.status if outcome == SignalReportBulkStateOutcome.TRANSITIONED else Noneif outcome == SignalReportBulkStateOutcome.TRANSITIONED:transitioned.append(report)+ if getattr(report, "_newly_suppressed", False):+ newly_dismissed.append(report)results.append({"id": report_id,@@ -3180,6 +3219,7 @@ class SignalReportViewSet(dismissal_reason=dismissal_reason,dismissal_note=dismissal_note,)+ self._capture_background_dismissals(reports=newly_dismissed, target=target, dismissal_reason=dismissal_reason)return Response({diff --git a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.tsindex 08c6a86dacea..2eb80934dfba 100644--- a/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxOnboardingLogic.ts@@ -267,7 +267,6 @@ export interface inboxOnboardingLogicValues {reportsCount: number | null // reportListLogicreportsCountLoading: boolean // reportListLogicsearchParams: Record<string, any> // router- enabledScoutsCount: number // scoutFleetLogicscoutConfigs: SignalScoutConfig[] | null // scoutFleetLogicscoutConfigsLoading: boolean // scoutFleetLogicenabledSourcesCount: number // signalSourcesLogic@@ -332,7 +331,7 @@ export interface inboxOnboardingLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface inboxOnboardingLogicMeta {__keaTypeGenInternalSelectorTypes: {- isSelfDrivingSetUp: (enabledSourcesCount: number, enabledScoutsCount: number) => boolean+ isSelfDrivingSetUp: (enabledSourcesCount: number, scoutConfigs: SignalScoutConfig[] | null) => booleanisSetupLoaded: (sourceConfigs: SignalSourceConfig[] | null,scoutConfigs: SignalScoutConfig[] | null,@@ -418,7 +417,7 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([signalSourcesLogic,['sourceConfigs', 'sourceConfigsLoading', 'enabledSourcesCount', 'hasEmittingScanner'],scoutFleetLogic,- ['scoutConfigs', 'scoutConfigsLoading', 'enabledCount as enabledScoutsCount'],+ ['scoutConfigs', 'scoutConfigsLoading'],// Mount the monitoring + needs-decision count loaders directly (cheap limit=1 each) so we// know whether there's existing work even during a takeover, when the view switcher that// usually mounts these isn't rendered. Same keyed instances it uses – no double-fetch.@@ -525,10 +524,12 @@ export const inboxOnboardingLogic = kea<inboxOnboardingLogicType>([}),selectors({+ // A background-managed scout is not set up: nobody on the project turned it on.isSelfDrivingSetUp: [- (s) => [s.enabledSourcesCount, s.enabledScoutsCount],- (enabledSourcesCount: number, enabledScoutsCount: number): boolean =>- enabledSourcesCount + enabledScoutsCount > 0,+ (s) => [s.enabledSourcesCount, s.scoutConfigs],+ (enabledSourcesCount: number, scoutConfigs: SignalScoutConfig[] | null): boolean =>+ enabledSourcesCount > 0 ||+ !!scoutConfigs?.some((config) => config.enabled && config.managed_by !== 'background'),],// Every watcher loader has settled, so the set-up verdict is trustworthy.isSetupLoaded: [