: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): reverse lookup from scout finding to linked inbox report (#63817)
Andrew Maguire6c9fad70c7fe
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex f5e3ee20ca56..93e4b2315c59 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -164,6 +164,35 @@ class SignalScoutEmissionSerializer(serializers.ModelSerializer):read_only_fields = fields+class LinkedSignalReportSerializer(serializers.Serializer):+ """Minimal inbox `SignalReport` projection for the scout reverse lookup — just enough+ for the scout UI to render a clickable chip and deep-link into the inbox, which loads+ the full report itself."""++ id = serializers.UUIDField(help_text="UUID of the linked `SignalReport`.")+ title = serializers.CharField(+ allow_null=True,+ help_text="LLM-generated report title, or null if the report hasn't been summarised yet.",+ )+ status = serializers.CharField(help_text="Current report status (e.g. `potential`, `ready`, `resolved`).")+++class ScoutEmissionReportLinkSerializer(serializers.Serializer):+ """One finding the run emitted, paired with the inbox report (if any) its signal grouped into.++ Best-effort reverse of the report -> signals link: `report` is null when the finding hasn't+ grouped into a report yet, was de-duplicated away, or its signal was deleted."""++ finding_id = serializers.CharField(help_text="Stable id the finding was emitted under.")+ source_id = serializers.CharField(+ help_text="Deterministic `run:<run_id>:finding:<finding_id>` join key into the signal store.",+ )+ report = LinkedSignalReportSerializer(+ allow_null=True,+ help_text="The inbox report this finding linked to, or null if none could be resolved.",+ )++class SearchRecentRunsQuerySerializer(serializers.Serializer):"""Query parameters for `search-recent-runs`."""diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex cde3c156f9f3..944c7c9150c6 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -22,6 +22,7 @@ from __future__ import annotationsimport uuidfrom dataclasses import dataclass+import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schemafrom rest_framework import exceptions, status, viewsets@@ -41,7 +42,13 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.permissions import APIScopePermission-from products.signals.backend.models import SignalProjectProfile, SignalScoutConfig, SignalScoutEmission, SignalScoutRun+from products.signals.backend.models import (+ SignalProjectProfile,+ SignalReport,+ SignalScoutConfig,+ SignalScoutEmission,+ SignalScoutRun,+)from products.signals.backend.scout_harness.config_registry import enabled_scout_countfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, canonical_skill_namesfrom products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAM@@ -54,6 +61,7 @@ from products.signals.backend.scout_harness.serializers import (ProjectProfileQuerySerializer,ProjectProfileSerializer,RememberRequestSerializer,+ ScoutEmissionReportLinkSerializer,ScratchpadEntrySerializer,SearchMemoryQuerySerializer,SearchRecentRunsQuerySerializer,@@ -72,8 +80,11 @@ from products.signals.backend.scout_harness.tools.scratchpad import (remember,search_scratchpad,)+from products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_idsfrom products.skills.backend.models.skills import LLMSkill+logger = structlog.get_logger(__name__)+# Hard cap on the per-run emissions response. Far above any realistic run (a scout emits a# handful of findings), so it never truncates in practice — it just bounds a pathological# retry-heavy run rather than leaving the payload unbounded.@@ -274,6 +285,86 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)[:MAX_EMISSIONS_PER_RUN]return Response(SignalScoutEmissionSerializer(emissions, many=True).data)+ @extend_schema(+ parameters=[_RUN_ID_PATH_PARAMETER],+ responses={+ 200: OpenApiResponse(+ response=ScoutEmissionReportLinkSerializer(many=True),+ description="Per-finding inbox report links for this run, newest finding first.",+ ),+ 404: OpenApiResponse(description="Run not found or not visible to this project."),+ },+ summary="List the inbox reports a run's findings linked to",+ description=(+ "Best-effort reverse of the report -> signals link. For each finding the run emitted, resolve "+ "the inbox `SignalReport` (if any) its underlying signal grouped into by walking the deterministic "+ "`source_id` back through the signal store. `report` is null when the finding hasn't grouped into a "+ "report yet, was de-duplicated away, or its signal was deleted. Lets the scout UI surface which "+ "inbox report a finding contributed to — the reverse of the report's evidence list. Strictly "+ "team-scoped — a run UUID belonging to another team returns 404."+ ),+ operation_id="signals_scout_runs_emission_reports",+ )+ @action(+ detail=True,+ methods=["get"],+ url_path="emissions/reports",+ # This action returns report titles, so it requires `task:read` (the scope+ # `SignalReportViewSet` gates report reads on) on top of `signal_scout:read` —+ # otherwise a scout-only token could read titles it can't reach canonically.+ required_scopes=["signal_scout:read", "task:read"],+ pagination_class=None,+ )+ def emission_reports(self, request: Request, **kwargs) -> Response:+ run_id = _parse_run_id_or_404(kwargs)+ team_id = _canonical_team_id(self)+ # Team-scope the run lookup first so a foreign-team UUID is a clean 404, not an empty list.+ if not SignalScoutRun.objects.filter(id=run_id, team_id=team_id).exists():+ raise exceptions.NotFound()++ emissions = list(+ SignalScoutEmission.objects.filter(scout_run_id=run_id, team_id=team_id).order_by("-emitted_at", "-id")[+ :MAX_EMISSIONS_PER_RUN+ ]+ )+ # One ClickHouse round-trip for the whole run: map every finding's source_id to the+ # report_id its signal grouped into (best effort — unmatched/deleted findings drop out).+ # Query with the canonical team so the injected `document_embeddings.team_id` guard+ # matches where signals persist (child-environment requests would otherwise find none).+ # CH/HogQL failures degrade to "no links" rather than 500-ing the whole page.+ canonical_team = self.team.parent_team or self.team+ source_ids = [e.source_id for e in emissions if e.source_id]+ source_id_to_report_id: dict[str, str] = {}+ if source_ids:+ try:+ source_id_to_report_id = fetch_report_ids_for_source_ids(canonical_team, source_ids)+ except Exception:+ logger.exception("scout_emission_reports_lookup_failed", run_id=str(run_id), team_id=team_id)++ # Hydrate the resolved report ids into minimal projections. Exclude DELETED and SUPPRESSED+ # reports — ClickHouse soft-delete and Postgres status can drift, and `SignalReportViewSet`+ # hides both from its default retrieve/list flow, so a chip linking to either would deep-link+ # to a page that can't load it. Treat that as "no link" rather than a dangling chip.+ report_ids = {rid for rid in source_id_to_report_id.values() if rid}+ reports_by_id = {+ str(row["id"]): row+ for row in SignalReport.objects.filter(team_id=team_id, id__in=report_ids)+ .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])+ .values("id", "title", "status")+ }++ links = []+ for emission in emissions:+ report_id = source_id_to_report_id.get(emission.source_id)+ links.append(+ {+ "finding_id": emission.finding_id,+ "source_id": emission.source_id,+ "report": reports_by_id.get(report_id) if report_id else None,+ }+ )+ return Response(ScoutEmissionReportLinkSerializer(links, many=True).data)+@validated_request(request_serializer=EmitFindingRequestSerializer,parameters=[_RUN_ID_PATH_PARAMETER],diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex 875f1a12858d..dfe964747a6d 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -589,3 +589,70 @@ def fetch_source_products_for_reports(team: Team, report_ids: list[str]) -> dict)return {row[0]: row[1] for row in (result.results or []) if row[0]}+++# ---------------------------------------------------------------------------+# fetch_report_ids_for_source_ids — synchronous, for the scout reverse lookup+# ---------------------------------------------------------------------------+++def fetch_report_ids_for_source_ids(team: Team, source_ids: list[str]) -> dict[str, str]:+ """Map each scout `source_id` to the report its emitted signal grouped into.++ Best-effort reverse of the report -> signals link. A scout finding is emitted as a+ signal whose ClickHouse metadata carries both its deterministic `source_id`+ (`run:<run_id>:finding:<finding_id>`) and, once grouping matches it, the `report_id`+ of the report it landed in. This walks that link backwards so the scout UI can show+ which inbox report (if any) a finding contributed to.++ Only `signals_scout` signals that resolved to a non-empty, non-deleted `report_id`+ are returned. A non-idempotent re-emit can produce several signals for one+ `source_id`; the most recent (by signal timestamp) wins. Uses argMax dedup so the+ result is stable regardless of ReplacingMergeTree merge state.+ """+ if not source_ids:+ return {}++ # Push the source_id filter into the document_embeddings scan so we only dedup the+ # handful of signals for these findings, not the team's entire signal history.+ # Resolve the newest signal per source_id FIRST (carrying its deleted/report state),+ # then decide whether to return a link. Filtering deleted/empty rows before the argMax+ # would let an older non-deleted report win when the latest signal was deleted or+ # report-less, surfacing a stale link instead of the documented "most recent wins" null.+ source_id_scan_filter = "JSONExtractString(metadata, 'source_id') IN ({source_ids})"+ ch_query = f"""+ SELECT source_id, report_id+ FROM (+ SELECT+ source_id,+ argMax(report_id, timestamp) as report_id,+ argMax(is_deleted, timestamp) as is_deleted+ FROM (+ SELECT+ JSONExtractString(metadata, 'source_id') as source_id,+ JSONExtractString(metadata, 'report_id') as report_id,+ JSONExtractBool(metadata, 'deleted') as is_deleted,+ JSONExtractString(metadata, 'source_product') as source_product,+ timestamp+ FROM ({_deduped_signals_subquery(extra_where=source_id_scan_filter)})+ )+ WHERE source_product = 'signals_scout'+ AND source_id != ''+ GROUP BY source_id+ )+ WHERE NOT is_deleted+ AND report_id != ''+ """++ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ result = execute_hogql_query(+ query_type="SignalsFetchReportIdsForSourceIds",+ query=ch_query,+ team=team,+ placeholders={+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),+ "source_ids": ast.Tuple(exprs=[ast.Constant(value=sid) for sid in source_ids]),+ },+ )++ return {row[0]: row[1] for row in (result.results or []) if row[0] and row[1]}diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 442f10bf348c..af2a7cc4ff48 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -17,6 +17,7 @@ from posthog.temporal.oauth import (from products.signals.backend.models import (SignalProjectProfile,+ SignalReport,SignalScoutConfig,SignalScoutEmission,SignalScoutRun,@@ -259,6 +260,88 @@ class TestScoutHarnessRunEmissionsAPI(APIBaseTest):assert response.status_code == status.HTTP_404_NOT_FOUND+# Patch target: the helper is hot-imported into the view module, so patch it there, not at source.+_FETCH_REPORT_IDS = "products.signals.backend.scout_harness.views.fetch_report_ids_for_source_ids"+++class TestScoutHarnessEmissionReportsAPI(APIBaseTest):+ def _url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/{run_id}/emissions/reports/"++ def test_pairs_each_finding_with_its_linked_report(self) -> None:+ run = _make_run(self.team, emitted_finding_ids=["f-a", "f-b"])+ linked = _make_emission(self.team, run, finding_id="f-a")+ _make_emission(self.team, run, finding_id="f-b") # unmatched — no report+ report = SignalReport.objects.create(team=self.team, title="Checkout 500s", status=SignalReport.Status.READY)+ with patch(_FETCH_REPORT_IDS, return_value={linked.source_id: str(report.id)}) as mock_fetch:+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ # The helper is called once for the whole run with every finding's source_id.+ assert sorted(mock_fetch.call_args.args[1]) == sorted(+ [f"run:{run.id}:finding:f-a", f"run:{run.id}:finding:f-b"]+ )+ body = {row["finding_id"]: row for row in response.json()}+ assert body["f-a"]["report"] == {+ "id": str(report.id),+ "title": "Checkout 500s",+ "status": "ready",+ }+ assert body["f-a"]["source_id"] == linked.source_id+ # A finding whose signal never grouped into a report links to null, not an error.+ assert body["f-b"]["report"] is None++ def test_deleted_report_is_treated_as_no_link(self) -> None:+ # ClickHouse soft-delete and Postgres status can drift, so the reverse lookup can resolve a+ # report id that's since been deleted — surface that as "no link", not a dangling chip.+ run = _make_run(self.team)+ emission = _make_emission(self.team, run, finding_id="f-a")+ deleted = SignalReport.objects.create(team=self.team, status=SignalReport.Status.DELETED)+ with patch(_FETCH_REPORT_IDS, return_value={emission.source_id: str(deleted.id)}):+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ assert response.json()[0]["report"] is None++ def test_suppressed_report_is_treated_as_no_link(self) -> None:+ # The inbox hides suppressed reports from its default flow, so a chip to one would deep-link+ # to a page that can't load it — surface suppressed reports as "no link" here too.+ run = _make_run(self.team)+ emission = _make_emission(self.team, run, finding_id="f-a")+ suppressed = SignalReport.objects.create(team=self.team, status=SignalReport.Status.SUPPRESSED)+ with patch(_FETCH_REPORT_IDS, return_value={emission.source_id: str(suppressed.id)}):+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ assert response.json()[0]["report"] is None++ def test_clickhouse_failure_degrades_to_null_links(self) -> None:+ # A transient CH/HogQL failure shouldn't 500 the whole page — each finding still+ # comes back, just with `report: null` instead of a resolved link.+ run = _make_run(self.team, emitted_finding_ids=["f-a"])+ _make_emission(self.team, run, finding_id="f-a")+ with patch(_FETCH_REPORT_IDS, side_effect=Exception("ClickHouse timeout")):+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ assert response.json()[0]["report"] is None++ def test_empty_run_returns_empty_and_skips_clickhouse(self) -> None:+ run = _make_run(self.team)+ with patch(_FETCH_REPORT_IDS) as mock_fetch:+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == []+ mock_fetch.assert_not_called()++ def test_unknown_run_returns_404(self) -> None:+ response = self.client.get(self._url("00000000-0000-0000-0000-000000000000"))+ assert response.status_code == status.HTTP_404_NOT_FOUND++ def test_other_teams_run_returns_404(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other")+ run = _make_run(other)+ _make_emission(other, run, finding_id="f-a")+ response = self.client.get(self._url(str(run.id)))+ assert response.status_code == status.HTTP_404_NOT_FOUND++class TestScoutHarnessEmitFindingAPI(APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 9ffd0a8d4e75..ca509b2aba2a 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -952,6 +952,38 @@ export interface SignalScoutEmissionApi {emitted_at: string}+/**+ * Minimal inbox `SignalReport` projection for the scout reverse lookup — just enough+ * for the scout UI to render a clickable chip and deep-link into the inbox, which loads+ * the full report itself.+ */+export interface LinkedSignalReportApi {+ /** UUID of the linked `SignalReport`. */+ id: string+ /**+ * LLM-generated report title, or null if the report hasn't been summarised yet.+ * @nullable+ */+ title: string | null+ /** Current report status (e.g. `potential`, `ready`, `resolved`). */+ status: string+}++/**+ * One finding the run emitted, paired with the inbox report (if any) its signal grouped into.+ *+ * Best-effort reverse of the report -> signals link: `report` is null when the finding hasn't+ * grouped into a report yet, was de-duplicated away, or its signal was deleted.+ */+export interface ScoutEmissionReportLinkApi {+ /** Stable id the finding was emitted under. */+ finding_id: string+ /** Deterministic `run:<run_id>:finding:<finding_id>` join key into the signal store. */+ source_id: string+ /** The inbox report this finding linked to, or null if none could be resolved. */+ report: LinkedSignalReportApi | null+}+/*** One citation attached to a finding. Mirrors `SignalsScoutEvidenceEntry`.*/diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex cd3df31b77d8..a31cd3d7985e 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -22,6 +22,7 @@ import type {PauseUntilRequestApi,ProjectProfileApi,RememberRequestApi,+ ScoutEmissionReportLinkApi,ScratchpadEntryApi,SignalReportApi,SignalReportStateRequestApi,@@ -365,6 +366,25 @@ export const signalsScoutRunsEmissions = async (})}+export const getSignalsScoutRunsEmissionReportsUrl = (projectId: string, runId: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/${runId}/emissions/reports/`+}++/**+ * Best-effort reverse of the report -> signals link. For each finding the run emitted, resolve the inbox `SignalReport` (if any) its underlying signal grouped into by walking the deterministic `source_id` back through the signal store. `report` is null when the finding hasn't grouped into a report yet, was de-duplicated away, or its signal was deleted. Lets the scout UI surface which inbox report a finding contributed to — the reverse of the report's evidence list. Strictly team-scoped — a run UUID belonging to another team returns 404.+ * @summary List the inbox reports a run's findings linked to+ */+export const signalsScoutRunsEmissionReports = async (+ projectId: string,+ runId: string,+ options?: RequestInit+): Promise<ScoutEmissionReportLinkApi[]> => {+ return apiMutator<ScoutEmissionReportLinkApi[]>(getSignalsScoutRunsEmissionReportsUrl(projectId, runId), {+ ...options,+ method: 'GET',+ })+}+export const getSignalsScoutEmitSignalUrl = (projectId: string, runId: string) => {return `/api/projects/${projectId}/signals/scout/runs/${runId}/emit-signal/`}diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 336985c47912..bf4a9fda4cc1 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -261,6 +261,9 @@ tools:`inbox-source-configs-list` / `inbox-reports-list` / `read-data-schema` / `activity-log-list`. Distinct from`signals-scout-scratchpad-list`: profile is ground truth from authoritative tables; scratchpad is thescout's inferred learnings.+ signals-scout-runs-emission-reports:+ operation: signals_scout_runs_emission_reports+ enabled: falsesignals-scout-runs-emissions-list:operation: signals_scout_runs_emissionsenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c7000dcb4a98..c43c8326efc9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23897,6 +23897,23 @@ export namespace Schemas {Sustained: 'sustained',} as const;+ /**+ * Minimal inbox `SignalReport` projection for the scout reverse lookup — just enough+ * for the scout UI to render a clickable chip and deep-link into the inbox, which loads+ * the full report itself.+ */+ export interface LinkedSignalReport {+ /** UUID of the linked `SignalReport`. */+ id: string;+ /**+ * LLM-generated report title, or null if the report hasn't been summarised yet.+ * @nullable+ */+ title: string | null;+ /** Current report status (e.g. `potential`, `ready`, `resolved`). */+ status: string;+ }+/*** Typed output for view set `list`.*/@@ -41447,6 +41464,21 @@ export namespace Schemas {base_version?: number;}+ /**+ * One finding the run emitted, paired with the inbox report (if any) its signal grouped into.+ *+ * Best-effort reverse of the report -> signals link: `report` is null when the finding hasn't+ * grouped into a report yet, was de-duplicated away, or its signal was deleted.+ */+ export interface ScoutEmissionReportLink {+ /** Stable id the finding was emitted under. */+ finding_id: string;+ /** Deterministic `run:<run_id>:finding:<finding_id>` join key into the signal store. */+ source_id: string;+ /** The inbox report this finding linked to, or null if none could be resolved. */+ report: LinkedSignalReport | null;+ }+/*** `SignalScratchpad` projection used by `search-memory` and `remember`.*/