: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): surface self-driving outcomes per scanner (#84382)
Tue Haulund65f560c70f45
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0a273c46169c..456240bea7d5 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7421,9 +7421,9 @@ snapshots:scenes-app-replay-vision--scanner-on-demand--light:hash: v1.k794b7964.c7fb3bef0e6746a00dee5acf2ea13684f9ceaafbf719a292c7c83ba6f1e66ce0.wXTvBQVYYqTn1h9VeKathC07umJLHQVSRaSI95Dduposcenes-app-replay-vision--scanner-scan-drought--dark:- hash: v1.k794b7964.645b4298695c0faaa6ce59fbc64f575f8a06c8f81ca03c46fdeb61dbd7c37118.e4UUyWY4Z1dRJmVhPQo_M59fR3fjBOwFqhiJP4RWDYw+ hash: v1.k794b7964.76130f9b73097aff10e53cb7edf5f4b90a445c5cc67c7979c3dffeac0d015b85.pJLj_cTQ5R0crsCU5AfXRXX5YgFBAMTPW50F_cfPgLUscenes-app-replay-vision--scanner-scan-drought--light:- hash: v1.k794b7964.04cee1856f76c7975432a18c1e3e8e3d9ebd7b03cfeb80c47b246e8262ff1428.RfhQ3_f5sR1MSglvHlFb513u4b0ISfmaNTNFlRdvoog+ hash: v1.k794b7964.5957cfc8e00b6b7720c4a4fa64f9cd81baf51e99e2e6f000df6799c1d452170d.tEhTyx0-12nMCnt57NysfmFJPnrgdzgNuFekVubJwLIscenes-app-replay-vision--scanner-templates--dark:hash: v1.k794b7964.5730130a0ab80bc33dc701a8cc69c354f8ac4f50df6c4a25f6b0627a4e90ceeb.0zwSfaSwHJZ0F2c__vQj7Bj3VUvQZD3nu5zcrxJym9oscenes-app-replay-vision--scanner-templates--light:@@ -7449,9 +7449,9 @@ snapshots:scenes-app-replay-vision--startup-program-cap--light:hash: v1.k794b7964.4f8607a7ad5d31f814e202a7446ef97eb6ccf74455147b068d08deecdd7b3136.vxVv8hYBIj7g6ps2cBMRTCP3vLTxQcmkkhnNBIU5JnAscenes-app-replay-vision--summarizer-overview--dark:- hash: v1.k794b7964.0ca77dfa7636705bd03957a4cb97b14e2c5fcf7fd87572c97b08acb90f3b83cd.Iq_Eaiw6uLvwJUpUiaQyMkij6FLw_7a6csbRr9ZIwDw+ hash: v1.k794b7964.977399e0f1a5cdd98967d020ed15d2aa08b47ec0dbb0d36c4287ccf4e16d6bc6.L1TFIxNhtYHGbq72h1LbR4v2KvenCDxpXaStGAA4J5Qscenes-app-replay-vision--summarizer-overview--light:- hash: v1.k794b7964.908b0e15c561ac57de772ff9fa297fd54b52c182eeb8af645aaaf18646b5a4ec.FCJjo-nOsab96YEv1fZh4QQK0DkWfcTbae5bI9GPxgw+ hash: v1.k794b7964.c4c10f01522dae58cfa74b31763cc511792be4e089715c3a2dc368069709903a.oNfnCNLDZrnVpzs6I9cQGdG22Hrp5C3PQ3LukYHNIE0scenes-app-replay-vision--usage-tab--dark:hash: v1.k794b7964.2cbe01468a4afb2779cd3ce13961c7f12f5de30b17ff2f1745d08aca2d90d6b1.h0UIDulO8w6XzMcfmA9URttOLJ9pT7XUKlPJpBwjwTYscenes-app-replay-vision--usage-tab--light:diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 4d2e9023c0d8..19580a68c715 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -107,7 +107,9 @@ from products.replay_vision.backend.scanner_draft import DraftError, draft_scannfrom products.replay_vision.backend.scanning import MAX_SESSIONS_PER_SCAN, run_inline_scan, scan_existing_scannerfrom products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTHfrom products.replay_vision.backend.tag_suggestions import SuggestionError, suggest_classifier_tags+from products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPEfrom products.replay_vision.backend.temporal.metrics import record_scanner_limit_reached+from products.signals.backend.facade.api import get_outcomes_for_signal_source_slice# Date is set by the schedule at trigger time, not by the user — strip on save._QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")@@ -1358,6 +1360,22 @@ class AffectedCohortResponseSerializer(serializers.Serializer):)+class ScannerSelfDrivingStatsSerializer(serializers.Serializer):+ """Response of GET /vision/scanners/:id/self_driving_stats/."""++ signals_emitted = serializers.IntegerField(+ help_text="Signals this scanner has pushed into the Signals inbox, all time."+ )+ reports_contributed = serializers.IntegerField(+ help_text=(+ "Signal reports that include at least one of this scanner's signals. Reports usually "+ "aggregate signals from several sources, so this counts contributions, not sole causes."+ )+ )+ prs_opened = serializers.IntegerField(help_text="Implementation PRs opened by self-driving on those reports.")+ prs_merged = serializers.IntegerField(help_text="Of the opened PRs, how many have merged.")++@extend_schema_view(list=extend_schema(parameters=[@@ -1379,7 +1397,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viscope_object = "replay_scanner"# Custom actions must be listed explicitly or personal-API-key callers 403 silently.- scope_object_read_actions = ["list", "retrieve", "creators", "stats"]+ scope_object_read_actions = ["list", "retrieve", "creators", "stats", "self_driving_stats"]scope_object_write_actions = ["create","update",@@ -1752,6 +1770,33 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viraise ValidationError(str(exc)) from excreturn Response(ScannerImpactSerializer(instance=impact).data)+ @extend_schema(responses={200: ScannerSelfDrivingStatsSerializer})+ @action(+ detail=True,+ methods=["get"],+ url_path="self_driving_stats",+ required_scopes=["replay_scanner:read", "task:read"],+ )+ def self_driving_stats(self, request: Request, **kwargs: Any) -> Response:+ """What self-driving did with this scanner's signals: reports contributed to and PRs opened."""+ scanner = self.get_object()+ outcomes = get_outcomes_for_signal_source_slice(+ team=self.team,+ source_product=VISION_SIGNALS_SOURCE_PRODUCT,+ source_type=VISION_SIGNALS_SOURCE_TYPE,+ extra_equals={"scanner_id": str(scanner.id)},+ )+ return Response(+ ScannerSelfDrivingStatsSerializer(+ instance={+ "signals_emitted": outcomes.signal_count,+ "reports_contributed": outcomes.report_count,+ "prs_opened": outcomes.pr_count,+ "prs_merged": outcomes.merged_pr_count,+ }+ ).data+ )+@extend_schema(request=AffectedCohortRequestSerializer,responses={201: AffectedCohortResponseSerializer},diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex a2429caaae6c..8ef3c47c81e9 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -54,6 +54,7 @@ from products.replay_vision.backend.tests.helpers import (seed_scanner_spend,snapshot_for as _snapshot_for,)+from products.signals.backend.facade.api import SignalSourceSliceOutcomesfrom products.signals.backend.models import SignalSourceConfig@@ -3531,3 +3532,28 @@ class TestInlineScanAction(_VisionAPITestCase):self.assertEqual(resp.status_code, 400, resp.content)self.assertFalse(ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE).exists())start_workflow.assert_not_called()+++class TestScannerSelfDrivingStatsAPI(_VisionAPITestCase):+ def test_returns_the_scanners_signal_outcomes(self) -> None:+ # Wiring guard: the endpoint must query the signals facade for this scanner's slice and+ # serialize the outcome counts; a dropped extra filter would return team-wide numbers.+ scanner = self._create_scanner()+ outcomes = SignalSourceSliceOutcomes(signal_count=5, report_count=2, pr_count=1, merged_pr_count=1)+ with patch(+ "products.replay_vision.backend.api.scanners.get_outcomes_for_signal_source_slice",+ return_value=outcomes,+ ) as mock_outcomes:+ response = self.client.get(f"{self.scanners_url}{scanner.id}/self_driving_stats/")++ assert response.status_code == 200+ assert response.json() == {+ "signals_emitted": 5,+ "reports_contributed": 2,+ "prs_opened": 1,+ "prs_merged": 1,+ }+ kwargs = mock_outcomes.call_args.kwargs+ assert kwargs["source_product"] == "replay_vision"+ assert kwargs["source_type"] == "scanner_finding"+ assert kwargs["extra_equals"] == {"scanner_id": str(scanner.id)}diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 8a683d777ae4..9e5f756c3237 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -1168,6 +1168,20 @@ export interface ObserveResponseApi {workflow_id: string}+/**+ * Response of GET /vision/scanners/:id/self_driving_stats/.+ */+export interface ScannerSelfDrivingStatsApi {+ /** Signals this scanner has pushed into the Signals inbox, all time. */+ signals_emitted: number+ /** Signal reports that include at least one of this scanner's signals. Reports usually aggregate signals from several sources, so this counts contributions, not sole causes. */+ reports_contributed: number+ /** Implementation PRs opened by self-driving on those reports. */+ prs_opened: number+ /** Of the opened PRs, how many have merged. */+ prs_merged: number+}+/*** * `running` - Running* * `paused_quota` - Paused (quota)diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 886e27060b3f..dc058d589a70 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -46,6 +46,7 @@ import type {RunActionResponseApi,ScannerCreatorsResponseApi,ScannerImpactApi,+ ScannerSelfDrivingStatsApi,ScannerStatsResponseApi,SuggestTagsRequestApi,SuggestTagsResponseApi,@@ -618,6 +619,24 @@ export const visionScannersObserveCreate = async (})}+export const getVisionScannersSelfDrivingStatsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/vision/scanners/${id}/self_driving_stats/`+}++/**+ * What self-driving did with this scanner's signals: reports contributed to and PRs opened.+ */+export const visionScannersSelfDrivingStatsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<ScannerSelfDrivingStatsApi> => {+ return apiMutator<ScannerSelfDrivingStatsApi>(getVisionScannersSelfDrivingStatsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisionScannersBackfillsListUrl = (projectId: string,scannerId: string,diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex ee8c5b7e1422..ca1cedbc6ae9 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -27,6 +27,7 @@ import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { LemonField } from 'lib/lemon-ui/LemonField'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { pluralize } from 'lib/utils/strings'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -55,6 +56,7 @@ import {scannerStepUrlWithParams,} from './scannerEditorSceneLogic'import { ScannerEditorStepper } from './ScannerEditorStepper'+import { scannerSelfDrivingStatsLogic } from './scannerSelfDrivingStatsLogic'import { SCANNER_TYPE_OPTIONS, getModelOptions, modelNamingVariant } from './types'const HedgehogConstruction2 = pngHoggie(construction2Png)@@ -268,6 +270,27 @@ function DetailsStep(): JSX.Element {)}+// Live outcomes under the self-driving toggle: what turning it on has already produced. Renders+// nothing until the scanner has emitted at least one signal, so a new scanner just sees the pitch.+function SelfDrivingOutcomesLine({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { selfDrivingStats } = useValues(scannerSelfDrivingStatsLogic({ scannerId }))+ if (!selfDrivingStats || selfDrivingStats.signals_emitted === 0) {+ return null+ }+ const { signals_emitted, reports_contributed, prs_opened, prs_merged } = selfDrivingStats+ return (+ <div className="text-xs text-muted" data-attr="vision-editor-self-driving-outcomes">+ So far this scanner has emitted <strong className="tabular-nums">{signals_emitted.toLocaleString()}</strong>{' '}+ {pluralize(signals_emitted, 'signal', undefined, false)}, contributing to{' '}+ <strong className="tabular-nums">{reports_contributed.toLocaleString()}</strong>{' '}+ {pluralize(reports_contributed, 'report', undefined, false)} and{' '}+ <strong className="tabular-nums">{prs_opened.toLocaleString()}</strong>{' '}+ {pluralize(prs_opened, 'PR', undefined, false)}+ {prs_opened > 0 ? <> ({prs_merged.toLocaleString()} merged)</> : null}.+ </div>+ )+}+function ConfigureStep(): JSX.Element {const { scannerId } = useValues(scannerEditorSceneLogic)const { scanner, isNew, goalDraft } = useValues(replayScannerLogic({ id: scannerId }))@@ -384,6 +407,7 @@ function ConfigureStep(): JSX.Element {</Link>.</div>+ {!isNew && <SelfDrivingOutcomesLine scannerId={scannerId} />}</div><LemonSwitchchecked={!!value}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex 811f88e3c489..e5669f5002e7 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -1,16 +1,19 @@import { useActions, useValues } from 'kea'import { IconPeople } from '@posthog/icons'-import { LemonButton, LemonTag, Spinner } from '@posthog/lemon-ui'+import { LemonButton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { BarChart } from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'import { creditsToUsd, formatCreditsRange } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab, replayScannerSceneLogic } from '../replayScannerSceneLogic'import { scannerOverviewLogic } from '../scannerOverviewLogic'+import { scannerSelfDrivingStatsLogic } from '../scannerSelfDrivingStatsLogic'import { ScannerType } from '../types'import { ScannerInsightsChart } from './ScannerInsightsChart'import { ScannerOverviewFilters } from './ScannerOverviewFilters'@@ -193,6 +196,89 @@ function ImpactOverview({ scannerId }: { scannerId: string }): JSX.Element | nul)}+// One stage of the self-driving funnel: a big count over a muted label, matching the panel grid density.+function SelfDrivingStage({ count, label }: { count: number; label: string }): JSX.Element {+ return (+ <div className="flex flex-col">+ <span className="text-lg font-semibold tabular-nums">{count.toLocaleString()}</span>+ <span className="text-xs text-muted">{label}</span>+ </div>+ )+}++function SelfDrivingOverview({ scannerId }: { scannerId: string }): JSX.Element {+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))+ const { selfDrivingStats, selfDrivingStatsLoading } = useValues(scannerSelfDrivingStatsLogic({ scannerId }))++ // Unresolved data renders as loading, never as the off-state nudge or the empty state.+ if (!scanner || (selfDrivingStatsLoading && !selfDrivingStats)) {+ return (+ <OverviewPanel title="Self-driving">+ <PanelEmpty loading message="" />+ </OverviewPanel>+ )+ }+ // Historical signals from before the toggle was turned off still count, so the off-state+ // nudge only replaces the funnel when there is nothing to show.+ if (!scanner.emits_signals && (!selfDrivingStats || selfDrivingStats.signals_emitted === 0)) {+ return (+ <OverviewPanel title="Self-driving" disabled>+ <div className="text-muted text-sm">+ This scanner doesn't emit signals. Turn on self-driving in the{' '}+ <Link to={urls.replayVisionScannerConfigure(scannerId)}>scanner's configuration</Link> to feed its+ findings into Signals, where agents investigate and draft pull requests.+ </div>+ </OverviewPanel>+ )+ }+ if (!selfDrivingStats || selfDrivingStats.signals_emitted === 0) {+ return (+ <OverviewPanel title="Self-driving">+ <PanelEmpty+ loading={selfDrivingStatsLoading}+ message={+ selfDrivingStats+ ? 'No signals emitted yet. Findings flow into Signals as sessions are scanned.'+ : "Couldn't load self-driving stats."+ }+ />+ </OverviewPanel>+ )+ }+ return (+ <OverviewPanel title="Self-driving" subtitle="all time">+ {/* Capped so the four stages read as one row on wide screens instead of drifting apart. */}+ <div className="grid grid-cols-4 gap-4 max-w-3xl" data-attr="vision-self-driving-funnel">+ <SelfDrivingStage+ count={selfDrivingStats.signals_emitted}+ label={pluralize(selfDrivingStats.signals_emitted, 'signal emitted', 'signals emitted', false)}+ />+ <SelfDrivingStage+ count={selfDrivingStats.reports_contributed}+ label={pluralize(+ selfDrivingStats.reports_contributed,+ 'report contributed to',+ 'reports contributed to',+ false+ )}+ />+ <SelfDrivingStage+ count={selfDrivingStats.prs_opened}+ label={pluralize(selfDrivingStats.prs_opened, 'PR opened', 'PRs opened', false)}+ />+ <SelfDrivingStage+ count={selfDrivingStats.prs_merged}+ label={pluralize(selfDrivingStats.prs_merged, 'PR merged', 'PRs merged', false)}+ />+ </div>+ <div className="text-xs text-muted">+ A report can combine signals from several scanners and other sources, so these are contributions, not+ sole causes.+ </div>+ </OverviewPanel>+ )+}+function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {const { monitorStats, hasActiveOverviewFilters, overviewStatsApiLoading } = useValues(scannerOverviewLogic({ scannerId })@@ -539,6 +625,7 @@ export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Eleme<div className="flex flex-col gap-4"><ScannerOverviewFilters scannerId={scannerId} />{body}+ <SelfDrivingOverview scannerId={scannerId} /><CreditLimitOverview scannerId={scannerId} /></div>)diff --git a/products/replay_vision/frontend/replay_scanners/scannerSelfDrivingStatsLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerSelfDrivingStatsLogic.tsnew file mode 100644index 000000000000..328ef7191f69--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerSelfDrivingStatsLogic.ts@@ -0,0 +1,56 @@+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { visionScannersSelfDrivingStatsRetrieve } from '../generated/api'+import type { ScannerSelfDrivingStatsApi } from '../generated/api.schemas'++export interface ScannerSelfDrivingStatsLogicProps {+ scannerId: string+}++interface scannerSelfDrivingStatsLogicValues {+ selfDrivingStats: ScannerSelfDrivingStatsApi | null+ selfDrivingStatsLoading: boolean+}++interface scannerSelfDrivingStatsLogicActions {+ loadSelfDrivingStats: () => void+ loadSelfDrivingStatsSuccess: (selfDrivingStats: ScannerSelfDrivingStatsApi | null) => {+ selfDrivingStats: ScannerSelfDrivingStatsApi | null+ }+ loadSelfDrivingStatsFailure: (error: string) => { error: string }+}++export type scannerSelfDrivingStatsLogicType = MakeLogicType<+ scannerSelfDrivingStatsLogicValues,+ scannerSelfDrivingStatsLogicActions,+ ScannerSelfDrivingStatsLogicProps+>++// What self-driving did with this scanner's signals (reports contributed to, PRs opened). Shared by+// the Overview tab's Self-driving panel and the editor's self-driving toggle, hence its own logic.+// Null after a failed load, so both surfaces can tell "couldn't load" from "loaded zeros".+export const scannerSelfDrivingStatsLogic = kea<scannerSelfDrivingStatsLogicType>([+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerSelfDrivingStatsLogic']),+ props({} as ScannerSelfDrivingStatsLogicProps),+ key((props) => props.scannerId),+ loaders(({ props }) => ({+ selfDrivingStats: [+ null as ScannerSelfDrivingStatsApi | null,+ {+ loadSelfDrivingStats: async (): Promise<ScannerSelfDrivingStatsApi | null> => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return null+ }+ return await visionScannersSelfDrivingStatsRetrieve(String(teamId), props.scannerId)+ },+ },+ ],+ })),+ afterMount(({ actions }) => {+ actions.loadSelfDrivingStats()+ }),+])diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 9ec4af9fc459..20ff216bfb0f 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -656,6 +656,9 @@ tools:you're examining. A scanner can observe a given session only once — re-triggering it on a session thatalready has an observation (even a failed or ineligible one) is a no-op and will not produce a fresh scan.requires_ai_consent: true+ vision-scanners-self-driving-stats-retrieve:+ operation: vision_scanners_self_driving_stats_retrieve+ enabled: falsevision-scanners-stats-retrieve:operation: vision_scanners_stats_retrieveenabled: falsediff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex 0763d8d1d1e0..e4e6a6f39b62 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -1,3 +1,4 @@+import uuidimport dataclassesfrom collections.abc import Callable, Sequencefrom datetime import timedelta@@ -19,7 +20,8 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connectfrom products.signals.backend.contracts import SIGNAL_VARIANT_LOOKUP, SignalRemediation-from products.signals.backend.models import SignalSourceConfig+from products.signals.backend.models import SignalReport, SignalSourceConfig+from products.signals.backend.signal_metadata import fetch_signal_stats_for_source_sliceif TYPE_CHECKING:from products.tasks.backend.facade.repo_selection import RepoSelectionResult@@ -586,3 +588,55 @@ def forward_report_discussion_note(scoped_team_ids=scoped_team_ids,api_scopes=api_scopes,)++[email protected](frozen=True)+class SignalSourceSliceOutcomes:+ """What one source slice's signals led to: reports they were grouped into and the PRs off those."""++ signal_count: int+ report_count: int+ pr_count: int+ merged_pr_count: int+++def get_outcomes_for_signal_source_slice(+ *, team: Team, source_product: str, source_type: str, extra_equals: dict[str, str]+) -> SignalSourceSliceOutcomes:+ """Aggregate downstream outcomes for signals of `(source_product, source_type)` narrowed by+ equality on `extra` keys (e.g. Replay Vision's `scanner_id`).++ Reports are counted only if the row still exists for this team and is not soft-deleted; a+ report usually aggregates signals from several sources, so these are contributions, not sole+ causes. PR counts come from the same implementation-PR resolution the inbox uses (latest+ PR-bearing task run per report), deduplicated by URL since reports can share a task's PR.+ """+ from products.signals.backend.implementation_pr import ( # noqa: PLC0415 — keeps the tasks facade off this module's import path+ fetch_implementation_pr_state_for_reports,+ )++ stats = fetch_signal_stats_for_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)+ ]+ prs = fetch_implementation_pr_state_for_reports(report_ids)+ pr_urls = {pr.url for pr in prs.values()}+ merged_pr_urls = {pr.url for pr in prs.values() if pr.merged}+ return SignalSourceSliceOutcomes(+ signal_count=stats.signal_count,+ report_count=len(report_ids),+ pr_count=len(pr_urls),+ merged_pr_count=len(merged_pr_urls),+ )diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.pyindex e02bb7cdf476..66f84246d76d 100644--- a/products/signals/backend/signal_metadata.py+++ b/products/signals/backend/signal_metadata.py@@ -31,6 +31,93 @@ SIGNAL_DOCUMENT_TYPE = "signal"SIGNAL_DOCUMENT_RENDERING = "plain"+def _deduped_signals_subquery(+ *,+ include_embedding: bool = False,+ include_content: bool = True,+ extra_where: str | None = None,+ candidate_document_filter: str | None = None,+) -> str:+ """Build the shared signal dedup subquery with an optional extra document_embeddings filter.++ `candidate_document_filter` bounds the dedup to documents that ever matched the filter, via a+ `document_id IN (SELECT DISTINCT ... WHERE <filter>)` prefilter — so the argMax aggregation runs+ over that slice instead of the team's whole signal history (its memory otherwise scales with the+ team's total signal count). Unlike `extra_where`, the filter selects candidate documents but does+ NOT restrict which versions feed the argMax, so "latest version wins" is preserved and the caller's+ own outer filter stays authoritative. Use it for re-groupable fields like `report_id`; use+ `extra_where` only for fields that are stable across a document's versions (e.g. `source_id`).++ `include_content=False` skips the heavy `content` column for callers that only aggregate metadata.++ Raises ValueError if both extra_where and candidate_document_filter are supplied — they are+ mutually exclusive (the extra_where branch returns early and silently drops candidate_document_filter).+ """+ if extra_where and candidate_document_filter:+ raise ValueError("_deduped_signals_subquery: extra_where and candidate_document_filter are mutually exclusive")+ selected_columns = ["document_id"]+ if include_content:+ selected_columns.append("argMax(content, inserted_at) as content")+ selected_columns.append("argMax(metadata, inserted_at) as metadata")+ if include_embedding:+ selected_columns.append("argMax(embedding, inserted_at) as embedding")+ selected_columns.extend(["argMax(timestamp, inserted_at) as timestamp", "max(inserted_at) as latest_inserted_at"])+ selected_columns_sql = ",\n ".join(selected_columns)++ if extra_where:+ # `extra_where` filters on the raw `metadata` JSON, but this SELECT also exposes+ # `metadata` as an `argMax(...)` alias. HogQL resolves the name in WHERE to that+ # aggregate alias and rejects the query ("aggregate function ... found in WHERE"),+ # so any caller that filtered on `metadata` silently failed. Apply the predicate in+ # a non-aggregating inner scan so it binds to the raw column, then dedupe in the+ # outer aggregate. Pushing the filter down here (vs. the caller's outer query) keeps+ # the dedup scan bounded to the matching rows.+ raw_columns = ["document_id"]+ if include_content:+ raw_columns.append("content")+ raw_columns.append("metadata")+ if include_embedding:+ raw_columns.append("embedding")+ raw_columns.extend(["inserted_at", "timestamp"])+ raw_columns_sql = ",\n ".join(raw_columns)+ return f"""+ SELECT+ {selected_columns_sql}+ FROM (+ SELECT+ {raw_columns_sql}+ FROM document_embeddings+ WHERE model_name = {{model_name}}+ AND product = 'signals'+ AND document_type = 'signal'+ AND {extra_where}+ )+ GROUP BY document_id+ """++ candidate_bound = ""+ if candidate_document_filter:+ candidate_bound = f"""+ AND document_id IN (+ SELECT DISTINCT document_id+ FROM document_embeddings+ WHERE model_name = {{model_name}}+ AND product = 'signals'+ AND document_type = 'signal'+ AND {candidate_document_filter}+ )"""++ return f"""+ SELECT+ {selected_columns_sql}+ FROM document_embeddings+ WHERE model_name = {{model_name}}+ AND product = 'signals'+ AND document_type = 'signal'{candidate_bound}+ GROUP BY document_id+ """++@dataclass(frozen=True)class ReportSignalMeta:"""Per-report signal metadata read off ClickHouse for the inbox list/detail views."""@@ -114,6 +201,68 @@ def fetch_source_products_for_reports(team: Team, report_ids: list[str]) -> dict}+@dataclass(frozen=True)+class SourceSliceSignalStats:+ """Aggregate over the latest versions of a source slice's non-deleted signals."""++ signal_count: int+ report_ids: list[str]+++def fetch_signal_stats_for_source_slice(+ team: Team, *, source_product: str, source_type: str, extra_equals: dict[str, str]+) -> SourceSliceSignalStats:+ """Count non-deleted signals of one source slice and collect the reports they were grouped into.++ A slice is `(source_product, source_type)` narrowed by equality on `extra` keys (e.g. a Replay+ Vision scanner's `scanner_id`). The slice fields are stable across a document's versions, so they+ go through `_deduped_signals_subquery(extra_where=...)`. The report-id set is uncapped: the+ store's 3-month TTL (restated as a timestamp bound so partition pruning applies) already bounds+ it, and a silent cap would make the counts wrong for exactly the busiest slices.+ """+ conditions = [+ "timestamp >= now() - INTERVAL 3 MONTH",+ "JSONExtractString(metadata, 'source_product') = {source_product}",+ "JSONExtractString(metadata, 'source_type') = {source_type}",+ ]+ placeholders: dict[str, ast.Expr] = {+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),+ "source_product": ast.Constant(value=source_product),+ "source_type": ast.Constant(value=source_type),+ }+ for index, (key, value) in enumerate(sorted(extra_equals.items())):+ conditions.append(f"JSONExtractString(metadata, 'extra', {{extra_key_{index}}}) = {{extra_value_{index}}}")+ placeholders[f"extra_key_{index}"] = ast.Constant(value=key)+ placeholders[f"extra_value_{index}"] = ast.Constant(value=value)++ deduped = _deduped_signals_subquery(extra_where=" AND ".join(conditions), include_content=False)+ ch_query = f"""+ SELECT+ count() as signal_count,+ groupUniqArrayIf(report_id, report_id != '') as report_ids+ FROM (+ SELECT+ JSONExtractString(metadata, 'report_id') as report_id,+ JSONExtractBool(metadata, 'deleted') as is_deleted+ FROM ({deduped})+ )+ WHERE NOT is_deleted+ """++ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)+ result = execute_hogql_query(+ query_type="SignalsFetchSignalStatsForSourceSlice",+ query=ch_query,+ team=team,+ placeholders=placeholders,+ )+ rows = result.results or []+ if not rows:+ return SourceSliceSignalStats(signal_count=0, report_ids=[])+ signal_count, report_ids = rows[0]+ return SourceSliceSignalStats(signal_count=signal_count, report_ids=list(report_ids))++@dataclass(frozen=True)class SignalSourceReference:"""A link back to the external issue a report's signal was emitted from."""diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex f49f5dea2d04..680669c0032d 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -24,6 +24,7 @@ from products.signals.backend.signal_metadata import (SIGNAL_DOCUMENT_PRODUCT,SIGNAL_DOCUMENT_RENDERING,SIGNAL_DOCUMENT_TYPE,+ _deduped_signals_subquery,)from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retry@@ -60,85 +61,6 @@ def _ensure_tz_aware(value: Union[datetime, str]) -> datetime:# ----------------------------------------------------------------------------def _deduped_signals_subquery(- *, include_embedding: bool = False, extra_where: str | None = None, candidate_document_filter: str | None = None-) -> str:- """Build the shared signal dedup subquery with an optional extra document_embeddings filter.-- `candidate_document_filter` bounds the dedup to documents that ever matched the filter, via a- `document_id IN (SELECT DISTINCT ... WHERE <filter>)` prefilter — so the argMax aggregation runs- over that slice instead of the team's whole signal history (its memory otherwise scales with the- team's total signal count). Unlike `extra_where`, the filter selects candidate documents but does- NOT restrict which versions feed the argMax, so "latest version wins" is preserved and the caller's- own outer filter stays authoritative. Use it for re-groupable fields like `report_id`; use- `extra_where` only for fields that are stable across a document's versions (e.g. `source_id`).-- Raises ValueError if both extra_where and candidate_document_filter are supplied — they are- mutually exclusive (the extra_where branch returns early and silently drops candidate_document_filter).- """- if extra_where and candidate_document_filter:- raise ValueError("_deduped_signals_subquery: extra_where and candidate_document_filter are mutually exclusive")- selected_columns = [- "document_id",- "argMax(content, inserted_at) as content",- "argMax(metadata, inserted_at) as metadata",- ]- if include_embedding:- selected_columns.append("argMax(embedding, inserted_at) as embedding")- selected_columns.extend(["argMax(timestamp, inserted_at) as timestamp", "max(inserted_at) as latest_inserted_at"])- selected_columns_sql = ",\n ".join(selected_columns)-- if extra_where:- # `extra_where` filters on the raw `metadata` JSON, but this SELECT also exposes- # `metadata` as an `argMax(...)` alias. HogQL resolves the name in WHERE to that- # aggregate alias and rejects the query ("aggregate function ... found in WHERE"),- # so any caller that filtered on `metadata` silently failed. Apply the predicate in- # a non-aggregating inner scan so it binds to the raw column, then dedupe in the- # outer aggregate. Pushing the filter down here (vs. the caller's outer query) keeps- # the dedup scan bounded to the matching rows.- raw_columns = ["document_id", "content", "metadata"]- if include_embedding:- raw_columns.append("embedding")- raw_columns.extend(["inserted_at", "timestamp"])- raw_columns_sql = ",\n ".join(raw_columns)- return f"""- SELECT- {selected_columns_sql}- FROM (- SELECT- {raw_columns_sql}- FROM document_embeddings- WHERE model_name = {{model_name}}- AND product = 'signals'- AND document_type = 'signal'- AND {extra_where}- )- GROUP BY document_id- """-- candidate_bound = ""- if candidate_document_filter:- candidate_bound = f"""- AND document_id IN (- SELECT DISTINCT document_id- FROM document_embeddings- WHERE model_name = {{model_name}}- AND product = 'signals'- AND document_type = 'signal'- AND {candidate_document_filter}- )"""-- return f"""- SELECT- {selected_columns_sql}- FROM document_embeddings- WHERE model_name = {{model_name}}- AND product = 'signals'- AND document_type = 'signal'{candidate_bound}- GROUP BY document_id- """--# Backwards-compatible aliases for callers that import the shared query constants directly._DEDUPED_SIGNALS_SUBQUERY = _deduped_signals_subquery()diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.pyindex dd5096a4520f..9c254016736f 100644--- a/products/signals/backend/test/test_signal_queries.py+++ b/products/signals/backend/test/test_signal_queries.py@@ -1,18 +1,24 @@from __future__ import annotationsimport json+import uuidfrom datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patchfrom 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.implementation_pr import ImplementationPr+from products.signals.backend.models import SignalReportfrom products.signals.backend.signal_metadata import (EMBEDDING_MODEL,ReportSignalMeta,SignalSourceReference,+ fetch_signal_stats_for_source_slice,fetch_source_products_for_reports,fetch_source_references_for_report,)@@ -34,6 +40,7 @@ class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):report_id: str,source_product: str,inserted_at: datetime,+ source_type: str = "some_type",deleted: bool = False,content: str = "the signal content",skill_name: str | None = None,@@ -47,7 +54,7 @@ class _SignalEmbeddingsTestBase(ClickhouseTestMixin, APIBaseTest):metadata: dict = {"report_id": report_id,"source_product": source_product,- "source_type": "some_type",+ "source_type": source_type,"source_id": f"src-{document_id}","deleted": deleted,}@@ -402,3 +409,82 @@ class TestFetchSignalsForReportSync(_SignalEmbeddingsTestBase):signals = fetch_signals_for_report_sync(self.team, "rA")assert [s["content"] for s in signals] == ["new text"]+++class TestFetchSignalStatsForSourceSlice(_SignalEmbeddingsTestBase):+ def test_counts_only_the_slice_and_skips_deleted_latest_versions(self) -> None:+ # Guards the extra_equals pushdown and the argMax dedup: a broken JSON path would leak other+ # scanners' signals into the count, and filtering beside the argMax would raise on the alias.+ self._emit_version(+ document_id="d1", report_id="rA", source_product="errors", inserted_at=self.base, extra={"scanner_id": "sA"}+ )+ self._emit_version(+ document_id="d2", report_id="", source_product="errors", inserted_at=self.base, extra={"scanner_id": "sA"}+ )+ # Latest version deleted: must drop out of the count entirely.+ self._emit_version(+ document_id="d3", report_id="rA", source_product="errors", inserted_at=self.base, extra={"scanner_id": "sA"}+ )+ self._emit_version(+ document_id="d3",+ report_id="rA",+ source_product="errors",+ inserted_at=self.base + timedelta(hours=1),+ deleted=True,+ extra={"scanner_id": "sA"},+ )+ # Other scanner and other source product: outside the slice.+ self._emit_version(+ document_id="d4", report_id="rB", source_product="errors", inserted_at=self.base, extra={"scanner_id": "sB"}+ )+ self._emit_version(+ document_id="d5", report_id="rC", source_product="replay", inserted_at=self.base, extra={"scanner_id": "sA"}+ )+ self._emit_version(+ document_id="d6",+ report_id="rD",+ source_product="errors",+ source_type="other_type",+ inserted_at=self.base,+ extra={"scanner_id": "sA"},+ )++ stats = fetch_signal_stats_for_source_slice(+ self.team, source_product="errors", source_type="some_type", extra_equals={"scanner_id": "sA"}+ )++ assert stats.signal_count == 2+ assert stats.report_ids == ["rA"]+++class TestGetOutcomesForSignalSourceSlice(_SignalEmbeddingsTestBase):+ def test_counts_only_live_reports_and_dedupes_shared_prs(self) -> None:+ # Guards the CH-to-Postgres handoff: malformed ids, missing rows, and soft-deleted reports+ # must not inflate the report count, and two reports sharing a task's PR count it once.+ existing = SignalReport.objects.create(team=self.team, title="report", summary="s")+ sibling = SignalReport.objects.create(team=self.team, title="sibling", summary="s")+ soft_deleted = SignalReport.objects.create(+ team=self.team, title="gone", summary="s", status=SignalReport.Status.DELETED+ )+ for index, report_id in enumerate(+ [str(existing.id), str(sibling.id), str(soft_deleted.id), str(uuid.uuid4()), "not-a-uuid"]+ ):+ self._emit_version(+ document_id=f"d{index}",+ report_id=report_id,+ source_product="errors",+ inserted_at=self.base,+ extra={"scanner_id": "sA"},+ )++ shared_pr = ImplementationPr(url="https://github.com/o/r/pull/1", merged=True)+ with patch(+ "products.signals.backend.implementation_pr.fetch_implementation_pr_state_for_reports",+ return_value={str(existing.id): shared_pr, str(sibling.id): shared_pr},+ ) as mock_prs:+ outcomes = get_outcomes_for_signal_source_slice(+ team=self.team, source_product="errors", source_type="some_type", extra_equals={"scanner_id": "sA"}+ )++ assert outcomes == SignalSourceSliceOutcomes(signal_count=5, report_count=2, pr_count=1, merged_pr_count=1)+ assert sorted(mock_prs.call_args.args[0]) == sorted([str(existing.id), str(sibling.id)])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex db37ef04e101..7f7cd0140ce9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -70851,6 +70851,20 @@ export namespace Schemas {readonly window_days: number;}+ /**+ * Response of GET /vision/scanners/:id/self_driving_stats/.+ */+ export interface ScannerSelfDrivingStats {+ /** Signals this scanner has pushed into the Signals inbox, all time. */+ signals_emitted: number;+ /** Signal reports that include at least one of this scanner's signals. Reports usually aggregate signals from several sources, so this counts contributions, not sole causes. */+ reports_contributed: number;+ /** Implementation PRs opened by self-driving on those reports. */+ prs_opened: number;+ /** Of the opened PRs, how many have merged. */+ prs_merged: number;+ }+/*** Per-scanner-type count of enabled vs total scanners.*/