Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): add ranking-label telemetry for inbox reports (#72132)

Andrew Maguire7e646fafa1cb
diff --git a/frontend/src/scenes/inbox/components/InboxReportList.tsx b/frontend/src/scenes/inbox/components/InboxReportList.tsx
index d3e01d3009e3..45edccdc084f 100644
--- a/frontend/src/scenes/inbox/components/InboxReportList.tsx
+++ b/frontend/src/scenes/inbox/components/InboxReportList.tsx
@@ -3,7 +3,7 @@ import { ComponentType, JSX, useEffect, useRef } from 'react'
import { LemonBanner } from '@posthog/lemon-ui'
-import { captureInboxViewed } from '../inboxAnalytics'
+import { captureInboxReportsImpressed, captureInboxViewed } from '../inboxAnalytics'
import { inboxSceneLogic } from '../inboxSceneLogic'
import { inboxFiltersLogic } from '../logics/inboxFiltersLogic'
import { reportListLogic, ReportListLogicProps } from '../logics/reportListLogic'
@@ -60,14 +60,15 @@ function ActiveFiltersBanner(): JSX.Element | null {
}
function InboxReportListInner({ tabKey, Card, emptyState }: InboxReportListProps): JSX.Element {
- const { reports, count, hasMore, reportsResponseLoading, isLoaded } = useValues(reportListLogic)
+ const { reports, count, totalCount, hasMore, reportsResponseLoading, isLoaded, loadedQueryKey, loadedContext } =
+ useValues(reportListLogic)
const { ensureLoaded, loadMore, archiveReport, restoreReport, refresh } = useActions(reportListLogic)
const { hasActiveFilters, sourceProductFilter, priorityFilter, scope } = useValues(inboxFiltersLogic)
// The list stays mounted (hidden) while a report/scout detail is open, so gate the view event on
// the list actually being the visible surface — otherwise a deep-link to a report fires a phantom
// `Inbox viewed` and then suppresses the real one when the user navigates back to the list.
- const { selectedReportId, selectedScoutSkillName, isScratchpadOpen } = useValues(inboxSceneLogic)
- const listVisible = !selectedReportId && !selectedScoutSkillName && !isScratchpadOpen
+ const { selectedReportId, selectedScoutSkillName, isScratchpadOpen, isFindingsOpen } = useValues(inboxSceneLogic)
+ const listVisible = !selectedReportId && !selectedScoutSkillName && !isScratchpadOpen && !isFindingsOpen
const sentinelRef = useRef<HTMLDivElement>(null)
// Fire `Inbox viewed` once per tab mount, the first time its list settles while visible.
@@ -87,6 +88,45 @@ function InboxReportListInner({ tabKey, Card, emptyState }: InboxReportListProps
}
}, [listVisible, isLoaded, count, reports, tabKey, hasActiveFilters, sourceProductFilter, priorityFilter, scope])
+ // Impression log for ranking-model training: record each report the first time it appears in
+ // the visible list (initial page, pagination, refresh), with its rank at that moment. Deduped
+ // per tab mount so re-renders and detail-pane round-trips don't refire.
+ const impressedIdsRef = useRef(new Set<string>())
+ // Dedupe is per query: a sort/search/filter/scope change is a new ranking context, so a report
+ // re-shown under the new query must impress again (at its new rank) for its later open/action
+ // events to have a matching impression.
+ const impressionQueryKeyRef = useRef('')
+ useEffect(() => {
+ // totalCount, loadedQueryKey, and loadedContext come from the same response as `reports`
+ // (not the live filter state or the separately-loaded badge count), so impressions can't
+ // be stamped with a stale total or with scope/filter context the user switched to after
+ // the request went out, and rows from the previous query are never attributed to the new
+ // one while its refetch is still in flight.
+ if (!listVisible || !isLoaded || totalCount === null || loadedQueryKey === null || loadedContext === null) {
+ return
+ }
+ if (loadedQueryKey !== impressionQueryKeyRef.current) {
+ impressionQueryKeyRef.current = loadedQueryKey
+ impressedIdsRef.current = new Set<string>()
+ }
+ const fresh = reports
+ .map((report, index) => ({ report, rank: index + 1 }))
+ .filter(({ report }) => !impressedIdsRef.current.has(report.id))
+ if (fresh.length === 0) {
+ return
+ }
+ fresh.forEach(({ report }) => impressedIdsRef.current.add(report.id))
+ captureInboxReportsImpressed({
+ tab: tabKey,
+ reports: fresh.map(({ report }) => report),
+ ranks: fresh.map(({ rank }) => rank),
+ listSize: reports.length,
+ totalCount,
+ hasActiveFilters: loadedContext.hasActiveFilters,
+ scope: loadedContext.scope,
+ })
+ }, [listVisible, isLoaded, totalCount, reports, tabKey, loadedQueryKey, loadedContext])
+
// Read fresh state at intersection time via refs so the observer is created once and not
// rebuilt twice per page fetch (`hasMore`/`reportsResponseLoading` both flip during a load).
const hasMoreRef = useRef(hasMore)
diff --git a/frontend/src/scenes/inbox/inboxAnalytics.test.ts b/frontend/src/scenes/inbox/inboxAnalytics.test.ts
index aeae2e4181c4..022aa585ff67 100644
--- a/frontend/src/scenes/inbox/inboxAnalytics.test.ts
+++ b/frontend/src/scenes/inbox/inboxAnalytics.test.ts
@@ -2,6 +2,7 @@ import posthog from 'posthog-js'
import {
captureInboxReportAction,
+ captureInboxReportsImpressed,
captureInboxViewed,
captureSignalSourceConnected,
INBOX_EVENTS,
@@ -82,6 +83,44 @@ describe('inboxAnalytics', () => {
})
})
+ it('logs one impression per shown report with its rank and render-time snapshot', () => {
+ captureInboxReportsImpressed({
+ tab: 'reports',
+ reports: [
+ makeReport({ id: 'a', priority: 'P0', signal_count: 3, is_suggested_reviewer: true }),
+ makeReport({ id: 'b', priority: null, actionability: null, source_products: ['error_tracking'] }),
+ ],
+ ranks: [1, 2],
+ listSize: 2,
+ totalCount: 10,
+ hasActiveFilters: false,
+ scope: 'for-you',
+ })
+ const props = lastCapture(INBOX_EVENTS.REPORTS_IMPRESSED)
+ expect(props).toMatchObject({
+ tab: 'reports',
+ list_size: 2,
+ total_count: 10,
+ impression_count: 2,
+ })
+ expect(props?.impressions).toEqual([
+ expect.objectContaining({
+ report_id: 'a',
+ rank: 1,
+ priority: 'P0',
+ signal_count: 3,
+ is_suggested_reviewer: true,
+ }),
+ expect.objectContaining({
+ report_id: 'b',
+ rank: 2,
+ priority: null,
+ actionability: null,
+ source_products: ['error_tracking'],
+ }),
+ ])
+ })
+
it('emits a single-report action with the report context', () => {
captureInboxReportAction({
report: makeReport(),
diff --git a/frontend/src/scenes/inbox/inboxAnalytics.ts b/frontend/src/scenes/inbox/inboxAnalytics.ts
index f6e10f01a5ea..3189f0c76163 100644
--- a/frontend/src/scenes/inbox/inboxAnalytics.ts
+++ b/frontend/src/scenes/inbox/inboxAnalytics.ts
@@ -14,6 +14,7 @@ export const INBOX_CLIENT = 'cloud' as const
export const INBOX_EVENTS = {
VIEWED: 'Inbox viewed',
+ REPORTS_IMPRESSED: 'Inbox reports impressed',
REPORT_OPENED: 'Inbox report opened',
REPORT_CLOSED: 'Inbox report closed',
REPORT_ACTION: 'Inbox report action',
@@ -136,6 +137,43 @@ export function captureInboxViewed(params: {
})
}
+/**
+ * Impression log for the report list: which reports were shown, at what rank, with the
+ * classification each carried at render time. This is the negative class (and position record)
+ * for ranking-model training — `Inbox report opened` alone only records the clicked report.
+ * Fired with the newly-shown reports each time the visible list grows (first page, pagination,
+ * refresh), never twice for the same report within a tab mount.
+ */
+export function captureInboxReportsImpressed(params: {
+ tab: string
+ /** Only the newly-impressed reports, in list order. */
+ reports: SignalReport[]
+ /** 1-based rank of each impressed report in the full loaded list, parallel to `reports`. */
+ ranks: number[]
+ listSize: number
+ totalCount: number | null
+ hasActiveFilters: boolean
+ scope: string
+}): void {
+ captureInboxEvent(INBOX_EVENTS.REPORTS_IMPRESSED, {
+ tab: params.tab,
+ list_size: params.listSize,
+ total_count: params.totalCount,
+ has_active_filters: params.hasActiveFilters,
+ scope: params.scope,
+ impression_count: params.reports.length,
+ impressions: params.reports.map((report, index) => ({
+ ...baseReportProperties(report),
+ rank: params.ranks[index],
+ status: report.status ?? null,
+ source_products: report.source_products ?? [],
+ signal_count: report.signal_count,
+ total_weight: report.total_weight,
+ is_suggested_reviewer: report.is_suggested_reviewer,
+ })),
+ })
+}
+
export function captureInboxReportOpened(params: {
report: SignalReport
openMethod: InboxReportOpenMethod
diff --git a/frontend/src/scenes/inbox/logics/reportListLogic.ts b/frontend/src/scenes/inbox/logics/reportListLogic.ts
index 46d32e2a95b6..5028342495dc 100644
--- a/frontend/src/scenes/inbox/logics/reportListLogic.ts
+++ b/frontend/src/scenes/inbox/logics/reportListLogic.ts
@@ -27,6 +27,12 @@ const PAGE_SIZE = 50
/** Fixed, tab-defining server filter (e.g. `{ has_implementation_pr: 'true' }`). */
export type ReportListParams = Record<string, string>
+/** A list response stamped with the query params and display context that produced it (see the loader). */
+export type ReportListResponse = CountedPaginatedResponse<SignalReport> & {
+ requestParams?: Record<string, unknown>
+ requestContext?: { scope: InboxScope; hasActiveFilters: boolean }
+}
+
export interface ReportListLogicProps {
tabKey: InboxFlatListTabKey
/** The tab's fixed server filter. User-driven chrome (search/sort/source/priority/scope) is layered on top. */
@@ -54,6 +60,22 @@ function teammateUuidFromScope(scope: string): string | undefined {
return scope.startsWith('teammate:') ? scope.slice('teammate:'.length).trim() || undefined : undefined
}
+/** Display context at request time, stamped onto the response for telemetry (mirrors `hasActiveFilters`). */
+function requestContextFromValues(values: {
+ scope: InboxScope
+ searchQuery: string
+ sourceProductFilter: string[]
+ priorityFilter: SignalReportPriority[]
+}): { scope: InboxScope; hasActiveFilters: boolean } {
+ return {
+ scope: values.scope,
+ hasActiveFilters:
+ values.searchQuery.trim().length > 0 ||
+ values.sourceProductFilter.length > 0 ||
+ values.priorityFilter.length > 0,
+ }
+}
+
/**
* Whether to auto-switch the reviewer scope to Entire project on first load. True only for the
* Pull requests tab when the user is still on the (default) For-you scope, hasn't chosen a scope
@@ -92,9 +114,15 @@ export interface reportListLogicValues {
hasMore: boolean
isLoaded: boolean
listApiParams: any
+ loadedContext: {
+ hasActiveFilters: boolean
+ scope: InboxScope
+ } | null
+ loadedQueryKey: string | null
reports: SignalReport[]
- reportsResponse: CountedPaginatedResponse<SignalReport> | null
+ reportsResponse: ReportListResponse | null
reportsResponseLoading: boolean
+ totalCount: number | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -172,20 +200,10 @@ export interface reportListLogicActions {
errorObject?: any
}
loadMoreReportsSuccess: (
- reportsResponse: {
- count: number
- next?: string | null | undefined
- previous?: string | null | undefined
- results: SignalReport[]
- },
+ reportsResponse: ReportListResponse,
payload?: any
) => {
- reportsResponse: {
- count: number
- next?: string | null | undefined
- previous?: string | null | undefined
- results: SignalReport[]
- }
+ reportsResponse: ReportListResponse
payload?: any
}
loadReports: () => any
@@ -197,10 +215,10 @@ export interface reportListLogicActions {
errorObject?: any
}
loadReportsSuccess: (
- reportsResponse: CountedPaginatedResponse<SignalReport>,
+ reportsResponse: ReportListResponse,
payload?: any
) => {
- reportsResponse: CountedPaginatedResponse<SignalReport>
+ reportsResponse: ReportListResponse
payload?: any
}
refresh: () => {
@@ -228,9 +246,15 @@ export interface reportListLogicMeta {
user: UserType | null,
arg: any
) => any
- reports: (reportsResponse: CountedPaginatedResponse<SignalReport> | null) => SignalReport[]
- hasMore: (reportsResponse: CountedPaginatedResponse<SignalReport> | null) => boolean
- isLoaded: (reportsResponse: CountedPaginatedResponse<SignalReport> | null) => boolean
+ reports: (reportsResponse: ReportListResponse | null) => SignalReport[]
+ hasMore: (reportsResponse: ReportListResponse | null) => boolean
+ isLoaded: (reportsResponse: ReportListResponse | null) => boolean
+ totalCount: (reportsResponse: ReportListResponse | null) => number | null
+ loadedQueryKey: (reportsResponse: ReportListResponse | null) => string | null
+ loadedContext: (reportsResponse: ReportListResponse | null) => {
+ hasActiveFilters: boolean
+ scope: InboxScope
+ } | null
}
}
@@ -306,19 +330,32 @@ export const reportListLogic = kea<reportListLogicType>([
},
],
reportsResponse: [
- null as CountedPaginatedResponse<SignalReport> | null,
+ null as ReportListResponse | null,
{
- loadReports: async () => {
- return await api.signalReports.list({ ...values.listApiParams, offset: 0, limit: PAGE_SIZE })
+ // `requestParams` records the query that produced the response, so consumers
+ // (impression telemetry) can key off what was actually fetched rather than the
+ // live `listApiParams`, which changes before the refetch lands.
+ loadReports: async (): Promise<ReportListResponse> => {
+ const params = values.listApiParams
+ const requestContext = requestContextFromValues(values)
+ const response = await api.signalReports.list({ ...params, offset: 0, limit: PAGE_SIZE })
+ return { ...response, requestParams: params, requestContext }
},
- loadMoreReports: async () => {
+ loadMoreReports: async (): Promise<ReportListResponse> => {
+ const params = values.listApiParams
+ const requestContext = requestContextFromValues(values)
const current = values.reportsResponse?.results ?? []
const response = await api.signalReports.list({
- ...values.listApiParams,
+ ...params,
offset: current.length,
limit: PAGE_SIZE,
})
- return { ...response, results: [...current, ...response.results] }
+ return {
+ ...response,
+ results: [...current, ...response.results],
+ requestParams: params,
+ requestContext,
+ }
},
},
],
@@ -378,17 +415,38 @@ export const reportListLogic = kea<reportListLogicType>([
],
reports: [
(s) => [s.reportsResponse],
- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): SignalReport[] =>
- reportsResponse?.results ?? [],
+ (reportsResponse: ReportListResponse | null): SignalReport[] => reportsResponse?.results ?? [],
],
hasMore: [
(s) => [s.reportsResponse],
- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): boolean =>
+ (reportsResponse: ReportListResponse | null): boolean =>
reportsResponse?.next !== null && reportsResponse?.next !== undefined,
],
isLoaded: [
(s) => [s.reportsResponse],
- (reportsResponse: CountedPaginatedResponse<SignalReport> | null): boolean => reportsResponse !== null,
+ (reportsResponse: ReportListResponse | null): boolean => reportsResponse !== null,
+ ],
+ // Total matching the *loaded* results — from the same response, so it can never be stale
+ // relative to `reports` the way the separately-loaded badge `count` can (filter/refresh races).
+ totalCount: [
+ (s) => [s.reportsResponse],
+ (reportsResponse: ReportListResponse | null): number | null => reportsResponse?.count ?? null,
+ ],
+ // Stable key for the query that produced the loaded response. Unlike `listApiParams`, this
+ // only changes when a response fetched with the new params actually lands, so consumers
+ // never associate the new query with rows from the previous one.
+ loadedQueryKey: [
+ (s) => [s.reportsResponse],
+ (reportsResponse: ReportListResponse | null): string | null =>
+ reportsResponse?.requestParams ? JSON.stringify(reportsResponse.requestParams) : null,
+ ],
+ // Display context (scope, active-filters flag) as it was when the loaded response was
+ // requested — for telemetry, so an in-flight response can't be labeled with context the
+ // user switched to after the request went out.
+ loadedContext: [
+ (s) => [s.reportsResponse],
+ (reportsResponse: ReportListResponse | null): { scope: InboxScope; hasActiveFilters: boolean } | null =>
+ reportsResponse?.requestContext ?? null,
],
}),
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index 10bfb9658e01..9f0b672443cf 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -179,6 +179,7 @@ post_save:products.feature_flags.backend.local_evaluation.experiment_changed
post_save:products.feature_flags.backend.local_evaluation.feature_flag_changed
post_save:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updates
post_save:products.review_hog.backend.receivers.handle_task_run_saved
+post_save:products.signals.backend.receivers.capture_status_change_analytics
post_save:products.signals.backend.receivers.close_pr_when_report_dismissed
post_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
post_save:products.slack_app.backend.signals.onboard_slack_inbox_on_install
@@ -220,7 +221,7 @@ pre_save:products.conversations.backend.signals.handle_comment_soft_delete
pre_save:products.customer_analytics.backend.models.account._enforce_account_group_type_index_drift_policy
pre_save:products.event_definitions.backend.models.event_definition._capture_event_definition_old_name
pre_save:products.feature_flags.backend.flag_version_sync.capture_cohort_definition_before_save
-pre_save:products.signals.backend.receivers.capture_prior_status_for_pr_close
+pre_save:products.signals.backend.receivers.capture_prior_status
pre_save:products.surveys.backend.models.pre_save_survey
user_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activity
user_logged_in:posthog.models.activity_logging.signal_handlers.post_login
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index eb1dc2dca8ea..16c2a3f7a956 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -4,38 +4,48 @@ Kept in one place so cross-cutting side effects of report state changes have a s
rather than being sprinkled across every dismissal entrypoint (Slack, REST, bulk, …).
"""
+import json
+from datetime import datetime, timedelta
from typing import Any
from django.db import transaction
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
+from django.utils import timezone
+
+import structlog
+import posthoganalytics
+
+from posthog.event_usage import groups
from products.signals.backend.implementation_pr import PrCloseReason
-from products.signals.backend.models import SignalReport
+from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.tasks import close_dismissed_report_pr
+logger = structlog.get_logger(__name__)
+
_SNOOZE_SOURCE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.RESOLVED})
@receiver(pre_save, sender=SignalReport)
-def capture_prior_status_for_pr_close(
+def capture_prior_status(
sender: type[SignalReport],
instance: SignalReport,
**kwargs: Any,
) -> None:
- """Stash the row's prior status so post_save can tell a real transition from a no-op edit."""
+ """Stash the row's prior status so post_save receivers can tell a real transition from a no-op edit."""
# UUIDModel PKs carry a Python-side default, so pk is set at construction, never None — use
# _state.adding to tell an unsaved row (no prior status) from an update.
if instance._state.adding:
- instance._prior_status_for_pr_close = None # type: ignore[attr-defined]
+ instance._prior_status = None # type: ignore[attr-defined]
return
update_fields = kwargs.get("update_fields")
if update_fields is not None and "status" not in update_fields:
- instance._prior_status_for_pr_close = None # type: ignore[attr-defined]
+ instance._prior_status = None # type: ignore[attr-defined]
return
- instance._prior_status_for_pr_close = sender.objects.filter(pk=instance.pk).values_list("status", flat=True).first() # type: ignore[attr-defined]
+ instance._prior_status = sender.objects.filter(pk=instance.pk).values_list("status", flat=True).first() # type: ignore[attr-defined]
def _pr_close_reason(
@@ -78,7 +88,7 @@ def close_pr_when_report_dismissed(
to SUPPRESSED, and snoozing a ready/resolved report ends in READY/RESOLVED → POTENTIAL, so
hooking the model here covers them all without each caller opting in.
"""
- prior_status = getattr(instance, "_prior_status_for_pr_close", None)
+ prior_status = getattr(instance, "_prior_status", None)
reason = _pr_close_reason(
instance,
created=created,
@@ -98,3 +108,147 @@ def close_pr_when_report_dismissed(
reason=reason,
)
)
+
+
+@receiver(post_save, sender=SignalReport)
+def capture_status_change_analytics(
+ sender: type[SignalReport],
+ instance: SignalReport,
+ created: bool,
+ update_fields: set[str] | None = None,
+ **kwargs: Any,
+) -> None:
+ """Emit `signal_report_status_changed` for every real status transition.
+
+ This is the server-side label stream for the inbox ranking model: every transition surface
+ (REST state/bulk-state, Slack dismissal, the pipeline, PR-merge resolution in the tasks
+ webhook) ends in a ``save`` that flips status, so hooking the model here yields one complete,
+ client-independent record of outcomes (resolved / suppressed / snoozed / …) per report.
+ """
+ if created:
+ return
+ if update_fields is not None and "status" not in update_fields:
+ return
+ prior_status = getattr(instance, "_prior_status", None)
+ if prior_status is None or prior_status == instance.status:
+ return
+
+ # Snapshot now — the instance may be mutated again before the commit callback runs.
+ properties = {
+ "team_id": instance.team_id,
+ "report_id": str(instance.id),
+ "previous_status": prior_status,
+ "status": instance.status,
+ "signal_count": instance.signal_count,
+ "total_weight": instance.total_weight,
+ "run_count": instance.run_count,
+ "report_created_at": instance.created_at.isoformat() if instance.created_at else None,
+ "promoted_at": instance.promoted_at.isoformat() if instance.promoted_at else None,
+ }
+ report_id = str(instance.id)
+ new_status = instance.status
+ team = instance.team
+ transition_at = timezone.now()
+
+ def _capture() -> None:
+ try:
+ # A single transaction can save the report through several statuses (e.g. ready →
+ # candidate on re-promotion in mark_report_ready_activity), queuing one callback per
+ # intermediate snapshot. Only the transition matching the durable, committed status
+ # emits — transient intermediate labels would corrupt the training stream. The skipped
+ # callback stashes its prior status on the shared instance so the emitting one reports
+ # the committed transition (in_progress → candidate), not a phantom hop through a
+ # state that never committed (ready → candidate).
+ current_status = sender.objects.filter(pk=instance.pk).values_list("status", flat=True).first()
+ if current_status != new_status:
+ if getattr(instance, "_collapsed_prior_status", None) is None:
+ instance._collapsed_prior_status = properties["previous_status"] # type: ignore[attr-defined]
+ return
+ collapsed_prior = getattr(instance, "_collapsed_prior_status", None)
+ instance._collapsed_prior_status = None # type: ignore[attr-defined]
+ previous_status = collapsed_prior or properties["previous_status"]
+ posthoganalytics.capture(
+ event="signal_report_status_changed",
+ distinct_id=str(team.uuid),
+ properties={
+ **properties,
+ "previous_status": previous_status,
+ **_classification_snapshot(
+ report_id,
+ include_dismissal=_is_dismissal_transition(previous_status, new_status),
+ transition_at=transition_at,
+ ),
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ # Analytics must never break the transition that triggered it.
+ logger.exception("Failed to capture signal_report_status_changed", report_id=report_id)
+
+ # After commit so a rolled-back transition never emits a phantom label. Post-commit also means
+ # artefacts written in the same transaction (e.g. the dismissal) are visible to the snapshot.
+ transaction.on_commit(_capture)
+
+
+# Latest-wins artefact values snapshotted onto `signal_report_status_changed`. Captured with the
+# event because artefacts can be re-judged or edited later — a training join by report_id after
+# the fact could otherwise see different values than existed when the transition happened.
+_SNAPSHOT_ARTEFACT_FIELDS = [
+ (SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, "priority", "priority"),
+ (SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, "actionability", "actionability"),
+ (SignalReportArtefact.ArtefactType.DISMISSAL, "reason", "dismissal_reason"),
+]
+
+
+def _is_dismissal_transition(previous_status: str, new_status: str) -> bool:
+ """Whether this transition is one the state API writes dismissal feedback for: a dismissal
+ (into suppressed) or a snooze (researched report back to potential)."""
+ return new_status == SignalReport.Status.SUPPRESSED or (
+ new_status == SignalReport.Status.POTENTIAL and previous_status in _SNOOZE_SOURCE_STATUSES
+ )
+
+
+# A dismissal artefact only counts as this transition's feedback if it was written around the
+# transition itself (same request/transaction). Generous so request ordering and clock skew never
+# exclude genuine feedback; a dismiss → restore → re-dismiss inside one minute is the only
+# (negligible) false-inclusion window.
+_DISMISSAL_FRESHNESS = timedelta(minutes=1)
+
+
+def _classification_snapshot(
+ report_id: str, *, include_dismissal: bool, transition_at: datetime
+) -> dict[str, str | None]:
+ # One DISTINCT ON query for all three types: the bulk-state endpoint can transition up to 100
+ # reports in a request, and each one's post-commit callback takes this path before the
+ # response returns, so per-type queries would multiply into hundreds.
+ latest_by_type = {
+ row[0]: (row[1], row[2])
+ for row in SignalReportArtefact.objects.filter(
+ report_id=report_id, type__in=[artefact_type for artefact_type, _, _ in _SNAPSHOT_ARTEFACT_FIELDS]
+ )
+ .order_by("type", "-created_at")
+ .distinct("type")
+ .values_list("type", "content", "created_at")
+ }
+ snapshot: dict[str, str | None] = {}
+ for artefact_type, content_key, prop in _SNAPSHOT_ARTEFACT_FIELDS:
+ content, created_at = latest_by_type.get(artefact_type, (None, None))
+ # Dismissal artefacts are append-only and never cleared, and the state API only writes one
+ # when the user actually gave feedback — so a stale reason from an earlier dismissal must
+ # not ride along on later transitions (including feedback-less re-dismissals). Only a
+ # dismissal/snooze label whose feedback was written as part of this transition includes it.
+ if artefact_type == SignalReportArtefact.ArtefactType.DISMISSAL and (
+ not include_dismissal or created_at is None or created_at < transition_at - _DISMISSAL_FRESHNESS
+ ):
+ snapshot[prop] = None
+ continue
+ value = None
+ if content:
+ try:
+ data = json.loads(content)
+ if isinstance(data, dict):
+ value = data.get(content_key)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ value = None
+ snapshot[prop] = value if isinstance(value, str) else None
+ return snapshot
diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.py
index ba6a6a010fcb..a19804b948cb 100644
--- a/products/signals/backend/test/test_assign_and_emit_signal.py
+++ b/products/signals/backend/test/test_assign_and_emit_signal.py
@@ -517,7 +517,13 @@ async def test_reresearch_within_cap_does_not_emit_skipped_event(ateam, patch_si
await assign_and_emit_signal_activity(input_)
- events = [call.kwargs["event"] for call in patch_side_effects["capture"].call_args_list]
+ # The model-level signal_report_status_changed label (READY -> CANDIDATE re-promotion) rides
+ # the same analytics client; this test asserts the pipeline's own telemetry only.
+ events = [
+ call.kwargs["event"]
+ for call in patch_side_effects["capture"].call_args_list
+ if call.kwargs["event"] != "signal_report_status_changed"
+ ]
assert events == ["signal_assigned_to_report"]
diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.py
index 6bea39f86b3a..9618fe86e45b 100644
--- a/products/signals/backend/test/test_report_telemetry.py
+++ b/products/signals/backend/test/test_report_telemetry.py
@@ -53,7 +53,9 @@ async def test_started_and_ready_fire_expected_captures(ateam):
)
)
- events = [call.kwargs for call in capture.call_args_list]
+ # Model-level signal_report_status_changed labels ride the same analytics client; this test
+ # asserts the pipeline's own telemetry only.
+ events = [call.kwargs for call in capture.call_args_list if call.kwargs["event"] != "signal_report_status_changed"]
assert [e["event"] for e in events] == ["signal_report_started", "signal_report_completed"]
for e in events:
assert e["distinct_id"] == str(ateam.uuid)
@@ -89,8 +91,9 @@ async def test_failed_fires_completed_with_failure_reason(ateam):
)
)
- capture.assert_called_once()
- kwargs = capture.call_args.kwargs
+ pipeline_calls = [call for call in capture.call_args_list if call.kwargs["event"] != "signal_report_status_changed"]
+ assert len(pipeline_calls) == 1
+ kwargs = pipeline_calls[0].kwargs
assert kwargs["event"] == "signal_report_completed"
assert kwargs["properties"]["result"] == "failed"
assert kwargs["properties"]["failure_reason"] == "safety_judge_rejected"
diff --git a/products/signals/backend/test/test_status_change_telemetry.py b/products/signals/backend/test/test_status_change_telemetry.py
new file mode 100644
index 000000000000..2cf8560616a1
--- /dev/null
+++ b/products/signals/backend/test/test_status_change_telemetry.py
@@ -0,0 +1,122 @@
+import json
+from datetime import timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import transaction
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+
+class TestCaptureStatusChangeAnalytics(BaseTest):
+ """The post_save receiver is the server-side label stream for the inbox ranking model:
+ it must fire exactly once per real status transition, from any surface, and never on
+ creations or unrelated edits."""
+
+ def _create_report(self, report_status=SignalReport.Status.READY) -> SignalReport:
+ return SignalReport.objects.create(
+ team=self.team,
+ status=report_status,
+ title="Test report",
+ summary="Test summary",
+ signal_count=3,
+ total_weight=2.5,
+ )
+
+ @parameterized.expand(
+ [
+ ("dismiss", SignalReport.Status.READY, SignalReport.Status.SUPPRESSED, {}),
+ ("resolve_on_pr_merge", SignalReport.Status.READY, SignalReport.Status.RESOLVED, {}),
+ ("snooze", SignalReport.Status.READY, SignalReport.Status.POTENTIAL, {"snooze_for": 5}),
+ ]
+ )
+ def test_transition_emits_label_event_with_previous_and_new_status(
+ self, _name, source_status, new_status, transition_kwargs
+ ):
+ report = self._create_report(report_status=source_status)
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ updated = report.transition_to(new_status, **transition_kwargs)
+ report.save(update_fields=updated)
+ assert mock_capture.call_count == 1
+ kwargs = mock_capture.call_args.kwargs
+ assert kwargs["event"] == "signal_report_status_changed"
+ assert kwargs["distinct_id"] == str(self.team.uuid)
+ assert kwargs["properties"]["report_id"] == str(report.id)
+ assert kwargs["properties"]["previous_status"] == source_status
+ assert kwargs["properties"]["status"] == new_status
+ assert kwargs["properties"]["signal_count"] == 3
+ assert kwargs["properties"]["total_weight"] == 2.5
+
+ @parameterized.expand(
+ [
+ ("dismissal_includes_fresh_reason", SignalReport.Status.SUPPRESSED, False, "wontfix_irrelevant"),
+ # Dismissal artefacts are append-only, so an old reason must not leak onto later
+ # non-dismissal transitions (e.g. a restored report getting resolved)...
+ ("non_dismissal_excludes_reason", SignalReport.Status.RESOLVED, False, None),
+ # ...nor onto a later feedback-less dismissal (the state API only writes a new
+ # dismissal artefact when the user actually gave a reason or note).
+ ("stale_reason_excluded_from_new_dismissal", SignalReport.Status.SUPPRESSED, True, None),
+ ]
+ )
+ def test_label_snapshots_latest_classification_artefacts(
+ self, _name, new_status, backdate_dismissal, expected_dismissal_reason
+ ):
+ report = self._create_report()
+ for artefact_type, content in [
+ (SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT, {"priority": "P1"}),
+ (SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT, {"actionability": "immediately_actionable"}),
+ (SignalReportArtefact.ArtefactType.DISMISSAL, {"reason": "wontfix_irrelevant"}),
+ ]:
+ SignalReportArtefact.objects.create(
+ team=self.team, report=report, type=artefact_type, content=json.dumps(content)
+ )
+ if backdate_dismissal:
+ SignalReportArtefact.objects.filter(report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL).update(
+ created_at=timezone.now() - timedelta(hours=1)
+ )
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ updated = report.transition_to(new_status)
+ report.save(update_fields=updated)
+ props = mock_capture.call_args.kwargs["properties"]
+ assert props["priority"] == "P1"
+ assert props["actionability"] == "immediately_actionable"
+ assert props["dismissal_reason"] == expected_dismissal_reason
+
+ def test_transient_intermediate_transition_in_one_transaction_is_collapsed(self):
+ report = self._create_report(report_status=SignalReport.Status.IN_PROGRESS)
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ with transaction.atomic():
+ report.save(update_fields=report.transition_to(SignalReport.Status.READY, title="t", summary="s"))
+ report.save(update_fields=report.transition_to(SignalReport.Status.CANDIDATE))
+ assert mock_capture.call_count == 1
+ props = mock_capture.call_args.kwargs["properties"]
+ # The committed transition, not a phantom hop through the never-committed READY state.
+ assert props["previous_status"] == SignalReport.Status.IN_PROGRESS
+ assert props["status"] == SignalReport.Status.CANDIDATE
+
+ @parameterized.expand(
+ [
+ ("full_save_without_status_change", SignalReport.Status.READY, None),
+ ("update_fields_without_status", SignalReport.Status.READY, ["title"]),
+ ]
+ )
+ def test_non_transition_save_does_not_emit(self, _name, report_status, update_fields):
+ report = self._create_report(report_status=report_status)
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ report.title = "edited"
+ report.save(update_fields=update_fields)
+ mock_capture.assert_not_called()
+
+ def test_report_creation_does_not_emit(self):
+ with patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture:
+ with self.captureOnCommitCallbacks(execute=True):
+ self._create_report()
+ mock_capture.assert_not_called()