: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(replay-vision): link an observation to the inbox reports its signals raised (#102525)
Tue Haulund0c82b19f968a
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex b3c29fd43fe8..5688166b9022 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -83,8 +83,10 @@ from products.replay_vision.backend.search_suggestions import (scope_sources,stamp_search_viewed,)+from products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPEfrom products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdictfrom products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshot+from products.signals.backend.facade.api import get_reports_for_signal_source_slicefrom products.tasks.backend.facade import api as tasks_facadefrom ee.hogai.utils.untrusted import as_untrusted_data@@ -753,6 +755,23 @@ class CreateTaskFromObservationResponseSerializer(serializers.Serializer):)+class ObservationSignalReportSerializer(serializers.Serializer):+ """An inbox report that this observation's emitted signals were grouped into."""++ id = serializers.UUIDField(help_text="ID of the inbox report, for linking to its inbox page.")+ title = serializers.CharField(+ allow_null=True,+ help_text="Report title, null while the report is still too new to have been summarized.",+ )+ status = serializers.CharField(+ help_text=(+ "The report's status in the inbox: potential, candidate, in_progress, pending_input, ready, "+ "resolved, failed, or suppressed."+ ),+ )+ created_at = serializers.DateTimeField(help_text="When the report was created.")++@dataclass(frozen=True)class _TaskContent:title: str@@ -854,8 +873,8 @@ class ReplayObservationViewSet().order_by("-created_at", "id")def filter_queryset(self, queryset: QuerySet[ReplayObservation]) -> QuerySet[ReplayObservation]:- # List filters scope prev/next neighbors only; the observation itself must always resolve on retrieve.- if self.action == "retrieve":+ # List filters scope prev/next neighbors only; the observation itself must always resolve on a detail read.+ if self.action in {"retrieve", "signal_reports"}:return querysetreturn super().filter_queryset(queryset)@@ -1006,6 +1025,29 @@ class ReplayObservationViewSet(locked.save(update_fields=["created_task_id"])return Response({"task_id": task_id}, status=status.HTTP_201_CREATED)+ @extend_schema(responses={200: ObservationSignalReportSerializer(many=True)})+ @action(+ detail=True,+ methods=["get"],+ url_path="signal_reports",+ pagination_class=None,+ required_scopes=["replay_scanner:read", "session_recording:read", "task:read"],+ )+ def signal_reports(self, request: Request, **kwargs: Any) -> Response:+ """The inbox reports this observation's emitted signals were grouped into, newest first."""+ # `required_scopes` only gates API keys, so a session member denied inbox access would+ # otherwise read report titles here that the reports endpoint never shows them.+ if not self.user_access_control.check_access_level_for_resource("task", required_level="viewer"):+ raise PermissionDenied("Reading an observation's signal reports requires inbox read access.")+ observation = self.get_object()+ reports = get_reports_for_signal_source_slice(+ team=self.team,+ source_product=VISION_SIGNALS_SOURCE_PRODUCT,+ source_type=VISION_SIGNALS_SOURCE_TYPE,+ extra_equals={"observation_id": str(observation.id)},+ )+ return Response(ObservationSignalReportSerializer(instance=reports, many=True).data)+@extend_schema(request=None, responses={204: None})@action(detail=True,diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 38d9e305cd09..3e90091a40ac 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1,3 +1,4 @@+import uuidfrom datetime import UTC, datetime, timedeltafrom typing import Any, cast@@ -65,7 +66,7 @@ from products.replay_vision.backend.tests.helpers import (seed_scanner_spend,snapshot_for as _snapshot_for,)-from products.signals.backend.facade.api import SignalSourceSliceOutcomes+from products.signals.backend.facade.api import SignalSourceSliceOutcomes, SignalSourceSliceReportfrom products.signals.backend.models import SignalSourceConfig@@ -4960,6 +4961,84 @@ class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):assert kwargs["extra_equals"] == {"scanner_id": str(scanner.id)}+class TestObservationSignalReportsAPI(_VisionAPITestCase):+ def test_returns_the_reports_this_observations_signals_landed_in(self) -> None:+ # Wiring guard: the endpoint must narrow the signals slice to this observation; a dropped+ # extra filter would list every report the scanner ever contributed to.+ scanner = self._create_scanner()+ observation = ReplayObservation.objects.create(+ scanner=scanner,+ session_id="sess-signal-reports",+ scanner_snapshot=_snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ report_id = uuid.uuid4()+ created_at = timezone.now()+ reports = [+ SignalSourceSliceReport(id=str(report_id), title="Checkout stalls", status="ready", created_at=created_at)+ ]+ with patch(+ "products.replay_vision.backend.api.observations.get_reports_for_signal_source_slice",+ return_value=reports,+ ) as mock_reports:+ response = self.client.get(+ f"/api/environments/{self.team.id}/vision/observations/{observation.id}/signal_reports/"+ )++ assert response.status_code == 200, response.json()+ assert response.json() == [+ {+ "id": str(report_id),+ "title": "Checkout stalls",+ "status": "ready",+ "created_at": created_at.isoformat().replace("+00:00", "Z"),+ }+ ]+ kwargs = mock_reports.call_args.kwargs+ assert kwargs["source_product"] == "replay_vision"+ assert kwargs["source_type"] == "scanner_finding"+ assert kwargs["extra_equals"] == {"observation_id": str(observation.id)}++ def test_denied_without_inbox_read_access(self) -> None:+ # Scopes only gate API keys, so a session member denied inbox access must not read titles here.+ scanner = self._create_scanner()+ observation = ReplayObservation.objects.create(+ scanner=scanner,+ session_id="sess-no-inbox",+ scanner_snapshot=_snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ with patch(+ "products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_resource",+ side_effect=lambda resource, required_level=None, **_: resource != "task",+ ):+ response = self.client.get(+ f"/api/environments/{self.team.id}/vision/observations/{observation.id}/signal_reports/"+ )++ assert response.status_code == 403, response.json()++ def test_resolves_the_observation_through_a_list_filter(self) -> None:+ # Without the detail-read exemption, a filter the observation does not match 404s the reports.+ scanner = self._create_scanner()+ observation = ReplayObservation.objects.create(+ scanner=scanner,+ session_id="sess-filtered",+ scanner_snapshot=_snapshot_for(scanner),+ triggered_by=ObservationTrigger.SCHEDULE,+ )+ with patch(+ "products.replay_vision.backend.api.observations.get_reports_for_signal_source_slice",+ return_value=[],+ ):+ response = self.client.get(+ f"{self.observations_url(str(scanner.id))}{observation.id}/signal_reports/?status=succeeded"+ )++ assert response.status_code == 200, response.json()+ assert response.json() == []++@patch("products.replay_vision.backend.api.trigger.async_to_sync")@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestReplayVisionProductIntent(_VisionAPITestCase):diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 5bbb7481b598..727312b2d2c5 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -691,6 +691,23 @@ export interface ReplayVisionErrorApi {detail: string}+/**+ * An inbox report that this observation's emitted signals were grouped into.+ */+export interface ObservationSignalReportApi {+ /** ID of the inbox report, for linking to its inbox page. */+ id: string+ /**+ * Report title, null while the report is still too new to have been summarized.+ * @nullable+ */+ title: string | null+ /** The report's status in the inbox: potential, candidate, in_progress, pending_input, ready, resolved, failed, or suppressed. */+ status: string+ /** When the report was created. */+ created_at: string+}+export interface ObservationSearchResultApi {/** The matching observation. */observation: ReplayObservationApi@@ -2797,6 +2814,61 @@ export type VisionScannersObservationsRetrieveParams = {verdict?: string}+export type VisionScannersObservationsSignalReportsListParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string+ /**+ * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.+ */+ date_from?: string+ /**+ * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.+ */+ date_to?: string+ /**+ * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.+ */+ labeled?: boolean+ /**+ * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.+ */+ max_score?: number+ /**+ * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.+ */+ min_score?: number+ /**+ * Sort observations by created_at, started_at, completed_at, status, recording_subject_email, result_score, result_verdict, result_confidence, or scanner_version. Prefix with `-` for descending. Keys that can be null (started_at, completed_at, recording_subject_email, result_*, scanner_version) sort nulls last regardless of direction.+ */+ order_by?: string+ /**+ * Filter to observations whose person email contains this value (case-insensitive).+ */+ recording_subject?: string+ /**+ * Filter to observations of one or more session recordings. Accepts a comma-separated list.+ */+ session_id?: string+ /**+ * Filter by observation status. Accepts a comma-separated list.+ */+ status?: string+ /**+ * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.+ */+ tags?: string+ /**+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.+ */+ triggered_by?: string+ /**+ * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).+ */+ verdict?: string+}+export type VisionScannersObservationsStatsRetrieveParams = {/*** Only observations dispatched by this backfill.diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex bb947dcc7505..bf156dde4bd8 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {InlineScanRequestApi,InlineScanResponseApi,ObservationSearchResponseApi,+ ObservationSignalReportApi,ObservationStatsApi,ObserveAlreadyScannedApi,ObserveRequestApi,@@ -71,6 +72,7 @@ import type {VisionScannersListParams,VisionScannersObservationsListParams,VisionScannersObservationsRetrieveParams,+ VisionScannersObservationsSignalReportsListParams,VisionScannersObservationsStatsRetrieveParams,VisionScannersPromptSuggestionsListParams,VisionScannersWatchFeedRetrieveParams,@@ -433,6 +435,24 @@ export const visionObservationsRetryCreate = async (})}+export const getVisionObservationsSignalReportsListUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/observations/${id}/signal_reports/`+}++/**+ * The inbox reports this observation's emitted signals were grouped into, newest first.+ */+export const visionObservationsSignalReportsList = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ObservationSignalReportApi[]> => {+ return apiMutator<ObservationSignalReportApi[]>(getVisionObservationsSignalReportsListUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionObservationsViewedCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/vision/observations/${id}/viewed/`}@@ -1124,6 +1144,46 @@ export const visionScannersObservationsRetryCreate = async (})}+export const getVisionScannersObservationsSignalReportsListUrl = (+ projectId: string,+ scannerId: string,+ id: string,+ params?: VisionScannersObservationsSignalReportsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/signal_reports/?${stringifiedParams}`+ : `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/signal_reports/`+}++/**+ * The inbox reports this observation's emitted signals were grouped into, newest first.+ */+export const visionScannersObservationsSignalReportsList = async (+ projectId: string,+ scannerId: string,+ id: string,+ params?: VisionScannersObservationsSignalReportsListParams,+ options?: RequestInit+): Promise<ObservationSignalReportApi[]> => {+ return apiMutator<ObservationSignalReportApi[]>(+ getVisionScannersObservationsSignalReportsListUrl(projectId, scannerId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getVisionScannersObservationsViewedCreateUrl = (projectId: string, scannerId: string, id: string) => {return `/api/projects/${projectId}/vision/scanners/${scannerId}/observations/${id}/viewed/`}diff --git a/products/replay_vision/frontend/observations/ObservationSignalReports.tsx b/products/replay_vision/frontend/observations/ObservationSignalReports.tsxnew file mode 100644index 000000000000..422e5f543e99--- /dev/null+++ b/products/replay_vision/frontend/observations/ObservationSignalReports.tsx@@ -0,0 +1,60 @@+import { useValues } from 'kea'++import { Link } from '@posthog/lemon-ui'++import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { urls } from 'scenes/urls'++import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/utils/reportPresentation'++import { LabeledRow } from '../components/LabeledRow'+import { observationSignalReportsLogic } from './observationSignalReportsLogic'++// Mounted only when the observation emitted something, so a no-signal observation never queries.+function ReportLinks({ observationId }: { observationId: string }): JSX.Element {+ const { signalReports, signalReportsLoading, signalReportsUnavailable } = useValues(+ observationSignalReportsLogic({ observationId })+ )++ if (signalReportsLoading) {+ return <LemonSkeleton className="h-4 w-40" />+ }+ if (signalReportsUnavailable) {+ return <span className="text-muted">Could not load linked reports</span>+ }+ if (!signalReports?.length) {+ // The lookup window is bounded, so an old observation can have a report this does not find.+ return <span className="text-muted">No linked report found</span>+ }+ return (+ <>+ {signalReports.map((report) => (+ <Link+ key={report.id}+ to={urls.inboxReport('reports', report.id)}+ data-attr="vision-observation-open-signal-report"+ >+ {displayConventionalCommitTitle(report.title, 'Untitled report')}+ </Link>+ ))}+ </>+ )+}++/** The signals this observation emitted, and the inbox reports they were grouped into. */+export function ObservationSignalReports({+ observationId,+ signalsCount,+}: {+ observationId: string+ signalsCount: number+}): JSX.Element {+ return (+ <LabeledRow label="Signals">+ <div className="flex flex-col items-start gap-1">+ <span>Emitted ({signalsCount})</span>+ {signalsCount > 0 && <ReportLinks observationId={observationId} />}+ </div>+ </LabeledRow>+ )+}diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsxindex e81458b2cd00..465584c0cb56 100644--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx@@ -70,6 +70,7 @@ import { ObservationLabelControl } from './ObservationLabelControl'import { observationLabelLogic } from './observationLabelLogic'import { ObservationPinnedProperties } from './ObservationPinnedProperties'import { ObservationShareButton } from './ObservationShareButton'+import { ObservationSignalReports } from './ObservationSignalReports'import {neighborFilterParams,observationDetailUrl,@@ -631,9 +632,10 @@ export function ReplayObservationSceneComponent(): JSX.Element {</LabeledRow>)}{snapshot?.emits_signals && (- <LabeledRow label="Signals">- <span>Emitted ({observation.scanner_result?.signals_count ?? 0})</span>- </LabeledRow>+ <ObservationSignalReports+ observationId={observation.id}+ signalsCount={observation.scanner_result?.signals_count ?? 0}+ />)}</div></LemonCard>diff --git a/products/replay_vision/frontend/observations/observationSignalReportsLogic.ts b/products/replay_vision/frontend/observations/observationSignalReportsLogic.tsnew file mode 100644index 000000000000..4ec125446761--- /dev/null+++ b/products/replay_vision/frontend/observations/observationSignalReportsLogic.ts@@ -0,0 +1,101 @@+import { MakeLogicType, actions, afterMount, kea, key, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { teamLogic } from 'scenes/teamLogic'++import { visionObservationsSignalReportsList } from '../generated/api'+import { ObservationSignalReportApi } from '../generated/api.schemas'++export interface ObservationSignalReportsLogicProps {+ observationId: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface observationSignalReportsLogicValues {+ signalReports: ObservationSignalReportApi[] | null+ signalReportsLoading: boolean+ signalReportsUnavailable: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface observationSignalReportsLogicActions {+ loadSignalReports: () => any+ loadSignalReportsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSignalReportsSuccess: (+ signalReports: ObservationSignalReportApi[] | null,+ payload?: any+ ) => {+ signalReports: ObservationSignalReportApi[] | null+ payload?: any+ }+ setSignalReportsUnavailable: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface observationSignalReportsLogicMeta {+ key: string+}++export type observationSignalReportsLogicType = MakeLogicType<+ observationSignalReportsLogicValues,+ observationSignalReportsLogicActions,+ ObservationSignalReportsLogicProps,+ observationSignalReportsLogicMeta+>++/** Grouping runs after the scan finishes, so an empty list means "not grouped yet" as much as "never grouped". */+export const observationSignalReportsLogic = kea<observationSignalReportsLogicType>([+ path(['products', 'replay_vision', 'frontend', 'observations', 'observationSignalReportsLogic']),+ props({} as ObservationSignalReportsLogicProps),+ key((props) => props.observationId),++ actions({+ setSignalReportsUnavailable: true,+ }),++ reducers({+ // A failed read must not read as "no reports": the caller may simply lack inbox access.+ signalReportsUnavailable: [+ false,+ {+ setSignalReportsUnavailable: () => true,+ loadSignalReports: () => false,+ },+ ],+ }),++ loaders(({ props, actions }) => ({+ signalReports: [+ null as ObservationSignalReportApi[] | null,+ {+ loadSignalReports: async () => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return null+ }+ try {+ return await visionObservationsSignalReportsList(String(teamId), props.observationId)+ } catch (e) {+ // Supplementary context on an already-rendered page: fail quiet, don't toast over it.+ posthog.captureException(e)+ actions.setSignalReportsUnavailable()+ return null+ }+ },+ },+ ],+ })),++ afterMount(({ actions }) => {+ actions.loadSignalReports()+ }),+])diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 3a2641240918..6ab62050506e 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -179,6 +179,9 @@ tools:vision-observations-search-viewed-create:operation: vision_observations_search_viewed_createenabled: false+ vision-observations-signal-reports-list:+ operation: vision_observations_signal_reports_list+ enabled: falsevision-observations-viewed-create:operation: vision_observations_viewed_createenabled: false@@ -493,6 +496,9 @@ tools:vision-scanners-observations-retry-create:operation: vision_scanners_observations_retry_createenabled: false+ vision-scanners-observations-signal-reports-list:+ operation: vision_scanners_observations_signal_reports_list+ enabled: falsevision-scanners-observations-stats:operation: vision_scanners_observations_stats_retrieveenabled: truediff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex 83c0761a2c5c..6a346b60267c 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -36,7 +36,7 @@ from products.signals.backend.scout_harness.workflow_runs import (# rule, the workflow cooldown, single-flight, dispatch) happens here.start_workflow_scout_run as start_workflow_scout_run,)-from products.signals.backend.signal_metadata import fetch_signal_stats_for_source_slice+from products.signals.backend.signal_metadata import SourceSliceSignalStats, fetch_signal_stats_for_source_slice# Re-exported for external products (tasks presentation catches it around facade create_task).from products.signals.backend.task_run_artefacts import ReportTaskCapExceeded as ReportTaskCapExceeded@@ -782,6 +782,47 @@ class SignalSourceSliceOutcomes:merged_pr_count: int+@frozen+class SignalSourceSliceReport:+ """One inbox report a source slice's signals were grouped into."""++ id: str+ title: str | None+ status: str+ created_at: datetime+++def _live_reports_for_signal_source_slice(+ team: Team, *, source_product: str, source_type: str, extra_equals: dict[str, str]+) -> tuple[SourceSliceSignalStats, list[SignalSourceSliceReport]]:+ """The slice's signal stats, plus its reports newest first.++ CH metadata is not authoritative, so only report ids that parse and still exist for this team+ survive.+ """+ stats = fetch_signal_stats_for_source_slice(+ team, source_product=source_product, source_type=source_type, extra_equals=extra_equals+ )+ candidate_ids = []+ for report_id in stats.report_ids:+ try:+ candidate_ids.append(uuid.UUID(report_id))+ except ValueError:+ continue+ if not candidate_ids:+ return stats, []+ reports = [+ SignalSourceSliceReport(+ id=str(row["id"]), title=row["title"], status=row["status"], created_at=row["created_at"]+ )+ for row in SignalReport.objects.filter(team=team, id__in=candidate_ids)+ .exclude(status=SignalReport.Status.DELETED)+ .order_by("-created_at")+ .values("id", "title", "status", "created_at")+ ]+ return stats, reports++def get_outcomes_for_signal_source_slice(*, team: Team, source_product: str, source_type: str, extra_equals: dict[str, str]) -> SignalSourceSliceOutcomes:@@ -797,22 +838,10 @@ def get_outcomes_for_signal_source_slice(fetch_implementation_prs_for_reports,)- stats = fetch_signal_stats_for_source_slice(+ stats, reports = _live_reports_for_signal_source_slice(team, source_product=source_product, source_type=source_type, extra_equals=extra_equals)- # CH metadata is not authoritative — keep only report ids that parse and still exist for this team.- candidate_ids = []- for report_id in stats.report_ids:- try:- candidate_ids.append(uuid.UUID(report_id))- except ValueError:- continue- report_ids = [- str(rid)- for rid in SignalReport.objects.filter(team=team, id__in=candidate_ids)- .exclude(status=SignalReport.Status.DELETED)- .values_list("id", flat=True)- ]+ report_ids = [report.id for report in reports]prs = fetch_implementation_prs_for_reports(report_ids, team_id=team.id)pr_urls = {pr.url for report_prs in prs.values() for pr in report_prs}merged_pr_urls = {pr.url for report_prs in prs.values() for pr in report_prs if pr.merged}@@ -824,6 +853,20 @@ def get_outcomes_for_signal_source_slice()+def get_reports_for_signal_source_slice(+ *, team: Team, source_product: str, source_type: str, extra_equals: dict[str, str]+) -> list[SignalSourceSliceReport]:+ """The same slice as `get_outcomes_for_signal_source_slice`, hydrated instead of counted, newest first.++ Grouping runs after the emitting caller returns, so an empty list means "not grouped yet" as+ much as "never grouped".+ """+ _, reports = _live_reports_for_signal_source_slice(+ team, source_product=source_product, source_type=source_type, extra_equals=extra_equals+ )+ return reports++@frozenclass ScoutCreated:"""What a scout creation produced. `created` is False when a scout of that name already existeddiff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pyindex ed9baaab500f..bd01c13c5044 100644--- a/products/signals/backend/test/test_signal_queries.py+++ b/products/signals/backend/test/test_signal_queries.py@@ -10,7 +10,11 @@ from parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute-from products.signals.backend.facade.api import SignalSourceSliceOutcomes, get_outcomes_for_signal_source_slice+from products.signals.backend.facade.api import (+ SignalSourceSliceOutcomes,+ get_outcomes_for_signal_source_slice,+ get_reports_for_signal_source_slice,+)from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalReportPullRequestfrom products.signals.backend.signal_metadata import (EMBEDDING_MODEL,@@ -499,3 +503,30 @@ class TestGetOutcomesForSignalSourceSlice(_SignalEmbeddingsTestBase):)assert outcomes == SignalSourceSliceOutcomes(signal_count=5, report_count=2, pr_count=2, merged_pr_count=1)++ def test_hydrates_the_same_slice_newest_first(self) -> None:+ # The link surface shares the slice query with the counters, so it must drop the same+ # malformed and soft-deleted ids, and order newest first rather than by CH's set order.+ older = SignalReport.objects.create(team=self.team, title="older", summary="s")+ newer = SignalReport.objects.create(team=self.team, title="newer", summary="s")+ SignalReport.objects.filter(pk=older.id).update(created_at=self.base - timedelta(hours=1))+ soft_deleted = SignalReport.objects.create(+ team=self.team, title="gone", summary="s", status=SignalReport.Status.DELETED+ )+ for index, report_id in enumerate([str(older.id), str(newer.id), str(soft_deleted.id), "not-a-uuid"]):+ self._emit_version(+ document_id=f"h{index}",+ report_id=report_id,+ source_product="errors",+ inserted_at=self.base,+ extra={"observation_id": "obs-1"},+ )++ reports = get_reports_for_signal_source_slice(+ team=self.team, source_product="errors", source_type="some_type", extra_equals={"observation_id": "obs-1"}+ )++ assert [(r.id, r.title, r.status) for r in reports] == [+ (str(newer.id), "newer", "potential"),+ (str(older.id), "older", "potential"),+ ]diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b81c379aabb5..222f785f7266 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57214,6 +57214,23 @@ export namespace Schemas {truncated: boolean;}+ /**+ * An inbox report that this observation's emitted signals were grouped into.+ */+ export interface ObservationSignalReport {+ /** ID of the inbox report, for linking to its inbox page. */+ id: string;+ /**+ * Report title, null while the report is still too new to have been summarized.+ * @nullable+ */+ title: string | null;+ /** The report's status in the inbox: potential, candidate, in_progress, pending_input, ready, resolved, failed, or suppressed. */+ status: string;+ /** When the report was created. */+ created_at: string;+ }+export interface ObservationStatusCounts {/** Total observations in the filtered set. */total: number;@@ -109495,6 +109512,61 @@ export namespace Schemas {verdict?: string;};+ export type VisionScannersObservationsSignalReportsListParams = {+ /**+ * Only observations dispatched by this backfill.+ */+ backfill_id?: string;+ /**+ * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.+ */+ date_from?: string;+ /**+ * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.+ */+ date_to?: string;+ /**+ * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.+ */+ labeled?: boolean;+ /**+ * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.+ */+ max_score?: number;+ /**+ * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.+ */+ min_score?: number;+ /**+ * Sort observations by created_at, started_at, completed_at, status, recording_subject_email, result_score, result_verdict, result_confidence, or scanner_version. Prefix with `-` for descending. Keys that can be null (started_at, completed_at, recording_subject_email, result_*, scanner_version) sort nulls last regardless of direction.+ */+ order_by?: string;+ /**+ * Filter to observations whose person email contains this value (case-insensitive).+ */+ recording_subject?: string;+ /**+ * Filter to observations of one or more session recordings. Accepts a comma-separated list.+ */+ session_id?: string;+ /**+ * Filter by observation status. Accepts a comma-separated list.+ */+ status?: string;+ /**+ * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.+ */+ tags?: string;+ /**+ * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.+ */+ triggered_by?: string;+ /**+ * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).+ */+ verdict?: string;+ };+export type VisionScannersObservationsStatsRetrieveParams = {/*** Only observations dispatched by this backfill.