: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-vision): close observability gaps ahead of launch (#75395)
Tue Haulundb036e280f3d1
diff --git a/Dockerfile.recording-rasterizer b/Dockerfile.recording-rasterizerindex 01b76c6e4a95..e0665dd85d95 100644--- a/Dockerfile.recording-rasterizer+++ b/Dockerfile.recording-rasterizer@@ -176,6 +176,6 @@ ENV NODE_ENV=production \# Validate runtime dependenciesRUN chrome-headless-shell --version && ffmpeg -version-EXPOSE 6740+EXPOSE 6738CMD ["node", "nodejs/dist/session-replay/recording-rasterizer/index.js"]diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.tsindex 04f84260f2a2..771f976020bb 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts@@ -206,7 +206,7 @@ describe('rasterizeRecordingActivity', () => {})it('re-throws retryable RasterizationError as plain Error (Temporal retries)', async () => {- const error = new RasterizationError('browser crashed', true, 'PLAYBACK_ERROR')+ const error = new RasterizationError('browser crashed', true, 'TIMEOUT')mockedRasterizeRecording.mockRejectedValue(error)const rejection = rasterizeRecordingActivity(baseInput())diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/browser-pool.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/browser-pool.test.tsindex 84ba2024c160..bb3d8919a26b 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/browser-pool.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/browser-pool.test.ts@@ -16,22 +16,23 @@ jest.mock('~/session-replay/recording-rasterizer/logger', () => {}})-jest.mock(- 'puppeteer-capture',- () => ({- launch: jest.fn(),- }),- { virtual: true }-)+jest.mock('puppeteer-capture', () => ({+ launch: jest.fn(),+}))const puppeteerCapture = require('puppeteer-capture')const ORIGINAL_ENV = process.envfunction mockBrowser(): jest.Mocked<Browser> {+ const handlers: Record<string, () => void> = {}return {newPage: jest.fn(),close: jest.fn(),+ on: jest.fn((event: string, handler: () => void) => {+ handlers[event] = handler+ }),+ emit: jest.fn((event: string) => handlers[event]?.()),} as any}@@ -110,6 +111,38 @@ describe('BrowserPool', () => {expect(puppeteerCapture.launch).toHaveBeenCalledTimes(1)})+ it('evicts a crashed browser instead of reusing it', async () => {+ const browser1 = mockBrowser()+ const browser2 = mockBrowser()+ browser1.newPage.mockResolvedValue(mockPage())+ browser2.newPage.mockResolvedValue(mockPage())+ puppeteerCapture.launch.mockResolvedValueOnce(browser1).mockResolvedValueOnce(browser2)++ pool = new BrowserPool(100)+ const p1 = await pool.getPage()+ await pool.releasePage(p1) // browser1 is now idle+ ;(browser1 as any).emit('disconnected') // crash while idle++ await pool.getPage()+ expect(puppeteerCapture.launch).toHaveBeenCalledTimes(2) // fresh launch, crashed one not reused+ })++ it('does not re-idle a browser that crashed while its page was checked out', async () => {+ const browser1 = mockBrowser()+ const browser2 = mockBrowser()+ browser1.newPage.mockResolvedValue(mockPage())+ browser2.newPage.mockResolvedValue(mockPage())+ puppeteerCapture.launch.mockResolvedValueOnce(browser1).mockResolvedValueOnce(browser2)++ pool = new BrowserPool(100)+ const p1 = await pool.getPage()+ ;(browser1 as any).emit('disconnected') // crash mid-capture+ await pool.releasePage(p1)++ await pool.getPage()+ expect(puppeteerCapture.launch).toHaveBeenCalledTimes(2)+ })+it('recycles browser when usage hits recycleAfter', async () => {const browser1 = mockBrowser()const browser2 = mockBrowser()diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.tsindex 3a9931a739d5..b18715c11b22 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts@@ -7,23 +7,19 @@ import { PlayerController } from '~/session-replay/recording-rasterizer/capture/import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'import { CaptureConfig } from '~/session-replay/recording-rasterizer/types'-jest.mock(- 'puppeteer-capture',- () => {- const recorder = {- start: jest.fn().mockResolvedValue(undefined),- stop: jest.fn().mockResolvedValue(undefined),- waitForTimeout: jest.fn().mockResolvedValue(undefined),- on: jest.fn(),- off: jest.fn(),- }- return {- __mockRecorder: recorder,- capture: jest.fn().mockResolvedValue(recorder),- }- },- { virtual: true }-)+jest.mock('puppeteer-capture', () => {+ const recorder = {+ start: jest.fn().mockResolvedValue(undefined),+ stop: jest.fn().mockResolvedValue(undefined),+ waitForTimeout: jest.fn().mockResolvedValue(undefined),+ on: jest.fn(),+ off: jest.fn(),+ }+ return {+ __mockRecorder: recorder,+ capture: jest.fn().mockResolvedValue(recorder),+ }+})jest.mock('~/session-replay/recording-rasterizer/logger', () => ({createLogger: () => ({@@ -274,6 +270,29 @@ describe('capturePlayback', () => {expect(mockRecorder.stop).toHaveBeenCalled()})+ it.each([+ {+ name: 'attributes an unexpected stop to fatalError when set',+ fatal: new RasterizationError(+ 'beginFrame timeout (15s) — compositor deadlock',+ true,+ 'BEGINFRAME_DEADLOCK'+ ),+ code: 'BEGINFRAME_DEADLOCK',+ },+ { name: 'falls back to CAPTURE_ABORTED without fatalError', fatal: null, code: 'CAPTURE_ABORTED' },+ ])('$name', async ({ fatal, code }) => {+ const player = mockPlayer({ fatalError: fatal })+ mockRecorder.waitForTimeout.mockImplementation(() => {+ const onCall = mockRecorder.on.mock.calls.find(([event]: [string]) => event === 'captureStopped')+ onCall?.[1]()+ })++ await expect(capturePlayback(player, baseCaptureConfig(), outputPath, jest.fn())).rejects.toMatchObject({+ code,+ })+ })+it('removes captureStopped listener and page listeners in finally block', async () => {const player = mockPlayer({ isEnded: jest.fn().mockReturnValue(true) })diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/errors.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/errors.test.tsindex 2a004a3bca22..218500ebe5c7 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/errors.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/errors.test.ts@@ -2,11 +2,11 @@ import { RasterizationError } from '~/session-replay/recording-rasterizer/errorsdescribe('RasterizationError', () => {it('sets name, message, retryable, and code', () => {- const err = new RasterizationError('something broke', true, 'PLAYBACK_ERROR')+ const err = new RasterizationError('something broke', true, 'TIMEOUT')expect(err.name).toBe('RasterizationError')expect(err.message).toBe('something broke')expect(err.retryable).toBe(true)- expect(err.code).toBe('PLAYBACK_ERROR')+ expect(err.code).toBe('TIMEOUT')expect(err).toBeInstanceOf(Error)})@@ -17,7 +17,7 @@ describe('RasterizationError', () => {it('stores cause when provided', () => {const cause = new Error('root cause')- const err = new RasterizationError('wrapper', true, 'TEST', cause)+ const err = new RasterizationError('wrapper', true, 'BLOCK_LISTING_FAILED', cause)expect(err.cause).toBe(cause)})@@ -38,7 +38,7 @@ describe('RasterizationError', () => {})it('does not include cause or stack in JSON', () => {- const err = new RasterizationError('test', true, 'ERR', new Error('cause'))+ const err = new RasterizationError('test', true, 'INVALID_INPUT', new Error('cause'))const json = err.toJSON()expect(json).not.toHaveProperty('cause')expect(json).not.toHaveProperty('stack')diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.tsindex 33f39d364ab0..ec9b6899a0bc 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts@@ -172,15 +172,15 @@ describe('PlayerController', () => {mp._emit({type: 'error',- code: 'PLAYBACK_ERROR',+ code: 'SOME_FUTURE_CODE',message: 'rendering failed',retryable: true,})const err = controller.getError()expect(err).toBeInstanceOf(RasterizationError)- expect(err!.message).toBe('[PLAYBACK_ERROR] rendering failed')- expect(err!.code).toBe('PLAYBACK_ERROR')+ expect(err!.message).toBe('[SOME_FUTURE_CODE] rendering failed')+ expect(err!.code).toBe('OTHER')expect(err!.retryable).toBe(true)})diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.tsindex a5397c00f331..cbde9271a69d 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts@@ -18,6 +18,17 @@ jest.mock('fs', () => ({createReadStream: jest.fn().mockReturnValue('mock-stream'),}))+// The real pino logger flushes through fs.write, which the fs mock above doesn't provide.+jest.mock('~/session-replay/recording-rasterizer/logger', () => ({+ createLogger: () => ({+ info: jest.fn(),+ warn: jest.fn(),+ error: jest.fn(),+ debug: jest.fn(),+ child: jest.fn().mockReturnThis(),+ }),+}))+const { Upload } = require('@aws-sdk/lib-storage')const fsModule = require('fs')diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts b/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.tsindex a834d5b08ae6..b5a7413b7b6d 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts@@ -45,12 +45,14 @@ function resolveProxyArgs(): string[] {interface BrowserSlot {browser: BrowserusageCount: number+ closing?: boolean}export class BrowserPool {private slots = new Map<Page, BrowserSlot>()private idle: BrowserSlot[] = []private proxyArgs = resolveProxyArgs()+ private shuttingDown = falseconstructor(private recycleAfter: number = config.browserRecycleAfter) {}@@ -74,10 +76,34 @@ export class BrowserPool {args: this.launchArgs(),})RasterizationMetrics.browserLaunched()- return { browser, usageCount: 0 }+ const slot: BrowserSlot = { browser, usageCount: 0 }+ browser.on('disconnected', () => this.handleDisconnect(slot))+ return slot+ }++ // A crashed browser must not be handed out again: evict it from the idle pool+ // and drop any page entries still pointing at it.+ private handleDisconnect(slot: BrowserSlot): void {+ // During pod shutdown Chrome can die before closeBrowser marks the slot; don't count that as a crash.+ if (slot.closing || this.shuttingDown) {+ return+ }+ const idleIdx = this.idle.indexOf(slot)+ if (idleIdx !== -1) {+ this.idle.splice(idleIdx, 1)+ }+ for (const [page, s] of this.slots) {+ if (s === slot) {+ this.slots.delete(page)+ }+ }+ RasterizationMetrics.browserCrashed()+ log.warn({ usage_count: slot.usageCount }, 'browser disconnected unexpectedly, evicted from pool')+ RasterizationMetrics.setBrowserCounts(this.slots.size, this.idle.length)}private async closeBrowser(slot: BrowserSlot): Promise<void> {+ slot.closing = truetry {await slot.browser.close()} catch (err) {@@ -135,6 +161,7 @@ export class BrowserPool {}async shutdown(): Promise<void> {+ this.shuttingDown = trueawait this.releaseAllPages()await Promise.all(this.idle.map((slot) => this.closeBrowser(slot)))this.idle = []diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/capture-page.ts b/nodejs/src/session-replay/recording-rasterizer/capture/capture-page.tsindex 72f3aa84b6ad..d992779ef30c 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/capture-page.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/capture-page.ts@@ -2,6 +2,7 @@ import * as fs from 'fs/promises'import { CDPSession, Page } from 'puppeteer'import { config as defaultConfig } from '~/session-replay/recording-rasterizer/config'+import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'export const playerHtmlCache = {@@ -33,6 +34,10 @@ export const playerHtmlCache = {* optional log forwarding, and frame filtering for puppeteer-capture.*/export class CapturePage {+ // Set at the site that detects a fatal cause (e.g. the beginFrame compositor deadlock)+ // so the generic captureStopped handler can attribute the abort instead of guessing.+ fatalError: RasterizationError | null = null+private constructor(readonly page: Page,readonly playerUrl: string,@@ -150,13 +155,20 @@ export class CapturePage {return result} catch (err) {if (timedOut) {+ this.fatalError = new RasterizationError(+ 'beginFrame timeout (15s) — compositor deadlock',+ true,+ 'BEGINFRAME_DEADLOCK'+ )log.error({ params }, 'beginFrame timed out, detaching CDP session')try {await session.detach()} catch {// session may already be disconnected}- throw new Error('beginFrame timeout (15s) — compositor deadlock')+ // Throw the typed error so this path classifies as BEGINFRAME_DEADLOCK even+ // when the rejection propagates via waitForTimeout instead of captureStopped.+ throw this.fatalError}throw err}diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts b/nodejs/src/session-replay/recording-rasterizer/capture/capture.tsindex 5c13720dfefc..9c890c654346 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts@@ -106,7 +106,7 @@ export async function capturePlayback(return}log.error({ stderr: ffmpegStderr.slice(-20), frames: frameCount }, 'capture stopped unexpectedly')- const err = new RasterizationError('capture stopped unexpectedly', true, 'CAPTURE_ABORTED')+ const err = player.fatalError ?? new RasterizationError('capture stopped unexpectedly', true, 'CAPTURE_ABORTED')captureAborted = errcaptureAbortReject?.(err)}diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts b/nodejs/src/session-replay/recording-rasterizer/capture/player.tsindex a686d9e569b7..d8b2de94188f 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts@@ -3,7 +3,7 @@ import type { Page } from 'puppeteer'import { PLAYER_CONFIG_KEY, PLAYER_EMIT_FN, PLAYER_START_EVENT } from '@posthog/replay-headless/protocol'import type { InactivityPeriod, PlayerConfig, PlayerMessage } from '@posthog/replay-headless/protocol'-import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'+import { RasterizationError, toRasterizationErrorCode } from '~/session-replay/recording-rasterizer/errors'import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'import { BlockProxy } from './block-proxy'@@ -49,8 +49,13 @@ export class PlayerController {return this.capturePage.page}+ get fatalError(): RasterizationError | null {+ return this.capturePage.fatalError+ }+private toError(err: { code: string; message: string; retryable: boolean }): RasterizationError {- return new RasterizationError(`[${err.code}] ${err.message}`, err.retryable, err.code)+ // The code is browser-supplied — clamp it to the known set so downstream labels stay bounded.+ return new RasterizationError(`[${err.code}] ${err.message}`, err.retryable, toRasterizationErrorCode(err.code))}private rejectWithError(err: { code: string; message: string; retryable: boolean }): void {diff --git a/nodejs/src/session-replay/recording-rasterizer/errors.ts b/nodejs/src/session-replay/recording-rasterizer/errors.tsindex 234d487b3b5c..d01ce5b76f37 100644--- a/nodejs/src/session-replay/recording-rasterizer/errors.ts+++ b/nodejs/src/session-replay/recording-rasterizer/errors.ts@@ -1,8 +1,31 @@+// Single source of truth for error codes. Includes the codes the in-browser player emits+// (NO_SNAPSHOTS, INIT_FAILED, DATA_LOAD_FAILED). UNKNOWN = a non-RasterizationError was+// thrown; OTHER = a browser-supplied code string we don't recognize (clamped in player.ts).+export const RASTERIZATION_ERROR_CODES = [+ 'UNKNOWN',+ 'OTHER',+ 'TIMEOUT',+ 'CAPTURE_ABORTED',+ 'BEGINFRAME_DEADLOCK',+ 'INVALID_INPUT',+ 'BLOCK_LISTING_FAILED',+ 'S3_UPLOAD_UNDECODABLE_RESPONSE',+ 'NO_SNAPSHOTS',+ 'INIT_FAILED',+ 'DATA_LOAD_FAILED',+] as const++export type RasterizationErrorCode = (typeof RASTERIZATION_ERROR_CODES)[number]++export function toRasterizationErrorCode(code: string): RasterizationErrorCode {+ return (RASTERIZATION_ERROR_CODES as readonly string[]).includes(code) ? (code as RasterizationErrorCode) : 'OTHER'+}+export class RasterizationError extends Error {readonly retryable: boolean- readonly code: string+ readonly code: RasterizationErrorCode- constructor(message: string, retryable: boolean, code = 'UNKNOWN', cause?: unknown) {+ constructor(message: string, retryable: boolean, code: RasterizationErrorCode = 'UNKNOWN', cause?: unknown) {super(message)this.name = 'RasterizationError'this.retryable = retryablediff --git a/nodejs/src/session-replay/recording-rasterizer/metrics.ts b/nodejs/src/session-replay/recording-rasterizer/metrics.tsindex b1947d4a867f..ed8ae31f137d 100644--- a/nodejs/src/session-replay/recording-rasterizer/metrics.ts+++ b/nodejs/src/session-replay/recording-rasterizer/metrics.ts@@ -1,6 +1,7 @@-import { Counter, Gauge, Summary } from 'prom-client'+import { Counter, Gauge, Histogram, Summary } from 'prom-client'-import { recordActivity, recordError } from './otel-metrics'+import { RasterizationErrorCode } from './errors'+import { ACTIVITY_DURATION_BOUNDARIES, recordActivity, recordError } from './otel-metrics'const QUANTILES = [0.5, 0.95, 0.99]const MAX_AGE_SECONDS = 600@@ -9,13 +10,13 @@ const AGE_BUCKETS = 5export class RasterizationMetrics {// --- Activity timing ---- private static readonly activityDuration = new Summary({+ // Histogram, not Summary: the RasterizerHighActivityDuration alert aggregates+ // _bucket series across pods with histogram_quantile.+ private static readonly activityDuration = new Histogram({name: 'recording_rasterizer_activity_duration_seconds',help: 'Total time for the rasterization activity',labelNames: ['result'],- percentiles: QUANTILES,- maxAgeSeconds: MAX_AGE_SECONDS,- ageBuckets: AGE_BUCKETS,+ buckets: ACTIVITY_DURATION_BOUNDARIES,})private static readonly setupDuration = new Summary({@@ -112,6 +113,11 @@ export class RasterizationMetrics {help: 'Total number of browser instances recycled due to usage limit',})+ private static readonly browserCrashesTotal = new Counter({+ name: 'recording_rasterizer_browser_crashes_total',+ help: 'Total number of browser instances that disconnected unexpectedly',+ })+// --- Concurrency ---private static readonly concurrentActivities = new Gauge({@@ -149,7 +155,7 @@ export class RasterizationMetrics {this.recordingDuration.observe(seconds)}- public static incrementError(code: string, retryable: boolean): void {+ public static incrementError(code: RasterizationErrorCode, retryable: boolean): void {this.errorsTotal.labels({ code, retryable: String(retryable) }).inc()recordError(code, retryable)}@@ -162,6 +168,17 @@ export class RasterizationMetrics {this.browserRecyclesTotal.inc()}+ public static browserCrashed(): void {+ this.browserCrashesTotal.inc()+ }++ // Labeled counters only expose series after the first increment; the+ // RasterizerMetricsAbsent alert needs activities_total present from pod start.+ public static initialize(): void {+ this.activitiesTotal.labels({ result: 'success' }).inc(0)+ this.activitiesTotal.labels({ result: 'error' }).inc(0)+ }+public static setBrowserCounts(active: number, idle: number): void {this.browserActive.set(active)this.browserIdle.set(idle)diff --git a/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts b/nodejs/src/session-replay/recording-rasterizer/otel-metrics.tsindex fb56a5ed8cce..ceab29a4b2ed 100644--- a/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts+++ b/nodejs/src/session-replay/recording-rasterizer/otel-metrics.ts@@ -14,7 +14,7 @@ import { createOtlpMeterProvider } from '~/common/metrics/otlp-provider'* 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).+ * (both activity duration metrics are histograms with the same bucket boundaries).** 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@@ -55,7 +55,8 @@ interface RasterizerInstruments {errorsTotal: Counter}-const ACTIVITY_DURATION_BOUNDARIES = [1, 5, 15, 30, 60, 120, 300, 600, 1200]+// Shared with the prom histogram in metrics.ts so the twins bucket identically.+export const ACTIVITY_DURATION_BOUNDARIES = [1, 5, 15, 30, 60, 120, 300, 600, 1200, 1800]let instruments: RasterizerInstruments | null = nulldiff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.tsindex ed8c16db847b..404e2db07402 100644--- a/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/worker.ts@@ -10,11 +10,13 @@ import { BrowserPool } from '~/session-replay/recording-rasterizer/capture/browsimport { 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 { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'import { initMetrics, shutdownMetrics } from '~/session-replay/recording-rasterizer/otel-metrics'import { createActivities } from './activities'prometheus.collectDefaultMetrics()+RasterizationMetrics.initialize()// OTLP push into the PostHog Metrics product; no-op unless OTEL_METRICS_EXPORT_URL/TOKEN are set.initMetrics()@@ -100,14 +102,14 @@ function startMetricsServer(): http.Server {})return Object.assign(server, {- setReady: () => {- ready = true+ setReady: (value: boolean) => {+ ready = value},})}async function main(): Promise<void> {- const metricsServer = startMetricsServer() as http.Server & { setReady: () => void }+ const metricsServer = startMetricsServer() as http.Server & { setReady: (value: boolean) => void }const address = `${config.temporalHost}:${config.temporalPort}`const tls = await buildTLSConfig()@@ -140,10 +142,12 @@ async function main(): Promise<void> {maxHeartbeatThrottleInterval: '5s',})- metricsServer.setReady()+ metricsServer.setReady(true)const shutdown = () => {log.info('shutting down')+ // Flip readiness first so the pod drops out of rotation while activities drain.+ metricsServer.setReady(false)worker.shutdown()}diff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.pyindex 35d5fdcc65c6..04d68d2bd157 100644--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py@@ -18,6 +18,12 @@ with wf.unsafe.imports_passed_through():["product", "task_queue"],)+ RASTERIZATION_FAILED_COUNTER = Counter(+ "posthog_rasterization_failed",+ "Rasterization workflow failures by product and task queue",+ ["product", "task_queue"],+ )+from .activities import (BumpStuckCounterInput,build_rasterization_input,@@ -33,6 +39,12 @@ from .types import ()+def _record_outcome(counter: Counter, inputs: RasterizeRecordingInputs) -> None:+ if wf.unsafe.is_replaying():+ return+ counter.labels(product=inputs.product, task_queue=wf.info().task_queue).inc()++@wf.defn(name="rasterize-recording")class RasterizeRecordingWorkflow(PostHogWorkflow):inputs_cls = RasterizeRecordingInputs@@ -50,12 +62,22 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):try:result = await self._run(inputs)except Exception:+ # Count runs, not attempts: only the final scheduled attempt is a failed run.+ if self._is_final_attempt():+ _record_outcome(RASTERIZATION_FAILED_COUNTER, inputs)await self._maybe_bump_stuck_counter()raiseawait self._maybe_clear_stuck_counter()- RASTERIZATION_COMPLETED_COUNTER.labels(product=inputs.product, task_queue=wf.info().task_queue).inc()+ _record_outcome(RASTERIZATION_COMPLETED_COUNTER, inputs)return result+ @staticmethod+ def _is_final_attempt() -> bool:+ info = wf.info()+ retry_policy = info.retry_policy+ max_attempts = retry_policy.maximum_attempts if retry_policy else 1+ return max_attempts is not None and 0 < max_attempts <= info.attempt+async def _maybe_bump_stuck_counter(self) -> None:info = wf.info()retry_policy = info.retry_policydiff --git a/products/replay_vision/backend/enqueue_claims.py b/products/replay_vision/backend/enqueue_claims.pyindex 260119d589de..177d1ca011a7 100644--- a/products/replay_vision/backend/enqueue_claims.py+++ b/products/replay_vision/backend/enqueue_claims.py@@ -17,6 +17,7 @@ from products.replay_vision.backend.temporal.constants import (MAX_IN_FLIGHT_APPLIES_PER_SCANNER,MAX_IN_FLIGHT_APPLIES_PER_TEAM,)+from products.replay_vision.backend.temporal.metrics import record_enqueue_claim_failurelogger = structlog.get_logger(__name__)@@ -93,6 +94,7 @@ def try_claim_enqueue_slot()return bool(allowed)except Exception:+ record_enqueue_claim_failure("claim")logger.warning("replay_vision.enqueue_claim.failed_open", team_id=team_id, exc_info=True)return True@@ -111,6 +113,7 @@ def release_enqueue_claim(*, team_id: int, scanner_id: UUID, workflow_id: str, ipipeline.zadd(_scanner_key(scanner_id), {workflow_id: expiry}, xx=True)pipeline.execute()except Exception:+ record_enqueue_claim_failure("release")logger.warning("replay_vision.enqueue_claim.release_failed", team_id=team_id, exc_info=True)@@ -127,5 +130,6 @@ def _pending(key: str) -> int:try:return int(redis.get_client().zcount(key, f"({time.time()}", "+inf"))except Exception:+ record_enqueue_claim_failure("count")logger.warning("replay_vision.enqueue_claim.count_failed", key=key, exc_info=True)return 0diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 1965c50bb463..70bfa34e05c3 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -25,6 +25,7 @@ from products.replay_vision.backend.temporal.activities import (mark_observation_running_activity,mark_observation_succeeded_activity,reap_orphaned_observations_activity,+ reap_stuck_vision_action_runs_activity,record_evaluation_result_activity,refresh_prompt_suggestion_activity,refresh_scanner_estimate_activity,@@ -91,6 +92,7 @@ ACTIVITIES: list[Callable[..., Any]] = [list_stale_scanner_estimates_activity,refresh_scanner_estimate_activity,reap_orphaned_observations_activity,+ reap_stuck_vision_action_runs_activity,sweep_gemini_files_activity,evaluate_alert_activity,evaluate_due_vision_actions_activity,@@ -141,6 +143,7 @@ __all__ = ["mark_observation_running_activity","mark_observation_succeeded_activity","reap_orphaned_observations_activity",+ "reap_stuck_vision_action_runs_activity","record_evaluation_result_activity","refresh_scanner_estimate_activity","select_evaluation_sessions_activity",diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.pyindex 0f803df5c8fd..19505d798f68 100644--- a/products/replay_vision/backend/temporal/activities/__init__.py+++ b/products/replay_vision/backend/temporal/activities/__init__.py@@ -32,6 +32,9 @@ from products.replay_vision.backend.temporal.activities.observation_state importfrom products.replay_vision.backend.temporal.activities.reap_orphaned_observations import (reap_orphaned_observations_activity,)+from products.replay_vision.backend.temporal.activities.reap_stuck_vision_action_runs import (+ reap_stuck_vision_action_runs_activity,+)from products.replay_vision.backend.temporal.activities.reconciler_activities import (delete_scanner_schedule_activity,list_enabled_scanners_activity,@@ -71,6 +74,7 @@ __all__ = ["mark_observation_running_activity","mark_observation_succeeded_activity","reap_orphaned_observations_activity",+ "reap_stuck_vision_action_runs_activity","record_evaluation_result_activity","refresh_scanner_estimate_activity","select_evaluation_sessions_activity",diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.pyindex b1e58c951abc..b4c05e5f4fe1 100644--- a/products/replay_vision/backend/temporal/activities/create_observation.py+++ b/products/replay_vision/backend/temporal/activities/create_observation.py@@ -14,7 +14,7 @@ from products.replay_vision.backend.models.replay_observation import Observationfrom products.replay_vision.backend.models.replay_scanner import ReplayScannerfrom products.replay_vision.backend.quota import compute_quota_snapshotfrom 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.metrics import record_consent_skip, record_quota_exhausted_skipfrom products.replay_vision.backend.temporal.types import (CreateObservationInputs,CreateObservationOutput,@@ -57,6 +57,7 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut# No AI processing of recordings without organization consent, even for scanners created earlier.if not scanner.team.organization.is_ai_data_processing_approved:+ record_consent_skip(scanner.scanner_type)activity.logger.info("Skipping observation: AI data processing not approved for organization",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/reap_orphaned_observations.py b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.pyindex 934033e6f791..d827b44d12a5 100644--- a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py@@ -6,14 +6,13 @@ from uuid import UUIDimport structlogfrom temporalio import activity-from temporalio.client import Client, WorkflowExecutionStatus-from temporalio.service import RPCError, RPCStatusCodefrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.client import async_connectfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.temporal.activities.observation_state import mark_observation_terminal+from products.replay_vision.backend.temporal.activities.reaping import classify_stale_rowsfrom products.replay_vision.backend.temporal.constants import (OBSERVATION_ORPHAN_CUTOFF,REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE,@@ -39,19 +38,6 @@ def _list_stale_observations() -> list[dict[str, Any]]:return cast(list[dict[str, Any]], list(rows))-async def _workflow_is_open(temporal: Client, workflow_id: str) -> bool | None:- """Whether the latest run of `workflow_id` is still open; `None` when Temporal couldn't answer."""- try:- desc = await temporal.get_workflow_handle(workflow_id).describe()- except RPCError as e:- if e.status == RPCStatusCode.NOT_FOUND:- return False- return None- except Exception:- return None- return desc.status == WorkflowExecutionStatus.RUNNING--def _mark_orphaned(observation_id: UUID, scanner_type: str) -> bool:return mark_observation_terminal(observation_id=observation_id,@@ -74,18 +60,11 @@ async def reap_orphaned_observations_activity() -> int:if not rows:return 0temporal = await async_connect()+ reapable, skipped_open, skipped_temporal_error = await classify_stale_rows(+ temporal, rows, workflow_id_key="workflow_id"+ )reaped = 0- skipped_open = 0- skipped_temporal_error = 0- for row in rows:- if row["workflow_id"]:- is_open = await _workflow_is_open(temporal, row["workflow_id"])- if is_open:- skipped_open += 1- continue- if is_open is None:- skipped_temporal_error += 1 # Can't prove it's closed — leave it for the next tick.- continue+ for row in reapable:snapshot = row["scanner_snapshot"] or {}scanner_type = snapshot.get("scanner_type") or "unknown"if await database_sync_to_async(_mark_orphaned, thread_sensitive=False)(row["id"], scanner_type):diff --git a/products/replay_vision/backend/temporal/activities/reap_stuck_vision_action_runs.py b/products/replay_vision/backend/temporal/activities/reap_stuck_vision_action_runs.pynew file mode 100644index 000000000000..d6346d5b2eac--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/reap_stuck_vision_action_runs.py@@ -0,0 +1,71 @@+"""Fails VisionActionRun rows stuck in `running` whose workflow is gone, so run history stays truthful."""++from datetime import UTC, datetime+from typing import Any, cast++import structlog+from temporalio import activity++from posthog.sync import database_sync_to_async+from posthog.temporal.common.client import async_connect++from products.replay_vision.backend.models.vision_action import VisionActionRun, VisionActionRunStatus+from products.replay_vision.backend.temporal.activities.reaping import classify_stale_rows+from products.replay_vision.backend.temporal.constants import (+ REAP_STUCK_VISION_ACTION_RUNS_BATCH_SIZE,+ VISION_ACTION_RUN_STUCK_CUTOFF,+)+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.metrics import record_vision_action_runs_reaped++logger = structlog.get_logger(__name__)++# delivery_unknown: the documented stuck-RUNNING cause is the final bookkeeping update failing+# after side effects (Slack/email) may already have gone out — we can't prove non-delivery.+_REAPED_ERROR = {"reaped": "The run stopped without recording an outcome.", "delivery_unknown": True}+++def _list_stuck_runs() -> list[dict[str, Any]]:+ cutoff = datetime.now(UTC) - VISION_ACTION_RUN_STUCK_CUTOFF+ rows = (+ VisionActionRun.all_teams.filter(status=VisionActionRunStatus.RUNNING, created_at__lt=cutoff)+ .order_by("created_at")+ .values("id", "temporal_workflow_id")[:REAP_STUCK_VISION_ACTION_RUNS_BATCH_SIZE]+ )+ # cast: django-stubs types `.values()` rows as a TypedDict, which mypy won't widen to dict[str, Any].+ return cast(list[dict[str, Any]], list(rows))+++def _mark_reaped(run_ids: list[Any]) -> int:+ # Status guard keeps this idempotent against workflows that terminated between listing and now.+ # `.update()` bypasses auto_now, so stamp updated_at explicitly.+ return VisionActionRun.all_teams.filter(id__in=run_ids, status=VisionActionRunStatus.RUNNING).update(+ status=VisionActionRunStatus.FAILED,+ error=_REAPED_ERROR,+ updated_at=datetime.now(UTC),+ )+++@track_activity()+async def reap_stuck_vision_action_runs_activity() -> int:+ """Fail running rows past the stuck cutoff whose workflow is no longer open; returns the count reaped."""+ rows = await database_sync_to_async(_list_stuck_runs, thread_sensitive=False)()+ if not rows:+ return 0+ temporal = await async_connect()+ reapable, skipped_open, skipped_temporal_error = await classify_stale_rows(+ temporal, rows, workflow_id_key="temporal_workflow_id"+ )+ reaped = 0+ if reapable:+ reaped = await database_sync_to_async(_mark_reaped, thread_sensitive=False)([row["id"] for row in reapable])+ record_vision_action_runs_reaped(reaped)+ logger.info(+ "replay_vision.reap_stuck_vision_action_runs",+ scanned=len(rows),+ reaped=reaped,+ skipped_open=skipped_open,+ skipped_temporal_error=skipped_temporal_error,+ )+ return reapeddiff --git a/products/replay_vision/backend/temporal/activities/reaping.py b/products/replay_vision/backend/temporal/activities/reaping.pynew file mode 100644index 000000000000..5c37043ebfcd--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/reaping.py@@ -0,0 +1,54 @@+"""Shared machinery for reaper activities that fail rows whose workflow is provably gone."""++import asyncio+from collections.abc import Sequence+from typing import Any++from temporalio.client import Client, WorkflowExecutionStatus+from temporalio.service import RPCError, RPCStatusCode++_DESCRIBE_CONCURRENCY = 20+++async def _workflow_is_open(temporal: Client, workflow_id: str) -> bool | None:+ """Whether the latest run of `workflow_id` is still open; `None` when Temporal couldn't answer."""+ try:+ desc = await temporal.get_workflow_handle(workflow_id).describe()+ except RPCError as e:+ if e.status == RPCStatusCode.NOT_FOUND:+ return False+ return None+ except Exception:+ return None+ return desc.status == WorkflowExecutionStatus.RUNNING+++async def classify_stale_rows(+ temporal: Client, rows: Sequence[dict[str, Any]], workflow_id_key: str+) -> tuple[list[dict[str, Any]], int, int]:+ """Partition stale rows into provably-reapable vs skipped, describing workflows concurrently.++ Rows without a workflow id are reapable outright. Returns (reapable, skipped_open, skipped_temporal_error);+ rows whose status Temporal couldn't answer are left for the next tick rather than reaped on uncertainty.+ """+ semaphore = asyncio.Semaphore(_DESCRIBE_CONCURRENCY)++ async def _check(row: dict[str, Any]) -> bool | None:+ if not row[workflow_id_key]:+ return False+ async with semaphore:+ return await _workflow_is_open(temporal, row[workflow_id_key])++ # No return_exceptions: _workflow_is_open maps every failure to None, so _check never raises.+ results = await asyncio.gather(*(_check(row) for row in rows))+ reapable: list[dict[str, Any]] = []+ skipped_open = 0+ skipped_temporal_error = 0+ for row, is_open in zip(rows, results):+ if is_open:+ skipped_open += 1+ elif is_open is None:+ skipped_temporal_error += 1+ else:+ reapable.append(row)+ return reapable, skipped_open, skipped_temporal_errordiff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex 406fc7d12868..e6ffd4a4d7ce 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -18,6 +18,12 @@ REAP_ORPHANED_OBSERVATIONS_TIMEOUT = dt.timedelta(minutes=3)PROCESS_VISION_ACTION_WORKFLOW_NAME = "process-vision-action"PROCESS_VISION_ACTION_EXECUTION_TIMEOUT = dt.timedelta(hours=1)+# Running runs older than twice the process execution timeout are provably stuck (the final+# update activity failed or the workflow was terminated without reaching it).+VISION_ACTION_RUN_STUCK_CUTOFF = PROCESS_VISION_ACTION_EXECUTION_TIMEOUT * 2+REAP_STUCK_VISION_ACTION_RUNS_BATCH_SIZE = 500+REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT = dt.timedelta(minutes=3)+def build_process_vision_action_workflow_id(vision_action_id: UUID) -> str:"""Deterministic id: a still-running action is skipped (WorkflowAlreadyStartedError), not double-fired."""diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.pyindex 9b6b24e5593f..d6d2862a7b07 100644--- a/products/replay_vision/backend/temporal/metrics.py+++ b/products/replay_vision/backend/temporal/metrics.py@@ -9,6 +9,7 @@ is swallowed so telemetry can never fail an activity."""from prometheus_client import Counter, Gauge, Histogram+from temporalio import workflowfrom posthog.otel_metrics import OtelInstrumentFactory@@ -90,6 +91,28 @@ REPLAY_VISION_SIDE_EFFECT_FAILURES = Counter(["effect"],)+REPLAY_VISION_CONSENT_SKIPS = Counter(+ "replay_vision_consent_skips_total",+ "Scans skipped because the organization has not approved AI data processing",+ ["scanner_type"],+)++REPLAY_VISION_ENQUEUE_CLAIM_FAILURES = Counter(+ "replay_vision_enqueue_claim_failures_total",+ "Redis enqueue-claim operations that failed (claims fail open, so failures over-admit)",+ ["operation"],+)++REPLAY_VISION_ACTION_OCCURRENCES_DROPPED = Counter(+ "replay_vision_action_occurrences_dropped_total",+ "Vision-action occurrences claimed but permanently dropped because the child workflow start failed",+)++REPLAY_VISION_ACTION_RUNS_REAPED = Counter(+ "replay_vision_action_runs_reaped_total",+ "VisionActionRun rows stuck in running whose workflow was gone, failed by the reaper",+)+REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge("replay_vision_gemini_cleanup_backlog","Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",@@ -155,6 +178,29 @@ def record_side_effect_failure(effect: str) -> None:_otel.record_counter_twin(REPLAY_VISION_SIDE_EFFECT_FAILURES, 1, {"effect": effect})+def record_consent_skip(scanner_type: str) -> None:+ REPLAY_VISION_CONSENT_SKIPS.labels(scanner_type=scanner_type).inc()+ _otel.record_counter_twin(REPLAY_VISION_CONSENT_SKIPS, 1, {"scanner_type": scanner_type})+++def record_enqueue_claim_failure(operation: str) -> None:+ REPLAY_VISION_ENQUEUE_CLAIM_FAILURES.labels(operation=operation).inc()+ _otel.record_counter_twin(REPLAY_VISION_ENQUEUE_CLAIM_FAILURES, 1, {"operation": operation})+++def record_vision_action_occurrence_dropped() -> None:+ # Callable from workflow code: replays must not double-count.+ if workflow.in_workflow() and workflow.unsafe.is_replaying():+ return+ REPLAY_VISION_ACTION_OCCURRENCES_DROPPED.inc()+ _otel.record_counter_twin(REPLAY_VISION_ACTION_OCCURRENCES_DROPPED, 1, {})+++def record_vision_action_runs_reaped(count: int) -> None:+ REPLAY_VISION_ACTION_RUNS_REAPED.inc(count)+ _otel.record_counter_twin(REPLAY_VISION_ACTION_RUNS_REAPED, count, {})++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/reconciler.py b/products/replay_vision/backend/temporal/reconciler.pyindex 6db145b9bf71..1250b2176704 100644--- a/products/replay_vision/backend/temporal/reconciler.py+++ b/products/replay_vision/backend/temporal/reconciler.py@@ -15,6 +15,7 @@ from products.replay_vision.backend.temporal.constants import (LIST_ENABLED_SCANNERS_TIMEOUT,LIST_SCANNER_SCHEDULES_TIMEOUT,REAP_ORPHANED_OBSERVATIONS_TIMEOUT,+ REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT,RECONCILE_SCHEDULE_OP_TIMEOUT,RECONCILER_EXECUTION_TIMEOUT,RECONCILER_INTERVAL,@@ -39,6 +40,7 @@ with workflow.unsafe.imports_passed_through():list_enabled_scanners_activity,list_scanner_schedules_activity,reap_orphaned_observations_activity,+ reap_stuck_vision_action_runs_activity,upsert_scanner_schedule_activity,)@@ -50,7 +52,7 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: ReconcileScannerSchedulesInputs) -> ReconcileScannerSchedulesResult:- # Best-effort and first: a schedule-sync failure below must not starve the reaper, and vice versa.+ # Best-effort and first: a schedule-sync failure below must not starve the reapers, and vice versa.try:await workflow.execute_activity(reap_orphaned_observations_activity,@@ -60,6 +62,16 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):except Exception:workflow.logger.exception("replay_vision.reap_orphaned_observations_failed")+ if workflow.patched("reap-stuck-vision-action-runs-2026-07"):+ try:+ await workflow.execute_activity(+ reap_stuck_vision_action_runs_activity,+ start_to_close_timeout=REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except Exception:+ workflow.logger.exception("replay_vision.reap_stuck_vision_action_runs_failed")+# A scanner toggled between the two listings recovers on the next tick.enabled_entries, existing_entries = await asyncio.gather(workflow.execute_activity(diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.pyindex ee84ad18e257..af634a483b40 100644--- a/products/replay_vision/backend/temporal/sweep_workflow.py+++ b/products/replay_vision/backend/temporal/sweep_workflow.py@@ -18,6 +18,8 @@ from posthog.temporal.common.search_attributes import (with wf.unsafe.imports_passed_through():from django.conf import settings+ from products.replay_vision.backend.temporal.metrics import record_vision_action_occurrence_dropped+from products.replay_vision.backend.models.replay_observation import ObservationTriggerfrom products.replay_vision.backend.temporal.activities import (advance_scanner_watermark_activity,@@ -181,8 +183,9 @@ class SweepScannerWorkflow(PostHogWorkflow):)except Exception:# The action was already claimed (next_run_at advanced in the eval txn), so a child- # that fails to start drops this occurrence until the next fire. Log it per-action- # so the drop is visible/graphable, and keep dispatching the rest.+ # that fails to start drops this occurrence until the next fire. Count and log it+ # per-action so the drop is visible/graphable, and keep dispatching the rest.+ record_vision_action_occurrence_dropped()wf.logger.exception("replay_vision.vision_action_claim_dispatch_failed",extra={"scanner_id": str(inputs.scanner_id), "vision_action_id": str(d.vision_action_id)},diff --git a/products/replay_vision/backend/temporal/vision_actions/workflows.py b/products/replay_vision/backend/temporal/vision_actions/workflows.pyindex 027f6619a590..c1c65b8f10c2 100644--- a/products/replay_vision/backend/temporal/vision_actions/workflows.py+++ b/products/replay_vision/backend/temporal/vision_actions/workflows.py@@ -146,8 +146,8 @@ class ProcessVisionActionWorkflow(PostHogWorkflow):# If the body already succeeded, the delivery event was emitted (Slack post happened);# a failed bookkeeping update must not flip the workflow to FAILED — re-running would# double-post. Log loudly and let the workflow finish; the run row may stay RUNNING- # (cosmetic, a post-MVP reconciler can resolve it). If the body failed, the original- # error still re-raises below — the update failure must not mask it.+ # (reap_stuck_vision_action_runs_activity fails it once provably stuck). If the body+ # failed, the original error still re-raises below — the update failure must not mask it.wf.logger.exception("vision_action.update_run_failed", vision_action_id=str(inputs.vision_action_id))diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.pyindex 99af61129450..eabe4d1cdbb2 100644--- a/products/replay_vision/backend/tests/test_reconciler.py+++ b/products/replay_vision/backend/tests/test_reconciler.py@@ -25,11 +25,13 @@ from products.replay_vision.backend.models.replay_observation import (ReplayObservation,)from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType+from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatusfrom products.replay_vision.backend.temporal.activities import (delete_scanner_schedule_activity,list_enabled_scanners_activity,list_scanner_schedules_activity,reap_orphaned_observations_activity,+ reap_stuck_vision_action_runs_activity,upsert_scanner_schedule_activity,)from products.replay_vision.backend.temporal.constants import (@@ -41,6 +43,7 @@ from products.replay_vision.backend.temporal.constants import (RECONCILER_WORKFLOW_NAME,SCANNER_SCHEDULE_ID_PREFIX,SWEEP_SCANNER_WORKFLOW_NAME,+ VISION_ACTION_RUN_STUCK_CUTOFF,)from products.replay_vision.backend.temporal.reconciler import (ReconcileScannerSchedulesWorkflow,@@ -210,13 +213,16 @@ class _ReconcileMocks:upsert_errors_for_ids: set[uuid.UUID] | None = None,delete_errors_for_ids: set[uuid.UUID] | None = None,reap_error: Exception | None = None,+ reap_stuck_runs_error: Exception | None = None,) -> None:self.enabled = enabledself.existing = existingself.upsert_errors = upsert_errors_for_ids or set()self.delete_errors = delete_errors_for_ids or set()self.reap_error = reap_error+ self.reap_stuck_runs_error = reap_stuck_runs_errorself.reap_calls = 0+ self.reap_stuck_run_calls = 0self.upserted: list[uuid.UUID] = []self.deleted: list[uuid.UUID] = []@@ -226,6 +232,11 @@ class _ReconcileMocks:if self.reap_error:raise self.reap_errorreturn 0+ if activity_fn is reap_stuck_vision_action_runs_activity:+ self.reap_stuck_run_calls += 1+ if self.reap_stuck_runs_error:+ raise self.reap_stuck_runs_error+ return 0if activity_fn is list_enabled_scanners_activity:return self.enabledif activity_fn is list_scanner_schedules_activity:@@ -243,7 +254,7 @@ class _ReconcileMocks:raise AssertionError(f"unexpected activity: {activity_fn!r}")-async def _run_reconcile(mocks: _ReconcileMocks):+async def _run_reconcile(mocks: _ReconcileMocks, patched: bool = True):# `workflow.logger` reaches into the workflow runtime, which isn't set up here.fake_logger = type("Logger",@@ -253,6 +264,7 @@ async def _run_reconcile(mocks: _ReconcileMocks):with (patch("temporalio.workflow.execute_activity", side_effect=mocks.execute_activity),patch("temporalio.workflow.logger", fake_logger),+ patch("temporalio.workflow.patched", return_value=patched),):return await ReconcileScannerSchedulesWorkflow().run(ReconcileScannerSchedulesInputs())@@ -375,6 +387,15 @@ async def test_reconcile_workflow(_name: str, build: Callable[[], tuple[_Reconciassert result.failed_delete == expected.get("failed_delete", [])+async def test_reconcile_workflow_pre_patch_skips_run_reaper() -> None:+ # Replays of pre-patch executions must not see the new activity command.+ mocks = _ReconcileMocks(enabled=_enabled(), existing=_existing())+ await _run_reconcile(mocks, patched=False)+ assert mocks.reap_calls == 1+ assert mocks.reap_stuck_run_calls == 0++@pytest.mark.asyncioasync def test_reconcile_workflow_survives_reap_failure() -> None:# The reaper is best-effort: its failure must not block schedule sync (and vice versa — it runs first).@@ -523,3 +544,59 @@ async def test_reap_orphaned_observations_activity(org_team) -> None:assert statuses[key].completed_at is None, key# The fresh row never reaches Temporal; the empty-workflow-id row is reaped without a describe.assert set(temporal.described) == {"wf-gone-1", "wf-timed-out", "wf-open", "wf-err"}+++def _make_run(action: VisionAction, *, status: str, workflow_id: str, age: dt.timedelta) -> VisionActionRun:+ run = VisionActionRun.all_teams.create(+ vision_action=action,+ team=action.team,+ temporal_workflow_id=workflow_id,+ idempotency_key=str(uuid.uuid4()),+ status=status,+ )+ VisionActionRun.all_teams.filter(pk=run.pk).update(created_at=timezone.now() - age)+ return run++[email protected]_db(transaction=True)+async def test_reap_stuck_vision_action_runs_activity(org_team) -> None:+ _, team = org_team+ scanner = await sync_to_async(_make_scanner)(team)+ stale = VISION_ACTION_RUN_STUCK_CUTOFF + dt.timedelta(minutes=5)++ def _setup() -> dict[str, VisionActionRun]:+ action = VisionAction.all_teams.create(team=team, scanner=scanner, name="reaper-test")+ return {+ "running_gone": _make_run(action, status=VisionActionRunStatus.RUNNING, workflow_id="wf-gone-1", age=stale),+ "running_open": _make_run(action, status=VisionActionRunStatus.RUNNING, workflow_id="wf-open", age=stale),+ "describe_error": _make_run(action, status=VisionActionRunStatus.RUNNING, workflow_id="wf-err", age=stale),+ "too_fresh": _make_run(+ action, status=VisionActionRunStatus.RUNNING, workflow_id="wf-gone-2", age=dt.timedelta(minutes=30)+ ),+ "already_completed": _make_run(+ action, status=VisionActionRunStatus.COMPLETED, workflow_id="wf-gone-3", age=stale+ ),+ }++ rows = await sync_to_async(_setup)()+ temporal = _StubReapTemporal({"wf-gone-1": "not_found", "wf-open": "open", "wf-err": "rpc_error"})++ with patch(+ "products.replay_vision.backend.temporal.activities.reap_stuck_vision_action_runs.async_connect",+ AsyncMock(return_value=temporal),+ ):+ reaped = await reap_stuck_vision_action_runs_activity()++ assert reaped == 1+ statuses = {+ key: await sync_to_async(lambda r=run: VisionActionRun.all_teams.get(pk=r.pk))() for key, run in rows.items()+ }+ assert statuses["running_gone"].status == VisionActionRunStatus.FAILED+ assert statuses["running_gone"].error == {+ "reaped": "The run stopped without recording an outcome.",+ "delivery_unknown": True,+ }+ for key in ("running_open", "describe_error", "too_fresh", "already_completed"):+ assert statuses[key].status == rows[key].status, key+ assert set(temporal.described) == {"wf-gone-1", "wf-open", "wf-err"}