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): emit inbox ranking labels from the today home (#114707)

posthog[bot]b65fc5dcb1c2
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
index 675987a41f5f..6fa627469fba 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.test.ts
@@ -1,5 +1,6 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -253,6 +254,61 @@ describe('todayLogic', () => {
expect(logic.values.briefingItems[0].state).toEqual(finalState)
})
+ it('sends the Inbox ranking label events for the reports the home shows and acts on', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ briefingResponses = [[200, makeBriefing()]]
+ const logic = todayLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ // A reload of the same briefing does not impress its reports again.
+ logic.actions.loadPersonalBriefing()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.itemOpened(logic.values.briefingItems[0], 'sidebar')
+ logic.actions.setReportVerdict(
+ { reportId: 'a', title: 'Signup form rejects emails', hasOpenPullRequest: false },
+ 'dismiss',
+ 'report_page'
+ )
+ logic.actions.leaveReportReview('a', 'sidebar')
+ await expectLogic(logic).toFinishAllListeners()
+
+ const inboxEvents = capture.mock.calls.filter(([event]) => event.startsWith('Inbox '))
+ expect(inboxEvents).toHaveLength(4)
+ expect(inboxEvents).toEqual(
+ expect.arrayContaining([
+ [
+ 'Inbox reports impressed',
+ expect.objectContaining({
+ surface: 'today',
+ list: 'briefing',
+ impressions: [expect.objectContaining({ report_id: 'a', rank: 1 })],
+ }),
+ undefined,
+ ],
+ [
+ 'Inbox report opened',
+ expect.objectContaining({ report_id: 'a', surface: 'today', list: 'briefing', rank: 1 }),
+ undefined,
+ ],
+ [
+ 'Inbox report action',
+ expect.objectContaining({ report_id: 'a', action_type: 'dismiss', surface: 'today' }),
+ undefined,
+ ],
+ [
+ 'Inbox report action',
+ expect.objectContaining({
+ report_id: 'a',
+ action_type: 'remove_suggested_reviewer',
+ surface: 'today',
+ }),
+ undefined,
+ ],
+ ])
+ )
+ })
+
it('keeps the last briefing on screen, polls while the next is written, and stops when it is ready', async () => {
jest.useFakeTimers()
const previous = makeBriefing({ id: 'b-previous', status: 'writing' })
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.ts
index 8d9341525eaf..64047b0e68a0 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts
@@ -31,9 +31,17 @@ import type {
} from 'products/signals/frontend/generated/api.schemas'
import { openDismissReportDialog } from 'products/signals/frontend/inbox/components/shell/DismissReportDialog'
import { openResolveReportDialog } from 'products/signals/frontend/inbox/components/shell/ResolveReportDialog'
+import {
+ TodayReportList,
+ TodayReportSnapshot,
+ captureTodayReportAction,
+ captureTodayReportOpened,
+ captureTodayReportsImpressed,
+} from 'products/signals/frontend/inbox/inboxAnalytics'
import { isActionCapableReport } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'
import { SignalReport } from 'products/signals/frontend/inbox/types'
import { suppressDismissalPayload } from 'products/signals/frontend/inbox/utils/dismissalReasons'
+import { reportPullRequests } from 'products/signals/frontend/inbox/utils/reportPullRequests'
import { todayBriefingRefreshCreate, todayBriefingRetrieve } from 'products/today/frontend/generated/api'
import type {
BriefingApi,
@@ -515,6 +523,31 @@ function previewsBySurface(
return { briefing: previews('briefing'), sidebar: previews('sidebar') }
}
+function signalReportSnapshot(report: SignalReport): TodayReportSnapshot {
+ return {
+ reportId: report.id,
+ priority: report.priority ?? null,
+ hasPr: reportPullRequests(report).length > 0,
+ signalCount: report.signal_count,
+ sourceProducts: report.source_products ?? [],
+ }
+}
+
+function briefingItemSnapshot(item: BriefingItemApi, reportId: string): TodayReportSnapshot {
+ return {
+ reportId,
+ priority: item.report?.priority ?? null,
+ hasPr: !!item.report?.pull_request_url,
+ signalCount: item.report?.signal_count ?? null,
+ sourceProducts: item.source_product ? [item.source_product] : [],
+ }
+}
+
+interface TodayRankedReport {
+ report: TodayReportSnapshot
+ rank: number
+}
+
export const todayLogic = kea<todayLogicType>([
path(['scenes', 'project-homepage', 'today', 'todayLogic']),
connect(() => ({
@@ -896,6 +929,49 @@ export const todayLogic = kea<todayLogicType>([
],
}),
listeners(({ actions, values, cache }) => {
+ // The ranking dataset reads these as the home's exposure log: one impression per report per mount,
+ // like the Inbox list.
+ const impress = (list: TodayReportList, ranked: TodayRankedReport[], listSize: number): void => {
+ const impressed: Set<string> = (cache.impressedReportIds ??= new Set<string>())
+ const fresh = ranked.filter(({ report }) => !impressed.has(report.reportId))
+ if (fresh.length === 0) {
+ return
+ }
+ fresh.forEach(({ report }) => impressed.add(report.reportId))
+ captureTodayReportsImpressed({
+ list,
+ reports: fresh.map(({ report }) => report),
+ ranks: fresh.map(({ rank }) => rank),
+ listSize,
+ })
+ }
+ const captureImpressions = (): void => {
+ if (values.useSampleData) {
+ return
+ }
+ if (values.showPersonalBriefing) {
+ const ranked = values.briefingItems.flatMap((item) => {
+ const reportId = itemReportId(item)
+ return reportId ? [{ report: briefingItemSnapshot(item, reportId), rank: item.rank }] : []
+ })
+ impress('briefing', ranked, values.briefingItems.length)
+ } else if (!values.personalBriefingLoading) {
+ // The team list only stands in for the briefing, so it counts once the briefing is known to be absent.
+ impress(
+ 'briefing',
+ values.reports.map((report, index) => ({ report: signalReportSnapshot(report), rank: index + 1 })),
+ values.reports.length
+ )
+ }
+ impress(
+ 'sidebar_more',
+ values.sidebarMoreReports.map((report, index) => ({
+ report: signalReportSnapshot(report),
+ rank: index + 1,
+ })),
+ values.sidebarMoreReports.length
+ )
+ }
const schedulePoll = (): void => {
cache.disposables.add(() => {
const poll = window.setTimeout(() => actions.pollBriefing(), BRIEFING_POLL_MS)
@@ -949,6 +1025,7 @@ export const todayLogic = kea<todayLogicType>([
}
},
loadPersonalBriefingSuccess: ({ personalBriefing }) => {
+ captureImpressions()
if (!personalBriefing) {
return
}
@@ -975,6 +1052,7 @@ export const todayLogic = kea<todayLogicType>([
})
},
loadPersonalBriefingFailure: ({ errorObject }) => {
+ captureImpressions()
// A poll that fails while the briefing is written keeps polling; a 404 means there is no
// briefing for this person, so the report list stays.
const notFound = errorObject instanceof ApiError && errorObject.status === 404
@@ -1006,6 +1084,16 @@ export const todayLogic = kea<todayLogicType>([
actions.itemOpened(item, surface)
},
itemOpened: ({ item, surface }) => {
+ const reportId = itemReportId(item)
+ if (reportId) {
+ captureTodayReportOpened({
+ report: briefingItemSnapshot(item, reportId),
+ list: 'briefing',
+ rank: item.rank,
+ listSize: values.briefingItems.length,
+ source: surface,
+ })
+ }
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today item opened', {
group: item.group,
@@ -1022,6 +1110,7 @@ export const todayLogic = kea<todayLogicType>([
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today report previewed', {
list: 'personal',
+ report_id: itemReportId(item),
source: item.source,
reason: item.reason,
rank: item.rank,
@@ -1043,6 +1132,7 @@ export const todayLogic = kea<todayLogicType>([
if (rank > 0) {
posthog.capture('today report previewed', {
list,
+ report_id: reports[rank - 1].id,
rank,
has_metric: !!reports[rank - 1].metrics?.length,
surface,
@@ -1061,6 +1151,7 @@ export const todayLogic = kea<todayLogicType>([
if (values.useSampleData) {
return
}
+ captureImpressions()
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today home loaded', {
report_count: topReports.results.length,
@@ -1097,10 +1188,17 @@ export const todayLogic = kea<todayLogicType>([
}
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today report state changed', {
+ report_id: target.reportId,
verdict,
surface,
closed_pull_request: target.hasOpenPullRequest,
})
+ captureTodayReportAction({
+ reportId: target.reportId,
+ actionType: verdict,
+ todaySurface: surface,
+ extra: { closed_pull_request: target.hasOpenPullRequest },
+ })
// A reason is optional, so the verdict is one click and the reason is one more.
lemonToast.success(target.hasOpenPullRequest ? copy.successClosingPullRequest : copy.success, {
button: { label: 'Add a reason', action: () => actions.addReportVerdictReason(target, verdict) },
@@ -1119,7 +1217,13 @@ export const todayLogic = kea<todayLogicType>([
return
}
// pinned: analytics event name and properties. Renaming them breaks dashboards.
- posthog.capture('today report review left', { surface })
+ posthog.capture('today report review left', { report_id: reportId, surface })
+ captureTodayReportAction({
+ reportId,
+ actionType: 'remove_suggested_reviewer',
+ todaySurface: surface,
+ extra: { suggested_reviewer_uuid: values.user?.uuid },
+ })
lemonToast.success('Removed you from the reviewers')
},
addReportVerdictReason: ({ target, verdict }) => {
@@ -1173,6 +1277,7 @@ export const todayLogic = kea<todayLogicType>([
posthog.capture('today more reports clicked', { shown_report_count: values.shownReportIds.length })
},
loadMoreReportsSuccess: () => {
+ captureImpressions()
// pinned: analytics event name and properties. Renaming them breaks dashboards.
posthog.capture('today more reports loaded', {
report_count: values.sidebarMoreReports.length,
@@ -1193,6 +1298,16 @@ export const todayLogic = kea<todayLogicType>([
has_pr: !!report.implementation_pr_url,
source,
})
+ const list: TodayReportList = source === 'sidebar_more' ? 'sidebar_more' : 'briefing'
+ const listReports = list === 'sidebar_more' ? values.sidebarMoreReports : values.reports
+ const rank = listReports.findIndex((candidate) => candidate.id === report.id) + 1
+ captureTodayReportOpened({
+ report: signalReportSnapshot(report),
+ list,
+ rank: rank > 0 ? rank : null,
+ listSize: listReports.length,
+ source,
+ })
},
}
}),
diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts
index b935d3c64c62..22c21b57342a 100644
--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts
+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts
@@ -45,6 +45,7 @@ describe('todayReportLogic', () => {
get: {
'/api/projects/:team_id/signals/reports/:id/': () => [200, report],
'/api/projects/:team_id/today/reports/:id/page/': () => [200, PAGE],
+ '/api/projects/:team_id/today/briefing/': () => [404, {}],
},
})
initKeaTests()
@@ -72,6 +73,7 @@ describe('todayReportLogic', () => {
get: {
'/api/projects/:team_id/signals/reports/:id/': () => [200, report],
'/api/projects/:team_id/today/reports/:id/page/': () => [200, PAGE],
+ '/api/projects/:team_id/today/briefing/': () => [404, {}],
'/api/projects/:team_id/today/reports/:id/figure_marks/': () => {
calls.figureMarks += 1
return [200, { marks: [] }]
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 150d449f6fdd..086004e24e68 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -836,6 +836,23 @@ def sync_report_latest_actionability_on_delete(
_sync_report_latest_actionability(instance)
+def _status_change_properties(
+ instance: SignalReport, previous_status: str, *, pending_reason: str | None
+) -> dict[str, Any]:
+ return {
+ "team_id": instance.team_id,
+ "report_id": str(instance.id),
+ "previous_status": previous_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,
+ "pending_reason": pending_reason,
+ }
+
+
@receiver(post_save, sender=SignalReport)
def capture_status_change_analytics(
sender: type[SignalReport],
@@ -867,18 +884,7 @@ def capture_status_change_analytics(
)
# 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,
- "pending_reason": pending_reason,
- }
+ properties = _status_change_properties(instance, prior_status, pending_reason=pending_reason)
report_id = str(instance.id)
new_status = instance.status
team = instance.team
@@ -933,6 +939,39 @@ def capture_status_change_analytics(
transaction.on_commit(_capture)
+def capture_verdict_reason_added_analytics(instance: SignalReport) -> None:
+ """Emit `signal_report_status_changed` when a reason lands on a verdict the report already holds.
+
+ The state API skips the save for a repeated verdict, so the receiver above stays quiet. The Today
+ home sets the verdict first and sends the reason in a second call, so without this event the
+ ranking labels never see the reason. `previous_status` equals `status` and `reason_added` is true,
+ so a reader that counts real transitions can filter the event out.
+ """
+ properties = {
+ **_status_change_properties(instance, instance.status, pending_reason=None),
+ "reason_added": True,
+ }
+ report_id = str(instance.id)
+ team = instance.team
+ transition_at = timezone.now()
+
+ def _capture() -> None:
+ try:
+ posthoganalytics.capture(
+ event="signal_report_status_changed",
+ distinct_id=str(team.uuid),
+ properties={
+ **properties,
+ **_classification_snapshot(report_id, include_dismissal=True, transition_at=transition_at),
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("Failed to capture signal_report_status_changed", report_id=report_id)
+
+ 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.
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index b97491b09b6c..0ac3cbc249ee 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -3014,6 +3014,7 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
with (
patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_close_pr,
+ patch("products.signals.backend.receivers.posthoganalytics.capture") as mock_capture,
self.captureOnCommitCallbacks(execute=True),
):
response = self.client.post(
@@ -3039,6 +3040,18 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
assert content["user_id"] == self.user.id
mock_close_pr.delay.assert_not_called()
+ status_events = [
+ call.kwargs["properties"]
+ for call in mock_capture.call_args_list
+ if call.kwargs.get("event") == "signal_report_status_changed"
+ ]
+ assert len(status_events) == 1
+ assert status_events[0]["report_id"] == str(report.id)
+ assert status_events[0]["previous_status"] == current_status
+ assert status_events[0]["status"] == current_status
+ assert status_events[0]["dismissal_reason"] == "report_unclear"
+ assert status_events[0]["reason_added"] is True
+
def test_repeating_a_verdict_without_feedback_is_a_no_op_success(self):
report = self._create_report(report_status=SignalReport.Status.SUPPRESSED)
response = self.client.post(
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index d29f65a90dfc..0823b05acc7c 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -136,6 +136,7 @@ from products.signals.backend.models import (
from products.signals.backend.pull_requests import import_report_pull_requests
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
from products.signals.backend.ranking.staleness import EDIT_ARTEFACT_TYPES, annotate_stale_score
+from products.signals.backend.receivers import capture_verdict_reason_added_analytics
from products.signals.backend.repo_corrections import sanitized_repository
from products.signals.backend.report_assignments import InvalidPullRequestUrl, ReportClaimConflict, claim_report
from products.signals.backend.report_check_authoring import (
@@ -3373,6 +3374,8 @@ class SignalReportViewSet(
# just-written reason/note instead of the previous (or empty) dismissal.
if hasattr(report, "prefetched_dismissal_artefacts"):
del report.prefetched_dismissal_artefacts
+ if already_holds_verdict:
+ capture_verdict_reason_added_analytics(report)
# A dismissal (transition into SUPPRESSED) or a resolve closes the linked implementation PR —
# handled centrally by the post_save receiver (receivers.close_pr_when_report_dismissed), so
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index f294ab8aca19..ee4960a52777 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -175,6 +175,11 @@ A report is a positive when someone clicked an intent action in the inbox UI (cr
Self-driving's own `task` and `system` writes do not count: they are internal operational work.
A resolve without a reason is the automatic resolve after a tracked PR merges, so it does not count either.
+The Today home sends the same client events as the Inbox, with `surface: 'today'` and a `list` property (`briefing` or `sidebar_more`) on impressions and opens.
+Filter on `surface` where a metric must stay Inbox-only.
+Today sets a verdict first and sends its optional reason in a second state call, which does not change the status.
+For that call the server emits `signal_report_status_changed` with `previous_status` equal to `status` and `reason_added: true`, so the reason reaches the status-stream heads.
+
`thumbs_up` (a positive rating on the report body) and `reviewer_fix` (a suggested reviewer added or removed) are the explicit human-feedback pair.
Both are rare, so neither clears its holdout bar on a single day.
They are carried for the pooled newborn grade and as scorer inputs, not for a holdout AUC, and the promotion gate keeps ignoring an unreadable head.
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index 8c7168bc5242..ee56373b473f 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -521,6 +521,99 @@ export function captureInboxReportAction(params: {
})
}
+/**
+ * What the Today home knows about a report it shows. A briefing item carries less than the Inbox's
+ * `SignalReport`, so the fields it cannot fill stay null on the event.
+ */
+export interface TodayReportSnapshot {
+ reportId: string
+ priority: string | null
+ hasPr: boolean
+ signalCount: number | null
+ sourceProducts: string[]
+}
+
+/**
+ * The Today list a report shows in. `briefing` is the top list, which the briefing and the sidebar
+ * both show. `sidebar_more` is the list that "Show more reports" loads.
+ */
+export type TodayReportList = 'briefing' | 'sidebar_more'
+
+function todayReportProperties(report: TodayReportSnapshot): Record<string, unknown> {
+ return {
+ report_id: report.reportId,
+ priority: report.priority,
+ actionability: null,
+ has_pr: report.hasPr,
+ signal_count: report.signalCount,
+ source_products: report.sourceProducts,
+ }
+}
+
+/**
+ * The Today home version of {@link captureInboxReportsImpressed}. The ranking dataset reads both
+ * surfaces from one event, and `surface` and `list` keep them apart for position-bias work.
+ */
+export function captureTodayReportsImpressed(params: {
+ list: TodayReportList
+ /** Only the newly impressed reports, in list order. */
+ reports: TodayReportSnapshot[]
+ /** 1-based rank of each impressed report in its list, parallel to `reports`. */
+ ranks: number[]
+ listSize: number
+}): void {
+ captureInboxEvent(INBOX_EVENTS.REPORTS_IMPRESSED, {
+ surface: 'today' satisfies InboxReportActionSurface,
+ list: params.list,
+ list_size: params.listSize,
+ impression_count: params.reports.length,
+ impressions: params.reports.map((report, index) => ({
+ ...todayReportProperties(report),
+ rank: params.ranks[index],
+ })),
+ })
+}
+
+/** The Today home version of {@link captureInboxReportOpened}. `source` is the control the person clicked. */
+export function captureTodayReportOpened(params: {
+ report: TodayReportSnapshot
+ list: TodayReportList
+ rank: number | null
+ listSize: number | null
+ source: string
+}): void {
+ captureInboxEvent(INBOX_EVENTS.REPORT_OPENED, {
+ ...todayReportProperties(params.report),
+ surface: 'today' satisfies InboxReportActionSurface,
+ open_method: 'click' satisfies InboxReportOpenMethod,
+ list: params.list,
+ rank: params.rank,
+ list_size: params.listSize,
+ source: params.source,
+ })
+}
+
+/**
+ * A report action from the Today home, where only the report id is at hand. `today_surface` is the
+ * Today control the person used.
+ */
+export function captureTodayReportAction(params: {
+ reportId: string
+ actionType: InboxReportActionType
+ todaySurface: string
+ extra?: Record<string, unknown>
+}): void {
+ captureInboxEvent(INBOX_EVENTS.REPORT_ACTION, {
+ report_id: params.reportId,
+ action_type: params.actionType,
+ surface: 'today' satisfies InboxReportActionSurface,
+ today_surface: params.todaySurface,
+ is_bulk: false,
+ bulk_size: 1,
+ ...params.extra,
+ })
+}
+
/**
* Feedback on a single report, fired from the thumbs at the end of the report body. Unlike a
* dismiss, this is feedback-only: the report stays in the inbox. The sentiment is the label the