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(self-driving): emit custom event when scout emits report (#66698)

Andrew Maguireea35d5f72866
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 1b6883b17da0..629ace8f9a12 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -18,13 +18,18 @@ that may have succeeded.
from __future__ import annotations
+import uuid
+import asyncio
import logging
from dataclasses import dataclass
from typing import Any
+from django.conf import settings
+
import posthoganalytics
from asgiref.sync import async_to_sync
+from posthog.api.capture import capture_internal
from posthog.event_usage import groups
from posthog.models import Team
from posthog.sync import database_sync_to_async
@@ -343,6 +348,90 @@ def _report_event_base(run: SignalScoutRun) -> dict[str, Any]:
}
+# Customer-facing copies of the report-channel lifecycle events, captured into the scout's *own team*
+# project (via `capture_internal`) — distinct from the `signals_scout_report_*` events above, which go to
+# PostHog's internal analytics via the `posthoganalytics` SDK. Landing them in the team's own event stream
+# lets a team act on its scout reports with no PostHog-side wiring: HogQL/insights/alerts over the events,
+# or a CDP destination (e.g. the Slack destination) filtering on the event and templating off `report_url`
+# / `title` / `summary`. The `$` prefix marks a PostHog-generated event (cf. `$session_summary_ready`,
+# `$ai_tag`), keeping them out of a customer's own custom-event namespace.
+CUSTOMER_REPORT_EMITTED_EVENT = "$scout_report_emitted"
+CUSTOMER_REPORT_EDITED_EVENT = "$scout_report_edited"
+_REPORT_EVENT_SOURCE = "signals_scout_report"
+
+# Gate-skip reasons that mean the scout isn't active — deliberately off (`scout_emit_disabled` /
+# `source_disabled`) or fail-closed because its dispatch-time config is gone (`scout_config_missing`,
+# from a deleted/nulled `SignalScoutConfig`). See `_preflight_emit_gates`. An inactive scout must produce
+# no side effects, so its attempt is still recorded on the internal stream but is NOT fanned out as a
+# customer-facing, automation-driving event. Other gate-skips that represent a real, customer-controlled
+# condition (e.g. `ai_processing_not_approved`) still forward the raw event.
+_INACTIVE_SKIP_REASONS = frozenset({"scout_emit_disabled", "source_disabled", "scout_config_missing"})
+
+
+@dataclass
+class _ReportForward:
+ """The payload for the customer-facing fan-out, built on the sync/DB thread and handed to
+ `_forward_report_event_to_team` — so the blocking `capture_internal` HTTP can be offloaded off the
+ DB-thread pool (via `asyncio.to_thread` on the async path) instead of running inside it."""
+
+ event_name: str
+ distinct_id: str
+ event_uuid: str
+ properties: dict[str, Any]
+
+
+def _report_url(team_id: int, report_id: str | None) -> str | None:
+ """Inbox deep link for an authored report, or None when no report exists yet (gate-skipped emit). The
+ canonical form used by the Slack inbox notifications (`slack_inbox_notifications.py`)."""
+ if not report_id:
+ return None
+ return f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+
+
+def _report_event_uuid(*parts: object) -> str:
+ """Deterministic event uuid from the parts that identify a distinct emit/edit. A retried capture of the
+ same authored report (or an identical re-applied edit) collapses to one event at ingestion instead of
+ double-firing a destination — `emit_report`/`edit_report` are non-idempotent, so the same logical action
+ can reach this path more than once. Distinct actions (a different report, a different edit) differ in
+ the parts and stay separate events."""
+ key = "|".join("" if part is None else str(part) for part in parts)
+ return str(uuid.uuid5(uuid.NAMESPACE_URL, f"signals_scout_report:{key}"))
+
+
+def _forward_report_event_to_team(*, team: Team, forward: _ReportForward) -> None:
+ """Mirror a report-channel lifecycle event into the scout's own team project through the sanctioned
+ `capture_internal` path, so the team can drive HogQL / alerts / CDP destinations off its reports.
+ Person processing is OFF with a synthetic per-scout `distinct_id` — a report is the scout's output, not
+ an end-user action, so it must never create or merge a person profile. `capture_internal` is a blocking
+ HTTP call (2s default timeout); the async callers offload it via `asyncio.to_thread` so it never holds a
+ DB-thread-pool thread. Best-effort: a forward failure must never fail or mask the emit/edit (it only
+ feeds downstream automation)."""
+ try:
+ capture_internal(
+ token=team.api_token,
+ event_name=forward.event_name,
+ event_source=_REPORT_EVENT_SOURCE,
+ distinct_id=forward.distinct_id,
+ properties=forward.properties,
+ event_uuid=forward.event_uuid,
+ process_person_profile=False,
+ ).raise_for_status()
+ except Exception:
+ logger.warning(
+ "signals_scout: failed to forward report event %s to team project",
+ forward.event_name,
+ extra={"team_id": team.id, "distinct_id": forward.distinct_id},
+ )
+
+
+async def _forward_report_event_async(team: Team, forward: _ReportForward | None) -> None:
+ """Offload the blocking customer-facing forward to a worker thread on the async path, keeping the
+ DB-thread pool free for DB work (mirrors the `$session_summary_ready` `asyncio.to_thread` pattern).
+ No-op when the capture decided not to fan out (a disabled / dry-run gate-skip)."""
+ if forward is not None:
+ await asyncio.to_thread(_forward_report_event_to_team, team=team, forward=forward)
+
+
def _capture_report_emitted(
*,
team: Team,
@@ -355,7 +444,7 @@ def _capture_report_emitted(
already_addressed: bool,
priority: str | None,
repository: str | None,
-) -> None:
+) -> _ReportForward | None:
"""Emit the scout-owned `signals_scout_report_emitted` event — the report-channel counterpart to
`signals_scout_run_finished`, fired once per `emit_report` call that reached a terminal outcome.
@@ -367,7 +456,11 @@ def _capture_report_emitted(
(dashboards, alerts, CDP forwards) can act on a report's substance, not just its ids. Content rides
every outcome, including `gate_skipped` (it records what would have been authored). Keyed on the team
and carrying the run / task ids so it joins to the run lifecycle events. Best-effort: a capture failure
- must never fail or mask the emit. Accesses `team.organization` — call on a sync thread."""
+ must never fail or mask the emit. Accesses `team.organization` — call on a sync thread.
+
+ Returns the customer-facing fan-out payload for the caller to forward, or None to suppress the
+ fan-out — a disabled / dry-run gate-skip records the attempt on the internal stream here but must
+ not fire an automation-driving event into the team's own project."""
if result.skipped_reason is not None:
outcome = "gate_skipped"
elif result.emitted:
@@ -388,6 +481,7 @@ def _capture_report_emitted(
"priority": priority,
"repository": repository,
"safety_explanation": _clip(result.safety_explanation, _MAX_TELEMETRY_TEXT_LEN),
+ "report_url": _report_url(team.id, result.report_id),
}
try:
posthoganalytics.capture(
@@ -401,6 +495,14 @@ def _capture_report_emitted(
"signals_scout: failed to capture report-emitted analytics event",
extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},
)
+ if result.skipped_reason in _INACTIVE_SKIP_REASONS:
+ return None
+ return _ReportForward(
+ event_name=CUSTOMER_REPORT_EMITTED_EVENT,
+ distinct_id=f"signals_scout:{run.skill_name}",
+ event_uuid=_report_event_uuid("emit", run.id, result.report_id, title),
+ properties=properties,
+ )
def _capture_report_edited(
@@ -411,13 +513,14 @@ def _capture_report_edited(
title: str | None,
summary: str | None,
note: str | None,
-) -> None:
+) -> _ReportForward:
"""Emit the scout-owned `signals_scout_report_edited` event when a scout mutates an existing report via
`edit_report`, so edits are observable separately from fresh authorship. `updated_fields` /
`note_appended` distinguish a title/summary rewrite from a note-only append; `title` / `summary` /
`note` carry the content the edit applied (each None when that field wasn't touched) — parity with the
emit event so a consumer sees *what* changed, not just that something did. Best-effort; never fails the
- edit. Accesses `team.organization` — call on a sync thread."""
+ edit. Accesses `team.organization` — call on a sync thread. Returns the customer-facing fan-out payload
+ for the caller to forward."""
properties = {
**_report_event_base(run),
"report_id": result.report_id,
@@ -426,6 +529,7 @@ def _capture_report_edited(
"title": _clip(title, MAX_REPORT_TITLE_LENGTH),
"summary": _clip(summary, _MAX_TELEMETRY_SUMMARY_LEN),
"note": _clip(note, _MAX_TELEMETRY_TEXT_LEN),
+ "report_url": _report_url(team.id, result.report_id),
}
try:
posthoganalytics.capture(
@@ -439,6 +543,17 @@ def _capture_report_edited(
"signals_scout: failed to capture report-edited analytics event",
extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},
)
+ # Sort `updated_fields` so a retried edit that changed the same set hashes to one `event_uuid` — the
+ # set's iteration order isn't guaranteed stable across worker processes, and an unstable key would
+ # double-fire a destination on retry.
+ return _ReportForward(
+ event_name=CUSTOMER_REPORT_EDITED_EVENT,
+ distinct_id=f"signals_scout:{run.skill_name}",
+ event_uuid=_report_event_uuid(
+ "edit", run.id, result.report_id, sorted(result.updated_fields), title, summary, note
+ ),
+ properties=properties,
+ )
async def emit_report(
@@ -477,7 +592,7 @@ async def emit_report(
preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)
if preflight is not None:
result = _gate_skip_result(preflight)
- await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
+ forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
team=team,
run=run,
result=result,
@@ -489,6 +604,7 @@ async def emit_report(
priority=priority,
repository=repository,
)
+ await _forward_report_event_async(team, forward)
return result
task_id = await database_sync_to_async(_resolve_task_id, thread_sensitive=False)(run)
@@ -524,7 +640,7 @@ async def emit_report(
if surfaced:
await _maybe_autostart_report(team_id=team.id, report_id=persisted.report_id)
result = _emit_result(persisted.report_id, judgement)
- await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
+ forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(
team=team,
run=run,
result=result,
@@ -536,6 +652,7 @@ async def emit_report(
priority=priority,
repository=repository,
)
+ await _forward_report_event_async(team, forward)
return result
@@ -574,7 +691,7 @@ def emit_report_sync(
preflight = _preflight_emit_gates(team, run)
if preflight is not None:
result = _gate_skip_result(preflight)
- _capture_report_emitted(
+ forward = _capture_report_emitted(
team=team,
run=run,
result=result,
@@ -586,6 +703,8 @@ def emit_report_sync(
priority=priority,
repository=repository,
)
+ if forward is not None:
+ _forward_report_event_to_team(team=team, forward=forward)
return result
task_id = _resolve_task_id(run)
@@ -621,7 +740,7 @@ def emit_report_sync(
if surfaced:
async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=persisted.report_id)
result = _emit_result(persisted.report_id, judgement)
- _capture_report_emitted(
+ forward = _capture_report_emitted(
team=team,
run=run,
result=result,
@@ -633,6 +752,8 @@ def emit_report_sync(
priority=priority,
repository=repository,
)
+ if forward is not None:
+ _forward_report_event_to_team(team=team, forward=forward)
return result
@@ -677,7 +798,6 @@ def _do_edit_report(
# title rewrite to its current value) must not claim the run touched the report.
if updated_fields or note_appended:
record_report_edit(team_id=team.id, run_id=run.id, report_id=report_id)
- _capture_report_edited(team=team, run=run, result=result, title=title, summary=summary, note=append_note)
return result
@@ -699,9 +819,14 @@ async def edit_report(
"""Edit an existing inbox report: rewrite title/summary and/or append a note. Team-scoped
fail-closed in the service. Async entry; runs the sync edit core in the thread pool."""
_validate_edit_inputs(team, run, title, summary, append_note)
- return await database_sync_to_async(_do_edit_report, thread_sensitive=False)(
+ result = await database_sync_to_async(_do_edit_report, thread_sensitive=False)(
team=team, run=run, report_id=report_id, title=title, summary=summary, append_note=append_note
)
+ forward = await database_sync_to_async(_capture_report_edited, thread_sensitive=False)(
+ team=team, run=run, result=result, title=title, summary=summary, note=append_note
+ )
+ await _forward_report_event_async(team, forward)
+ return result
def edit_report_sync(
@@ -715,6 +840,9 @@ def edit_report_sync(
) -> EditReportResult:
"""Sync entry used by the DRF view path. Same behavior as `edit_report`, on the calling thread."""
_validate_edit_inputs(team, run, title, summary, append_note)
- return _do_edit_report(
+ result = _do_edit_report(
team=team, run=run, report_id=report_id, title=title, summary=summary, append_note=append_note
)
+ forward = _capture_report_edited(team=team, run=run, result=result, title=title, summary=summary, note=append_note)
+ _forward_report_event_to_team(team=team, forward=forward)
+ return result
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index 2eb14ca01580..eb5cf160e35d 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -18,6 +18,8 @@ EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_r
# Patched at its source module so the lazy import inside `_maybe_autostart_report` picks up the mock.
AUTOSTART_PATH = "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts"
CAPTURE_PATH = "products.signals.backend.scout_harness.tools.report.posthoganalytics.capture"
+# The customer-facing copy lands in the scout's own team project via capture_internal (a network boundary).
+CAPTURE_INTERNAL_PATH = "products.signals.backend.scout_harness.tools.report.capture_internal"
REPORT_TOOLS = ["emit_report", "edit_report"]
@@ -48,6 +50,11 @@ class TestScoutReportAPI(APIBaseTest):
# The report channel requires `signal_scout_report:write`, granted only by the
# `signals_scout_reports` posture (mirrors the runner's opt-in posture selection).
_authenticate_as_scout(self, scopes="signals_scout_reports")
+ # The customer-facing event fans out through capture_internal (a network call to capture-rs).
+ # Keep it inert by default so emit/edit tests don't hit the network; the two dedicated tests
+ # assert against this mock.
+ self.capture_internal_mock = patch(CAPTURE_INTERNAL_PATH).start()
+ self.addCleanup(patch.stopall)
def _emit_url(self, run_id: str) -> str:
return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/emit-report/"
@@ -264,6 +271,19 @@ class TestScoutReportAPI(APIBaseTest):
assert props["title"] == "Checkout p99 regressed after 4.2"
assert props["summary"] == "The /checkout endpoint p99 doubled after the 4.2 deploy."
assert props["actionability"] == "immediately_actionable"
+ # The customer-facing copy must land in the team's *own* project (their token), never create a
+ # person (it's the scout's output, not a user action), and carry a report deep link when a report
+ # exists — that link is what a CDP Slack destination templates the message from.
+ forward = next(
+ c for c in self.capture_internal_mock.call_args_list if c.kwargs["event_name"] == "$scout_report_emitted"
+ )
+ assert forward.kwargs["token"] == self.team.api_token
+ assert forward.kwargs["process_person_profile"] is False
+ expected_url = None if expected_outcome == "gate_skipped" else f"/inbox/reports/{body['report_id']}"
+ if expected_url is None:
+ assert forward.kwargs["properties"]["report_url"] is None
+ else:
+ assert forward.kwargs["properties"]["report_url"].endswith(expected_url)
def test_edit_report_captures_edited_event(self) -> None:
run = _make_run(self.team)
@@ -283,6 +303,51 @@ class TestScoutReportAPI(APIBaseTest):
assert props["title"] == "new title"
assert props["note"] == "re-validated"
assert props["summary"] is None
+ # The edit also fans out to the team's own project, deep-linking the edited report.
+ forward = next(
+ c for c in self.capture_internal_mock.call_args_list if c.kwargs["event_name"] == "$scout_report_edited"
+ )
+ assert forward.kwargs["token"] == self.team.api_token
+ assert forward.kwargs["process_person_profile"] is False
+ assert forward.kwargs["properties"]["report_url"].endswith(f"/inbox/reports/{created['report_id']}")
+
+ @parameterized.expand(
+ [
+ ("scout_emit_disabled",),
+ ("source_disabled",),
+ ("scout_config_missing",),
+ ]
+ )
+ def test_emit_report_inactive_scout_does_not_fan_out(self, reason: str) -> None:
+ # An inactive scout produces no side effects: a gate-skip from a deliberate off-toggle
+ # (`scout_emit_disabled` / `source_disabled`) or a fail-closed missing config
+ # (`scout_config_missing`) still records the attempt on the internal
+ # `signals_scout_report_emitted` stream, but must NOT fire a customer-facing, automation-driving
+ # event into the team's own project. (A non-inactive gate-skip like `ai_processing_not_approved`
+ # still fans out — covered by the lifecycle test above.)
+ run = _make_run(self.team)
+ config = run.scout_config
+ assert config is not None
+ if reason == "scout_emit_disabled":
+ config.emit = False
+ config.save(update_fields=["emit"])
+ elif reason == "source_disabled":
+ SignalSourceConfig.objects.filter(
+ team=self.team, source_product="signals_scout", source_type="cross_source_issue"
+ ).update(enabled=False)
+ else:
+ # Deleting the dispatch-time config nulls the run's FK (SET_NULL) → fail-closed gate-skip.
+ config.delete()
+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()), patch(CAPTURE_PATH) as capture:
+ body = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
+ assert body["skipped_reason"] == reason
+ # Internal telemetry still records the inactive attempt...
+ event = next(c for c in capture.call_args_list if c.kwargs["event"] == "signals_scout_report_emitted")
+ assert event.kwargs["properties"]["skipped_reason"] == reason
+ # ...but no customer-facing copy is forwarded.
+ assert not any(
+ c.kwargs.get("event_name") == "$scout_report_emitted" for c in self.capture_internal_mock.call_args_list
+ )
@parameterized.expand(
[