: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): dogfood posthog.metrics from replay and replay vision frontends (#70553)
Arno Hillenc394e15711a3
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.tsindex 17b8747a1504..dc09952b6e10 100644--- a/frontend/jest.setup.ts+++ b/frontend/jest.setup.ts@@ -186,6 +186,7 @@ jest.mock('posthog-js', () => {updateEarlyAccessFeatureEnrollment: jest.fn(),people: { set: jest.fn() },featureFlags: { override: jest.fn() },+ metrics: { count: jest.fn(), gauge: jest.fn(), histogram: jest.fn() },}mock.init = jest.fn(() => mock)diff --git a/frontend/src/lib/operationalMetrics.test.ts b/frontend/src/lib/operationalMetrics.test.tsnew file mode 100644index 000000000000..c6675aff1bec--- /dev/null+++ b/frontend/src/lib/operationalMetrics.test.ts@@ -0,0 +1,41 @@+import posthog from 'posthog-js'++import { metricCount, metricHistogram } from 'lib/operationalMetrics'++describe('operationalMetrics', () => {+ // posthog-js is mocked app-wide in jest.setup.ts, including posthog.metrics.+ const metrics = posthog.metrics as unknown as { count: jest.Mock; histogram: jest.Mock }++ beforeEach(() => {+ jest.clearAllMocks()+ ;(posthog as { metrics?: unknown }).metrics = metrics+ })++ it('forwards counts with attributes in the options envelope', () => {+ metricCount('replay_test_total', 2, { kind: 'meta' })++ expect(metrics.count).toHaveBeenCalledWith('replay_test_total', 2, { attributes: { kind: 'meta' } })+ })++ it('omits the options envelope when there are no attributes', () => {+ metricCount('replay_test_total')++ expect(metrics.count).toHaveBeenCalledWith('replay_test_total', 1, undefined)+ })++ it('forwards histograms with unit and attributes', () => {+ metricHistogram('replay_test_ms', 187, 'ms', { source: 'list' })++ expect(metrics.histogram).toHaveBeenCalledWith('replay_test_ms', 187, {+ unit: 'ms',+ attributes: { source: 'list' },+ })+ })++ it('is a no-op when the SDK build has no metrics extension', () => {+ ;(posthog as { metrics?: unknown }).metrics = undefined++ expect(() => metricCount('replay_test_total')).not.toThrow()+ expect(() => metricHistogram('replay_test_ms', 1, 'ms')).not.toThrow()+ })+})diff --git a/frontend/src/lib/operationalMetrics.ts b/frontend/src/lib/operationalMetrics.tsnew file mode 100644index 000000000000..35a8d5509315--- /dev/null+++ b/frontend/src/lib/operationalMetrics.ts@@ -0,0 +1,29 @@+import type { MetricAttributes } from 'posthog-js'+import posthog from 'posthog-js'++/**+ * Operational metrics into the PostHog Metrics product via the SDK's aggregated+ * `posthog.metrics` API (samples are batched to one data point per series every 10s).+ *+ * Attributes must stay low-cardinality: no user ids, session ids, or URLs. Every distinct+ * attribute combination is its own series, and no user or session context is attached.+ *+ * Both helpers are hard no-ops when the loaded posthog-js build doesn't ship the metrics+ * extension, and they swallow errors so telemetry can never break product code.+ */++export function metricCount(name: string, value: number = 1, attributes?: MetricAttributes): void {+ try {+ posthog.metrics?.count(name, value, attributes ? { attributes } : undefined)+ } catch {+ // never let telemetry break the product+ }+}++export function metricHistogram(name: string, value: number, unit: string, attributes?: MetricAttributes): void {+ try {+ posthog.metrics?.histogram(name, value, { unit, ...(attributes ? { attributes } : {}) })+ } catch {+ // never let telemetry break the product+ }+}diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.tsindex 4658b307cd11..bf18ac1478fa 100644--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.ts@@ -14,6 +14,7 @@ import {} from '@posthog/replay-shared'import { Dayjs, dayjs, now } from 'lib/dayjs'+import { metricCount } from 'lib/operationalMetrics'import {RecordingSegment,@@ -186,6 +187,13 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCooractions.reportUsageIfFullyLoaded()},+ loadRecordingMetaFailure: ({ errorObject }) => {+ // A 404 is an expected outcome (expired or deleted recording), not a player+ // failure; separate series so real failures stay alertable.+ const is404 = (errorObject as { status?: number } | undefined)?.status === 404+ metricCount('replay_player_load_failures', 1, { kind: is404 ? 'meta_not_found' : 'meta' })+ },+loadNextSnapshotSource: () => {actions.reportUsageIfFullyLoaded()},@@ -265,6 +273,7 @@ export const sessionRecordingDataCoordinatorLogic = kea<sessionRecordingDataCoor} else {// Give up loudly: nothing re-triggers processing from here, so surface a terminal// error instead of leaving the player buffering forever.+ metricCount('replay_player_load_failures', 1, { kind: 'snapshot_processing' })actions.snapshotProcessingFailed()}returndiff --git a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.test.ts b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.test.tsnew file mode 100644index 000000000000..0deef6b1618b--- /dev/null+++ b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.test.ts@@ -0,0 +1,42 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'+import { SessionPlayerData, SessionRecordingType } from '~/types'++import { sessionRecordingEventUsageLogic } from './sessionRecordingEventUsageLogic'++describe('sessionRecordingEventUsageLogic', () => {+ let logic: ReturnType<typeof sessionRecordingEventUsageLogic.build>++ const playerData = {+ durationMs: 1000,+ sessionRecordingId: 'abc',+ } as SessionPlayerData++ beforeEach(() => {+ initKeaTests()+ jest.clearAllMocks()+ logic = sessionRecordingEventUsageLogic()+ logic.mount()+ })++ // snapshot_source is caller-controlled at runtime, so anything outside the+ // allowlist must be normalized to keep the metric series bounded+ it.each([+ ['web', 'web'],+ ['mobile', 'mobile'],+ ['some-arbitrary-caller-value', 'unknown'],+ [undefined, 'unknown'],+ ])('reports recording loaded metric with snapshot_source %p as %p', async (rawSource, expectedLabel) => {+ const metadata = { snapshot_source: rawSource } as unknown as SessionRecordingType++ await expectLogic(logic, () => {+ logic.actions.reportRecordingLoaded(playerData, metadata)+ }).toFinishAllListeners()++ expect(posthog.metrics?.count).toHaveBeenCalledWith('replay_player_recordings_loaded', 1, {+ attributes: { snapshot_source: expectedLabel },+ })+ })+})diff --git a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.tsindex f7e7e07c9d33..b43daa5da193 100644--- a/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts+++ b/frontend/src/scenes/session-recordings/sessionRecordingEventUsageLogic.ts@@ -3,6 +3,7 @@ import posthog from 'posthog-js'import { isLogEntryPropertyFilter, isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'import { isActionFilter, isEventFilter } from 'lib/components/UniversalFilters/utils'+import { metricCount, metricHistogram } from 'lib/operationalMetrics'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { MiniFilterKey } from 'scenes/session-recordings/player/inspector/miniFiltersLogic'import { InspectorListItemType } from 'scenes/session-recordings/player/inspector/playerInspectorLogic'@@ -84,21 +85,26 @@ export const sessionRecordingEventUsageLogic = kea<sessionRecordingEventUsageLog}),listeners(() => ({reportRecordingLoaded: ({ playerData, metadata }) => {+ // older recordings did not store this, and so "null" is equivalent to web,+ // but for reporting we want to distinguish between not loaded and no value to load+ const snapshotSource = metadata?.snapshot_source || 'unknown'const payload: Partial<RecordingViewedProps> = {duration: playerData.durationMs,recording_id: playerData.sessionRecordingId,start_time: playerData.start?.valueOf() ?? 0,end_time: playerData.end?.valueOf() ?? 0,- // older recordings did not store this, and so "null" is equivalent to web,- // but for reporting we want to distinguish between not loaded and no value to load- snapshot_source: metadata?.snapshot_source || 'unknown',+ snapshot_source: snapshotSource,}posthog.capture(`recording loaded`, payload)+ // the runtime value is caller-controlled, so allowlist it to keep the metric series bounded+ const snapshotSourceLabel = ['web', 'mobile'].includes(snapshotSource) ? snapshotSource : 'unknown'+ metricCount('replay_player_recordings_loaded', 1, { snapshot_source: snapshotSourceLabel })},reportRecordingsListFilterAdded: ({ filterType }) => {posthog.capture('recording list filter added', { filter_type: filterType })},reportRecordingsListFetched: ({ loadTime, filters, defaultDurationFilter }) => {+ metricHistogram('replay_list_load_ms', loadTime, 'ms')try {const filterValues = filtersFromUniversalFilterGroups(filters)diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.tsindex 1c7acf90986a..fb48718d7c47 100644--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts@@ -1,6 +1,7 @@import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { metricCount } from 'lib/operationalMetrics'import { teamLogic } from 'scenes/teamLogic'import { visionObservationsList, visionScannersObserveCreate } from '../generated/api'@@ -140,6 +141,7 @@ export const observationsDockLogic = kea<observationsDockLogicType>([const response = await visionObservationsList(String(teamId), { session_id: props.sessionId })actions.loadObservationsSuccess(response.results ?? [])} catch {+ metricCount('replay_vision_frontend_observations_load_failures')actions.loadObservationsFailure()}},@@ -170,6 +172,9 @@ export const observationsDockLogic = kea<observationsDockLogicType>([actions.loadObservations()refreshVisionQuota()} catch (error: any) {+ // Counted here rather than on observeFailure, which also fires for benign+ // paths (scanner already run, no team) that would pollute the failure rate.+ metricCount('replay_vision_frontend_observe_failures')lemonToast.error(`Failed to start observation${error.detail ? `: ${error.detail}` : ''}`)actions.observeFailure()}diff --git a/products/replay_vision/frontend/logics/visionScannersListLogic.ts b/products/replay_vision/frontend/logics/visionScannersListLogic.tsindex fba68d0b1057..e5a567309f83 100644--- a/products/replay_vision/frontend/logics/visionScannersListLogic.ts+++ b/products/replay_vision/frontend/logics/visionScannersListLogic.ts@@ -1,6 +1,7 @@import { actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'import { loaders } from 'kea-loaders'+import { metricCount } from 'lib/operationalMetrics'import { teamLogic } from 'scenes/teamLogic'import { visionScannersList } from '../generated/api'@@ -53,6 +54,8 @@ export const visionScannersListLogic = kea<visionScannersListLogicType>([if (error instanceof Error && isBreakpoint(error)) {throw error}+ // Degrades silently to the stale list, so count it or it is invisible.+ metricCount('replay_vision_frontend_scanners_load_failures')return values.scanners}},