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.

fix(replay): harden the rasterizer after a full service review (#83928)

Tue Haulundfa280bf52f9c
diff --git a/bin/temporal-recording-rasterizer-worker b/bin/temporal-recording-rasterizer-worker
index 30c41852ceb2..ae01c0be7223 100755
--- a/bin/temporal-recording-rasterizer-worker
+++ b/bin/temporal-recording-rasterizer-worker
@@ -99,6 +99,7 @@ docker run --rm \
-e SCREENSHOT_FORMAT="${SCREENSHOT_FORMAT:-jpeg}" \
-e SCREENSHOT_JPEG_QUALITY="${SCREENSHOT_JPEG_QUALITY:-80}" \
-e CHROME_HOST_RESOLVER_RULES="MAP localhost host.docker.internal" \
+ -e RASTERIZER_USE_PROXY="${RASTERIZER_USE_PROXY:-false}" \
-v "$ROOT_DIR/nodejs/dist/session-replay/recording-rasterizer:/code/nodejs/dist/session-replay/recording-rasterizer" \
-v "$ROOT_DIR/common/replay-headless/dist:/code/common/replay-headless/dist" \
"$IMAGE_NAME" \
diff --git a/ee/hogai/videos/session_moments.py b/ee/hogai/videos/session_moments.py
index 29159c0f3376..dd9fad189124 100644
--- a/ee/hogai/videos/session_moments.py
+++ b/ee/hogai/videos/session_moments.py
@@ -19,7 +19,10 @@ from posthog.storage import object_storage
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
-from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs
+from posthog.temporal.session_replay.rasterize_recording.types import (
+ RASTERIZE_WORKFLOW_TIMEOUT,
+ RasterizeRecordingInputs,
+)
from products.exports.backend.models.exported_asset import ExportedAsset
@@ -162,7 +165,7 @@ class SessionMomentsLLMAnalyzer:
task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=int(TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- execution_timeout=timedelta(minutes=30),
+ execution_timeout=RASTERIZE_WORKFLOW_TIMEOUT,
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=self.team_id),
diff --git a/nodejs/src/session-replay/recording-rasterizer/README.md b/nodejs/src/session-replay/recording-rasterizer/README.md
index d435582489ac..6c1438524a33 100644
--- a/nodejs/src/session-replay/recording-rasterizer/README.md
+++ b/nodejs/src/session-replay/recording-rasterizer/README.md
@@ -38,8 +38,7 @@ recording-rasterizer/
│
├── temporal/ ← Temporal integration
│ ├── worker.ts ← worker bootstrap (browser pool, Temporal connection, metrics server)
-│ ├── activities.ts ← activity handler (record → upload → cleanup)
-│ └── codec.ts ← Fernet encryption codec for Temporal payloads
+│ └── activities.ts ← activity handler (record → upload → cleanup)
│
├── capture/ ← Puppeteer capture pipeline
│ ├── browser-pool.ts ← warm Chromium lifecycle manager
@@ -75,27 +74,33 @@ Key environment variables (see `config.ts` for full list):
| `SCREENSHOT_JPEG_QUALITY` | `80` | JPEG quality (1-100), only used when format is `jpeg` |
| `MAX_CONCURRENT_ACTIVITIES` | `4` | Max parallel recording activities |
| `BROWSER_RECYCLE_AFTER` | `100` | Recycle Chromium after N page uses |
+| `MAX_IDLE_BROWSERS` | `2` | Warm Chromiums kept alive; extras close on release |
| `CAPTURE_BROWSER_LOGS` | `0` | Forward browser console/error logs to worker logger |
+| `ENABLE_PLAYER_CSP` | `1` | Script-locking CSP on the player page (`0` disables) |
+
+Egress from the browser and the S3 client is routed through the proxy in `HTTPS_PROXY`/`HTTP_PROXY`.
+In production a missing proxy URL is a startup error; `RASTERIZER_USE_PROXY=false` explicitly disables containment.
## Activity inputs
The `rasterize-recording` activity accepts `RasterizeRecordingInput` (see `types.ts`):
-| Field | Required | Default | Description |
-| ---------------------- | -------- | ------- | ------------------------------------------- |
-| `session_id` | yes | — | Session to rasterize |
-| `team_id` | yes | — | Team ID |
-| `s3_bucket` | yes | — | S3 bucket for output |
-| `s3_key_prefix` | yes | — | S3 key prefix |
-| `playback_speed` | no | `4` | Playback speed multiplier |
-| `recording_fps` | no | `24` | Output video framerate |
-| `start_offset_s` | no | — | Start playback N seconds from session start |
-| `end_offset_s` | no | — | Stop playback N seconds from session start |
-| `trim` | no | — | Max output duration in seconds |
-| `max_virtual_time` | no | — | Max virtual time in seconds before stopping |
-| `output_format` | no | `mp4` | Output video format (`mp4` or `webm`) |
-| `viewport_width` | no | `1280` | Capture viewport width |
-| `viewport_height` | no | `720` | Capture viewport height |
-| `show_metadata_footer` | no | `false` | Include metadata footer in output |
-| `skip_inactivity` | no | `true` | Skip inactive periods during playback |
-| `mouse_tail` | no | `true` | Show mouse trail in replay |
+| Field | Required | Default | Description |
+| ---------------------- | -------- | ------- | --------------------------------------------- |
+| `session_id` | yes | — | Session to rasterize |
+| `team_id` | yes | — | Team ID |
+| `s3_bucket` | yes | — | S3 bucket for output |
+| `s3_key_prefix` | yes | — | S3 key prefix |
+| `playback_speed` | no | `4` | Playback speed multiplier |
+| `recording_fps` | no | `24` | Output video framerate |
+| `start_offset_s` | no | — | Start playback N seconds from session start |
+| `end_offset_s` | no | — | Stop playback N seconds from session start |
+| `trim` | no | — | Max output duration in seconds |
+| `max_virtual_time` | no | — | Max virtual time in seconds before stopping |
+| `output_format` | no | `mp4` | Output video format (`mp4`, `webm` or `gif`) |
+| `recording_api_token` | no | — | Team-scoped read JWT relayed to recording-api |
+| `viewport_width` | no | `1280` | Capture viewport width |
+| `viewport_height` | no | `720` | Capture viewport height |
+| `show_metadata_footer` | no | `false` | Include metadata footer in output |
+| `skip_inactivity` | no | `true` | Skip inactive periods during playback |
+| `mouse_tail` | no | `true` | Show mouse trail in replay |
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
index 23f92ff30a0b..649d59cc2a8e 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts
@@ -15,6 +15,7 @@ jest.mock('@temporalio/activity', () => ({
workflowExecution: { workflowId: 'test-workflow-1', runId: 'test-run-1' },
},
heartbeat: jest.fn(),
+ cancellationSignal: new AbortController().signal,
}),
},
}))
@@ -66,15 +67,13 @@ function baseInput(overrides: Partial<RasterizeRecordingInput> = {}): RasterizeR
}
}
-function baseRecordingResult(videoPath: string, overrides: Partial<RecordingResult> = {}): RecordingResult {
+function baseRecordingResult(_videoPath: string, overrides: Partial<RecordingResult> = {}): RecordingResult {
return {
- video_path: videoPath,
playback_speed: 4,
capture_duration_s: 3.0,
frame_count: 72,
truncated: false,
inactivity_periods: [{ ts_from_s: 0, ts_to_s: 10, active: true }],
- custom_fps: 3,
timings: { setup_s: 1.5, capture_s: 3.2 },
...overrides,
}
@@ -105,7 +104,6 @@ describe('rasterizeRecordingActivity', () => {
]
mockSuccessfulRecording({
playback_speed: 1,
- custom_fps: 24,
inactivity_periods: inactivityPeriods,
})
@@ -132,10 +130,11 @@ describe('rasterizeRecordingActivity', () => {
expect.stringContaining('ph-video-'),
playerHtml,
expect.any(Function),
- // Progress object — phase transitions to 'upload' after capture completes.
- { phase: 'upload', frame: 0, estimatedTotalFrames: 0 },
- undefined,
- expect.any(Object)
+ expect.objectContaining({
+ // Progress object — phase transitions to 'upload' after capture completes.
+ progress: { phase: 'upload', frame: 0, estimatedTotalFrames: 0 },
+ signal: expect.any(AbortSignal),
+ })
)
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
index 89681abfd2b0..1a7c9884f2e5 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/block-proxy.test.ts
@@ -88,6 +88,11 @@ describe('BlockProxy', () => {
it.each([
[500, true],
[403, false],
+ // 404: a recording still being ingested has no blocks yet, the same race NO_SNAPSHOTS
+ // deliberately keeps retryable.
+ [404, true],
+ [429, true],
+ [401, false],
])('marks %i response as retryable=%s', async (status, expectedRetryable) => {
mockInternalFetch.mockResolvedValue({
status,
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.ts
index bb3d8919a26b..83b7b34e9b7a 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
@@ -96,6 +96,39 @@ describe('BrowserPool', () => {
expect(pool.stats.activePages).toBe(0)
})
+ it('closes the browser instead of orphaning it when newPage throws', async () => {
+ const browser = mockBrowser()
+ browser.newPage.mockRejectedValue(new Error('Target closed'))
+ puppeteerCapture.launch.mockResolvedValue(browser)
+
+ pool = new BrowserPool(100)
+ await expect(pool.getPage()).rejects.toThrow('Target closed')
+
+ // The slot was already popped from idle; without the close this Chrome process leaks.
+ expect(browser.close).toHaveBeenCalled()
+ expect(pool.stats.activePages).toBe(0)
+ })
+
+ it('closes released browsers beyond the idle cap instead of keeping them warm', async () => {
+ const browsers = [mockBrowser(), mockBrowser(), mockBrowser()]
+ for (const b of browsers) {
+ b.newPage.mockImplementation(() => Promise.resolve(mockPage()))
+ }
+ puppeteerCapture.launch
+ .mockResolvedValueOnce(browsers[0])
+ .mockResolvedValueOnce(browsers[1])
+ .mockResolvedValueOnce(browsers[2])
+
+ pool = new BrowserPool(100)
+ const pages = [await pool.getPage(), await pool.getPage(), await pool.getPage()]
+ for (const p of pages) {
+ await pool.releasePage(p)
+ }
+
+ // maxIdleBrowsers defaults to 2: the third release closes its browser.
+ expect(browsers.filter((b) => b.close.mock.calls.length > 0)).toHaveLength(1)
+ })
+
it('reuses idle browser for sequential getPage calls', async () => {
const browser = mockBrowser()
browser.newPage.mockImplementation(() => Promise.resolve(mockPage()))
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
index b18715c11b22..05268609d182 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/capture.test.ts
@@ -293,6 +293,26 @@ describe('capturePlayback', () => {
})
})
+ it('treats a stop at the trim frame limit as completion, not an abort', async () => {
+ const player = mockPlayer()
+ // ffmpeg's -t can exit before the loop observes trimFrameLimit; previously this raced into
+ // a retryable CAPTURE_ABORTED that re-rendered an already-complete video.
+ mockRecorder.waitForTimeout.mockImplementation(() => {
+ simulateFrames(30)
+ const onCall = mockRecorder.on.mock.calls.find(([event]: [string]) => event === 'captureStopped')
+ onCall?.[1]()
+ })
+
+ const result = await capturePlayback(
+ player,
+ baseCaptureConfig({ trim: 10, trimFrameLimit: 30, outputFps: 3 }),
+ outputPath,
+ jest.fn()
+ )
+ expect(result.frame_count).toBe(30)
+ expect(result.truncated).toBe(false)
+ })
+
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__/config.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
index b53e24debe63..bb5935701e02 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/config.test.ts
@@ -57,8 +57,9 @@ describe('config', () => {
})
it.each([
- { field: 'playback_speed', value: 0, error: 'playback_speed must be positive' },
- { field: 'playback_speed', value: -1, error: 'playback_speed must be positive' },
+ { field: 'playback_speed', value: 0, error: 'playback_speed must be >= 1' },
+ { field: 'playback_speed', value: 0.5, error: 'playback_speed must be >= 1' },
+ { field: 'playback_speed', value: -1, error: 'playback_speed must be >= 1' },
{ field: 'max_virtual_time', value: 0, error: 'max_virtual_time must be positive' },
{ field: 'max_virtual_time', value: -5, error: 'max_virtual_time must be positive' },
{ field: 'recording_fps', value: 0, error: 'recording_fps must be positive' },
@@ -168,6 +169,15 @@ describe('config', () => {
expect(config.ffmpegOutputOpts).toContain('-crf 23')
expect(config.ffmpegOutputOpts).toContain('-pix_fmt yuv420p')
expect(config.ffmpegOutputOpts).toContain('-movflags +faststart')
+ expect(config.ffmpegOutputOpts).toContain('-threads 2')
+ })
+
+ // puppeteer-capture pins the container rate to captureFps; without a later -r override
+ // the fps-filtered stream is duplicated back up by the playback-speed factor.
+ it('pins the output rate to outputFps, not captureFps', () => {
+ const config = buildCaptureConfig(baseInput({ playback_speed: 8, recording_fps: 3 }))
+ expect(config.ffmpegOutputOpts).toContain('-r 3')
+ expect(config.ffmpegOutputOpts).not.toContain('-r 24')
})
it('uses VP9 output opts for WebM format', () => {
@@ -177,9 +187,23 @@ describe('config', () => {
expect(config.ffmpegOutputOpts).toContain('-c:v libvpx-vp9')
expect(config.ffmpegOutputOpts).toContain('-crf 30')
expect(config.ffmpegOutputOpts).toContain('-b:v 0')
+ // Default libvpx settings encode at single-digit fps and would blow the render timeout.
+ expect(config.ffmpegOutputOpts).toContain('-deadline realtime')
+ expect(config.ffmpegOutputOpts).toContain('-cpu-used 5')
+ expect(config.ffmpegOutputOpts).toContain('-row-mt 1')
expect(config.ffmpegOutputOpts).not.toContain('-movflags +faststart')
})
+ // Frames the fps filter would drop still cost a full CDP screenshot round-trip each.
+ it('clamps gif capture to 12fps instead of discarding frames in the filter', () => {
+ const config = buildCaptureConfig(
+ baseInput({ output_format: 'gif', playback_speed: 4, recording_fps: 24 })
+ )
+ expect(config.outputFps).toBe(12)
+ expect(config.captureFps).toBe(48)
+ expect(config.ffmpegVideoFilters).toContain('fps=12')
+ })
+
it('adds trim to WebM output opts', () => {
const config = buildCaptureConfig(baseInput({ output_format: 'webm', trim: 30 }))
expect(config.ffmpegOutputOpts).toContain('-t 30')
@@ -253,7 +277,7 @@ describe('config', () => {
it('emits the -t value as a single numeric token (no embedded flags)', () => {
const config = buildCaptureConfig(baseInput({ trim: 60 }))
- const tOpt = config.ffmpegOutputOpts.find((o) => o.startsWith('-t'))
+ const tOpt = config.ffmpegOutputOpts.find((o) => o.startsWith('-t '))
// Exactly two space-separated tokens → fluent-ffmpeg passes ['-t', '60'],
// so an attacker can never split the value into extra ffmpeg arguments.
expect(tOpt!.split(' ')).toEqual(['-t', '60'])
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
index 6e0aeff6d5f9..ceecf64ce305 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/player.test.ts
@@ -135,6 +135,26 @@ describe('PlayerController', () => {
jest.useRealTimers()
})
+ it('waitForStart() surfaces an error that arrived before it was called', async () => {
+ const mp = mockCapturePage()
+ const controller = new PlayerController(mp.capturePage, mockBlockProxy, jest.fn())
+ await controller.load(basePlayerConfig())
+
+ // Error lands between load() and waitForStart(); previously it was shelved and the wait
+ // idled into a bogus retryable TIMEOUT that masked the terminal code.
+ mp._emit({
+ type: 'error',
+ code: 'NO_SNAPSHOTS',
+ message: 'No snapshot data found',
+ retryable: false,
+ })
+
+ await expect(controller.waitForStart(basePlayerConfig(), 5000)).rejects.toMatchObject({
+ code: 'NO_SNAPSHOTS',
+ retryable: false,
+ })
+ })
+
it('waitForStart() rejects when player sends error message', async () => {
const mp = mockCapturePage()
const controller = new PlayerController(mp.capturePage, mockBlockProxy, jest.fn())
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
index 2e14e02d4ed8..6649852a0d40 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/recorder.test.ts
@@ -109,13 +109,13 @@ describe('rasterizeRecording', () => {
return Promise.resolve(baseCaptureResult)
})
- await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
expect(callOrder).toEqual(['getPage', 'prepare', 'fetchBlocks', 'load', 'waitForStart', 'capturePlayback'])
})
it('releases page and disposes player on success', async () => {
- await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
expect(mockPlayer.dispose).toHaveBeenCalled()
expect(mockPool.releasePage).toHaveBeenCalledWith(mockPage)
@@ -125,7 +125,7 @@ describe('rasterizeRecording', () => {
mockedCapturePlayback.mockRejectedValue(new Error('capture failed'))
await expect(
- rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
).rejects.toThrow('capture failed')
expect(mockPlayer.dispose).toHaveBeenCalled()
@@ -136,7 +136,7 @@ describe('rasterizeRecording', () => {
mockPlayer.load.mockRejectedValue(new Error('navigation failed'))
await expect(
- rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
).rejects.toThrow('navigation failed')
expect(mockPool.releasePage).toHaveBeenCalledWith(mockPage)
@@ -146,14 +146,14 @@ describe('rasterizeRecording', () => {
mockedBlockProxy.prototype.fetchBlocks = jest.fn().mockRejectedValue(new Error('API down'))
await expect(
- rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
).rejects.toThrow('API down')
expect(mockPool.releasePage).toHaveBeenCalledWith(mockPage)
})
it('passes playerHtml to CapturePage.prepare', async () => {
- await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html>player</html>', jest.fn(), null, cfg)
+ await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html>player</html>', jest.fn(), { cfg })
expect(mockedCapturePage.prepare).toHaveBeenCalledWith(
mockPage,
@@ -172,8 +172,7 @@ describe('rasterizeRecording', () => {
'/tmp/out.mp4',
'<html></html>',
jest.fn(),
- null,
- cfg
+ { cfg }
)
expect(mockedCapturePage.prepare).toHaveBeenCalledWith(
@@ -187,7 +186,7 @@ describe('rasterizeRecording', () => {
})
it('defaults viewport to 1280x720', async () => {
- await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), null, cfg)
+ await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), { cfg })
expect(mockedCapturePage.prepare).toHaveBeenCalledWith(
mockPage,
@@ -206,11 +205,9 @@ describe('rasterizeRecording', () => {
'/tmp/out.mp4',
'<html></html>',
jest.fn(),
- null,
- cfg
+ { cfg }
)
- expect(result.video_path).toBe('/tmp/out.mp4')
expect(result.playback_speed).toBe(8)
expect(result.capture_duration_s).toBe(5)
expect(result.frame_count).toBe(120)
@@ -219,10 +216,43 @@ describe('rasterizeRecording', () => {
expect(result.timings.setup_s).toBeGreaterThanOrEqual(0)
})
+ it('throws before taking a page when the signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ await expect(
+ rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), {
+ cfg,
+ signal: controller.signal,
+ })
+ ).rejects.toThrow()
+ expect(mockPool.getPage).not.toHaveBeenCalled()
+ })
+
+ it('closes the page when the signal aborts mid-render', async () => {
+ // Closing the page is what unsticks a wedged CDP send and frees the pool slot; without it a
+ // cancelled activity keeps rendering to completion.
+ const pageWithClose = { close: jest.fn().mockResolvedValue(undefined) } as any
+ ;(mockPool.getPage as jest.Mock).mockResolvedValue(pageWithClose)
+ const controller = new AbortController()
+ mockedCapturePlayback.mockImplementation(() => {
+ controller.abort()
+ return Promise.reject(new Error('capture aborted'))
+ })
+
+ await expect(
+ rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', jest.fn(), {
+ cfg,
+ signal: controller.signal,
+ })
+ ).rejects.toThrow('capture aborted')
+ expect(pageWithClose.close).toHaveBeenCalled()
+ })
+
it('calls onProgress after waitForStart', async () => {
const onProgress = jest.fn()
- await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', onProgress, null, cfg)
+ await rasterizeRecording(mockPool, baseInput(), '/tmp/out.mp4', '<html></html>', onProgress, { cfg })
expect(onProgress).toHaveBeenCalledTimes(1)
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts
index cbde9271a69d..53e7f6621a3d 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/storage.test.ts
@@ -121,17 +121,27 @@ describe('uploadToS3', () => {
it.each([
{
- failure: 'a modeled service error whose body parsed fine',
+ // Even a 403 stays retryable: it can be a transient credential-refresh race, and a
+ // wasted retry is cheaper than discarding a finished render.
+ failure: 'a modeled 403 service error',
error: Object.assign(new Error('Access Denied'), {
name: 'AccessDenied',
$response: { statusCode: 403 },
$metadata: { httpStatusCode: 403 },
}),
},
- { failure: 'a failure carrying no HTTP response', error: new Error('socket hang up') },
- ])('rethrows $failure untouched, so callers still see the SDK error', async ({ error }) => {
+ {
+ failure: 'a failure carrying no HTTP response',
+ error: new Error('socket hang up'),
+ },
+ ])('wraps $failure into a retryable typed S3_UPLOAD_FAILED', async ({ error }) => {
mockDone.mockRejectedValue(error)
- await expect(uploadToS3('/tmp/v.mp4', 'bucket', 'prefix', 'id')).rejects.toBe(error)
+ await expect(uploadToS3('/tmp/v.mp4', 'bucket', 'prefix', 'id')).rejects.toMatchObject({
+ name: 'RasterizationError',
+ code: 'S3_UPLOAD_FAILED',
+ retryable: true,
+ cause: error,
+ })
})
})
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
index 7063bb5ae10a..707c5e619775 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts
@@ -50,14 +50,30 @@ export class BlockProxy {
const url = `${this.cfg.recordingApiBaseUrl}/api/projects/${input.team_id}/recordings/${encodeURIComponent(
input.session_id
)}/blocks`
- const resp = await internalFetch(url, {
- headers: this.authHeaders(),
- })
+ let resp
+ try {
+ resp = await internalFetch(url, {
+ headers: this.authHeaders(),
+ })
+ } catch (err) {
+ // Connection-level failures (recording-api rollout, DNS blip) would otherwise surface as
+ // UNKNOWN; they are the most retryable failure this call has.
+ throw new RasterizationError(
+ `Failed to fetch block listing: ${(err as Error)?.message ?? String(err)}`,
+ true,
+ 'BLOCK_LISTING_FAILED',
+ err
+ )
+ }
if (resp.status < 200 || resp.status >= 300) {
const body = await resp.text()
+ // 404 stays retryable because a recording still being ingested has no blocks yet, the
+ // same race the player's NO_SNAPSHOTS handling deliberately keeps retryable. 408/429
+ // are transient by definition. Remaining 4xx (auth, bad request) cannot heal on retry.
+ const retryable = resp.status >= 500 || [404, 408, 429].includes(resp.status)
throw new RasterizationError(
`Failed to fetch block listing: ${resp.status} - ${body}`,
- resp.status >= 500,
+ retryable,
'BLOCK_LISTING_FAILED'
)
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts b/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts
index b5a7413b7b6d..89af56efa549 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/browser-pool.ts
@@ -2,25 +2,17 @@ import { Browser, Page } from 'puppeteer'
import { launch as launchForCapture } from 'puppeteer-capture'
import { config } from '~/session-replay/recording-rasterizer/config'
+import { resolveEgressProxyUrl } from '~/session-replay/recording-rasterizer/egress-proxy'
import { createLogger } from '~/session-replay/recording-rasterizer/logger'
import { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'
const log = createLogger()
function resolveProxyArgs(): string[] {
- const killed = ['false', '0', 'no', 'off'].includes((process.env.RASTERIZER_USE_PROXY ?? '').trim().toLowerCase())
- const upstream =
- process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy
+ const upstream = resolveEgressProxyUrl()
if (!upstream) {
return []
}
- if (killed) {
- log.warn(
- { RASTERIZER_USE_PROXY: process.env.RASTERIZER_USE_PROXY },
- 'RASTERIZER_USE_PROXY disables egress proxy — chrome will dial direct'
- )
- return []
- }
// Chrome's --proxy-server takes scheme://host:port — drop userinfo / path.
// `new URL("smokescreen:4750")` parses as scheme-only with empty host; fail
// fast rather than silently rendering --proxy-server=smokescreen:// (which
@@ -124,7 +116,16 @@ export class BrowserPool {
} else {
slot = await this.launchBrowser()
}
- const page = await slot.browser.newPage()
+ let page: Page
+ try {
+ page = await slot.browser.newPage()
+ } catch (err) {
+ // The slot is already out of the idle list, so a live-but-unresponsive browser would
+ // otherwise be orphaned as a zombie Chrome process (`disconnected` only fires when the
+ // process actually dies).
+ await this.closeBrowser(slot)
+ throw err
+ }
slot.usageCount++
this.slots.set(page, slot)
RasterizationMetrics.setBrowserCounts(this.slots.size, this.idle.length)
@@ -149,6 +150,11 @@ export class BrowserPool {
log.info({ usage_count: slot.usageCount }, 'recycling browser')
RasterizationMetrics.browserRecycled()
await this.closeBrowser(slot)
+ } else if (this.idle.length >= config.maxIdleBrowsers) {
+ // Beyond the warm-pool cap, an idle Chromium is pure RSS: close it instead of keeping
+ // the pod's memory footprint at its all-time concurrency high-water mark.
+ log.info({ idle: this.idle.length }, 'idle pool full, closing browser')
+ await this.closeBrowser(slot)
} else {
this.idle.push(slot)
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts b/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
index 9c890c654346..fcaccb2224cc 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/capture.ts
@@ -79,8 +79,8 @@ export async function capturePlayback(
})
// Monitor page lifecycle events that can terminate capture.
- // Named functions so we can remove them in the finally block — the page
- // is pooled and reused, so anonymous listeners would accumulate.
+ // Named functions so we can remove them in the finally block; leaving them attached would
+ // fire stale error logs when the page is closed on release.
let captureDone = false
const onPageClose = (): void => {
if (!captureDone) {
@@ -96,19 +96,24 @@ export async function capturePlayback(
page.on('error', onPageError)
// When ffmpeg dies, puppeteer-capture stops capturing but waitForTimeout()
- // hangs forever. Listen for captureStopped to break out of the loop.
- let captureAborted: Error | null = null
- let captureAbortReject: ((err: Error) => void) | null = null
+ // hangs forever. Listen for captureStopped to break out of the loop: settled with an error
+ // on an unexpected stop, settled cleanly when ffmpeg exiting is the end of the render.
+ // undefined = still capturing, null = stopped cleanly, Error = stopped with a failure.
+ let stopResult: Error | null | undefined = undefined
+ let captureStopSettle: ((err: Error | null) => void) | null = null
const onCaptureStopped = (): void => {
- if (captureDone || player.isEnded()) {
+ // ffmpeg exits on its own once -t reaches the trim duration, and can do so before the
+ // 250ms loop observes trimFrameLimit; that is a completed render, not an abort.
+ if (captureDone || player.isEnded() || frameCount >= captureConfig.trimFrameLimit) {
// Playback finished naturally — ffmpeg exiting is expected.
log.info({ frames: frameCount }, 'capture stopped after playback ended')
- return
+ stopResult = null
+ } else {
+ log.error({ stderr: ffmpegStderr.slice(-20), frames: frameCount }, 'capture stopped unexpectedly')
+ stopResult =
+ player.fatalError ?? new RasterizationError('capture stopped unexpectedly', true, 'CAPTURE_ABORTED')
}
- log.error({ stderr: ffmpegStderr.slice(-20), frames: frameCount }, 'capture stopped unexpectedly')
- const err = player.fatalError ?? new RasterizationError('capture stopped unexpectedly', true, 'CAPTURE_ABORTED')
- captureAborted = err
- captureAbortReject?.(err)
+ captureStopSettle?.(stopResult)
}
recorder.on('captureStopped', onCaptureStopped)
@@ -130,16 +135,20 @@ export async function capturePlayback(
const checkIntervalMs = 250
while (virtualElapsed < captureConfig.maxVirtualTimeMs) {
- if (captureAborted) {
- throw captureAborted
+ if (stopResult !== undefined) {
+ if (stopResult) {
+ throw stopResult
+ }
+ log.info({ frames: frameCount }, 'capture already stopped, ending loop')
+ break
}
- await Promise.race([
- recorder.waitForTimeout(checkIntervalMs),
- new Promise<never>((_, reject) => {
- captureAbortReject = reject
- }),
- ])
- captureAbortReject = null
+ await new Promise<void>((resolve, reject) => {
+ captureStopSettle = (err) => (err ? reject(err) : resolve())
+ // A rejection landing after captureStopSettle already settled the promise is
+ // swallowed here instead of surfacing as an unhandled rejection.
+ Promise.resolve(recorder.waitForTimeout(checkIntervalMs)).then(resolve, reject)
+ })
+ captureStopSettle = null
virtualElapsed += checkIntervalMs
if (frameCount >= captureConfig.trimFrameLimit) {
@@ -167,7 +176,7 @@ export async function capturePlayback(
}
} finally {
captureDone = true
- captureAbortReject = null
+ captureStopSettle = null
page.off('close', onPageClose)
page.off('error', onPageError)
// puppeteer-capture's PuppeteerCapture extends EventEmitter but only
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
index 911800b4c324..786eb9905fff 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/config.ts
@@ -1,10 +1,13 @@
import type { PlayerConfig } from '@posthog/replay-headless/protocol'
+import { config as workerConfig } from '~/session-replay/recording-rasterizer/config'
import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'
import { CaptureConfig, RasterizeRecordingInput } from '~/session-replay/recording-rasterizer/types'
const DEFAULT_PLAYBACK_SPEED = 4
const DEFAULT_FPS = 24
+// GIFs at high frame rates are enormous; 12fps is the ceiling worth encoding.
+const GIF_MAX_FPS = 12
// Kept in step with SESSION_RECORDING_ID_RE in products/exports/backend/models/exported_asset.py.
// The lookahead drops a dot-only id, which is a relative path segment rather than a session.
const SESSION_ID_RE = /^(?!\.+$)[A-Za-z0-9_.:-]{1,200}$/
@@ -13,7 +16,7 @@ const SESSION_ID_RE = /^(?!\.+$)[A-Za-z0-9_.:-]{1,200}$/
// finite number. ffmpeg is spawned without a shell, but a non-finite/non-numeric value reaching
// here (e.g. from a future caller that skips upstream validation) could still land in the option
// list or filtergraph as a raw string. Throwing keeps interpolation injection-proof regardless of
-// the caller: a finite number stringifies to [0-9.eE+-] only — no spaces or filter metacharacters.
+// the caller: a finite number stringifies to [0-9.eE+-] only, so no spaces or filter metacharacters.
function toFiniteNumber(value: unknown, field: string): number {
const n = Number(value)
if (!Number.isFinite(n)) {
@@ -34,9 +37,12 @@ export function validateInput(input: RasterizeRecordingInput): void {
if (!input.team_id || input.team_id <= 0) {
throw new RasterizationError('team_id must be a positive integer', false, 'INVALID_INPUT')
}
- if (input.playback_speed !== undefined && input.playback_speed <= 0) {
+ // Speeds below 1 would need a slow-motion filter chain the pipeline doesn't have: frames come
+ // in at captureFps = outputFps * speed, and without the setpts stretch the file's real duration
+ // is 1/speed times what we report downstream (video_duration_s, inactivity mapping, trim).
+ if (input.playback_speed !== undefined && input.playback_speed < 1) {
throw new RasterizationError(
- `playback_speed must be positive, got: ${input.playback_speed}`,
+ `playback_speed must be >= 1, got: ${input.playback_speed}`,
false,
'INVALID_INPUT'
)
@@ -71,18 +77,34 @@ export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfi
const playbackSpeed = input.playback_speed
? toFiniteNumber(input.playback_speed, 'playback_speed')
: DEFAULT_PLAYBACK_SPEED
- const outputFps = input.recording_fps ? toFiniteNumber(input.recording_fps, 'recording_fps') : DEFAULT_FPS
+ let outputFps = input.recording_fps ? toFiniteNumber(input.recording_fps, 'recording_fps') : DEFAULT_FPS
+ const outputFormat = input.output_format || 'mp4'
+ // Clamp before deriving captureFps so GIF renders don't capture frames the fps filter would
+ // discard: every captured frame is a full CDP screenshot round-trip.
+ if (outputFormat === 'gif') {
+ outputFps = Math.min(outputFps, GIF_MAX_FPS)
+ }
const trim = input.trim ? toFiniteNumber(input.trim, 'trim') : undefined
// e.g. 3fps output × 8x speed = 24fps capture → setpts stretches 8x → 3fps
const captureFps = outputFps * playbackSpeed
- const outputFormat = input.output_format || 'mp4'
const ffmpegOutputOpts: string[] =
outputFormat === 'webm'
- ? ['-f webm', '-c:v libvpx-vp9', '-crf 30', '-b:v 0']
+ ? // Default libvpx-vp9 settings (deadline good, cpu-used 0) encode at single-digit fps;
+ // realtime deadline with row multithreading keeps encode well ahead of capture.
+ ['-f webm', '-c:v libvpx-vp9', '-crf 30', '-b:v 0', '-deadline realtime', '-cpu-used 5', '-row-mt 1']
: outputFormat === 'gif'
? ['-f gif', '-c:v gif', '-loop', '0']
: ['-f mp4', '-c:v libx264', '-preset veryfast', '-crf 23', '-pix_fmt yuv420p', '-movflags +faststart']
+ if (outputFormat !== 'gif') {
+ // nproc inside a CFS-limited pod reports host cores, so an uncapped encoder spawns far more
+ // threads than the pod can run and throttles the capture loop competing for the same quota.
+ ffmpegOutputOpts.push('-threads 2')
+ }
+ // puppeteer-capture forces the output rate to captureFps (outputFPS in PuppeteerCaptureBase),
+ // which resamples the fps-filtered stream back up by duplicating every frame `speed` times.
+ // A later -r wins, so pin the container rate to what the filter chain actually produces.
+ ffmpegOutputOpts.push(`-r ${outputFps}`)
if (trim) {
ffmpegOutputOpts.push(`-t ${trim}`)
}
@@ -103,10 +125,10 @@ export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfi
// Scale down to 800px wide — GIFs at full viewport size are enormous.
// -2 ensures even height; lanczos gives sharp downscaling.
ffmpegVideoFilters.push('scale=800:-2:flags=lanczos')
- // 12fps keeps file size reasonable. Per-frame palette (stats_mode=single)
- // with Bayer dithering and rectangle diff mode produces better quality
- // and smaller files than ffmpeg's defaults.
- ffmpegVideoFilters.push('fps=12')
+ // Per-frame palette (stats_mode=single) with Bayer dithering and rectangle diff mode
+ // produces better quality and smaller files than ffmpeg's defaults. No fps filter here:
+ // the setpts branch already emits fps=outputFps for speeds above 1, and at speed 1 the
+ // capture rate equals the clamped output rate.
ffmpegVideoFilters.push(
'split[s0][s1];[s0]palettegen=stats_mode=single[p];[s1][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle'
)
@@ -122,8 +144,8 @@ export function buildCaptureConfig(input: RasterizeRecordingInput): CaptureConfi
outputFormat,
ffmpegOutputOpts,
ffmpegVideoFilters,
- screenshotFormat: input.screenshot_format || 'jpeg',
- screenshotQuality: input.screenshot_quality ?? 80,
+ screenshotFormat: input.screenshot_format || workerConfig.screenshotFormat,
+ screenshotQuality: input.screenshot_quality ?? workerConfig.screenshotJpegQuality,
}
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
index d8b2de94188f..9a74530bea53 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts
@@ -104,6 +104,13 @@ export class PlayerController {
timeoutMsg: string,
resetOnProgress = false
): Promise<void> {
+ // An error emitted before this registers errorReject (e.g. NO_SNAPSHOTS arriving between
+ // load() and waitForStart()) was shelved in playbackError; without this check it would sit
+ // there while we idle out and misreport a retryable TIMEOUT over the real, possibly
+ // terminal, code.
+ if (this.playbackError) {
+ return Promise.reject(this.playbackError)
+ }
return new Promise<void>((resolve, reject) => {
const onTimeout = (): void => {
this.startedResolve = null
@@ -182,7 +189,16 @@ export class PlayerController {
playerConfig
)
- await page.goto(this.capturePage.playerUrl, { waitUntil: 'load', timeout: 30000 })
+ try {
+ await page.goto(this.capturePage.playerUrl, { waitUntil: 'load', timeout: 30000 })
+ } catch (err) {
+ // Puppeteer's TimeoutError would classify as UNKNOWN downstream; it is the same failure
+ // mode as every other load stall, so give it the same retryable TIMEOUT code.
+ if ((err as Error)?.name === 'TimeoutError') {
+ throw new RasterizationError('player page load timed out', true, 'TIMEOUT', err)
+ }
+ throw err
+ }
this.log.info({ origin: this.capturePage.playerUrl }, 'player loaded')
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
index 67b563cba9fb..58c0e6f0e761 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts
@@ -45,24 +45,45 @@ function estimateTotalFrames(
return Math.max(0, Math.ceil(videoS * captureFps))
}
+export interface RasterizeOptions {
+ progress?: RasterizationProgress | null
+ cfg?: typeof defaultConfig
+ log?: Logger
+ // Aborting closes the page, which unsticks a pending CDP send and makes the capture loop fail
+ // fast, so the browser-pool slot is reclaimed instead of riding out a doomed attempt.
+ signal?: AbortSignal
+}
+
export async function rasterizeRecording(
pool: BrowserPool,
input: RasterizeRecordingInput,
outputPath: string,
playerHtml: string,
onProgress: () => void,
- progress: RasterizationProgress | null = null,
- cfg: typeof defaultConfig = defaultConfig,
- log: Logger = createLogger({ session_id: input.session_id, team_id: input.team_id })
+ options: RasterizeOptions = {}
): Promise<RecordingResult> {
+ const progress = options.progress ?? null
+ const cfg = options.cfg ?? defaultConfig
+ const log = options.log ?? createLogger({ session_id: input.session_id, team_id: input.team_id })
+ const signal = options.signal
+
validateInput(input)
+ signal?.throwIfAborted()
const setupStart = process.hrtime()
const captureConfig = buildCaptureConfig(input)
const rawPage = await pool.getPage()
+ const onAbort = (): void => {
+ log.warn('abort requested, closing page to stop capture')
+ rawPage.close().catch(() => {})
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
let player: PlayerController | null = null
try {
+ // An abort that fired while getPage was launching Chromium predates the listener above and
+ // would otherwise be silently missed; the finally below releases the page.
+ signal?.throwIfAborted()
const viewport = {
width: input.viewport_width || 1280,
height: input.viewport_height || 720,
@@ -109,16 +130,15 @@ export async function rasterizeRecording(
const captureResult = await capturePlayback(player, captureConfig, outputPath, onProgress, progress, log)
return {
- video_path: outputPath,
playback_speed: captureConfig.playbackSpeed,
capture_duration_s: captureResult.capture_duration_s,
frame_count: captureResult.frame_count,
truncated: captureResult.truncated,
inactivity_periods: captureResult.inactivity_periods,
- custom_fps: captureConfig.outputFps,
timings: { setup_s: setupS, capture_s: captureResult.timings.capture_s },
}
} finally {
+ signal?.removeEventListener('abort', onAbort)
player?.dispose()
await pool.releasePage(rawPage)
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
index 170c293824d1..eeadb42e5a1f 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
@@ -154,10 +154,16 @@ export class RequestInterceptor {
private async proxyStylesheet(request: HTTPRequest): Promise<void> {
const url = request.url()
try {
- const headers = request.headers()
- delete headers['host']
- delete headers['connection']
- delete headers['content-length']
+ // Forward an allowlist rather than the browser's full header set: the URL is
+ // attacker-controlled (a <link href> in a recorded sub-frame), and the browser's
+ // Referer would disclose the internal player URL to arbitrary third-party hosts.
+ const browserHeaders = request.headers()
+ const headers: Record<string, string> = {}
+ for (const name of ['accept', 'accept-language', 'user-agent']) {
+ if (browserHeaders[name]) {
+ headers[name] = browserHeaders[name]
+ }
+ }
const resp = await fetch(url, { headers, timeoutMs: PROXY_TIMEOUT_MS })
const body = await resp.text()
await request.respond({
diff --git a/nodejs/src/session-replay/recording-rasterizer/config.ts b/nodejs/src/session-replay/recording-rasterizer/config.ts
index 2a2bb59adc3e..b59ff2839c3b 100644
--- a/nodejs/src/session-replay/recording-rasterizer/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/config.ts
@@ -5,6 +5,13 @@ export function parseList(text: string | undefined): string[] {
return text.split(',').map((item) => item.trim())
}
+// parseInt returns NaN on junk, and NaN flows silently into Worker.create / pool sizing,
+// so every numeric env var goes through a fallback plus a positivity bound.
+export function parsePositiveInt(raw: string | undefined, fallback: number): number {
+ const n = parseInt(raw ?? '', 10)
+ return Number.isFinite(n) && n > 0 ? n : fallback
+}
+
export const config = {
// Temporal
temporalHost: process.env.TEMPORAL_HOST || '127.0.0.1',
@@ -17,16 +24,19 @@ export const config = {
// Worker
logLevel: (process.env.LOG_LEVEL || 'info') as 'debug' | 'info' | 'warn' | 'error',
- maxConcurrentActivities: parseInt(process.env.MAX_CONCURRENT_ACTIVITIES || '4', 10),
- browserRecycleAfter: parseInt(process.env.BROWSER_RECYCLE_AFTER || '100', 10),
+ maxConcurrentActivities: parsePositiveInt(process.env.MAX_CONCURRENT_ACTIVITIES, 4),
+ browserRecycleAfter: parsePositiveInt(process.env.BROWSER_RECYCLE_AFTER, 100),
+ // Browsers held warm beyond this are closed on release: each idle Chromium pins 100-250MB RSS,
+ // and a pod that once ran at full concurrency would otherwise keep that footprint forever.
+ maxIdleBrowsers: parsePositiveInt(process.env.MAX_IDLE_BROWSERS, 2),
disableBrowserSecurity: process.env.DISABLE_BROWSER_SECURITY === '1',
captureBrowserLogs: process.env.CAPTURE_BROWSER_LOGS === '1',
screenshotFormat: (process.env.SCREENSHOT_FORMAT || 'jpeg') as 'png' | 'jpeg',
// Hard cap on a single beginFrame; mass-image-decode stalls legitimately run 30-60s, so keep
// this well above that. It only exists to bound a truly wedged compositor.
- beginFrameTimeoutMs: parseInt(process.env.BEGINFRAME_TIMEOUT_MS || '120000', 10) || 120_000,
- screenshotJpegQuality: parseInt(process.env.SCREENSHOT_JPEG_QUALITY || '80', 10),
- metricsPort: parseInt(process.env.METRICS_PORT || '6738', 10),
+ beginFrameTimeoutMs: parsePositiveInt(process.env.BEGINFRAME_TIMEOUT_MS, 120_000),
+ screenshotJpegQuality: parsePositiveInt(process.env.SCREENSHOT_JPEG_QUALITY, 80),
+ metricsPort: parsePositiveInt(process.env.METRICS_PORT, 6738),
// Encryption
secretKey: process.env.TEMPORAL_SECRET_KEY || process.env.SECRET_KEY,
@@ -36,14 +46,15 @@ export const config = {
s3Endpoint: process.env.VIDEO_EXPORT_OBJECT_STORAGE_ENDPOINT,
s3Region: process.env.VIDEO_EXPORT_OBJECT_STORAGE_REGION || 'us-east-1',
- // Recording API
- recordingApiBaseUrl: process.env.RECORDING_API_BASE_URL || 'http://localhost:6738',
+ // Recording API. The dev recording-api listens on 6741 (bin/temporal-recording-rasterizer-worker).
+ recordingApiBaseUrl: process.env.RECORDING_API_BASE_URL || 'http://localhost:6741',
recordingApiSecret: process.env.INTERNAL_API_SECRET || '',
// Player
siteUrl: process.env.SITE_URL || 'http://localhost:8000',
playerHtmlPath: process.env.PLAYER_HTML_PATH || '/code/common/replay-headless/dist/player.html',
- // Opt-in: serve the player under a script-locking CSP (nonce). Off by default so it can be
- // rolled out and verified in dev before enabling in production.
- enablePlayerCsp: process.env.ENABLE_PLAYER_CSP === '1',
+ // Serve the player under a script-locking CSP (nonce). On by default: recordings are untrusted,
+ // and the CSP is the backstop if the replay iframe sandbox ever regresses. ENABLE_PLAYER_CSP=0
+ // is the escape hatch if a player build ships without the nonce placeholder.
+ enablePlayerCsp: process.env.ENABLE_PLAYER_CSP !== '0',
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/egress-proxy.ts b/nodejs/src/session-replay/recording-rasterizer/egress-proxy.ts
new file mode 100644
index 000000000000..6cb7cd87c899
--- /dev/null
+++ b/nodejs/src/session-replay/recording-rasterizer/egress-proxy.ts
@@ -0,0 +1,35 @@
+import { isProdEnv, stringToBoolean } from '~/common/utils/env-utils'
+
+import { createLogger } from './logger'
+
+const log = createLogger()
+
+// Egress containment for attacker-controlled recording content rests entirely on routing Chrome
+// (and the S3 client) through the smokescreen proxy. Both consumers previously resolved the proxy
+// env vars independently with subtly different logic, which is the drift that caused the STS 407
+// outage. This is the single source of truth, and in production it fails closed: a missing proxy
+// URL refuses to start rather than silently letting Chrome dial internal endpoints directly.
+export function resolveEgressProxyUrl(): string | null {
+ const upstream =
+ process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy
+ const killed = stringToBoolean((process.env.RASTERIZER_USE_PROXY ?? '').trim(), true) === false
+
+ if (killed) {
+ log.warn(
+ { RASTERIZER_USE_PROXY: process.env.RASTERIZER_USE_PROXY },
+ 'RASTERIZER_USE_PROXY disables the egress proxy — chrome and s3 will dial direct'
+ )
+ return null
+ }
+ if (!upstream) {
+ if (isProdEnv()) {
+ throw new Error(
+ 'No egress proxy configured (HTTPS_PROXY/HTTP_PROXY): recordings are untrusted content, so ' +
+ 'production refuses to run without egress containment. Set the proxy URL, or set ' +
+ 'RASTERIZER_USE_PROXY=false to explicitly accept direct egress.'
+ )
+ }
+ return null
+ }
+ return upstream
+}
diff --git a/nodejs/src/session-replay/recording-rasterizer/errors.ts b/nodejs/src/session-replay/recording-rasterizer/errors.ts
index d01ce5b76f37..095449db4463 100644
--- a/nodejs/src/session-replay/recording-rasterizer/errors.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/errors.ts
@@ -9,6 +9,7 @@ export const RASTERIZATION_ERROR_CODES = [
'BEGINFRAME_DEADLOCK',
'INVALID_INPUT',
'BLOCK_LISTING_FAILED',
+ 'S3_UPLOAD_FAILED',
'S3_UPLOAD_UNDECODABLE_RESPONSE',
'NO_SNAPSHOTS',
'INIT_FAILED',
diff --git a/nodejs/src/session-replay/recording-rasterizer/storage.ts b/nodejs/src/session-replay/recording-rasterizer/storage.ts
index 33f3b8285c59..33262d872b36 100644
--- a/nodejs/src/session-replay/recording-rasterizer/storage.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/storage.ts
@@ -6,6 +6,7 @@ import * as fs from 'fs'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { config } from './config'
+import { resolveEgressProxyUrl } from './egress-proxy'
import { RasterizationError } from './errors'
import { createLogger } from './logger'
@@ -31,26 +32,9 @@ function undecodableResponse(err: unknown): { status?: number; body: string } |
let s3Client: S3Client | null = null
-function resolveProxyUrl(): string | null {
- const upstream =
- process.env.HTTPS_PROXY || process.env.HTTP_PROXY || process.env.https_proxy || process.env.http_proxy
- if (!upstream) {
- return null
- }
- const killed = ['false', '0', 'no', 'off'].includes((process.env.RASTERIZER_USE_PROXY ?? '').trim().toLowerCase())
- if (killed) {
- log.warn(
- { RASTERIZER_USE_PROXY: process.env.RASTERIZER_USE_PROXY },
- 'RASTERIZER_USE_PROXY disables egress proxy — s3 will dial direct'
- )
- return null
- }
- return upstream
-}
-
function getS3Client(): S3Client {
if (!s3Client) {
- const proxyUrl = resolveProxyUrl()
+ const proxyUrl = resolveEgressProxyUrl()
const requestHandler = proxyUrl ? { httpsAgent: new HttpsProxyAgent(proxyUrl) } : undefined
s3Client = new S3Client({
region: config.s3Region,
@@ -105,7 +89,18 @@ export async function uploadToS3(
} catch (err) {
const undecodable = undecodableResponse(err)
if (!undecodable) {
- throw err
+ // Raw SDK errors would surface as UNKNOWN in the error metrics and as untyped
+ // ApplicationFailures to the workflow. Always retryable: a 403 can be a transient
+ // credential-refresh race, and a wasted retry is cheaper than discarding a finished
+ // render over a misclassified permanent failure.
+ const status = (err as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode
+ log.warn({ bucket, key, status, err: (err as Error)?.message }, 'S3 upload failed')
+ throw new RasterizationError(
+ `S3 upload failed${status ? ` (status ${status})` : ''}: ${(err as Error)?.message ?? String(err)}`,
+ true,
+ 'S3_UPLOAD_FAILED',
+ err
+ )
}
// Bucket, key and the raw body stay in this log line. The thrown message reaches team users as
// ReplayObservation.error_reason, and the body is whatever an upstream proxy or gateway chose to
diff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
index 458adbe6e72c..71eb2c4aa195 100644
--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts
@@ -63,16 +63,55 @@ async function rasterizeRecordingActivity(
// `pending_activities[].heartbeat_details` for the parent workflow to read.
const progress: RasterizationProgress = { phase: 'setup', frame: 0, estimatedTotalFrames: 0 }
let lastProgressAt = Date.now()
+ // Stage timings are tracked here rather than trusted from the recorder so they exist on the
+ // error path too: knowing how long failing renders run, and in which stage, is the main
+ // question the metrics need to answer.
+ let phaseStartedAt = Date.now()
+ let lastPhase: RasterizationProgress['phase'] = progress.phase
+ // Heartbeats fire from puppeteer emitter callbacks and a timer; once the activity context is
+ // gone (worker shutdown, cancellation) an uncaught throw would kill the process.
+ const safeHeartbeat = (): void => {
+ try {
+ Context.current().heartbeat(progress)
+ } catch {
+ // Context gone; nothing to report to.
+ }
+ }
const onProgress = (): void => {
lastProgressAt = Date.now()
- Context.current().heartbeat(progress)
+ if (progress.phase !== lastPhase) {
+ lastPhase = progress.phase
+ phaseStartedAt = Date.now()
+ }
+ safeHeartbeat()
+ }
+
+ // Cancellation (workflow cancel, heartbeat-timeout detection) aborts the render by closing the
+ // page; without this, the render runs to completion holding a browser and a concurrency slot
+ // the server has already given up on.
+ const abort = new AbortController()
+ const ctx = Context.current()
+ const onCancel = (): void => abort.abort()
+ ctx.cancellationSignal.addEventListener('abort', onCancel, { once: true })
+ if (ctx.cancellationSignal.aborted) {
+ abort.abort()
}
// Progress-driven heartbeats stop while a beginFrame stalls, so beat on wall clock too, but
// only up to the stall tolerance, so a hang anywhere else still trips the 30s heartbeat timeout.
const keepaliveCutoffMs = config.beginFrameTimeoutMs + 30_000
+ // Past the cutoff the server has necessarily timed this attempt out (heartbeats stopped), and
+ // cancellation can no longer be delivered over heartbeat responses, so a local watchdog is the
+ // only thing left that can reclaim the slot from a wedged render.
+ const watchdogCutoffMs = keepaliveCutoffMs + 60_000
const heartbeatInterval = setInterval(() => {
- if (Date.now() - lastProgressAt > keepaliveCutoffMs) {
+ const sinceProgress = Date.now() - lastProgressAt
+ if (sinceProgress > watchdogCutoffMs && !abort.signal.aborted) {
+ log.error({ since_progress_s: Math.round(sinceProgress / 1000) }, 'no progress past watchdog, aborting')
+ abort.abort()
+ return
+ }
+ if (sinceProgress > keepaliveCutoffMs) {
return
}
try {
@@ -83,16 +122,11 @@ async function rasterizeRecordingActivity(
}, 10_000)
try {
- const result = await rasterizeRecording(
- pool,
- input,
- outputPath,
- playerHtml,
- onProgress,
+ const result = await rasterizeRecording(pool, input, outputPath, playerHtml, onProgress, {
progress,
- undefined,
- log
- )
+ log,
+ signal: abort.signal,
+ })
timings.setup_s = result.timings.setup_s
timings.capture_s = result.timings.capture_s
RasterizationMetrics.observeSetup('success', timings.setup_s)
@@ -113,8 +147,10 @@ async function rasterizeRecordingActivity(
RasterizationMetrics.observeActivity('success', timings.total_s)
RasterizationMetrics.observeVideo(result.capture_duration_s, stat.size, result.frame_count)
- // Total recording duration = active playback time + skipped inactivity
- const activeSessionS = result.capture_duration_s * result.playback_speed
+ // Total recording duration = active playback time + skipped inactivity. The output video is
+ // real-time (the setpts filter undoes the capture speed-up), so capture_duration_s already
+ // is active session seconds; multiplying by playback_speed would overstate it.
+ const activeSessionS = result.capture_duration_s
const skippedS = result.inactivity_periods
.filter((p) => !p.active && p.ts_to_s != null)
.reduce((sum, p) => sum + (p.ts_to_s! - p.ts_from_s), 0)
@@ -146,6 +182,16 @@ async function rasterizeRecordingActivity(
} catch (err) {
timings.total_s = elapsed(activityStart)
RasterizationMetrics.observeActivity('error', timings.total_s)
+ // Record how long the failed stage ran; without this the setup/capture/upload series only
+ // exist for successes and cannot answer where failing renders spend their time.
+ const failedStageS = (Date.now() - phaseStartedAt) / 1000
+ if (lastPhase === 'setup') {
+ RasterizationMetrics.observeSetup('error', failedStageS)
+ } else if (lastPhase === 'capture') {
+ RasterizationMetrics.observeCapture('error', failedStageS)
+ } else {
+ RasterizationMetrics.observeUpload('error', failedStageS)
+ }
if (err instanceof RasterizationError) {
RasterizationMetrics.incrementError(err.code, err.retryable)
} else {
@@ -154,6 +200,7 @@ async function rasterizeRecordingActivity(
throw toActivityError(err)
} finally {
clearInterval(heartbeatInterval)
+ ctx.cancellationSignal.removeEventListener('abort', onCancel)
RasterizationMetrics.activityFinished()
await fs.rm(outputPath, { force: true })
}
diff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.ts
index 793a76955b3f..b6d2ce521ae8 100644
--- a/nodejs/src/session-replay/recording-rasterizer/types.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts
@@ -81,12 +81,10 @@ export interface CaptureConfig {
/** Internal result from the recorder before S3 upload */
export interface RecordingResult {
- video_path: string
playback_speed: number
capture_duration_s: number // wall-clock seconds of useful capture (up to RECORDING_ENDED)
frame_count: number // total frames captured
truncated: boolean // true when max_virtual_time stopped the recording early
inactivity_periods: InactivityPeriod[]
- custom_fps: number
timings: Pick<ActivityTimings, 'setup_s' | 'capture_s'>
}
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
index 5b068b7d386b..7d46a3d74d02 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py
@@ -5,6 +5,7 @@ from django.db import close_old_connections, transaction
import structlog
from temporalio import activity
+from temporalio.exceptions import ApplicationError
from posthog.session_recordings.recordings.recording_api_jwt import mint_recording_api_token, recording_api_jwt_enabled
from posthog.storage import object_storage
@@ -41,18 +42,24 @@ _PERSISTED_OUTPUT_FIELDS: frozenset[str] = frozenset(
def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResult:
close_old_connections()
- asset = ExportedAsset.objects.select_related("team").get(pk=exported_asset_id)
+ asset = ExportedAsset.objects.get(pk=exported_asset_id)
ctx = asset.export_context or {}
session_id = ctx.get("session_recording_id")
if not session_id:
- raise ValueError(f"ExportedAsset {exported_asset_id} has no session_recording_id in export_context")
+ # non_retryable: the asset's export_context is permanently invalid; retrying re-reads the
+ # same row, and the eventual workflow failure would wrongly mark the session as stuck.
+ raise ApplicationError(
+ f"ExportedAsset {exported_asset_id} has no session_recording_id in export_context", non_retryable=True
+ )
# Assets reach this activity from several writers, not all of them behind the exports serializer,
# so the id is re-checked here before it becomes part of an internal recording API path.
if not is_valid_session_recording_id(session_id):
# Logged as well as raised so a session id we reject wrongly is greppable, not just a failed render.
logger.warning("rasterize.malformed_session_recording_id", asset_id=exported_asset_id)
- raise ValueError(f"ExportedAsset {exported_asset_id} has a malformed session_recording_id")
+ raise ApplicationError(
+ f"ExportedAsset {exported_asset_id} has a malformed session_recording_id", non_retryable=True
+ )
output_format = ExportedAsset.RASTERIZED_FORMATS.get(asset.export_format, "mp4")
@@ -72,17 +79,19 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResul
if viewport_height is not None:
viewport_height = max(300, min(2160, int(viewport_height)))
- # 1x for short clips so output plays in real time; 4x for full sessions to cap file size.
+ # The output video is always real-time (the ffmpeg setpts filter undoes the speed-up); speed
+ # only reduces the virtual time a render spends playing the session. 1x for short clips keeps
+ # capture simple; 4x for full sessions bounds virtual time on long recordings.
default_speed = 1 if (duration is not None and duration <= 5) else 4
- playback_speed = ctx.get("playback_speed", default_speed)
- recording_fps = ctx.get("recording_fps", 24)
- # Cap the render rate so a large fps × speed product can't exhaust the shared rasterizer pool.
- # Upper bound only: positivity is enforced in the Node validateInput, and fractional
- # slow-motion speeds (< 1) are valid.
- if playback_speed is not None:
- playback_speed = min(360.0, float(playback_speed))
- if recording_fps is not None:
- recording_fps = min(60, int(recording_fps))
+ # `or` rather than a .get default so an explicit null in export_context also falls back instead
+ # of failing pydantic validation three retries in a row.
+ playback_speed = ctx.get("playback_speed") or default_speed
+ recording_fps = ctx.get("recording_fps") or 24
+ # Clamp the render rate so a large fps × speed product can't exhaust the shared rasterizer pool.
+ # The lower bound matches Node's validateInput: speeds below 1 have no slow-motion filter chain
+ # and would misreport the video duration.
+ playback_speed = max(1.0, min(360.0, float(playback_speed)))
+ recording_fps = min(60, int(recording_fps))
# Empty until the signing secret is configured; the rasterizer then relays the legacy shared
# secret instead, so rollout can happen per environment without breaking rendering.
diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/stuck_counter.py b/posthog/temporal/session_replay/rasterize_recording/activities/stuck_counter.py
index 522a9b088579..f1faca29ba44 100644
--- a/posthog/temporal/session_replay/rasterize_recording/activities/stuck_counter.py
+++ b/posthog/temporal/session_replay/rasterize_recording/activities/stuck_counter.py
@@ -2,10 +2,9 @@ from dataclasses import dataclass
from datetime import timedelta
import structlog
-from redis.asyncio import Redis as AsyncRedis
from temporalio import activity
-from posthog.redis import get_async_client
+from posthog.redis import get_async_client, get_client
logger = structlog.get_logger(__name__)
@@ -48,16 +47,20 @@ async def clear_stuck_counter_activity(inputs: BumpStuckCounterInput) -> None:
await redis_client.delete(key)
-async def read_stuck_session_ids(
- redis_client: AsyncRedis,
+# A run only bumps the counter after its final scheduled attempt, so 2 means the session has burned
+# through two whole retry envelopes inside the TTL window without a success.
+STUCK_SESSION_THRESHOLD = 2
+
+
+def read_stuck_session_ids(
team_id: int,
session_ids: list[str],
- threshold: int,
+ threshold: int = STUCK_SESSION_THRESHOLD,
) -> set[str]:
+ """Which of `session_ids` are quarantined. Sync because every caller is a synchronous activity."""
if not session_ids:
return set()
- keys = [_stuck_key(team_id, sid) for sid in session_ids]
- values = await redis_client.mget(keys)
+ values = get_client().mget([_stuck_key(team_id, sid) for sid in session_ids])
stuck: set[str] = set()
for sid, val in zip(session_ids, values):
if val is None:
diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.py
index 1c988b7a37d4..2a14e67cd324 100644
--- a/posthog/temporal/session_replay/rasterize_recording/types.py
+++ b/posthog/temporal/session_replay/rasterize_recording/types.py
@@ -12,9 +12,16 @@ RASTERIZE_RENDER_MAX_ATTEMPTS = 2
# Envelope for the whole workflow: the render's retry budget plus room for the prep and finalize
# activities and queue wait. The exports API uses this both as the workflow's execution_timeout and
# as the age at which it reports an export stuck, so the two can't drift and start calling a render
-# that is still legitimately working a failure.
+# that is still legitimately working a failure. A tighter caller timeout silently converts the second
+# render attempt into an untyped WorkflowExecutionTimeout, bypassing error-code-based failure
+# classification downstream.
RASTERIZE_WORKFLOW_TIMEOUT = RASTERIZE_RENDER_TIMEOUT * RASTERIZE_RENDER_MAX_ATTEMPTS + timedelta(minutes=15)
+# execution_timeout that funds exactly one render attempt plus prep/finalize headroom, for callers
+# with their own phase budget (the replay_vision sweep and evaluation). It still exceeds the render
+# start-to-close, so a fast first failure leaves room to schedule a retry that fits the budget.
+RASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT = RASTERIZE_RENDER_TIMEOUT + timedelta(minutes=10)
+
class RasterizeRecordingInputs(BaseModel, frozen=True):
"""Input to the RasterizeRecordingWorkflow."""
diff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.py
index 5974c31ccd13..2c1c233b7484 100644
--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py
+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py
@@ -74,16 +74,18 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):
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
+ def _max_attempts() -> int | None:
+ retry_policy = wf.info().retry_policy
+ return retry_policy.maximum_attempts if retry_policy else 1
+
+ @classmethod
+ def _is_final_attempt(cls) -> bool:
+ max_attempts = cls._max_attempts()
+ return max_attempts is not None and 0 < max_attempts <= wf.info().attempt
async def _maybe_bump_stuck_counter(self) -> None:
info = wf.info()
- retry_policy = info.retry_policy
- max_attempts = retry_policy.maximum_attempts if retry_policy else 1
+ max_attempts = self._max_attempts()
# Bump only on the final scheduled attempt; recoverable failures would otherwise over-count.
if max_attempts is None or max_attempts <= 0:
wf.logger.warning(
@@ -145,6 +147,9 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):
raw_result: dict[str, Any] = await wf.execute_activity(
"rasterize-recording",
prep.activity_input.model_dump(exclude_none=True),
+ # Reading a Django setting inside a workflow body is normally banned (it is not part of
+ # recorded history); it is tolerated here because Temporal does not replay-check the
+ # task-queue attribute, and a mid-flight change only redirects retries.
task_queue=settings.RASTERIZATION_TASK_QUEUE,
start_to_close_timeout=RASTERIZE_RENDER_TIMEOUT,
heartbeat_timeout=dt.timedelta(seconds=30),
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
index 8b958b086477..77012da5a1f6 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_activities.py
@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
from posthog.jwt import PosthogJwtAudience, decode_jwt
from posthog.session_recordings.recordings.recording_api_jwt import recording_api_signing_keys
@@ -173,15 +174,17 @@ class TestBuildRasterizationInput:
asset = _make_asset(pk=99, export_context={"playback_speed": 4})
patches, _ = _patches(asset)
with patches[0], patches[1], patches[2], patches[3], patches[4]:
- with pytest.raises(ValueError, match="no session_recording_id"):
+ with pytest.raises(ApplicationError, match="no session_recording_id") as excinfo:
build_rasterization_input(99)
+ assert excinfo.value.non_retryable
def test_none_export_context_raises(self):
asset = _make_asset(pk=100, export_context=None)
patches, _ = _patches(asset)
with patches[0], patches[1], patches[2], patches[3], patches[4]:
- with pytest.raises(ValueError, match="no session_recording_id"):
+ with pytest.raises(ApplicationError, match="no session_recording_id") as excinfo:
build_rasterization_input(100)
+ assert excinfo.value.non_retryable
@parameterized.expand(
[
@@ -197,8 +200,25 @@ class TestBuildRasterizationInput:
asset = _make_asset(pk=101, export_context={"session_recording_id": session_id})
patches, _ = _patches(asset)
with patches[0], patches[1], patches[2], patches[3], patches[4]:
- with pytest.raises(ValueError, match="malformed session_recording_id"):
+ with pytest.raises(ApplicationError, match="malformed session_recording_id") as excinfo:
build_rasterization_input(101)
+ assert excinfo.value.non_retryable
+
+ @parameterized.expand(
+ [
+ ("null_speed", {"session_recording_id": "s1", "playback_speed": None}, "playback_speed", 4),
+ ("null_fps", {"session_recording_id": "s1", "recording_fps": None}, "recording_fps", 24),
+ ]
+ )
+ def test_explicit_null_falls_back_to_default(self, _name, export_context, field, expected):
+ # An explicit null in export_context used to reach pydantic as None and fail validation
+ # three retries in a row instead of falling back.
+ asset = _make_asset(pk=50, export_context=export_context)
+ patches, _ = _patches(asset)
+ with patches[0], patches[1], patches[2], patches[3], patches[4]:
+ result = build_rasterization_input(50)
+ assert result.activity_input is not None
+ assert getattr(result.activity_input, field) == expected
def test_timestamp_and_duration_mapped_to_offsets(self):
asset = _make_asset(
@@ -318,7 +338,9 @@ class TestBuildRasterizationInput:
@parameterized.expand(
[
- ("slow_motion_preserved", 0.5, 0.5),
+ # Speeds below 1 are clamped up: Node rejects them because the pipeline has no
+ # slow-motion filter chain and the reported duration would be wrong.
+ ("below_one_clamped", 0.5, 1.0),
("default_in_range", 4, 4),
("at_cap", 360, 360),
("above_cap", 1000, 360),
diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_stuck_counter.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_stuck_counter.py
index 51be015fa989..fe554de1d6ba 100644
--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_stuck_counter.py
+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_stuck_counter.py
@@ -31,51 +31,37 @@ async def test_bump_stuck_counter_pipelines_incr_and_expire():
pipeline.execute.assert_awaited_once()
-async def test_read_stuck_returns_empty_for_empty_input():
+def _patched_client(mget_result=None, side_effect=None):
redis_client = MagicMock()
- redis_client.mget = AsyncMock(side_effect=AssertionError("should not call mget for empty input"))
- result = await read_stuck_session_ids(redis_client, team_id=1, session_ids=[], threshold=3)
- assert result == set()
-
+ redis_client.mget = MagicMock(return_value=mget_result, side_effect=side_effect)
+ return patch(
+ "posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter.get_client",
+ return_value=redis_client,
+ ), redis_client
-async def test_read_stuck_thresholds_correctly():
- redis_client = MagicMock()
- redis_client.mget = AsyncMock(return_value=[b"3", b"2", b"5", None])
- result = await read_stuck_session_ids(
- redis_client,
- team_id=42,
- session_ids=["s1", "s2", "s3", "s4"],
- threshold=3,
- )
- # s1 == threshold (stuck), s2 below (not stuck), s3 above (stuck), s4 None (not stuck)
- assert result == {"s1", "s3"}
+def test_read_stuck_returns_empty_for_empty_input():
+ patcher, _ = _patched_client(side_effect=AssertionError("should not mget empty input"))
+ with patcher:
+ assert read_stuck_session_ids(team_id=1, session_ids=[], threshold=3) == set()
-async def test_read_stuck_skips_non_integer_values():
- redis_client = MagicMock()
- redis_client.mget = AsyncMock(return_value=[b"not-an-int", b"5"])
- result = await read_stuck_session_ids(
- redis_client,
- team_id=42,
- session_ids=["bad", "good"],
- threshold=3,
- )
- assert result == {"good"}
+def test_read_stuck_thresholds_correctly():
+ patcher, _ = _patched_client(mget_result=[b"3", b"2", b"5", None])
+ with patcher:
+ result = read_stuck_session_ids(team_id=42, session_ids=["s1", "s2", "s3", "s4"], threshold=3)
+ assert result == {"s1", "s3"}
-async def test_read_stuck_uses_team_scoped_keys():
- redis_client = MagicMock()
- captured_keys: list[str] = []
+def test_read_stuck_skips_non_integer_values():
+ patcher, _ = _patched_client(mget_result=[b"not-an-int", b"5"])
+ with patcher:
+ result = read_stuck_session_ids(team_id=42, session_ids=["s1", "s2"], threshold=3)
+ assert result == {"s2"}
- async def _mget(keys):
- captured_keys.extend(keys)
- return [None] * len(keys)
- redis_client.mget = _mget
- await read_stuck_session_ids(redis_client, team_id=42, session_ids=["s1", "s2"], threshold=3)
- assert captured_keys == ["replay:rasterize:stuck:42:s1", "replay:rasterize:stuck:42:s2"]
+def test_read_stuck_uses_team_scoped_keys():
+ patcher, redis_client = _patched_client(mget_result=[None, None])
+ with patcher:
+ read_stuck_session_ids(team_id=42, session_ids=["s1", "s2"], threshold=3)
+ redis_client.mget.assert_called_once_with(["replay:rasterize:stuck:42:s1", "replay:rasterize:stuck:42:s2"])
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index db7cbf0d87d6..e8b7a39768cb 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -17,6 +17,7 @@ from posthog.schema import RecordingsQuery
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
+from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_ids
from products.replay_vision.backend.enqueue_claims import claim_enqueue_slot_prefix
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
@@ -196,7 +197,10 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
scanner_id=str(backfill.scanner_id),
seconds_remaining=FIND_BACKFILL_CANDIDATES_TIMEOUT.total_seconds() - (time.monotonic() - started_at),
)
- dispatchable = [c for c in unobserved if c.session_id not in excluded]
+ # Same quarantine as the live sweep: a session past the stuck threshold cannot render, and the
+ # cursor steps over it exactly like an excluded session.
+ stuck = read_stuck_session_ids(inputs.team_id, [c.session_id for c in unobserved])
+ dispatchable = [c for c in unobserved if c.session_id not in excluded and c.session_id not in stuck]
# Only sessions the live sweep reached after this backfill was quoted were in its total, so only those
# count as work done; earlier successes were already excluded at creation.
overtaken = {
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 29b7e9602bea..c7f4b42690b1 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 temporalio.exceptions import ApplicationError
from posthog.schema import RecordingsQuery
from posthog.rbac.user_access_control import UserAccessControl
+from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_ids
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner
@@ -113,6 +114,17 @@ def find_scanner_candidates_activity(inputs: FindScannerCandidatesInputs) -> Fin
elif deep_limit > 0:
deep_candidates, deep_swept_through = _deep_sweep(scanner, query, candidate_query, deep_limit)
+ # Sessions that repeatedly exhausted the rasterizer's whole retry envelope (the Class B
+ # compositor wedge) get quarantined for the counter's TTL window; each dispatch would otherwise
+ # burn up to an hour of shared rasterizer capacity on a render that cannot finish. The watermark
+ # still advances past them, so they are skipped, not retried forever.
+ stuck = read_stuck_session_ids(inputs.team_id, [c.session_id for c in [*candidates, *deep_candidates]])
+ if stuck:
+ activity.logger.warning("replay_vision.stuck_sessions_skipped %d", len(stuck))
+ record_sweep_outcome("stuck_sessions_skipped")
+ candidates = [c for c in candidates if c.session_id not in stuck]
+ deep_candidates = [c for c in deep_candidates if c.session_id not in stuck]
+
record_sweep_outcome(
"candidates_found" if candidates or deep_candidates else "no_candidates",
candidates=len(candidates) + len(deep_candidates),
diff --git a/products/replay_vision/backend/temporal/evaluation_workflow.py b/products/replay_vision/backend/temporal/evaluation_workflow.py
index 14c6897eb592..c74a820ae755 100644
--- a/products/replay_vision/backend/temporal/evaluation_workflow.py
+++ b/products/replay_vision/backend/temporal/evaluation_workflow.py
@@ -12,7 +12,10 @@ from temporalio.common import SearchAttributePair, TypedSearchAttributes, Workfl
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.errors import unwrap_temporal_cause
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
-from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs
+from posthog.temporal.session_replay.rasterize_recording.types import (
+ RASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT,
+ RasterizeRecordingInputs,
+)
with wf.unsafe.imports_passed_through():
from django.conf import settings
@@ -136,7 +139,7 @@ class EvaluatePromptSuggestionWorkflow(PostHogWorkflow):
task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
retry_policy=common.RetryPolicy(maximum_attempts=int(settings.TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
- execution_timeout=dt.timedelta(minutes=30),
+ execution_timeout=RASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT,
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index fe8a16f273cb..c80417982c92 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -8,13 +8,21 @@ from temporalio import common
from temporalio.common import SearchAttributePair, TypedSearchAttributes, WorkflowIDReusePolicy
from temporalio.exceptions import (
ActivityError,
+ ChildWorkflowError,
TimeoutError as TemporalTimeoutError,
)
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.errors import MAX_ERROR_MESSAGE_CHARS, truncate_for_temporal_payload, unwrap_temporal_cause
from posthog.temporal.common.search_attributes import POSTHOG_SESSION_RECORDING_ID_KEY, POSTHOG_TEAM_ID_KEY
-from posthog.temporal.session_replay.rasterize_recording.types import RasterizeRecordingInputs
+from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import (
+ BumpStuckCounterInput,
+ bump_stuck_counter_activity,
+)
+from posthog.temporal.session_replay.rasterize_recording.types import (
+ RASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT,
+ RasterizeRecordingInputs,
+)
with wf.unsafe.imports_passed_through():
from django.conf import settings
@@ -396,11 +404,9 @@ class ApplyScannerWorkflow(PostHogWorkflow):
task_queue=settings.SESSION_REPLAY_TASK_QUEUE,
retry_policy=common.RetryPolicy(maximum_attempts=int(settings.TEMPORAL_WORKFLOW_MAX_ATTEMPTS)),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
- # Temporal counts the whole retry chain against this, and the child's own render activity is allowed
- # 30 minutes. Must exceed that 30m start-to-close, or a first render that fails fast leaves no room to
- # schedule a retry at all. Held below a second full 30m render on purpose, to stay within the parent's
- # phase budget.
- execution_timeout=dt.timedelta(minutes=40),
+ # Temporal counts the whole retry chain against this. Held below the full two-attempt
+ # envelope on purpose, to stay within the parent's phase budget.
+ execution_timeout=RASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT,
search_attributes=TypedSearchAttributes(
search_attributes=[
SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=inputs.team_id),
@@ -414,6 +420,26 @@ class ApplyScannerWorkflow(PostHogWorkflow):
# "nothing to analyze" as a session with no events, which we already gate as ineligible, so calling
# it a failure would point the user at support over a recording that can never produce a video.
raise IneligibleSessionError(_root_cause_message(e), kind=IneligibleSessionKind.NO_SNAPSHOTS) from e
+ # Direct cause only: a nested activity timeout inside the child already bumped the
+ # counter there, and matching it here would double-count one run.
+ if (
+ isinstance(e, ChildWorkflowError)
+ and isinstance(e.cause, TemporalTimeoutError)
+ and wf.patched("bump-stuck-on-rasterize-timeout-2026-08")
+ ):
+ # The single-attempt execution_timeout terminates the child before its own final-attempt
+ # bump can run, so a render that rode out the whole budget would never reach the
+ # quarantine threshold. Bump from here instead; the child's own bump covers every
+ # failure that surfaces as an exception.
+ try:
+ await wf.execute_activity(
+ bump_stuck_counter_activity,
+ BumpStuckCounterInput(team_id=inputs.team_id, session_id=inputs.session_id),
+ start_to_close_timeout=dt.timedelta(seconds=10),
+ retry_policy=common.RetryPolicy(maximum_attempts=2),
+ )
+ except Exception as exc:
+ wf.logger.warning("replay_vision.stuck_counter_bump_failed", extra={"error": str(exc)})
# Re-classify the rasterizer's failure so the user sees a rasterizer label, not a generic "internal error".
raise ScannerFailureError(_root_cause_message(e), kind=FailureKind.RASTERIZATION_FAILED) from e
diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.py
index a3e4fb9cad6f..4e983db4b33d 100644
--- a/products/replay_vision/backend/tests/test_backfills.py
+++ b/products/replay_vision/backend/tests/test_backfills.py
@@ -11,6 +11,11 @@ from rest_framework.status import HTTP_429_TOO_MANY_REQUESTS
from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import Organization, Team
+from posthog.redis import get_client
+from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import (
+ STUCK_SESSION_THRESHOLD,
+ _stuck_key,
+)
from products.replay_vision.backend.api.backfills import (
MAX_BACKFILL_WINDOW_DAYS,
@@ -519,6 +524,30 @@ class TestBackfillTickActivities:
# walked past the excluded row, not stopped at the survivor
assert result.next_cursor_session_id == "blocked"
+ def test_stuck_sessions_are_walked_over_not_dispatched(self) -> None:
+ # A session quarantined by the rasterizer's stuck counter cannot render; dispatching it from
+ # a backfill burns retry envelopes the same way the live sweep's filter prevents.
+ scanner = _make_scanner()
+ backfill = _make_backfill(scanner)
+ fetched = [
+ CandidateSession(session_id="keep", session_end=timezone.now() - dt.timedelta(hours=2)),
+ CandidateSession(session_id="wedged", session_end=timezone.now() - dt.timedelta(hours=1)),
+ ]
+ redis_client = get_client()
+ for _ in range(STUCK_SESSION_THRESHOLD):
+ redis_client.incr(_stuck_key(backfill.team_id, "wedged"))
+ with (
+ patch("products.replay_vision.backend.temporal.activities.backfill.WindowedCandidateQuery") as query_cls,
+ patch.object(excluded_sessions, "excluded_session_ids", return_value=set()),
+ ):
+ query_cls.return_value.run.return_value = fetched
+ result = find_backfill_candidates_activity(
+ FindBackfillCandidatesInputs(backfill_id=backfill.id, team_id=backfill.team_id, candidate_limit=50)
+ )
+
+ assert [c.session_id for c in result.candidates] == ["keep"]
+ assert result.next_cursor_session_id == "wedged"
+
def test_exclusion_failure_fails_the_tick_rather_than_dispatching(self) -> None:
# In-query blocklists are off by this point, so swallowing would dispatch unfiltered.
scanner = _make_scanner()
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 2868d52702a4..e03dcc3201a7 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -9,6 +9,11 @@ from parameterized import parameterized
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
from posthog.models import Organization, Team
+from posthog.redis import get_client
+from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import (
+ STUCK_SESSION_THRESHOLD,
+ _stuck_key,
+)
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
@@ -181,6 +186,31 @@ class TestFindScannerCandidatesActivity:
assert query_kwargs["sampling_rate"] == scanner.sampling_rate
assert query_kwargs["events_lookback"] == SWEEP_EVENTS_LOOKBACK
+ def test_skips_sessions_quarantined_by_the_stuck_counter(self) -> None:
+ # A session past the stuck threshold has burned two whole rasterizer retry envelopes;
+ # dispatching it again wastes up to an hour of shared render capacity per sweep tick.
+ scanner = _make_scanner()
+ candidate_ok = CandidateSession(
+ session_id="sess-ok", session_end=dt.datetime(2026, 5, 1, 10, 0, 0, tzinfo=dt.UTC)
+ )
+ candidate_stuck = CandidateSession(
+ session_id="sess-stuck", session_end=dt.datetime(2026, 5, 1, 10, 5, 0, tzinfo=dt.UTC)
+ )
+
+ redis_client = get_client()
+ for _ in range(STUCK_SESSION_THRESHOLD):
+ redis_client.incr(_stuck_key(scanner.team_id, "sess-stuck"))
+
+ with patch(
+ "products.replay_vision.backend.temporal.activities.find_scanner_candidates.ScannerCandidateQuery"
+ ) as MockQuery:
+ MockQuery.return_value.run.return_value = [candidate_ok, candidate_stuck]
+ result = find_scanner_candidates_activity(
+ FindScannerCandidatesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert [c.session_id for c in result.candidates] == ["sess-ok"]
+
def test_threads_last_seen_session_id_when_set(self) -> None:
scanner = _make_scanner(last_seen_session_id="prev-id")