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(replay): emit replay and replay vision metrics via otlp (#70535)

Arno Hillenb3068b5c296b
diff --git a/nodejs/src/common/metrics/instruments.ts b/nodejs/src/common/metrics/instruments.ts
new file mode 100644
index 000000000000..8ef62928cdc7
--- /dev/null
+++ b/nodejs/src/common/metrics/instruments.ts
@@ -0,0 +1,31 @@
+import { Counter, Histogram, Meter, MetricOptions } from '@opentelemetry/api'
+
+import { counterWithExemplars, histogramWithExemplars } from './exemplars'
+
+/**
+ * Shared helpers for the OTLP twin modules (logs, session replay ingestion, rasterizer),
+ * so every instrument gets the exemplar wrap and every record path swallows telemetry
+ * errors the same way.
+ */
+
+// The wrappers buffer an exemplar (active span context) per record, which the
+// OTLP JSON exporter attaches at export — the upstream SDK path can't do this.
+export const createCounterWithExemplars = (meter: Meter, name: string, options?: MetricOptions): Counter =>
+ counterWithExemplars(name, meter.createCounter(name, options))
+
+export const createHistogramWithExemplars = (meter: Meter, name: string, options?: MetricOptions): Histogram =>
+ histogramWithExemplars(name, meter.createHistogram(name, options))
+
+/**
+ * Twin recording runs in hot paths, finally blocks, and error handlers. A throw here
+ * would mask the real processing error, so recording failures are swallowed.
+ */
+export function swallowing<Args extends unknown[]>(record: (...args: Args) => void): (...args: Args) => void {
+ return (...args: Args): void => {
+ try {
+ record(...args)
+ } catch {
+ // never let telemetry break the caller
+ }
+ }
+}
diff --git a/nodejs/src/common/metrics/otel-metrics.ts b/nodejs/src/common/metrics/otel-metrics.ts
index e79794ef2ed8..8eea93f9b241 100644
--- a/nodejs/src/common/metrics/otel-metrics.ts
+++ b/nodejs/src/common/metrics/otel-metrics.ts
@@ -1,15 +1,12 @@
import { Counter, metrics as metricsApi } from '@opentelemetry/api'
-import { resourceFromAttributes } from '@opentelemetry/resources'
-import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
-import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'
-import { hostname } from 'os'
+import { MeterProvider } from '@opentelemetry/sdk-metrics'
import { defaultConfig } from '~/common/config/config'
import { logger } from '~/common/utils/logger'
import { registerShutdownHandler } from '~/lifecycle'
import { counterWithExemplars } from './exemplars'
-import { OtlpJsonMetricExporter } from './otlp-json-exporter'
+import { createOtlpMeterProvider } from './otlp-provider'
/**
* OTLP metrics push — the same OTel-SDK path customers use, pointed at our own
@@ -33,28 +30,11 @@ export const initMetrics = (): void => {
logger.info('Starting OTLP metrics push', { endpoint: defaultConfig.OTEL_METRICS_EXPORT_URL })
- provider = new MeterProvider({
- resource: resourceFromAttributes({
- [ATTR_SERVICE_NAME]:
- defaultConfig.OTEL_SERVICE_NAME ?? `node-${defaultConfig.PLUGIN_SERVER_MODE ?? 'nodejs'}`,
- [ATTR_SERVICE_VERSION]: process.env.COMMIT_SHA ?? 'dev',
- // Per-replica identity. Without it every pod shares one series, and
- // their interleaved cumulative counters read as constant resets —
- // rate()/increase() overcount by roughly the replica count.
- 'service.instance.id': hostname(),
- }),
- readers: [
- new PeriodicExportingMetricReader({
- // Not the stock OTLPMetricExporter: the upstream JS pipeline drops
- // exemplars, and the metric-to-trace pivot needs them (see the
- // exporter's docstring).
- exporter: new OtlpJsonMetricExporter({
- url: defaultConfig.OTEL_METRICS_EXPORT_URL,
- headers: { Authorization: `Bearer ${defaultConfig.OTEL_METRICS_EXPORT_TOKEN}` },
- }),
- exportIntervalMillis: defaultConfig.OTEL_METRICS_EXPORT_INTERVAL_MS,
- }),
- ],
+ provider = createOtlpMeterProvider({
+ url: defaultConfig.OTEL_METRICS_EXPORT_URL,
+ token: defaultConfig.OTEL_METRICS_EXPORT_TOKEN,
+ serviceName: defaultConfig.OTEL_SERVICE_NAME ?? `node-${defaultConfig.PLUGIN_SERVER_MODE ?? 'nodejs'}`,
+ exportIntervalMillis: defaultConfig.OTEL_METRICS_EXPORT_INTERVAL_MS,
})
metricsApi.setGlobalMeterProvider(provider)
diff --git a/nodejs/src/common/metrics/otlp-provider.ts b/nodejs/src/common/metrics/otlp-provider.ts
new file mode 100644
index 000000000000..613dc06febfb
--- /dev/null
+++ b/nodejs/src/common/metrics/otlp-provider.ts
@@ -0,0 +1,47 @@
+import { resourceFromAttributes } from '@opentelemetry/resources'
+import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
+import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'
+import { hostname } from 'os'
+
+import { OtlpJsonMetricExporter } from './otlp-json-exporter'
+
+export interface OtlpMeterProviderOptions {
+ url: string
+ token: string
+ serviceName: string
+ exportIntervalMillis: number
+}
+
+/**
+ * One MeterProvider wired for the PostHog Metrics product ingest. Shared so every service
+ * gets the same exporter (the exemplar-preserving OTLP/JSON one) and the same resource
+ * identity, whichever config source supplies the url/token.
+ *
+ * This file must stay import-light: entrypoints without the full plugin-server env (the
+ * recording rasterizer) import it, and anything that evaluates defaultConfig at import
+ * would crash them at boot.
+ */
+export function createOtlpMeterProvider(options: OtlpMeterProviderOptions): MeterProvider {
+ return new MeterProvider({
+ resource: resourceFromAttributes({
+ [ATTR_SERVICE_NAME]: options.serviceName,
+ [ATTR_SERVICE_VERSION]: process.env.COMMIT_SHA ?? 'dev',
+ // Per-replica identity. Without it every pod shares one series, and
+ // their interleaved cumulative counters read as constant resets —
+ // rate()/increase() overcount by roughly the replica count.
+ 'service.instance.id': hostname(),
+ }),
+ readers: [
+ new PeriodicExportingMetricReader({
+ // Not the stock OTLPMetricExporter: the upstream JS pipeline drops
+ // exemplars, and the metric-to-trace pivot needs them (see the
+ // exporter's docstring).
+ exporter: new OtlpJsonMetricExporter({
+ url: options.url,
+ headers: { Authorization: `Bearer ${options.token}` },
+ }),
+ exportIntervalMillis: options.exportIntervalMillis,
+ }),
+ ],
+ })
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index dc5fbcd78bca..f7d4e0cdd5be 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -1,5 +1,7 @@
import { Counter, Gauge, Histogram, Summary } from 'prom-client'
+import { recordMessagesDroppedByRestrictions } from './otel-metrics'
+
const BUCKETS_KB_WRITTEN = [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity]
/** Which anonymizer produced the output; the label makes the flag rollout a direct A/B. */
@@ -77,6 +79,7 @@ export class SessionRecordingIngesterMetrics {
public static observeDroppedByRestrictions(count: number): void {
this.messagesDroppedByRestrictions.inc(count)
+ recordMessagesDroppedByRestrictions(count)
}
public static observeOverflowedByRestrictions(count: number): void {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.test.ts
new file mode 100644
index 000000000000..babbdcbbe46a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.test.ts
@@ -0,0 +1,147 @@
+import { metrics as metricsApi } from '@opentelemetry/api'
+import {
+ type DataPoint,
+ type Histogram as HistogramDataPointValue,
+ InMemoryMetricExporter,
+ MeterProvider,
+ PeriodicExportingMetricReader,
+} from '@opentelemetry/sdk-metrics'
+
+import {
+ E2E_LAG_BOUNDARIES,
+ recordE2eLag,
+ recordEventsRateLimited,
+ recordMessagesDroppedByRestrictions,
+ recordNewSessionsRateLimited,
+ recordS3UploadError,
+ recordS3UploadLatency,
+ recordSessionsFlushed,
+ resetReplayIngestionInstrumentsForTests,
+} from './otel-metrics'
+
+describe('sessionreplay otel-metrics', () => {
+ let exporter: InMemoryMetricExporter
+ let provider: MeterProvider
+ let reader: PeriodicExportingMetricReader
+
+ beforeEach(() => {
+ // Simulate the real startup-order hazard: a record call may run before a
+ // provider exists (bound to the noop meter), with the provider registered
+ // afterwards. Lazily acquired instruments must still deliver data recorded
+ // after registration.
+ resetReplayIngestionInstrumentsForTests()
+ recordSessionsFlushed(1)
+
+ exporter = new InMemoryMetricExporter(0)
+ reader = new PeriodicExportingMetricReader({ exporter, exportIntervalMillis: 60_000 })
+ provider = new MeterProvider({ readers: [reader] })
+ metricsApi.setGlobalMeterProvider(provider)
+ resetReplayIngestionInstrumentsForTests()
+ })
+
+ afterEach(async () => {
+ await provider.shutdown()
+ metricsApi.disable()
+ })
+
+ const dataPointsFor = <T>(name: string): readonly DataPoint<T>[] =>
+ exporter
+ .getMetrics()
+ .flatMap((rm) => rm.scopeMetrics)
+ .flatMap((sm) => sm.metrics)
+ .filter((m) => m.descriptor.name === name)
+ .flatMap((m) => m.dataPoints as unknown as readonly DataPoint<T>[])
+
+ it.each([
+ [
+ 'recordSessionsFlushed',
+ 'recording_blob_ingestion_v2_sessions_flushed_total',
+ () => recordSessionsFlushed(7),
+ {},
+ 7,
+ ],
+ [
+ 'recordEventsRateLimited',
+ 'recording_blob_ingestion_v2_events_rate_limited_total',
+ () => recordEventsRateLimited(3),
+ {},
+ 3,
+ ],
+ [
+ 'recordMessagesDroppedByRestrictions',
+ 'recording_blob_ingestion_v2_messages_dropped_by_restrictions',
+ () => recordMessagesDroppedByRestrictions(2),
+ {},
+ 2,
+ ],
+ [
+ 'recordNewSessionsRateLimited',
+ 'recording_blob_ingestion_v2_new_sessions_rate_limited_total',
+ () => recordNewSessionsRateLimited(42, 5),
+ { team_id: '42' },
+ 5,
+ ],
+ [
+ 'recordS3UploadError',
+ 'recording_blob_ingestion_v2_s3_upload_errors_total',
+ () => recordS3UploadError(),
+ {},
+ 1,
+ ],
+ ] as const)('%s emits %s', async (_name, metricName, record, attributes, value) => {
+ record()
+
+ await reader.forceFlush()
+
+ const points = dataPointsFor<number>(metricName)
+ expect(points).toHaveLength(1)
+ expect(points[0].attributes).toEqual(attributes)
+ expect(points[0].value).toEqual(value)
+ })
+
+ it('skips zero and negative counts so no empty series are created', async () => {
+ recordSessionsFlushed(0)
+ recordEventsRateLimited(-1)
+
+ await reader.forceFlush()
+
+ expect(dataPointsFor('recording_blob_ingestion_v2_sessions_flushed_total')).toHaveLength(0)
+ expect(dataPointsFor('recording_blob_ingestion_v2_events_rate_limited_total')).toHaveLength(0)
+ })
+
+ it('records e2e lag with the prom bucket ladder', async () => {
+ recordE2eLag(42.5)
+
+ await reader.forceFlush()
+
+ const points = dataPointsFor<HistogramDataPointValue>('recording_blob_ingestion_v2_e2e_lag_seconds')
+ expect(points).toHaveLength(1)
+ expect(points[0].value.count).toEqual(1)
+ expect(points[0].value.sum).toBeCloseTo(42.5)
+ // Bucket parity with the prom histogram, so dashboards translate 1:1 between the two sinks.
+ expect(points[0].value.buckets.boundaries).toEqual(E2E_LAG_BOUNDARIES)
+ })
+
+ it.each([
+ ['recordSessionsFlushed', () => recordSessionsFlushed(1)],
+ ['recordS3UploadLatency', () => recordS3UploadLatency(0.5)],
+ ['recordE2eLag', () => recordE2eLag(1)],
+ ] as const)('%s swallows a throwing OTel SDK so callers keep the original error', (_name, record) => {
+ // These run in the ingestion hot path and in error handlers; a throw here
+ // would mask the real processing error.
+ const throwing = () => {
+ throw new Error('otel exploded')
+ }
+ metricsApi.disable() // the API ignores a second setGlobalMeterProvider without this
+ metricsApi.setGlobalMeterProvider({
+ getMeter: () =>
+ ({
+ createCounter: () => ({ add: throwing }),
+ createHistogram: () => ({ record: throwing }),
+ }) as any,
+ } as any)
+ resetReplayIngestionInstrumentsForTests()
+
+ expect(record).not.toThrow()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.ts
new file mode 100644
index 000000000000..599a39c6876b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/otel-metrics.ts
@@ -0,0 +1,179 @@
+import { Attributes, Counter, Histogram, metrics as metricsApi } from '@opentelemetry/api'
+
+import { createCounterWithExemplars, createHistogramWithExemplars, swallowing } from '~/common/metrics/instruments'
+
+/**
+ * OTLP-pushed twins of the core session replay ingestion prom counters. The prom side keeps
+ * feeding the scrape/VictoriaMetrics dashboards; these land in the PostHog metrics product
+ * through the exporter installed by initMetrics (common/metrics/otel-metrics.ts).
+ *
+ * Names and label sets deliberately match the prom counters so dashboards translate 1:1.
+ *
+ * Instruments are acquired lazily on first record: the OTel metrics API has no proxy
+ * provider, so instruments created at module load (before initMetrics runs) would be
+ * bound to the noop meter forever.
+ */
+
+interface ReplayIngestionInstruments {
+ sessionsFlushed: Counter
+ eventsFlushed: Counter
+ bytesWritten: Counter
+ sessionsDroppedMissingRetention: Counter
+ messagesDroppedByRestrictions: Counter
+ sessionsRateLimited: Counter
+ eventsRateLimited: Counter
+ sessionsBlocked: Counter
+ newSessionsRateLimited: Counter
+ s3UploadErrors: Counter
+ s3UploadTimeouts: Counter
+ s3UploadLatency: Histogram
+ e2eLag: Histogram
+}
+
+/** Keep in lockstep with the recording_blob_ingestion_v2_s3_upload_latency_seconds prom buckets. */
+const S3_UPLOAD_LATENCY_BOUNDARIES = [0, 0.1, 0.5, 1, 2, 5, 10, 30, 60, 120, 300]
+
+/** Buffering dominates the lag, so buckets span seconds to the batch-flush ceiling and beyond. */
+export const E2E_LAG_BOUNDARIES = [5, 15, 30, 60, 120, 300, 600, 1200, 1800, 3600]
+
+let instruments: ReplayIngestionInstruments | null = null
+
+function getInstruments(): ReplayIngestionInstruments {
+ if (instruments === null) {
+ const meter = metricsApi.getMeter('session-replay-ingestion')
+ instruments = {
+ sessionsFlushed: createCounterWithExemplars(meter, 'recording_blob_ingestion_v2_sessions_flushed_total', {
+ description: 'Number of individual sessions that have been flushed',
+ }),
+ eventsFlushed: createCounterWithExemplars(meter, 'recording_blob_ingestion_v2_events_flushed_total', {
+ description: 'Number of individual events that have been flushed',
+ }),
+ bytesWritten: createCounterWithExemplars(meter, 'recording_blob_ingestion_v2_bytes_written_total', {
+ description: 'Number of bytes written to storage',
+ unit: 'By',
+ }),
+ sessionsDroppedMissingRetention: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_sessions_dropped_missing_retention_total',
+ {
+ description: 'Number of sessions dropped before recording because retention could not be resolved',
+ }
+ ),
+ messagesDroppedByRestrictions: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_messages_dropped_by_restrictions',
+ { description: 'The number of messages dropped due to event ingestion restrictions' }
+ ),
+ sessionsRateLimited: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_sessions_rate_limited_total',
+ {
+ description: 'Number of sessions that were rate limited',
+ }
+ ),
+ eventsRateLimited: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_events_rate_limited_total',
+ {
+ description: 'Number of events that were rate limited',
+ }
+ ),
+ sessionsBlocked: createCounterWithExemplars(meter, 'recording_blob_ingestion_v2_sessions_blocked_total', {
+ description: 'Number of sessions dropped by the session filter blocklist',
+ }),
+ newSessionsRateLimited: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_new_sessions_rate_limited_total',
+ { description: 'Number of new sessions dropped by the per-team new-session rate limiter' }
+ ),
+ s3UploadErrors: createCounterWithExemplars(meter, 'recording_blob_ingestion_v2_s3_upload_errors_total', {
+ description: 'Number of S3 upload errors',
+ }),
+ s3UploadTimeouts: createCounterWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_s3_upload_timeouts_total',
+ {
+ description: 'Number of S3 upload timeouts',
+ }
+ ),
+ s3UploadLatency: createHistogramWithExemplars(
+ meter,
+ 'recording_blob_ingestion_v2_s3_upload_latency_seconds',
+ {
+ description: 'Time taken to upload batches to S3 in seconds',
+ unit: 's',
+ advice: { explicitBucketBoundaries: S3_UPLOAD_LATENCY_BOUNDARIES },
+ }
+ ),
+ e2eLag: createHistogramWithExemplars(meter, 'recording_blob_ingestion_v2_e2e_lag_seconds', {
+ description: 'Per-session staleness at flush: wall clock minus the newest flushed event timestamp',
+ unit: 's',
+ advice: { explicitBucketBoundaries: E2E_LAG_BOUNDARIES },
+ }),
+ }
+ }
+ return instruments
+}
+
+function addPositive(counter: Counter, value: number, attributes?: Attributes): void {
+ if (value > 0) {
+ counter.add(value, attributes)
+ }
+}
+
+export const recordSessionsFlushed = swallowing((count: number): void => {
+ addPositive(getInstruments().sessionsFlushed, count)
+})
+
+export const recordEventsFlushed = swallowing((count: number): void => {
+ addPositive(getInstruments().eventsFlushed, count)
+})
+
+export const recordBytesWritten = swallowing((bytes: number): void => {
+ addPositive(getInstruments().bytesWritten, bytes)
+})
+
+export const recordSessionsDroppedMissingRetention = swallowing((count: number): void => {
+ addPositive(getInstruments().sessionsDroppedMissingRetention, count)
+})
+
+export const recordMessagesDroppedByRestrictions = swallowing((count: number): void => {
+ addPositive(getInstruments().messagesDroppedByRestrictions, count)
+})
+
+export const recordSessionsRateLimited = swallowing((count: number): void => {
+ addPositive(getInstruments().sessionsRateLimited, count)
+})
+
+export const recordEventsRateLimited = swallowing((count: number): void => {
+ addPositive(getInstruments().eventsRateLimited, count)
+})
+
+export const recordSessionsBlocked = swallowing((count: number): void => {
+ addPositive(getInstruments().sessionsBlocked, count)
+})
+
+export const recordNewSessionsRateLimited = swallowing((teamId: number, count: number): void => {
+ addPositive(getInstruments().newSessionsRateLimited, count, { team_id: teamId.toString() })
+})
+
+export const recordS3UploadError = swallowing((): void => {
+ getInstruments().s3UploadErrors.add(1)
+})
+
+export const recordS3UploadTimeout = swallowing((): void => {
+ getInstruments().s3UploadTimeouts.add(1)
+})
+
+export const recordS3UploadLatency = swallowing((seconds: number): void => {
+ getInstruments().s3UploadLatency.record(seconds)
+})
+
+export const recordE2eLag = swallowing((seconds: number): void => {
+ getInstruments().e2eLag.record(seconds)
+})
+
+/** Test seam: forget cached instruments so a test-installed provider is picked up. */
+export function resetReplayIngestionInstrumentsForTests(): void {
+ instruments = null
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts
index b0ac38d23cad..dd0145d18056 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/metrics.ts
@@ -1,5 +1,21 @@
import { Counter, Histogram } from 'prom-client'
+import {
+ E2E_LAG_BOUNDARIES,
+ recordBytesWritten,
+ recordE2eLag,
+ recordEventsFlushed,
+ recordEventsRateLimited,
+ recordNewSessionsRateLimited,
+ recordS3UploadError,
+ recordS3UploadLatency,
+ recordS3UploadTimeout,
+ recordSessionsBlocked,
+ recordSessionsDroppedMissingRetention,
+ recordSessionsFlushed,
+ recordSessionsRateLimited,
+} from '~/ingestion/pipelines/sessionreplay/otel-metrics'
+
export class SessionBatchMetrics {
private static readonly batchesFlushed = new Counter({
name: 'recording_blob_ingestion_v2_batches_flushed_total',
@@ -13,6 +29,7 @@ export class SessionBatchMetrics {
public static incrementSessionsDroppedMissingRetention(count: number = 1): void {
this.sessionsDroppedMissingRetention.inc(count)
+ recordSessionsDroppedMissingRetention(count)
}
private static readonly sessionsFlushed = new Counter({
@@ -147,20 +164,29 @@ export class SessionBatchMetrics {
buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
})
+ private static readonly e2eLag = new Histogram({
+ name: 'recording_blob_ingestion_v2_e2e_lag_seconds',
+ help: 'Per-session staleness at flush: wall clock minus the newest flushed event timestamp',
+ buckets: E2E_LAG_BOUNDARIES,
+ })
+
public static incrementBatchesFlushed(): void {
this.batchesFlushed.inc()
}
public static incrementSessionsFlushed(count: number = 1): void {
this.sessionsFlushed.inc(count)
+ recordSessionsFlushed(count)
}
public static incrementEventsFlushed(count: number = 1): void {
this.eventsFlushed.inc(count)
+ recordEventsFlushed(count)
}
public static incrementBytesWritten(bytes: number): void {
this.bytesWritten.inc(bytes)
+ recordBytesWritten(bytes)
}
public static incrementConsoleLogsStored(count: number = 1): void {
@@ -178,14 +204,17 @@ export class SessionBatchMetrics {
public static incrementS3UploadErrors(): void {
this.s3UploadErrors.inc()
+ recordS3UploadError()
}
public static incrementS3UploadTimeouts(): void {
this.s3UploadTimeouts.inc()
+ recordS3UploadTimeout()
}
public static observeS3UploadLatency(seconds: number): void {
this.s3UploadLatency.observe(seconds)
+ recordS3UploadLatency(seconds)
}
public static incrementS3BytesWritten(bytes: number): void {
@@ -194,10 +223,12 @@ export class SessionBatchMetrics {
public static incrementSessionsRateLimited(count: number = 1): void {
this.sessionsRateLimited.inc(count)
+ recordSessionsRateLimited(count)
}
public static incrementEventsRateLimited(count: number = 1): void {
this.eventsRateLimited.inc(count)
+ recordEventsRateLimited(count)
}
public static incrementNewSessionsDetected(count: number = 1): void {
@@ -206,6 +237,7 @@ export class SessionBatchMetrics {
public static incrementNewSessionsRateLimited(teamId: number, count: number = 1): void {
this.newSessionsRateLimited.labels({ team_id: teamId }).inc(count)
+ recordNewSessionsRateLimited(teamId, count)
}
public static incrementSessionTrackerCacheHit(count: number = 1): void {
@@ -222,6 +254,12 @@ export class SessionBatchMetrics {
public static incrementSessionsBlocked(count: number = 1): void {
this.sessionsBlocked.inc(count)
+ recordSessionsBlocked(count)
+ }
+
+ public static observeE2eLag(seconds: number): void {
+ this.e2eLag.observe(seconds)
+ recordE2eLag(seconds)
}
public static incrementSessionFilterCacheHit(count: number = 1): void {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
index ed42fc5ad9f4..b95e97c64d9d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
@@ -182,6 +182,7 @@ jest.mock('./metrics', () => ({
incrementEventsRateLimited: jest.fn(),
incrementNewSessionsDetected: jest.fn(),
incrementNewSessionsRateLimited: jest.fn(),
+ observeE2eLag: jest.fn(),
},
}))
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
index f0bffdecfc63..3d1da7132452 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
@@ -391,6 +391,16 @@ export class SessionBatchRecorder {
SessionBatchMetrics.incrementSessionsFlushed(totalSessions)
SessionBatchMetrics.incrementEventsFlushed(totalEvents)
SessionBatchMetrics.incrementBytesWritten(totalBytes)
+ const flushedAtMillis = Date.now()
+ for (const block of blockMetadata) {
+ const endMillis = block.endDateTime.toMillis()
+ // endDateTime falls back to epoch 0 when a block somehow has no timestamped
+ // events; skip those rather than record a nonsense multi-year lag. Clock skew
+ // can put an event timestamp slightly in the future, hence the clamp.
+ if (endMillis > 0) {
+ SessionBatchMetrics.observeE2eLag(Math.max(0, (flushedAtMillis - endMillis) / 1000))
+ }
+ }
// Clear sessions, partition sizes, total size, and rate limiter state after successful flush
this.sessions = new SessionMap()
diff --git a/nodejs/src/logs/ingestion-otel-metrics.ts b/nodejs/src/logs/ingestion-otel-metrics.ts
index 2858bd88ba0f..3195ff163331 100644
--- a/nodejs/src/logs/ingestion-otel-metrics.ts
+++ b/nodejs/src/logs/ingestion-otel-metrics.ts
@@ -1,6 +1,6 @@
-import { Attributes, Counter, Histogram, Meter, MetricOptions, metrics as metricsApi } from '@opentelemetry/api'
+import { Attributes, Counter, Histogram, metrics as metricsApi } from '@opentelemetry/api'
-import { counterWithExemplars, histogramWithExemplars } from '~/common/metrics/exemplars'
+import { createCounterWithExemplars, createHistogramWithExemplars, swallowing } from '~/common/metrics/instruments'
/**
* OTLP-pushed twins of the core logs-ingestion prom counters. The prom side keeps
@@ -32,45 +32,38 @@ const PROCESSING_DURATION_BOUNDARIES = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1]
let instruments: LogsIngestionInstruments | null = null
-// The wrappers buffer an exemplar (active span context) per record, which the
-// OTLP JSON exporter attaches at export — the upstream SDK path can't do this.
-const createCounter = (meter: Meter, name: string, options?: MetricOptions): Counter =>
- counterWithExemplars(name, meter.createCounter(name, options))
-const createHistogram = (meter: Meter, name: string, options?: MetricOptions): Histogram =>
- histogramWithExemplars(name, meter.createHistogram(name, options))
-
function getInstruments(): LogsIngestionInstruments {
if (instruments === null) {
const meter = metricsApi.getMeter('logs-ingestion')
instruments = {
- bytesReceived: createCounter(meter, 'logs_ingestion_bytes_received_total', {
+ bytesReceived: createCounterWithExemplars(meter, 'logs_ingestion_bytes_received_total', {
description: 'Total uncompressed bytes received for logs ingestion',
unit: 'By',
}),
- recordsReceived: createCounter(meter, 'logs_ingestion_records_received_total', {
+ recordsReceived: createCounterWithExemplars(meter, 'logs_ingestion_records_received_total', {
description: 'Total log records received',
}),
- bytesAllowed: createCounter(meter, 'logs_ingestion_bytes_allowed_total', {
+ bytesAllowed: createCounterWithExemplars(meter, 'logs_ingestion_bytes_allowed_total', {
description: 'Total uncompressed bytes allowed through quota and rate limiting',
unit: 'By',
}),
- recordsAllowed: createCounter(meter, 'logs_ingestion_records_allowed_total', {
+ recordsAllowed: createCounterWithExemplars(meter, 'logs_ingestion_records_allowed_total', {
description: 'Total log records allowed through quota and rate limiting',
}),
- bytesDropped: createCounter(meter, 'logs_ingestion_bytes_dropped_total', {
+ bytesDropped: createCounterWithExemplars(meter, 'logs_ingestion_bytes_dropped_total', {
description: 'Total uncompressed bytes dropped due to quota or rate limiting',
unit: 'By',
}),
- recordsDropped: createCounter(meter, 'logs_ingestion_records_dropped_total', {
+ recordsDropped: createCounterWithExemplars(meter, 'logs_ingestion_records_dropped_total', {
description: 'Total log records dropped due to quota or rate limiting',
}),
- messagesDropped: createCounter(meter, 'logs_ingestion_message_dropped_count', {
+ messagesDropped: createCounterWithExemplars(meter, 'logs_ingestion_message_dropped_count', {
description: 'The number of logs ingestion messages dropped',
}),
- messagesDlq: createCounter(meter, 'logs_ingestion_message_dlq_count', {
+ messagesDlq: createCounterWithExemplars(meter, 'logs_ingestion_message_dlq_count', {
description: 'The number of logs ingestion messages sent to DLQ',
}),
- processingDuration: createHistogram(meter, 'logs_ingestion_processing_duration_seconds', {
+ processingDuration: createHistogramWithExemplars(meter, 'logs_ingestion_processing_duration_seconds', {
description: 'Time spent processing log messages (AVRO decode/encode cycle)',
unit: 's',
advice: { explicitBucketBoundaries: PROCESSING_DURATION_BOUNDARIES },
@@ -86,21 +79,6 @@ function addPositive(counter: Counter, value: number, attributes?: Attributes):
}
}
-/**
- * These run in finally blocks and error handlers of the ingestion hot path — a throw
- * here would mask the real processing error and DLQ the message with the wrong reason,
- * so recording failures are swallowed.
- */
-function swallowing<Args extends unknown[]>(record: (...args: Args) => void): (...args: Args) => void {
- return (...args: Args): void => {
- try {
- record(...args)
- } catch {
- // never let telemetry break ingestion
- }
- }
-}
-
export const recordLogsReceived = swallowing((bytes: number, records: number): void => {
const { bytesReceived, recordsReceived } = getInstruments()
addPositive(bytesReceived, bytes)
diff --git a/nodejs/src/session-replay/recording-rasterizer/metrics.ts b/nodejs/src/session-replay/recording-rasterizer/metrics.ts
index b6f135262630..b1947d4a867f 100644
--- a/nodejs/src/session-replay/recording-rasterizer/metrics.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/metrics.ts
@@ -1,5 +1,7 @@
import { Counter, Gauge, Summary } from 'prom-client'
+import { recordActivity, recordError } from './otel-metrics'
+
const QUANTILES = [0.5, 0.95, 0.99]
const MAX_AGE_SECONDS = 600
const AGE_BUCKETS = 5
@@ -122,6 +124,7 @@ export class RasterizationMetrics {
public static observeActivity(result: 'success' | 'error', seconds: number): void {
this.activityDuration.labels({ result }).observe(seconds)
this.activitiesTotal.labels({ result }).inc()
+ recordActivity(result, seconds)
}
public static observeSetup(result: 'success' | 'error', seconds: number): void {
@@ -148,6 +151,7 @@ export class RasterizationMetrics {
public static incrementError(code: string, retryable: boolean): void {
this.errorsTotal.labels({ code, retryable: String(retryable) }).inc()
+ recordError(code, retryable)
}
public static browserLaunched(): void {
diff --git a/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts b/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts
new file mode 100644
index 000000000000..fb56a5ed8cce
--- /dev/null
+++ b/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts
@@ -0,0 +1,95 @@
+import { Counter, Histogram, metrics as metricsApi } from '@opentelemetry/api'
+import { MeterProvider } from '@opentelemetry/sdk-metrics'
+
+import { createCounterWithExemplars, createHistogramWithExemplars, swallowing } from '~/common/metrics/instruments'
+import { createOtlpMeterProvider } from '~/common/metrics/otlp-provider'
+
+/**
+ * OTLP-pushed twins of the rasterizer's headline prom metrics. The prom side keeps feeding
+ * the scrape/VictoriaMetrics dashboards; these land in the PostHog metrics product.
+ *
+ * The rasterizer has its own initMetrics rather than reusing common/metrics/otel-metrics:
+ * that module evaluates defaultConfig at import, which throws without Postgres env vars
+ * the rasterizer deployment doesn't have. This one reads the same env names directly and
+ * builds the provider through the shared createOtlpMeterProvider.
+ *
+ * Names and label sets deliberately match the prom metrics so dashboards translate 1:1
+ * (the prom activity duration is a Summary; the OTLP twin is a histogram).
+ *
+ * Instruments are acquired lazily on first record: the OTel metrics API has no proxy
+ * provider, so instruments created at module load (before initMetrics runs) would be
+ * bound to the noop meter forever.
+ */
+
+let provider: MeterProvider | null = null
+
+/** Off unless both OTEL_METRICS_EXPORT_URL and OTEL_METRICS_EXPORT_TOKEN are set. */
+export const initMetrics = (): void => {
+ if (provider) {
+ return
+ }
+ const url = process.env.OTEL_METRICS_EXPORT_URL
+ const token = process.env.OTEL_METRICS_EXPORT_TOKEN
+ if (!url || !token) {
+ return
+ }
+
+ provider = createOtlpMeterProvider({
+ url,
+ token,
+ serviceName: process.env.OTEL_SERVICE_NAME ?? 'recording-rasterizer',
+ exportIntervalMillis: parseInt(process.env.OTEL_METRICS_EXPORT_INTERVAL_MS ?? '60000', 10),
+ })
+ metricsApi.setGlobalMeterProvider(provider)
+}
+
+/** Flush and stop the exporter; call once on worker shutdown. */
+export const shutdownMetrics = async (): Promise<void> => {
+ await provider?.shutdown()
+ provider = null
+}
+
+interface RasterizerInstruments {
+ activitiesTotal: Counter
+ activityDuration: Histogram
+ errorsTotal: Counter
+}
+
+const ACTIVITY_DURATION_BOUNDARIES = [1, 5, 15, 30, 60, 120, 300, 600, 1200]
+
+let instruments: RasterizerInstruments | null = null
+
+function getInstruments(): RasterizerInstruments {
+ if (instruments === null) {
+ const meter = metricsApi.getMeter('recording-rasterizer')
+ instruments = {
+ activitiesTotal: createCounterWithExemplars(meter, 'recording_rasterizer_activities_total', {
+ description: 'Number of rasterization activities completed',
+ }),
+ activityDuration: createHistogramWithExemplars(meter, 'recording_rasterizer_activity_duration_seconds', {
+ description: 'Total time for the rasterization activity',
+ unit: 's',
+ advice: { explicitBucketBoundaries: ACTIVITY_DURATION_BOUNDARIES },
+ }),
+ errorsTotal: createCounterWithExemplars(meter, 'recording_rasterizer_errors_total', {
+ description: 'Rasterization errors by code',
+ }),
+ }
+ }
+ return instruments
+}
+
+export const recordActivity = swallowing((result: 'success' | 'error', seconds: number): void => {
+ const { activitiesTotal, activityDuration } = getInstruments()
+ activitiesTotal.add(1, { result })
+ activityDuration.record(seconds, { result })
+})
+
+export const recordError = swallowing((code: string, retryable: boolean): void => {
+ getInstruments().errorsTotal.add(1, { code, retryable: retryable.toString() })
+})
+
+/** Test seam: forget cached instruments so a test-installed provider is picked up. */
+export function resetRasterizerInstrumentsForTests(): void {
+ instruments = null
+}
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
index 5b978e95ce0b..ed8c16db847b 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts
@@ -10,10 +10,13 @@ import { BrowserPool } from '~/session-replay/recording-rasterizer/capture/brows
import { playerHtmlCache } from '~/session-replay/recording-rasterizer/capture/capture-page'
import { config } from '~/session-replay/recording-rasterizer/config'
import { createLogger } from '~/session-replay/recording-rasterizer/logger'
+import { initMetrics, shutdownMetrics } from '~/session-replay/recording-rasterizer/otel-metrics'
import { createActivities } from './activities'
prometheus.collectDefaultMetrics()
+// OTLP push into the PostHog Metrics product; no-op unless OTEL_METRICS_EXPORT_URL/TOKEN are set.
+initMetrics()
const log = createLogger()
@@ -152,6 +155,7 @@ async function main(): Promise<void> {
// run() resolves after shutdown drains all in-flight activities
await pool.shutdown()
+ await shutdownMetrics()
metricsServer.close()
}
diff --git a/posthog/otel_metrics.py b/posthog/otel_metrics.py
new file mode 100644
index 000000000000..5438b942a299
--- /dev/null
+++ b/posthog/otel_metrics.py
@@ -0,0 +1,238 @@
+"""OTLP metrics push into the PostHog Metrics product (Python twin of nodejs/src/common/metrics/otel-metrics.ts).
+
+Pushes metrics through the same OTel-SDK path customers use, pointed at our own ingest
+(the `capture-logs` service, path `/i/v1/metrics`), authenticated with a project token.
+Off unless both OTEL_METRICS_EXPORT_URL and OTEL_METRICS_EXPORT_TOKEN are set, so nothing
+changes for deployments that don't opt in. This complements Prometheus instrumentation
+(scraped, Grafana) rather than replacing it. Callers keep emitting the same metric names
+to both so dashboards translate 1:1.
+
+Initialization is lazy and per-process (keyed on PID): preforking servers (gunicorn,
+celery) get a live exporter thread in each worker instead of a dead one inherited from
+the parent, and no explicit init call is needed anywhere.
+"""
+
+import os
+import time
+import socket
+import threading
+from collections.abc import Callable, Generator, Sequence
+from contextlib import contextmanager
+from typing import TYPE_CHECKING, Any, NamedTuple
+
+from django.conf import settings
+
+from opentelemetry.metrics import Counter, Histogram, Meter, NoOpMeter, _Gauge
+from prometheus_client import (
+ Counter as PromCounter,
+ Gauge as PromGauge,
+ Histogram as PromHistogram,
+)
+
+if TYPE_CHECKING:
+ from opentelemetry.sdk.metrics import MeterProvider
+
+_lock = threading.Lock()
+_provider: "MeterProvider | None" = None
+_provider_pid: int | None = None
+# Bumped whenever the provider is (re)built, so factory caches know to drop instruments
+# bound to a previous provider (after a fork, or after a test reset).
+_epoch = 0
+
+
+def _ensure_provider() -> "MeterProvider | None":
+ global _provider, _provider_pid, _epoch
+ pid = os.getpid()
+ if _provider_pid != pid:
+ with _lock:
+ if _provider_pid != pid:
+ _provider = _build_provider()
+ _provider_pid = pid
+ _epoch += 1
+ return _provider
+
+
+def get_otel_meter(name: str) -> Meter:
+ """Return a meter bound to the OTLP-push provider, initializing it on first use.
+
+ Without both env vars this returns a no-op meter, so recording is free and safe
+ everywhere. Prefer `OtelInstrumentFactory` over calling this directly: instruments
+ must be cached (re-creating them per record triggers SDK duplicate warnings), and
+ the factory handles that plus fork safety.
+ """
+ provider = _ensure_provider()
+ if provider is None:
+ return NoOpMeter(name)
+ return provider.get_meter(name)
+
+
+def _build_provider() -> "MeterProvider | None":
+ if not settings.OTEL_METRICS_EXPORT_URL or not settings.OTEL_METRICS_EXPORT_TOKEN:
+ return None
+
+ # Deferred so the SDK + protobuf exporter stay off the django.setup() path; this only
+ # runs once per process, and only in deployments that opt in.
+ from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter # noqa: PLC0415
+ from opentelemetry.sdk.metrics import MeterProvider # noqa: PLC0415
+ from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader # noqa: PLC0415
+ from opentelemetry.sdk.resources import Resource # noqa: PLC0415
+
+ from posthog.security.outbound_proxy import internal_requests_session # noqa: PLC0415
+
+ exporter = OTLPMetricExporter(
+ endpoint=settings.OTEL_METRICS_EXPORT_URL,
+ headers={"authorization": f"Bearer {settings.OTEL_METRICS_EXPORT_TOKEN}"},
+ # capture-logs is in-cluster (a private ClusterIP); the export must bypass the
+ # Smokescreen egress proxy or every batch silently 407s.
+ session=internal_requests_session(),
+ )
+ resource = Resource.create(
+ {
+ "service.name": os.environ.get("OTEL_SERVICE_NAME") or "posthog-python",
+ "service.version": os.environ.get("COMMIT_SHA") or "dev",
+ # Per-process identity. Without it every worker process shares one series, and
+ # their interleaved cumulative counters read as constant resets. rate() and
+ # increase() would overcount by roughly the process count.
+ "service.instance.id": f"{socket.gethostname()}-{os.getpid()}",
+ }
+ )
+ return MeterProvider(
+ resource=resource,
+ metric_readers=[
+ PeriodicExportingMetricReader(exporter, export_interval_millis=settings.OTEL_METRICS_EXPORT_INTERVAL_MS)
+ ],
+ )
+
+
+class _TwinMeta(NamedTuple):
+ name: str
+ description: str
+ boundaries: list[float] | None
+
+
+class OtelInstrumentFactory:
+ """Per-process lazy instrument cache for one meter.
+
+ Products declare a module-level factory and fetch instruments by name at record time.
+ Instruments are created on first use, after the provider exists. The OTel API has no
+ proxy provider, so instruments created at module import would bind to the no-op meter
+ forever. The cache is dropped whenever the provider epoch changes (a fork, or a test
+ reset) so records rebuild against the live provider.
+ """
+
+ def __init__(self, meter_name: str) -> None:
+ self._meter_name = meter_name
+ self._epoch: int | None = None
+ self._cache: dict[str, Any] = {}
+ self._twin_meta: dict[int, _TwinMeta] = {}
+ self._cache_lock = threading.Lock()
+
+ def counter(self, name: str, *, description: str = "", unit: str = "") -> Counter:
+ return self._get(name, lambda meter: meter.create_counter(name, unit=unit, description=description))
+
+ def histogram(
+ self,
+ name: str,
+ *,
+ description: str = "",
+ unit: str = "",
+ boundaries: Sequence[float] | None = None,
+ ) -> Histogram:
+ return self._get(
+ name,
+ lambda meter: meter.create_histogram(
+ name,
+ unit=unit,
+ description=description,
+ explicit_bucket_boundaries_advisory=list(boundaries) if boundaries is not None else None,
+ ),
+ )
+
+ def gauge(self, name: str, *, description: str = "", unit: str = "") -> _Gauge:
+ return self._get(name, lambda meter: meter.create_gauge(name, unit=unit, description=description))
+
+ # The record_*_twin methods mirror an existing Prometheus instrument into the Metrics
+ # product, deriving name, description, and bucket boundaries from the instrument itself
+ # so the two sinks can't drift. They swallow all errors: twins run in hot paths and
+ # error handlers, where a telemetry throw would mask the real failure.
+
+ def record_counter_twin(self, metric: PromCounter, value: float, attributes: dict[str, str]) -> None:
+ try:
+ meta = self._describe_twin(metric)
+ self.counter(meta.name, description=meta.description).add(value, attributes)
+ except Exception:
+ pass
+
+ def record_histogram_twin(self, metric: PromHistogram, value: float, attributes: dict[str, str]) -> None:
+ try:
+ meta = self._describe_twin(metric)
+ self.histogram(meta.name, description=meta.description, unit="s", boundaries=meta.boundaries).record(
+ value, attributes
+ )
+ except Exception:
+ pass
+
+ def record_gauge_twin(self, metric: PromGauge, value: float) -> None:
+ try:
+ meta = self._describe_twin(metric)
+ self.gauge(meta.name, description=meta.description).set(value)
+ except Exception:
+ pass
+
+ @contextmanager
+ def timed_histogram_twin(self, metric: PromHistogram, attributes: dict[str, str]) -> Generator[None]:
+ """Times the block into the prom histogram and its OTLP twin, observing even when
+ the body raises (the exception still propagates)."""
+ started = time.perf_counter()
+ try:
+ yield
+ finally:
+ seconds = time.perf_counter() - started
+ metric.labels(**attributes).observe(seconds)
+ self.record_histogram_twin(metric, seconds, attributes)
+
+ def _describe_twin(self, metric: PromCounter | PromHistogram | PromGauge) -> _TwinMeta:
+ # Keyed by id(): prom instruments are module-level singletons, so ids are stable.
+ meta = self._twin_meta.get(id(metric))
+ if meta is None:
+ described = next(iter(metric.describe()))
+ name = described.name
+ boundaries: list[float] | None = None
+ if described.type == "counter":
+ # prometheus_client strips _total from counter names internally and re-appends
+ # it on scraped samples; restore it so the OTLP name matches the scraped name.
+ name = f"{name}_total"
+ elif described.type == "histogram":
+ # _upper_bounds is prometheus_client-private but stable; the last entry is +Inf,
+ # which OTLP boundaries must not include.
+ boundaries = list(metric._upper_bounds[:-1]) # type: ignore[union-attr]
+ meta = _TwinMeta(name, described.documentation, boundaries)
+ with self._cache_lock:
+ self._twin_meta[id(metric)] = meta
+ return meta
+
+ def _get(self, name: str, build: Callable[[Meter], Any]) -> Any:
+ _ensure_provider()
+ if self._epoch != _epoch:
+ with self._cache_lock:
+ if self._epoch != _epoch:
+ self._cache = {}
+ self._epoch = _epoch
+ instrument = self._cache.get(name)
+ if instrument is None:
+ with self._cache_lock:
+ instrument = self._cache.get(name)
+ if instrument is None:
+ instrument = build(get_otel_meter(self._meter_name))
+ self._cache[name] = instrument
+ return instrument
+
+
+def reset_otel_metrics_for_tests() -> None:
+ """Shut down and forget the cached provider so a test can exercise gating with patched settings."""
+ global _provider, _provider_pid
+ with _lock:
+ if _provider is not None:
+ _provider.shutdown()
+ _provider = None
+ _provider_pid = None
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 4cd0ab26712c..2e2fdd2541eb 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -82,6 +82,7 @@ from posthog.models.comment import Comment
from posthog.models.person.util import get_persons_mapped_by_distinct_id
from posthog.models.team.extensions import get_or_create_team_extension
from posthog.models.utils import hash_key_value
+from posthog.otel_metrics import OtelInstrumentFactory
from posthog.personhog_client.caller_tag import personhog_caller_tag
from posthog.rate_limit import (
ClickHouseBurstRateThrottle,
@@ -185,6 +186,14 @@ SESSION_RECORDING_THROTTLED = Counter(
labelnames=["location", "auth_type"],
)
+_OTEL_PLAYBACK = OtelInstrumentFactory("session-replay-playback")
+
+
+def _count_session_recording_throttled(location: str, auth_type: str) -> None:
+ SESSION_RECORDING_THROTTLED.labels(location=location, auth_type=auth_type).inc()
+ _OTEL_PLAYBACK.record_counter_twin(SESSION_RECORDING_THROTTLED, 1, {"location": location, "auth_type": auth_type})
+
+
logger = structlog.get_logger(__name__)
tracer = trace.get_tracer(__name__)
@@ -783,7 +792,7 @@ def get_replay_listing_throttle_error(request, view) -> str | None:
continue
wait = throttle.wait()
scope = throttle.scope or "listing"
- SESSION_RECORDING_THROTTLED.labels(location=scope, auth_type=auth_type).inc()
+ _count_session_recording_throttled(location=scope, auth_type=auth_type)
if wait:
return f"Rate limit exceeded. Expected available in {wait} seconds."
return "Rate limit exceeded. Try again later."
@@ -817,7 +826,7 @@ class SharingTokenReplayThrottle(SimpleRateThrottle):
return True
if super().allow_request(request, view):
return True
- SESSION_RECORDING_THROTTLED.labels(location=self.scope, auth_type="sharing_token").inc()
+ _count_session_recording_throttled(location=self.scope, auth_type="sharing_token")
return False
@@ -944,7 +953,7 @@ class SessionRecordingViewSet(
return response
except CHQueryErrorTooManySimultaneousQueries:
- SESSION_RECORDING_THROTTLED.labels(location="too_many_simultaneous_queries", auth_type=auth_type).inc()
+ _count_session_recording_throttled(location="too_many_simultaneous_queries", auth_type=auth_type)
raise Throttled(detail="Too many simultaneous queries. Try again later.")
except (ExposedHogQLError, ExposedCHQueryError) as e:
# A bad filter or query (e.g. a property referencing a field that doesn't exist on the
@@ -958,7 +967,7 @@ class SessionRecordingViewSet(
raise
except (ServerException, Exception) as e:
if isinstance(e, ServerException) and "CHQueryErrorTimeoutExceeded" in str(e):
- SESSION_RECORDING_THROTTLED.labels(location="query_timeout_exceeded", auth_type=auth_type).inc()
+ _count_session_recording_throttled(location="query_timeout_exceeded", auth_type=auth_type)
raise Throttled(detail="Query timeout exceeded. Try again later.")
posthoganalytics.capture_exception(
@@ -1546,7 +1555,7 @@ class SessionRecordingViewSet(
) -> Response:
sources: list[dict] = []
- with GATHER_RECORDING_SOURCES_HISTOGRAM.labels(blob_version="v2").time():
+ with _OTEL_PLAYBACK.timed_histogram_twin(GATHER_RECORDING_SOURCES_HISTOGRAM, {"blob_version": "v2"}):
if recording.full_recording_v2_path:
# Parse S3 URL to extract prefix (path without query parameters)
# Example: s3://bucket/path?range=bytes=0-1372588 -> path
@@ -1766,7 +1775,9 @@ class SessionRecordingViewSet(
blob_key: str,
decompress: bool = True,
) -> HttpResponse:
- with STREAM_RESPONSE_TO_CLIENT_HISTOGRAM.labels(blob_version="v2", decompress=decompress).time():
+ with _OTEL_PLAYBACK.timed_histogram_twin(
+ STREAM_RESPONSE_TO_CLIENT_HISTOGRAM, {"blob_version": "v2", "decompress": str(decompress)}
+ ):
with (
tracer.start_as_current_span("list_blocks__stream_lts_blob_v2_to_client_async"),
):
@@ -1891,7 +1902,7 @@ class SessionRecordingViewSet(
span_name = f"fetch_{compress_label}_blocks"
async with recording_api_client() as storage:
- with FETCH_BLOCKS_HISTOGRAM.labels(decompress=str(decompress)).time():
+ with _OTEL_PLAYBACK.timed_histogram_twin(FETCH_BLOCKS_HISTOGRAM, {"decompress": str(decompress)}):
with timer(span_name), tracer.start_as_current_span(span_name):
return await self._fetch_blocks_parallel(
blocks, min_blob_key, max_blob_key, recording, storage, decompress
@@ -1907,7 +1918,9 @@ class SessionRecordingViewSet(
decompress: bool = True,
) -> HttpResponse:
async def _run() -> HttpResponse:
- with STREAM_RESPONSE_TO_CLIENT_HISTOGRAM.labels(blob_version="v2", decompress=decompress).time():
+ with _OTEL_PLAYBACK.timed_histogram_twin(
+ STREAM_RESPONSE_TO_CLIENT_HISTOGRAM, {"blob_version": "v2", "decompress": str(decompress)}
+ ):
blocks = await self._fetch_and_validate_blocks(recording, timer, min_blob_key, max_blob_key)
blocks_data = await self._fetch_blocks_with_storage(
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index 386d0dfd6a1e..ffff3fb7f2dc 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -60,6 +60,16 @@ CAPTURE_REPLAY_INTERNAL_URL = os.getenv("CAPTURE_REPLAY_INTERNAL_URL", "http://l
# empty = emission disabled (the activity skips/raises rather than shipping to the wrong place); set
# per-region via charts in prod, and to the local capture proxy when testing locally.
OTLP_LOGS_INGEST_ENDPOINT = os.getenv("OTLP_LOGS_INGEST_ENDPOINT", "")
+
+# Internal OTLP/HTTP endpoint for first-party metric emission into the Metrics product (the
+# `capture-logs` service, path `/i/v1/metrics`), with a project token as the OTLP Bearer.
+# Names match the Node twins (nodejs/src/common/metrics/otel-metrics.ts) so one env pair
+# configures both runtimes. Defaults to empty = emission disabled (posthog/otel_metrics.py
+# records into a no-op meter).
+OTEL_METRICS_EXPORT_URL = os.getenv("OTEL_METRICS_EXPORT_URL", "")
+OTEL_METRICS_EXPORT_TOKEN = os.getenv("OTEL_METRICS_EXPORT_TOKEN", "")
+OTEL_METRICS_EXPORT_INTERVAL_MS = get_from_env("OTEL_METRICS_EXPORT_INTERVAL_MS", type_cast=int, default=60_000)
+
# Thread-pool size for capture_internal batch chunk fan-out (default 8, was per-event fan-out pre-v1).
CAPTURE_INTERNAL_MAX_WORKERS = get_from_env("CAPTURE_INTERNAL_MAX_WORKERS", type_cast=int, default=8)
diff --git a/posthog/test/test_otel_metrics.py b/posthog/test/test_otel_metrics.py
new file mode 100644
index 000000000000..6868e3b0a022
--- /dev/null
+++ b/posthog/test/test_otel_metrics.py
@@ -0,0 +1,112 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from django.test import SimpleTestCase, override_settings
+
+from opentelemetry.metrics import NoOpMeter
+from opentelemetry.sdk.metrics.export import MetricExporter, MetricExportResult
+from prometheus_client import (
+ CollectorRegistry,
+ Counter as PromCounter,
+ Histogram as PromHistogram,
+)
+
+from posthog.otel_metrics import OtelInstrumentFactory, get_otel_meter, reset_otel_metrics_for_tests
+
+
+class _CapturingExporter(MetricExporter):
+ def __init__(self) -> None:
+ super().__init__()
+ self.exported: list[Any] = []
+
+ def export(self, metrics_data: Any, timeout_millis: float = 10_000, **kwargs: Any) -> MetricExportResult:
+ self.exported.append(metrics_data)
+ return MetricExportResult.SUCCESS
+
+ def force_flush(self, timeout_millis: float = 10_000) -> bool:
+ return True
+
+ def shutdown(self, timeout_millis: float = 30_000, **kwargs: Any) -> None:
+ pass
+
+
+class TestOtelMetrics(SimpleTestCase):
+ def setUp(self) -> None:
+ reset_otel_metrics_for_tests()
+ self.addCleanup(reset_otel_metrics_for_tests)
+
+ def test_unconfigured_is_a_safe_noop(self) -> None:
+ assert isinstance(get_otel_meter("test"), NoOpMeter)
+ factory = OtelInstrumentFactory("test")
+ factory.counter("test_counter_total").add(1, {"a": "b"})
+ factory.histogram("test_histogram_seconds", boundaries=(1, 5)).record(0.1)
+ factory.gauge("test_gauge").set(3)
+
+ @override_settings(
+ OTEL_METRICS_EXPORT_URL="http://capture-logs.local/i/v1/metrics",
+ OTEL_METRICS_EXPORT_TOKEN="phc_test",
+ )
+ def test_configured_records_through_the_sdk_pipeline(self) -> None:
+ exporters: list[_CapturingExporter] = []
+
+ def _make_exporter(**kwargs: Any) -> _CapturingExporter:
+ assert kwargs["endpoint"] == "http://capture-logs.local/i/v1/metrics"
+ assert kwargs["headers"] == {"authorization": "Bearer phc_test"}
+ exporter = _CapturingExporter()
+ exporters.append(exporter)
+ return exporter
+
+ with mock.patch(
+ "opentelemetry.exporter.otlp.proto.http.metric_exporter.OTLPMetricExporter",
+ side_effect=_make_exporter,
+ ):
+ meter = get_otel_meter("test")
+ assert not isinstance(meter, NoOpMeter)
+
+ factory = OtelInstrumentFactory("test")
+ factory.counter("test_counter_total").add(2, {"a": "b"})
+ factory.histogram("test_histogram_seconds", boundaries=(1, 5)).record(0.1)
+ factory.gauge("test_gauge").set(3)
+
+ # Twins derive their identity from the prom instrument: the counter must get the
+ # _total suffix back that prometheus_client strips internally, and the histogram
+ # must inherit the prom bucket ladder so the two sinks stay 1:1.
+ registry = CollectorRegistry()
+ factory.record_counter_twin(PromCounter("twin_probe_total", "d", registry=registry), 3, {"a": "b"})
+ factory.record_histogram_twin(
+ PromHistogram("twin_probe_seconds", "d", registry=registry, buckets=(0.5, 1, 5)), 0.2, {}
+ )
+
+ # Shutdown performs the final collect + export into the capturing exporter.
+ reset_otel_metrics_for_tests()
+
+ assert len(exporters) == 1
+ exported = {
+ metric.name: metric
+ for metrics_data in exporters[0].exported
+ for resource_metrics in metrics_data.resource_metrics
+ for scope_metrics in resource_metrics.scope_metrics
+ for metric in scope_metrics.metrics
+ }
+ assert {
+ "test_counter_total",
+ "test_histogram_seconds",
+ "test_gauge",
+ "twin_probe_total",
+ "twin_probe_seconds",
+ } <= exported.keys()
+ twin_histogram_points = exported["twin_probe_seconds"].data.data_points
+ assert [list(point.explicit_bounds) for point in twin_histogram_points] == [[0.5, 1, 5]]
+
+ def test_timed_histogram_twin_observes_prom_and_propagates_exceptions(self) -> None:
+ registry = CollectorRegistry()
+ histogram = PromHistogram("timed_probe_seconds", "d", ["stage"], registry=registry)
+ factory = OtelInstrumentFactory("test")
+
+ with pytest.raises(ValueError):
+ with factory.timed_histogram_twin(histogram, {"stage": "fetch"}):
+ raise ValueError("boom")
+
+ assert registry.get_sample_value("timed_probe_seconds_count", {"stage": "fetch"}) == 1
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 27574425d278..5029b6d4a9e1 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -33,7 +33,7 @@ from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureError
from products.replay_vision.backend.temporal.events_tool import build_events_index, dispatch_events_tool, events_tool
from products.replay_vision.backend.temporal.gemini import gemini_api_key
-from products.replay_vision.backend.temporal.metrics import REPLAY_VISION_PROVIDER_CALL
+from products.replay_vision.backend.temporal.metrics import record_provider_call
from products.replay_vision.backend.temporal.scanners import scanner_from_snapshot
from products.replay_vision.backend.temporal.scanners.base import (
BaseScanner,
@@ -330,8 +330,8 @@ async def _run_step(
if function_calls(response):
# Tool budget spent and the model still wants a lookup. Rather than hard-fail, complete the
# round-trip and force one final tool-free turn so it answers from what it has already seen.
- REPLAY_VISION_PROVIDER_CALL.labels(**metric_labels, outcome="tool_budget_exhausted").observe(
- time.monotonic() - started
+ record_provider_call(
+ **metric_labels, outcome="tool_budget_exhausted", seconds=time.monotonic() - started
)
logger.warning(
"replay_vision.call_scanner_provider.tool_budget_exhausted", step=step.name, attempt=attempt + 1
@@ -341,25 +341,23 @@ async def _run_step(
generate=lambda c: _generate(c, forced_config), convo=convo, exhausted=response, dispatch=dispatch
)
except Exception:
- REPLAY_VISION_PROVIDER_CALL.labels(**metric_labels, outcome="provider_error").observe(
- time.monotonic() - started
- )
+ record_provider_call(**metric_labels, outcome="provider_error", seconds=time.monotonic() - started)
raise
if not response.candidates:
# No candidate (safety filter / content policy): record a failed attempt and retry without indexing [0].
last_error = "model returned no candidates"
- REPLAY_VISION_PROVIDER_CALL.labels(**metric_labels, outcome="validation_failed").observe(
- time.monotonic() - started
- )
+ record_provider_call(**metric_labels, outcome="validation_failed", seconds=time.monotonic() - started)
logger.warning("replay_vision.call_scanner_provider.empty_response", step=step.name, attempt=attempt + 1)
continue
text = (response.text or "").strip()
parsed, error = _parse_and_validate(step, text)
- REPLAY_VISION_PROVIDER_CALL.labels(
- **metric_labels, outcome="ok" if error is None else "validation_failed"
- ).observe(time.monotonic() - started)
+ record_provider_call(
+ **metric_labels,
+ outcome="ok" if error is None else "validation_failed",
+ seconds=time.monotonic() - started,
+ )
if error is None:
convo.append(response.candidates[0].content) # carry the answer into the next turn
diff --git a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
index a36fc906fef6..4b47ac8afa85 100644
--- a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
+++ b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
@@ -6,7 +6,9 @@ from temporalio import activity
from posthog.temporal.common.client import async_connect
from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.temporal.constants import in_flight_headroom
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs, InFlightApplyCounts
logger = structlog.get_logger(__name__)
@@ -42,4 +44,8 @@ def count_in_flight_by_team_activity(inputs: CountInFlightAppliesInputs) -> InFl
team=Count("id"),
scanner=Count("id", filter=Q(scanner_id=inputs.scanner_id)),
)
+ # The workflow makes the same call on these counts; recorded here because metrics
+ # can't be emitted from deterministic workflow code.
+ if in_flight_headroom(counts["scanner"], counts["team"]) <= 0:
+ record_sweep_outcome("throttled")
return InFlightApplyCounts(scanner=counts["scanner"], team=counts["team"])
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 01b44ff94552..16960437456e 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -13,6 +13,7 @@ from products.replay_vision.backend.models.replay_observation import Observation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.metrics import record_quota_exhausted_skip
from products.replay_vision.backend.temporal.types import (
CreateObservationInputs,
CreateObservationOutput,
@@ -52,6 +53,7 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv
)
if compute_quota_snapshot(scanner.team.organization_id).would_exceed(observation_credits_for_model(scanner.model)):
+ record_quota_exhausted_skip(scanner.scanner_type)
activity.logger.info(
"Skipping observation: monthly quota exhausted",
extra={"scanner_id": str(inputs.scanner_id), "team_id": inputs.team_id, "session_id": inputs.session_id},
diff --git a/products/replay_vision/backend/temporal/activities/embed_observation.py b/products/replay_vision/backend/temporal/activities/embed_observation.py
index bd9b1bc2f90d..3fb9a547c05f 100644
--- a/products/replay_vision/backend/temporal/activities/embed_observation.py
+++ b/products/replay_vision/backend/temporal/activities/embed_observation.py
@@ -111,7 +111,7 @@ async def _emit_embeddings(
@activity.defn
-@track_activity()
+@track_activity(side_effect="embed")
async def embed_observation_activity(inputs: EmbedObservationInputs) -> None:
"""Emit one embedding per non-empty rendering of the observation's explanation text."""
metadata = {
diff --git a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
index d0c6d6afda2f..a733cf7b05a1 100644
--- a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
+++ b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py
@@ -32,7 +32,7 @@ def _load_session_identity(observation_id: UUID) -> tuple[str | None, datetime |
@activity.defn
-@track_activity()
+@track_activity(side_effect="tags")
async def emit_classifier_tags_activity(inputs: EmitClassifierTagsInputs) -> None:
"""Merge classifier tags into the session row via Kafka. Raises on failure."""
# distinct_id + start_time were persisted by `fetch_session_events`, so reuse them instead of re-querying CH.
diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
index e6314a21b185..9bee3b2e8094 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py
@@ -22,7 +22,7 @@ _EVENT_SOURCE = "replay_vision"
@activity.defn
-@track_activity()
+@track_activity(side_effect="event")
async def emit_observation_event_activity(inputs: EmitObservationEventInputs) -> None:
"""Capture the `$recording_observed` event into the customer's events table; dedup-keyed by observation_id."""
await database_sync_to_async(_emit_event, thread_sensitive=False)(inputs)
diff --git a/products/replay_vision/backend/temporal/activities/emit_observation_signal.py b/products/replay_vision/backend/temporal/activities/emit_observation_signal.py
index d8ff1aa8819d..8bb84f6e6639 100644
--- a/products/replay_vision/backend/temporal/activities/emit_observation_signal.py
+++ b/products/replay_vision/backend/temporal/activities/emit_observation_signal.py
@@ -8,6 +8,7 @@ from temporalio import activity
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.temporal.constants import VISION_SIGNALS_SOURCE_PRODUCT, VISION_SIGNALS_SOURCE_TYPE
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.metrics import record_side_effect_failure
from products.replay_vision.backend.temporal.scanners.base import MIN_SIGNAL_CONFIDENCE
from products.replay_vision.backend.temporal.state import load_scanner_llm_inputs
from products.replay_vision.backend.temporal.types import EmitObservationSignalInputs, ScannerLlmInputs, ScannerSnapshot
@@ -25,7 +26,7 @@ def _load_llm_inputs(observation_id: UUID) -> ScannerLlmInputs | None:
@activity.defn
-@track_activity()
+@track_activity(side_effect="signal")
def emit_observation_signal_activity(inputs: EmitObservationSignalInputs) -> int:
"""Emit the observation's side-mission findings as PostHog Signals; fails soft, returns the emitted count."""
try:
@@ -71,6 +72,7 @@ def emit_observation_signal_activity(inputs: EmitObservationSignalInputs) -> int
base_extra["recording_active_seconds"] = meta.active_seconds
emitted = 0
+ any_failed = False
for index, signal in enumerate(inputs.signals):
if signal.confidence < MIN_SIGNAL_CONFIDENCE:
continue
@@ -95,13 +97,19 @@ def emit_observation_signal_activity(inputs: EmitObservationSignalInputs) -> int
emitted += 1
except Exception:
# One bad finding never blocks the rest; signals are advisory.
+ any_failed = True
logger.exception(
"replay_vision.signal_emission_failed",
observation_id=str(inputs.observation_id),
finding_index=index,
)
+ if any_failed:
+ # Per activity, not per finding, so the counter is comparable to the other effects.
+ record_side_effect_failure("signal")
return emitted
except Exception:
- # Never fail the observation over emission.
+ # Never fail the observation over emission. Counted here because the swallow means
+ # track_activity sees a success.
+ record_side_effect_failure("signal")
logger.exception("replay_vision.signal_emission_failed", observation_id=str(inputs.observation_id))
return 0
diff --git a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
index 8ed2f53abc9d..6a0b5e8fa92a 100644
--- a/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
+++ b/products/replay_vision/backend/temporal/activities/find_scanner_candidates.py
@@ -10,6 +10,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import (
ScannerCandidateQuery,
)
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
from products.replay_vision.backend.temporal.sweep_types import (
CandidateSessionPayload,
FindScannerCandidatesInputs,
@@ -55,6 +56,7 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
)
candidates = candidate_query.run()
+ record_sweep_outcome("candidates_found" if candidates else "no_candidates", candidates=len(candidates))
return FindScannerCandidatesOutput(
candidates=[CandidateSessionPayload(session_id=c.session_id, session_end=c.session_end) for c in candidates],
# A full batch means there may be more past the keyset; the next sweep resumes from the last candidate.
diff --git a/products/replay_vision/backend/temporal/activities/observation_state.py b/products/replay_vision/backend/temporal/activities/observation_state.py
index fc7e6bfa0feb..0dfd0396f1b7 100644
--- a/products/replay_vision/backend/temporal/activities/observation_state.py
+++ b/products/replay_vision/backend/temporal/activities/observation_state.py
@@ -13,9 +13,11 @@ from products.replay_vision.backend.models.replay_observation_usage import Repla
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind, IneligibleSessionKind
from products.replay_vision.backend.temporal.metrics import (
- REPLAY_VISION_FAILURE_KINDS,
- REPLAY_VISION_INELIGIBLE_KINDS,
- REPLAY_VISION_OBSERVATIONS,
+ record_credits_consumed,
+ record_failure_kind,
+ record_ineligible_kind,
+ record_observation,
+ record_observation_e2e,
)
from products.replay_vision.backend.temporal.types import (
MarkObservationFailedInputs,
@@ -74,7 +76,7 @@ def mark_observation_terminal(
if not updated:
return False # No state transition — retry against an already-terminal row.
kind = _kind_from_error_reason(error_reason, valid_kinds)
- REPLAY_VISION_OBSERVATIONS.labels(status=status.value, scanner_type=scanner_type).inc()
+ record_observation(status.value, scanner_type)
count_kind(kind)
logger.info(
f"replay_vision.observation.{status.value}",
@@ -96,7 +98,7 @@ def mark_observation_failed_activity(inputs: MarkObservationFailedInputs) -> Non
error_reason=inputs.error_reason,
scanner_type=inputs.scanner_type,
valid_kinds=_FAILURE_KIND_VALUES,
- count_kind=lambda kind: REPLAY_VISION_FAILURE_KINDS.labels(kind=kind, scanner_type=inputs.scanner_type).inc(),
+ count_kind=lambda kind: record_failure_kind(kind, inputs.scanner_type),
)
@@ -110,7 +112,7 @@ def mark_observation_ineligible_activity(inputs: MarkObservationIneligibleInputs
error_reason=inputs.error_reason,
scanner_type=inputs.scanner_type,
valid_kinds=_INELIGIBLE_KIND_VALUES,
- count_kind=lambda kind: REPLAY_VISION_INELIGIBLE_KINDS.labels(kind=kind).inc(),
+ count_kind=lambda kind: record_ineligible_kind(kind),
)
@@ -134,17 +136,22 @@ def mark_observation_succeeded_activity(inputs: MarkObservationSucceededInputs)
"team_id", "team__organization_id", "created_at", "scanner_snapshot__model"
).get(pk=inputs.observation_id)
model = obs["scanner_snapshot__model"] or ""
- ReplayObservationUsage.objects.get_or_create(
+ credits = observation_credits_for_model(model)
+ _, receipt_created = ReplayObservationUsage.objects.get_or_create(
observation_id=inputs.observation_id,
defaults={
"organization_id": obs["team__organization_id"],
"team_id": obs["team_id"],
"observation_created_at": obs["created_at"],
"model": model,
- "credits": observation_credits_for_model(model),
+ "credits": credits,
},
)
- REPLAY_VISION_OBSERVATIONS.labels(status="succeeded", scanner_type=inputs.scanner_type).inc()
+ record_observation("succeeded", inputs.scanner_type)
+ record_observation_e2e(inputs.scanner_type, (timezone.now() - obs["created_at"]).total_seconds())
+ if receipt_created:
+ # Gate on the receipt so a lost-result retry can't double count the burn rate.
+ record_credits_consumed(inputs.scanner_type, model, credits)
logger.info(
"replay_vision.observation.succeeded",
observation_id=str(inputs.observation_id),
diff --git a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
index 439098f7d8f1..934033e6f791 100644
--- a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
@@ -20,7 +20,7 @@ from products.replay_vision.backend.temporal.constants import (
)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind
-from products.replay_vision.backend.temporal.metrics import REPLAY_VISION_FAILURE_KINDS
+from products.replay_vision.backend.temporal.metrics import record_failure_kind
logger = structlog.get_logger(__name__)
@@ -59,7 +59,7 @@ def _mark_orphaned(observation_id: UUID, scanner_type: str) -> bool:
error_reason=_ORPHANED_ERROR_REASON,
scanner_type=scanner_type,
valid_kinds={FailureKind.ORPHANED.value},
- count_kind=lambda kind: REPLAY_VISION_FAILURE_KINDS.labels(kind=kind, scanner_type=scanner_type).inc(),
+ count_kind=lambda kind: record_failure_kind(kind, scanner_type),
)
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 6ad9b5609782..406fc7d12868 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -89,6 +89,19 @@ MAX_IN_FLIGHT_APPLIES_PER_TEAM = 300
COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)
+def in_flight_headroom(scanner_in_flight: int, team_in_flight: int) -> int:
+ """Dispatch headroom for a sweep tick: the tighter of the per-scanner and per-team caps.
+
+ The sweep workflow throttles on this and the count activity records the throttled
+ metric from it, so the decision and the metric can't drift apart. Pure, so it is safe
+ inside deterministic workflow code.
+ """
+ return min(
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,
+ )
+
+
ESTIMATES_WORKFLOW_NAME = "replay-vision-refresh-scanner-estimates"
ESTIMATES_WORKFLOW_ID = "replay-vision-estimate-refresher"
ESTIMATES_SCHEDULE_ID = "replay-vision-estimate-refresher-schedule"
diff --git a/products/replay_vision/backend/temporal/decorators.py b/products/replay_vision/backend/temporal/decorators.py
index a06bcdef7c32..0fb13ea52e0c 100644
--- a/products/replay_vision/backend/temporal/decorators.py
+++ b/products/replay_vision/backend/temporal/decorators.py
@@ -6,17 +6,27 @@ from collections.abc import Callable
from functools import wraps
from typing import Any, TypeVar, cast
-from products.replay_vision.backend.temporal.metrics import REPLAY_VISION_ACTIVITY_DURATION
+from products.replay_vision.backend.temporal.metrics import record_activity_duration, record_side_effect_failure
F = TypeVar("F", bound=Callable[..., Any])
-def track_activity(name: str | None = None) -> Callable[[F], F]:
- """Wrap an activity body to record `replay_vision_activity_duration_seconds`; apply below `@activity.defn`."""
+def track_activity(name: str | None = None, side_effect: str | None = None) -> Callable[[F], F]:
+ """Wrap an activity body to record `replay_vision_activity_duration_seconds`; apply below `@activity.defn`.
+
+ Pass `side_effect` on fail-soft post-success activities so their failed attempts also
+ count into `replay_vision_side_effect_failures_total`. The workflow swallows their
+ errors, so nothing downstream would surface the degradation.
+ """
def decorator(fn: F) -> F:
label = name or fn.__name__
+ def _record(status: str, started: float) -> None:
+ record_activity_duration(label, status, time.monotonic() - started)
+ if status == "failed" and side_effect is not None:
+ record_side_effect_failure(side_effect)
+
if inspect.iscoroutinefunction(fn):
@wraps(fn)
@@ -25,13 +35,9 @@ def track_activity(name: str | None = None) -> Callable[[F], F]:
try:
result = await fn(*args, **kwargs)
except Exception:
- REPLAY_VISION_ACTIVITY_DURATION.labels(activity=label, status="failed").observe(
- time.monotonic() - started
- )
+ _record("failed", started)
raise
- REPLAY_VISION_ACTIVITY_DURATION.labels(activity=label, status="succeeded").observe(
- time.monotonic() - started
- )
+ _record("succeeded", started)
return result
return cast(F, async_wrapper)
@@ -42,13 +48,9 @@ def track_activity(name: str | None = None) -> Callable[[F], F]:
try:
result = fn(*args, **kwargs)
except Exception:
- REPLAY_VISION_ACTIVITY_DURATION.labels(activity=label, status="failed").observe(
- time.monotonic() - started
- )
+ _record("failed", started)
raise
- REPLAY_VISION_ACTIVITY_DURATION.labels(activity=label, status="succeeded").observe(
- time.monotonic() - started
- )
+ _record("succeeded", started)
return result
return cast(F, sync_wrapper)
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
index ce1c96b0a8dc..fbfd4ec334ff 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
@@ -28,6 +28,7 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import (
CleanupSweepResult,
TrackedFile,
)
+from products.replay_vision.backend.temporal.metrics import record_gemini_cleanup_backlog
logger = structlog.get_logger(__name__)
@@ -73,6 +74,7 @@ async def _sweep_gemini_files(inputs: CleanupSweepInputs) -> CleanupSweepResult:
cutoff = datetime.now(UTC) - SWEEP_MIN_AGE
total_tracked = await index_size()
+ record_gemini_cleanup_backlog(total_tracked)
hit_max_files_cap = total_tracked > MAX_FILES_PER_SWEEP
scanned = 0
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index f21961d59880..9b6b24e5593f 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -1,6 +1,18 @@
-"""Prometheus metrics for the Replay Vision workflow + activities; auto-scraped by the worker's combined metrics server."""
+"""Replay Vision workflow + activity metrics.
-from prometheus_client import Counter, Histogram
+Every metric is emitted twice from one `record_*` helper: a Prometheus instrument
+(auto-scraped by the worker's combined metrics server, feeds Grafana) and an OTLP twin
+with the same name and attributes pushed into the PostHog Metrics product via
+posthog/otel_metrics.py (no-op unless OTEL_METRICS_EXPORT_URL/TOKEN are configured).
+The twin derives its name and description from the prom instrument, and its recording
+is swallowed so telemetry can never fail an activity.
+"""
+
+from prometheus_client import Counter, Gauge, Histogram
+
+from posthog.otel_metrics import OtelInstrumentFactory
+
+_otel = OtelInstrumentFactory("replay-vision")
REPLAY_VISION_OBSERVATIONS = Counter(
"replay_vision_observations_total",
@@ -30,9 +42,119 @@ REPLAY_VISION_ACTIVITY_DURATION = Histogram(
buckets=_ACTIVITY_DURATION_BUCKETS,
)
+_PROVIDER_CALL_BUCKETS = (0.5, 1, 2.5, 5, 10, 30, 60, 120, 300)
+
REPLAY_VISION_PROVIDER_CALL = Histogram(
"replay_vision_provider_call_seconds",
"Provider call latency",
["provider", "model", "scanner_type", "outcome"],
- buckets=(0.5, 1, 2.5, 5, 10, 30, 60, 120, 300),
+ buckets=_PROVIDER_CALL_BUCKETS,
+)
+
+REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS = Counter(
+ "replay_vision_quota_exhausted_skips_total",
+ "Observations skipped because the org's monthly credit quota was exhausted",
+ ["scanner_type"],
)
+
+REPLAY_VISION_CREDITS_CONSUMED = Counter(
+ "replay_vision_credits_consumed_total",
+ "Credits billed onto usage receipts at observation success",
+ ["scanner_type", "model"],
+)
+
+REPLAY_VISION_SWEEP_OUTCOMES = Counter(
+ "replay_vision_sweep_outcomes_total",
+ "Sweep tick outcomes: throttled at an in-flight cap, no candidates, or candidates found",
+ ["outcome"],
+)
+
+REPLAY_VISION_SWEEP_CANDIDATES = Counter(
+ "replay_vision_sweep_candidates_total",
+ "Candidate sessions returned to sweeps for dispatch",
+)
+
+# Creation to success spans queueing, rasterization, upload, and the provider call.
+_E2E_BUCKETS = (30.0, 60.0, 120.0, 300.0, 600.0, 1200.0, 1800.0, 3600.0, 7200.0)
+
+REPLAY_VISION_OBSERVATION_E2E = Histogram(
+ "replay_vision_observation_e2e_seconds",
+ "Wall time from observation creation to success",
+ ["scanner_type"],
+ buckets=_E2E_BUCKETS,
+)
+
+REPLAY_VISION_SIDE_EFFECT_FAILURES = Counter(
+ "replay_vision_side_effect_failures_total",
+ "Failed attempts of fail-soft post-success side effects",
+ ["effect"],
+)
+
+REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge(
+ "replay_vision_gemini_cleanup_backlog",
+ "Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",
+)
+
+
+def record_observation(status: str, scanner_type: str) -> None:
+ labels = {"status": status, "scanner_type": scanner_type}
+ REPLAY_VISION_OBSERVATIONS.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_OBSERVATIONS, 1, labels)
+
+
+def record_failure_kind(kind: str, scanner_type: str) -> None:
+ labels = {"kind": kind, "scanner_type": scanner_type}
+ REPLAY_VISION_FAILURE_KINDS.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_FAILURE_KINDS, 1, labels)
+
+
+def record_ineligible_kind(kind: str) -> None:
+ REPLAY_VISION_INELIGIBLE_KINDS.labels(kind=kind).inc()
+ _otel.record_counter_twin(REPLAY_VISION_INELIGIBLE_KINDS, 1, {"kind": kind})
+
+
+def record_activity_duration(activity: str, status: str, seconds: float) -> None:
+ labels = {"activity": activity, "status": status}
+ REPLAY_VISION_ACTIVITY_DURATION.labels(**labels).observe(seconds)
+ _otel.record_histogram_twin(REPLAY_VISION_ACTIVITY_DURATION, seconds, labels)
+
+
+def record_provider_call(provider: str, model: str, scanner_type: str, outcome: str, seconds: float) -> None:
+ labels = {"provider": provider, "model": model, "scanner_type": scanner_type, "outcome": outcome}
+ REPLAY_VISION_PROVIDER_CALL.labels(**labels).observe(seconds)
+ _otel.record_histogram_twin(REPLAY_VISION_PROVIDER_CALL, seconds, labels)
+
+
+def record_quota_exhausted_skip(scanner_type: str) -> None:
+ REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS.labels(scanner_type=scanner_type).inc()
+ _otel.record_counter_twin(REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS, 1, {"scanner_type": scanner_type})
+
+
+def record_credits_consumed(scanner_type: str, model: str, credits: int) -> None:
+ labels = {"scanner_type": scanner_type, "model": model}
+ REPLAY_VISION_CREDITS_CONSUMED.labels(**labels).inc(credits)
+ _otel.record_counter_twin(REPLAY_VISION_CREDITS_CONSUMED, credits, labels)
+
+
+def record_sweep_outcome(outcome: str, candidates: int = 0) -> None:
+ REPLAY_VISION_SWEEP_OUTCOMES.labels(outcome=outcome).inc()
+ _otel.record_counter_twin(REPLAY_VISION_SWEEP_OUTCOMES, 1, {"outcome": outcome})
+ if candidates > 0:
+ REPLAY_VISION_SWEEP_CANDIDATES.inc(candidates)
+ _otel.record_counter_twin(REPLAY_VISION_SWEEP_CANDIDATES, candidates, {})
+
+
+def record_observation_e2e(scanner_type: str, seconds: float) -> None:
+ labels = {"scanner_type": scanner_type}
+ REPLAY_VISION_OBSERVATION_E2E.labels(**labels).observe(seconds)
+ _otel.record_histogram_twin(REPLAY_VISION_OBSERVATION_E2E, seconds, labels)
+
+
+def record_side_effect_failure(effect: str) -> None:
+ REPLAY_VISION_SIDE_EFFECT_FAILURES.labels(effect=effect).inc()
+ _otel.record_counter_twin(REPLAY_VISION_SIDE_EFFECT_FAILURES, 1, {"effect": effect})
+
+
+def record_gemini_cleanup_backlog(count: int) -> None:
+ REPLAY_VISION_GEMINI_CLEANUP_BACKLOG.set(count)
+ _otel.record_gauge_twin(REPLAY_VISION_GEMINI_CLEANUP_BACKLOG, count)
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index 5d163bc6d769..ee84ad18e257 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -30,14 +30,13 @@ from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
- MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
- MAX_IN_FLIGHT_APPLIES_PER_TEAM,
PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
PROCESS_VISION_ACTION_WORKFLOW_NAME,
REFRESH_PROMPT_SUGGESTION_TIMEOUT,
SWEEP_SCANNER_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
build_process_vision_action_workflow_id,
+ in_flight_headroom,
)
from products.replay_vision.backend.temporal.sweep_types import (
AdvanceScannerWatermarkInputs,
@@ -109,10 +108,7 @@ class SweepScannerWorkflow(PostHogWorkflow):
retry_policy=common.RetryPolicy(maximum_attempts=1),
)
team_in_flight = 0
- headroom = min(
- MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,
- MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,
- )
+ headroom = in_flight_headroom(scanner_in_flight, team_in_flight)
if headroom <= 0:
# At a cap — drain before fetching more. Don't advance the watermark; resume next tick.
wf.logger.info(
diff --git a/products/replay_vision/backend/tests/test_metrics.py b/products/replay_vision/backend/tests/test_metrics.py
new file mode 100644
index 000000000000..4caafdebde50
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_metrics.py
@@ -0,0 +1,127 @@
+from collections.abc import Callable
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+
+from products.replay_vision.backend.temporal.metrics import (
+ record_activity_duration,
+ record_credits_consumed,
+ record_failure_kind,
+ record_gemini_cleanup_backlog,
+ record_ineligible_kind,
+ record_observation,
+ record_observation_e2e,
+ record_provider_call,
+ record_quota_exhausted_skip,
+ record_side_effect_failure,
+ record_sweep_outcome,
+)
+
+
+def _sample(name: str, labels: dict[str, str]) -> float:
+ return REGISTRY.get_sample_value(name, labels) or 0.0
+
+
+class TestRecordHelpers(SimpleTestCase):
+ # Each helper runs inside activity bodies and error handlers, where a prom label
+ # mismatch would raise at runtime; one call per helper locks the label sets in.
+ @parameterized.expand(
+ [
+ (
+ "observation",
+ lambda: record_observation("succeeded", "monitor"),
+ "replay_vision_observations_total",
+ {"status": "succeeded", "scanner_type": "monitor"},
+ 1.0,
+ ),
+ (
+ "failure_kind",
+ lambda: record_failure_kind("provider_transient", "monitor"),
+ "replay_vision_failure_kinds_total",
+ {"kind": "provider_transient", "scanner_type": "monitor"},
+ 1.0,
+ ),
+ (
+ "ineligible_kind",
+ lambda: record_ineligible_kind("too_short"),
+ "replay_vision_ineligible_kinds_total",
+ {"kind": "too_short"},
+ 1.0,
+ ),
+ (
+ "activity_duration",
+ lambda: record_activity_duration("some_activity", "failed", 1.5),
+ "replay_vision_activity_duration_seconds_count",
+ {"activity": "some_activity", "status": "failed"},
+ 1.0,
+ ),
+ (
+ "provider_call",
+ lambda: record_provider_call("gemini", "gemini-3-flash", "monitor", "ok", 2.0),
+ "replay_vision_provider_call_seconds_count",
+ {"provider": "gemini", "model": "gemini-3-flash", "scanner_type": "monitor", "outcome": "ok"},
+ 1.0,
+ ),
+ (
+ "quota_exhausted_skip",
+ lambda: record_quota_exhausted_skip("monitor"),
+ "replay_vision_quota_exhausted_skips_total",
+ {"scanner_type": "monitor"},
+ 1.0,
+ ),
+ (
+ "credits_consumed",
+ lambda: record_credits_consumed("monitor", "gemini-3-flash", 5),
+ "replay_vision_credits_consumed_total",
+ {"scanner_type": "monitor", "model": "gemini-3-flash"},
+ 5.0,
+ ),
+ (
+ "sweep_outcome",
+ lambda: record_sweep_outcome("throttled"),
+ "replay_vision_sweep_outcomes_total",
+ {"outcome": "throttled"},
+ 1.0,
+ ),
+ (
+ "sweep_candidates",
+ lambda: record_sweep_outcome("candidates_found", candidates=3),
+ "replay_vision_sweep_candidates_total",
+ {},
+ 3.0,
+ ),
+ (
+ "observation_e2e",
+ lambda: record_observation_e2e("monitor", 120.0),
+ "replay_vision_observation_e2e_seconds_count",
+ {"scanner_type": "monitor"},
+ 1.0,
+ ),
+ (
+ "side_effect_failure",
+ lambda: record_side_effect_failure("signal"),
+ "replay_vision_side_effect_failures_total",
+ {"effect": "signal"},
+ 1.0,
+ ),
+ ]
+ )
+ def test_record_helper_increments_prom_sample(
+ self,
+ _name: str,
+ record: Callable[[], None],
+ sample_name: str,
+ labels: dict[str, str],
+ expected_delta: float,
+ ) -> None:
+ before = _sample(sample_name, labels)
+ record()
+ assert _sample(sample_name, labels) == before + expected_delta
+
+ def test_gemini_cleanup_backlog_is_a_gauge(self) -> None:
+ record_gemini_cleanup_backlog(7)
+ assert _sample("replay_vision_gemini_cleanup_backlog", {}) == 7.0
+ record_gemini_cleanup_backlog(2)
+ assert _sample("replay_vision_gemini_cleanup_backlog", {}) == 2.0