: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): build a frozen benchmark from labeled recordings (#107548)
Tue Haulund147ca7bdee5a
diff --git a/bin/build-recording-rasterizer-image b/bin/build-recording-rasterizer-imagenew file mode 100755index 000000000000..61afb566b12b--- /dev/null+++ b/bin/build-recording-rasterizer-image@@ -0,0 +1,70 @@+#!/bin/bash++# Builds the headless player, the nodejs dist and the rasterizer image (cached by dependency hash).+# Shared by bin/temporal-recording-rasterizer-worker and bin/rasterize-recording-file.++set -e+set -o pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"++IMAGE_NAME="recording-rasterizer:local"+DOCKERFILE="$ROOT_DIR/Dockerfile.recording-rasterizer"+HASH_FILE="$ROOT_DIR/.posthog/.generated/rasterizer-image.hash"++# Build for the host: chrome-headless-shell ships an arm64 build, and an emulated amd64 Chromium is+# far too slow to render with. Apple Silicon and the arm64 devboxes both land here.+case "$(uname -m)" in+arm64 | aarch64) PLATFORM="linux/arm64" ;;+*) PLATFORM="linux/amd64" ;;+esac++cd "$ROOT_DIR"++# --- Step 1: Build TypeScript locally ---++echo "Building headless player..."+pnpm --filter=@posthog/replay-headless build++echo "Building recording-rasterizer worker..."+pnpm --filter=@posthog/nodejs build++# --- Step 2: Build Docker image if needed ---++# Hash the Dockerfile and key dependency files to detect when a rebuild is needed.+# Source code changes are picked up via volume mounts, so we only need to rebuild+# when the image structure (deps, base image, system packages) changes.+# The platform is part of the hash so a cached image from another architecture is rebuilt.+current_hash=$( { cat \+ "$DOCKERFILE" \+ "$ROOT_DIR/pnpm-lock.yaml" \+ "$ROOT_DIR/nodejs/package.json" \+ "$ROOT_DIR/common/replay-headless/package.json" \+ 2>/dev/null; echo "$PLATFORM"; } | shasum -a 256 | cut -d' ' -f1)++previous_hash=""+if [ -f "$HASH_FILE" ]; then+ previous_hash=$(cat "$HASH_FILE")+fi++# Also rebuild if the image doesn't exist+if ! docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then+ previous_hash="missing"+fi++if [ "$current_hash" != "$previous_hash" ]; then+ echo "Docker image outdated or missing, rebuilding..."+ docker build \+ --platform "$PLATFORM" \+ -f "$DOCKERFILE" \+ -t "$IMAGE_NAME" \+ "$ROOT_DIR"++ mkdir -p "$(dirname "$HASH_FILE")"+ echo "$current_hash" > "$HASH_FILE"+ echo "Docker image built and cached."+else+ echo "Docker image up-to-date (cached)."+fi+diff --git a/bin/rasterize-recording-file b/bin/rasterize-recording-filenew file mode 100755index 000000000000..f70e95dd6918--- /dev/null+++ b/bin/rasterize-recording-file@@ -0,0 +1,48 @@+#!/bin/bash++# Renders one recording file (`[windowId, event]` JSONL, optionally zstd) to video in the rasterizer+# image, without Temporal, recording-api or S3. Writes <out-dir>/video.mp4 and <out-dir>/rasterize.json.+#+# bin/rasterize-recording-file <events.jsonl[.zst]> <out-dir> ['<RasterizeRecordingInput json>']++set -e+set -o pipefail++if [ $# -lt 2 ]; then+ echo "usage: $0 <events.jsonl[.zst]> <out-dir> ['<options json>']" >&2+ exit 1+fi++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"+IMAGE_NAME="recording-rasterizer:local"++INPUT="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"+mkdir -p "$2"+OUT_DIR="$(cd "$2" && pwd)"+OPTIONS="${3:-{\}}"++case "$(uname -m)" in+arm64 | aarch64) PLATFORM="linux/arm64" ;;+*) PLATFORM="linux/amd64" ;;+esac++if [ -z "$SKIP_BUILD" ]; then+ "$SCRIPT_DIR/build-recording-rasterizer-image" >&2+fi++# Chromium needs the relaxed seccomp/apparmor profile, as in bin/temporal-recording-rasterizer-worker.+# nosemgrep: trailofbits.generic.container-privileged.container-privileged+docker run --rm --security-opt seccomp=unconfined --security-opt apparmor=unconfined \+ --platform "$PLATFORM" \+ -e NODE_ENV=development \+ -e LOG_LEVEL="${LOG_LEVEL:-warn}" \+ -e DISABLE_BROWSER_SECURITY=1 \+ -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" \+ -v "$INPUT:/input/$(basename "$INPUT"):ro" \+ -v "$OUT_DIR:/output" \+ --user "$(id -u):$(id -g)" \+ "$IMAGE_NAME" \+ node nodejs/dist/session-replay/recording-rasterizer/rasterize-file.js \+ --input "/input/$(basename "$INPUT")" --out /output --options "$OPTIONS"diff --git a/bin/temporal-recording-rasterizer-worker b/bin/temporal-recording-rasterizer-workerindex c718523b8b24..984f6ed6c277 100755--- a/bin/temporal-recording-rasterizer-worker+++ b/bin/temporal-recording-rasterizer-worker@@ -8,8 +8,6 @@ ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"CONTAINER_NAME="posthog-recording-rasterizer"IMAGE_NAME="recording-rasterizer:local"-DOCKERFILE="$ROOT_DIR/Dockerfile.recording-rasterizer"-HASH_FILE="$ROOT_DIR/.posthog/.generated/rasterizer-image.hash"# Build for the host: chrome-headless-shell ships an arm64 build, and an emulated amd64 Chromium is# far too slow to render with. Apple Silicon and the arm64 devboxes both land here.@@ -18,54 +16,9 @@ arm64 | aarch64) PLATFORM="linux/arm64" ;;*) PLATFORM="linux/amd64" ;;esac-cd "$ROOT_DIR"--# --- Step 1: Build TypeScript locally -----echo "Building headless player..."-pnpm --filter=@posthog/replay-headless build--echo "Building recording-rasterizer worker..."-pnpm --filter=@posthog/nodejs build--# --- Step 2: Build Docker image if needed -----# Hash the Dockerfile and key dependency files to detect when a rebuild is needed.-# Source code changes are picked up via volume mounts, so we only need to rebuild-# when the image structure (deps, base image, system packages) changes.-# The platform is part of the hash so a cached image from another architecture is rebuilt.-current_hash=$( { cat \- "$DOCKERFILE" \- "$ROOT_DIR/pnpm-lock.yaml" \- "$ROOT_DIR/nodejs/package.json" \- "$ROOT_DIR/common/replay-headless/package.json" \- 2>/dev/null; echo "$PLATFORM"; } | shasum -a 256 | cut -d' ' -f1)--previous_hash=""-if [ -f "$HASH_FILE" ]; then- previous_hash=$(cat "$HASH_FILE")-fi--# Also rebuild if the image doesn't exist-if ! docker image inspect "$IMAGE_NAME" >/dev/null 2>&1; then- previous_hash="missing"-fi--if [ "$current_hash" != "$previous_hash" ]; then- echo "Docker image outdated or missing, rebuilding..."- docker build \- --platform "$PLATFORM" \- -f "$DOCKERFILE" \- -t "$IMAGE_NAME" \- "$ROOT_DIR"-- mkdir -p "$(dirname "$HASH_FILE")"- echo "$current_hash" > "$HASH_FILE"- echo "Docker image built and cached."-else- echo "Docker image up-to-date (cached)."-fi+"$SCRIPT_DIR/build-recording-rasterizer-image"+cd "$ROOT_DIR"# --- Step 3: Stop existing container ---if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; thendiff --git a/hogli.yaml b/hogli.yamlindex c273fb1c7efd..152cdd615e6a 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1299,3 +1299,11 @@ environment:bin_script: docker-worker-ai-training-privacydescription: 'Start the dedicated AI training privacy worker'hidden: true+ build:recording:rasterizer:image:+ bin_script: build-recording-rasterizer-image+ description: 'Build the recording rasterizer Docker image'+ hidden: true+ rasterize:recording:file:+ bin_script: rasterize-recording-file+ description: 'Render a recording JSONL file to video with the rasterizer'+ hidden: truediff --git a/nodejs/src/session-replay/recording-rasterizer/README.md b/nodejs/src/session-replay/recording-rasterizer/README.mdindex 6c1438524a33..f97827077ff5 100644--- a/nodejs/src/session-replay/recording-rasterizer/README.md+++ b/nodejs/src/session-replay/recording-rasterizer/README.md@@ -27,13 +27,14 @@ giving ~30% faster frame capture than the hardcoded PNG in puppeteer-capture.```textrecording-rasterizer/├── index.ts ← thin entry point, delegates to temporal/worker.ts+├── rasterize-file.ts ← offline render of a JSONL file (bin/rasterize-recording-file)├── config.ts ← environment variable configuration├── errors.ts ← RasterizationError class├── logger.ts ← pino logger factory├── metrics.ts ← Prometheus metrics├── types.ts ← input/output contracts├── utils.ts ← timing utilities-├── storage.ts ← S3 upload+├── storage.ts ← S3 upload and download├── postprocess.ts ← map inactivity periods to video timestamps│├── temporal/ ← Temporal integration@@ -48,6 +49,7 @@ recording-rasterizer/│ ├── capture.ts ← frame capture loop with abort/timeout handling│ ├── request-interceptor.ts ← request interception + stylesheet proxying│ ├── block-proxy.ts ← recording block fetcher (recording-api)+│ ├── file-block-source.ts ← serves one JSONL file or allowlisted S3 object (source_s3_uri)│ └── config.ts ← input validation + capture config builder│└── __tests__/ ← all testsdiff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.tsindex 80733be8fc96..4066b8230c51 100644--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/activities.test.ts@@ -205,6 +205,21 @@ describe('rasterizeRecordingActivity', () => {})describe('error classification', () => {+ it('refuses a source_s3_uri outside the allowed prefixes before rendering', async () => {+ await expect(+ rasterizeRecordingActivity(+ baseInput({ source_s3_uri: 's3://test-bucket/exports/mp4/team-2/task-9/x.mp4' })+ )+ ).rejects.toThrow('outside the allowed prefixes')++ expect(ApplicationFailure.nonRetryable).toHaveBeenCalledWith(+ expect.any(String),+ 'INVALID_INPUT',+ expect.anything()+ )+ expect(mockedRasterizeRecording).not.toHaveBeenCalled()+ })+it('wraps non-retryable RasterizationError as ApplicationFailure.nonRetryable', async () => {const error = new RasterizationError('No snapshot data', false, 'NO_SNAPSHOTS')mockedRasterizeRecording.mockRejectedValue(error)diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/file-block-source.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/file-block-source.test.tsnew file mode 100644index 000000000000..e743e2170302--- /dev/null+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/file-block-source.test.ts@@ -0,0 +1,62 @@+import * as fs from 'fs/promises'+import * as os from 'os'+import * as path from 'path'+import { PassThrough, Readable } from 'stream'+import { pipeline } from 'stream/promises'+import { zstdCompressSync } from 'zlib'++import { FileBlockSource, isAllowedSource } from '~/session-replay/recording-rasterizer/capture/file-block-source'+import { byteLimit } from '~/session-replay/recording-rasterizer/storage'++describe('FileBlockSource', () => {+ let dir: string++ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'file-block-source-'))+ })++ afterEach(async () => {+ await fs.rm(dir, { recursive: true, force: true })+ })++ async function serve(source: FileBlockSource): Promise<{ status: number; body: string }> {+ const respond = jest.fn()+ await source.handleRequest({ respond } as any, '/__blocks/0')+ const { status, body } = respond.mock.calls[0][0]+ return { status, body: Buffer.from(body).toString('utf-8') }+ }++ it.each([+ ['serves a zstd file decompressed', 1_000, 200, '["w",{"type":4}]\n'],+ // A source that inflates past the bound is refused as a failed block, not decompressed into memory.+ ['refuses one that decompresses past the bound', 8, 502, 'block read failed'],+ ])('%s', async (_name, maxDecompressedBytes, expectedStatus, expectedBody) => {+ const file = path.join(dir, 'events.jsonl.zst')+ await fs.writeFile(file, zstdCompressSync(Buffer.from('["w",{"type":4}]\n')))+ const source = new FileBlockSource(file, maxDecompressedBytes)++ await source.fetchBlocks()++ expect(await serve(source)).toEqual({ status: expectedStatus, body: expectedBody })+ })++ // The allowlist is the only thing between a render input and every object the rasterizer's role can read.+ it.each([+ ['s3://bench/rv-benchmark/v1/cases/a/events.jsonl.zst', true],+ ['s3://bench/rv-benchmark-private/v1/events.jsonl.zst', false],+ ['s3://other/rv-benchmark/v1/events.jsonl.zst', false],+ ['s3://bench/rv-benchmark/../exports/mp4/x.mp4', false],+ ])('isAllowedSource(%s) is %s under s3://bench/rv-benchmark', (uri, expected) => {+ expect(isAllowedSource(uri, ['s3://bench/rv-benchmark'])).toBe(expected)+ })++ // A source download with no Content-Length to check up front still stops at the size gate.+ it('byteLimit fails a download once it passes the limit', async () => {+ const sink = new PassThrough()+ sink.resume()++ await expect(+ pipeline(Readable.from([Buffer.alloc(6), Buffer.alloc(6)]), byteLimit(10), sink)+ ).rejects.toMatchObject({ code: 'RECORDING_TOO_LARGE' })+ })+})diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.tsindex 1f221dfa6454..96ae5b38ae30 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/block-proxy.ts@@ -12,7 +12,14 @@ type RecordingBlock = Pick<FullRecordingBlock, 'key' | 'start_byte' | 'end_byte'export { BLOCK_REQUEST_PREFIX }-export class BlockProxy {+export interface BlockSource {+ readonly blockCount: number+ readonly totalCompressedBytes: number+ fetchBlocks(input: RasterizeRecordingInput): Promise<number>+ handleRequest(request: HTTPRequest, path: string): Promise<void>+}++export class BlockProxy implements BlockSource {private blocks: RecordingBlock[] = []private teamId = 0private sessionId = ''diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/file-block-source.ts b/nodejs/src/session-replay/recording-rasterizer/capture/file-block-source.tsnew file mode 100644index 000000000000..5d714f4f6e00--- /dev/null+++ b/nodejs/src/session-replay/recording-rasterizer/capture/file-block-source.ts@@ -0,0 +1,99 @@+import * as fs from 'fs/promises'+import { HTTPRequest } from 'puppeteer'+import { promisify } from 'util'+import { zstdDecompress } from 'zlib'++import { RasterizationError } from '~/session-replay/recording-rasterizer/errors'+import { downloadFromS3, parseS3Uri } from '~/session-replay/recording-rasterizer/storage'++import { BLOCK_REQUEST_PREFIX, BlockSource } from './block-proxy'++const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])+const zstdDecompressAsync = promisify(zstdDecompress)++// Serves one recording file as block 0; `cv` payloads inside stay compressed for the player to decode.+export class FileBlockSource implements BlockSource {+ private fileBytes: number | null = null++ constructor(+ private filePath: string,+ private maxDecompressedBytes: number+ ) {}++ get blockCount(): number {+ return this.fileBytes === null ? 0 : 1+ }++ get totalCompressedBytes(): number {+ return this.fileBytes ?? 0+ }++ // Size only: the recorder's size gate runs on it before anything is read or decompressed.+ async fetchBlocks(): Promise<number> {+ this.fileBytes = (await fs.stat(this.filePath)).size+ return this.blockCount+ }++ async handleRequest(request: HTTPRequest, path: string): Promise<void> {+ if (path !== `${BLOCK_REQUEST_PREFIX}0` || this.fileBytes === null) {+ await request.respond({ status: 404, body: 'block not found' })+ return+ }+ try {+ const raw = await fs.readFile(this.filePath)+ const body = raw.subarray(0, 4).equals(ZSTD_MAGIC)+ ? await zstdDecompressAsync(raw, { maxOutputLength: this.maxDecompressedBytes })+ : raw+ await request.respond({ status: 200, contentType: 'text/plain', body })+ } catch {+ // A failed block is what the player reports, rather than a render left waiting on a response.+ try {+ await request.respond({ status: 502, body: 'block read failed' })+ } catch {+ // The page is already gone; nothing is left to tell.+ }+ }+ }+}++export interface SourceLimits {+ allowedPrefixes: string[]+ maxCompressedBytes: number+ maxDecompressedBytes: number+ signal?: AbortSignal+}++const S3_URI = /^s3:\/\/([^/]+)\/?(.*)$/++/**+ * Whether the object sits under one of the allowed `s3://bucket/prefix` locations. Compared as a bucket plus a+ * whole key prefix, so `s3://b/bench` does not also admit `s3://b/bench-other/`, and a `..` segment is refused.+ */+export function isAllowedSource(uri: string, allowedPrefixes: string[]): boolean {+ const source = S3_URI.exec(uri)+ if (!source || !source[2] || source[2].split('/').includes('..')) {+ return false+ }+ return allowedPrefixes.some((prefix) => {+ const allowed = S3_URI.exec(prefix)+ if (!allowed || allowed[1] !== source[1]) {+ return false+ }+ const allowedKey = allowed[2] && !allowed[2].endsWith('/') ? `${allowed[2]}/` : allowed[2]+ return source[2].startsWith(allowedKey)+ })+}++// The rasterizer's role can read every team's exports, so the allowlist bounds what a source can point at.+export async function blockSourceFromS3(+ uri: string,+ localPath: string,+ limits: SourceLimits+): Promise<FileBlockSource> {+ if (!isAllowedSource(uri, limits.allowedPrefixes)) {+ throw new RasterizationError(`source_s3_uri is outside the allowed prefixes: ${uri}`, false, 'INVALID_INPUT')+ }+ const { bucket, key } = parseS3Uri(uri)+ await downloadFromS3(bucket, key, localPath, { maxBytes: limits.maxCompressedBytes, signal: limits.signal })+ return new FileBlockSource(localPath, limits.maxDecompressedBytes)+}diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts b/nodejs/src/session-replay/recording-rasterizer/capture/player.tsindex ff6a878ccbdf..ad76ce3e9f07 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/player.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/player.ts@@ -11,7 +11,7 @@ import type { InactivityPeriod, PlayerConfig, PlayerMessage } from '@posthog/repimport { RasterizationError, toRasterizationErrorCode } from '~/session-replay/recording-rasterizer/errors'import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'-import { BlockProxy } from './block-proxy'+import { BlockSource } from './block-proxy'import { CapturePage } from './capture-page'import { RequestInterceptor } from './request-interceptor'@@ -41,7 +41,7 @@ export class PlayerController {constructor(capturePage: CapturePage,- blockProxy: BlockProxy,+ blockProxy: BlockSource,onProgress: () => void,log: Logger = createLogger()) {diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.tsindex 97c8245cf768..0d6def2acbaf 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/recorder.ts@@ -10,7 +10,7 @@ import {} from '~/session-replay/recording-rasterizer/types'import { elapsed } from '~/session-replay/recording-rasterizer/utils'-import { BlockProxy } from './block-proxy'+import { BlockProxy, BlockSource } from './block-proxy'import { BrowserPool } from './browser-pool'import { capturePlayback } from './capture'import { CapturePage } from './capture-page'@@ -53,6 +53,7 @@ export interface RasterizeOptions {// 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+ blockSource?: BlockSource}export async function rasterizeRecording(@@ -99,7 +100,7 @@ export async function rasterizeRecording(log)- const blockProxy = new BlockProxy(cfg, log)+ const blockProxy = options.blockSource ?? new BlockProxy(cfg, log)const blockCount = await blockProxy.fetchBlocks(input)const compressedBytes = blockProxy.totalCompressedByteslog.info({ blockCount, compressedBytes }, 'block listing fetched')diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.tsindex 1a524328f87c..cfa6583affca 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts@@ -5,7 +5,7 @@ import { fetch } from '~/common/utils/request'import { config } from '~/session-replay/recording-rasterizer/config'import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'-import { BLOCK_REQUEST_PREFIX, BlockProxy } from './block-proxy'+import { BLOCK_REQUEST_PREFIX, BlockSource } from './block-proxy'import { CapturePage } from './capture-page'const PROXY_TIMEOUT_MS = 10_000@@ -17,7 +17,7 @@ const NONCE_PLACEHOLDER = '__CSP_NONCE__'/*** Centralizes all Puppeteer request interception: serves the player HTML,- * forwards block requests to {@link BlockProxy}, proxies sub-frame+ * forwards block requests to {@link BlockSource}, proxies sub-frame* stylesheets, and aborts sub-frame media to prevent beginFrame deadlocks.** {@link waitForSettled} gates beginFrame until proxied stylesheets resolve.@@ -29,7 +29,7 @@ export class RequestInterceptor {constructor(private capturePage: CapturePage,- private blockProxy: BlockProxy,+ private blockProxy: BlockSource,private log: Logger = createLogger(),private enablePlayerCsp: boolean = config.enablePlayerCsp) {diff --git a/nodejs/src/session-replay/recording-rasterizer/config.ts b/nodejs/src/session-replay/recording-rasterizer/config.tsindex 38056af59472..17a4a9cb2009 100644--- a/nodejs/src/session-replay/recording-rasterizer/config.ts+++ b/nodejs/src/session-replay/recording-rasterizer/config.ts@@ -45,6 +45,11 @@ export const config = {// S3s3Endpoint: process.env.VIDEO_EXPORT_OBJECT_STORAGE_ENDPOINT,s3Region: process.env.VIDEO_EXPORT_OBJECT_STORAGE_REGION || 'us-east-1',+ // `s3://bucket/prefix/` entries a render's source_s3_uri may point into. Empty disables file sources.+ sourceS3Prefixes: parseList(process.env.RASTERIZER_SOURCE_S3_PREFIXES ?? '').filter(Boolean),+ // Bounds a zstd source's decompressed size, which its compressed size under the gate above does not. The+ // body reaches the page as base64 text, so it has to stay well under V8's string limit.+ maxSourceDecompressedBytes: parsePositiveInt(process.env.MAX_SOURCE_DECOMPRESSED_BYTES, 256 * 1024 * 1024),// Recording API. The dev recording-api listens on 6741 (bin/temporal-recording-rasterizer-worker).recordingApiBaseUrl: process.env.RECORDING_API_BASE_URL || 'http://localhost:6741',diff --git a/nodejs/src/session-replay/recording-rasterizer/postprocess.ts b/nodejs/src/session-replay/recording-rasterizer/postprocess.tsindex 583617f90936..a0f5776e7fab 100644--- a/nodejs/src/session-replay/recording-rasterizer/postprocess.ts+++ b/nodejs/src/session-replay/recording-rasterizer/postprocess.ts@@ -1,4 +1,6 @@-import { InactivityPeriod } from './types'+import { METADATA_FOOTER_HEIGHT_PX } from '@posthog/replay-headless/protocol'++import { InactivityPeriod, RasterizeRecordingInput, RasterizeRecordingOutput, RecordingResult } from './types'/*** Place each period on the video clock from the timeline measured during capture.@@ -107,3 +109,23 @@ export function computeVideoTimestamps(periods: InactivityPeriod[]): InactivityPreturn results}++/** The render's output metadata, shared by the Temporal activity and the file CLI so the two cannot drift. */+export function renderOutputFields(+ result: RecordingResult,+ input: RasterizeRecordingInput+): Omit<RasterizeRecordingOutput, 's3_uri' | 'file_size_bytes' | 'timings'> {+ return {+ video_duration_s: result.capture_duration_s,+ playback_speed: result.playback_speed,+ show_metadata_footer: !!input.show_metadata_footer,+ footer_height_px: input.show_metadata_footer ? METADATA_FOOTER_HEIGHT_PX : 0,+ truncated: result.truncated,+ inactivity_periods: videoTimestampsFromFrames(+ result.inactivity_periods,+ result.frame_session_ms,+ result.output_fps,+ result.pre_roll_frames+ ),+ }+}diff --git a/nodejs/src/session-replay/recording-rasterizer/rasterize-file.ts b/nodejs/src/session-replay/recording-rasterizer/rasterize-file.tsnew file mode 100644index 000000000000..2870b2ca5a7b--- /dev/null+++ b/nodejs/src/session-replay/recording-rasterizer/rasterize-file.ts@@ -0,0 +1,85 @@+// Renders a recording file without Temporal, recording-api or S3, for offline datasets such as the+// Replay Vision labeling benchmark. See bin/rasterize-recording-file.+import * as fs from 'fs/promises'+import * as path from 'path'+import { parseArgs } from 'util'++import { parseJSON } from '~/common/utils/json-parse'++import { BrowserPool } from './capture/browser-pool'+import { playerHtmlCache } from './capture/capture-page'+import { FileBlockSource } from './capture/file-block-source'+import { rasterizeRecording } from './capture/recorder'+import { config } from './config'+import { createLogger } from './logger'+import { renderOutputFields } from './postprocess'+import { RasterizeRecordingInput, RasterizeRecordingOutput } from './types'++export type RasterizeFileOutput = Omit<RasterizeRecordingOutput, 's3_uri'> & { video_file: string }++export async function rasterizeFile(+ pool: BrowserPool,+ playerHtml: string,+ inputPath: string,+ outDir: string,+ options: Partial<RasterizeRecordingInput>+): Promise<RasterizeFileOutput> {+ // validateInput requires ids shaped like production ones; nothing reads them for a file source.+ const input: RasterizeRecordingInput = {+ session_id: 'file',+ team_id: 1,+ ...options,+ s3_bucket: '',+ s3_key_prefix: '',+ }+ const format = input.output_format || 'mp4'+ await fs.mkdir(outDir, { recursive: true })+ const videoFile = `video.${format}`+ const log = createLogger({ input: inputPath })++ // A metadata file left from an earlier run would otherwise describe a video this run failed to replace.+ await fs.rm(path.join(outDir, 'rasterize.json'), { force: true })++ const result = await rasterizeRecording(pool, input, path.join(outDir, videoFile), playerHtml, () => {}, {+ log,+ blockSource: new FileBlockSource(inputPath, config.maxSourceDecompressedBytes),+ })+ const stat = await fs.stat(path.join(outDir, videoFile))+ const output: RasterizeFileOutput = {+ video_file: videoFile,+ ...renderOutputFields(result, input),+ file_size_bytes: stat.size,+ timings: { ...result.timings, upload_s: 0, total_s: result.timings.setup_s + result.timings.capture_s },+ }+ await fs.writeFile(path.join(outDir, 'rasterize.json'), JSON.stringify(output, null, 2))+ return output+}++async function main(): Promise<void> {+ const { values } = parseArgs({+ options: {+ input: { type: 'string' },+ out: { type: 'string' },+ options: { type: 'string', default: '{}' },+ },+ })+ if (!values.input || !values.out) {+ throw new Error('usage: rasterize-file --input <events.jsonl[.zst]> --out <dir> [--options <json>]')+ }+ const pool = new BrowserPool()+ await pool.launch()+ try {+ const playerHtml = await playerHtmlCache.load()+ const output = await rasterizeFile(pool, playerHtml, values.input, values.out, parseJSON(values.options))+ process.stdout.write(JSON.stringify(output) + '\n')+ } finally {+ await pool.shutdown()+ }+}++if (require.main === module) {+ main().catch((err) => {+ process.stderr.write(`${err?.stack ?? err}\n`)+ process.exit(1)+ })+}diff --git a/nodejs/src/session-replay/recording-rasterizer/storage.ts b/nodejs/src/session-replay/recording-rasterizer/storage.tsindex 7cd84aa54953..d253b21bb222 100644--- a/nodejs/src/session-replay/recording-rasterizer/storage.ts+++ b/nodejs/src/session-replay/recording-rasterizer/storage.ts@@ -4,7 +4,7 @@ import { Upload } from '@aws-sdk/lib-storage'import { NodeHttpHandler } from '@smithy/node-http-handler'import * as fs from 'fs'import { HttpsProxyAgent } from 'https-proxy-agent'-import { Readable } from 'stream'+import { Readable, Transform } from 'stream'import { pipeline } from 'stream/promises'import { config } from './config'@@ -124,15 +124,56 @@ export async function uploadToS3(return target}+export function parseS3Uri(uri: string): { bucket: string; key: string } {+ const match = /^s3:\/\/([^/]+)\/(.+)$/.exec(uri)+ if (!match) {+ throw new RasterizationError(`Not an S3 URI: ${uri}`, false, 'INVALID_INPUT')+ }+ return { bucket: match[1], key: match[2] }+}++/** Fails the download once more than `maxBytes` arrive, for a response that sent no Content-Length to check first. */+export function byteLimit(maxBytes: number): Transform {+ let seen = 0+ return new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ seen += chunk.length+ if (seen > maxBytes) {+ callback(+ new RasterizationError(`S3 object too large: over ${maxBytes} bytes`, false, 'RECORDING_TOO_LARGE')+ )+ return+ }+ callback(null, chunk)+ },+ })+}+/** Fetch one object to a local path. The thumbnail activity reads the analysis MP4 this way. */-export async function downloadFromS3(bucket: string, key: string, localPath: string): Promise<void> {+export async function downloadFromS3(+ bucket: string,+ key: string,+ localPath: string,+ options: { maxBytes?: number; signal?: AbortSignal } = {}+): Promise<void> {try {- const res = await getS3Client().send(new GetObjectCommand({ Bucket: bucket, Key: key }))+ const res = await getS3Client().send(new GetObjectCommand({ Bucket: bucket, Key: key }), {+ abortSignal: options.signal,+ })if (!res.Body) {throw new RasterizationError(`S3 object is empty: s3://${bucket}/${key}`, false, 'S3_DOWNLOAD_EMPTY')}+ if (options.maxBytes !== undefined && (res.ContentLength ?? 0) > options.maxBytes) {+ ;(res.Body as Readable).destroy()+ throw new RasterizationError(+ `S3 object too large: ${res.ContentLength} bytes (limit ${options.maxBytes})`,+ false,+ 'RECORDING_TOO_LARGE'+ )+ }// Streamed, not buffered: thumbnail extraction reads several tens-of-megabytes MP4s at once.- await pipeline(res.Body as Readable, fs.createWriteStream(localPath))+ const stages: NodeJS.ReadWriteStream[] = options.maxBytes !== undefined ? [byteLimit(options.maxBytes)] : []+ await pipeline([res.Body as Readable, ...stages, fs.createWriteStream(localPath)], { signal: options.signal })} catch (err) {if (err instanceof RasterizationError) {throw errdiff --git a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.tsindex 164a3f79dca6..79121338c31d 100644--- a/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts+++ b/nodejs/src/session-replay/recording-rasterizer/temporal/activities.ts@@ -5,15 +5,14 @@ import * as fs from 'fs/promises'import * as os from 'os'import * as path from 'path'-import { METADATA_FOOTER_HEIGHT_PX } from '@posthog/replay-headless/protocol'-import { BrowserPool } from '~/session-replay/recording-rasterizer/capture/browser-pool'+import { blockSourceFromS3 } from '~/session-replay/recording-rasterizer/capture/file-block-source'import { rasterizeRecording } from '~/session-replay/recording-rasterizer/capture/recorder'import { config } from '~/session-replay/recording-rasterizer/config'import { asRasterizationError } from '~/session-replay/recording-rasterizer/errors'import { createLogger } from '~/session-replay/recording-rasterizer/logger'import { RasterizationMetrics } from '~/session-replay/recording-rasterizer/metrics'-import { videoTimestampsFromFrames } from '~/session-replay/recording-rasterizer/postprocess'+import { renderOutputFields } from '~/session-replay/recording-rasterizer/postprocess'import { uploadToS3 } from '~/session-replay/recording-rasterizer/storage'import { extractThumbnail } from '~/session-replay/recording-rasterizer/thumbnail'import {@@ -60,6 +59,7 @@ async function rasterizeRecordingActivity(const workDir = process.env.VIDEO_WORK_DIR || os.tmpdir()const ext = input.output_format || 'mp4'const outputPath = path.join(workDir, `ph-video-${id}.${ext}`)+ const sourcePath = path.join(workDir, `ph-source-${id}.jsonl`)const timings: ActivityTimings = { total_s: 0, setup_s: 0, capture_s: 0, upload_s: 0 }@@ -127,23 +127,25 @@ async function rasterizeRecordingActivity(}, 10_000)try {+ const blockSource = input.source_s3_uri+ ? await blockSourceFromS3(input.source_s3_uri, sourcePath, {+ allowedPrefixes: config.sourceS3Prefixes,+ maxCompressedBytes: config.maxRecordingCompressedBytes,+ maxDecompressedBytes: config.maxSourceDecompressedBytes,+ signal: abort.signal,+ })+ : undefinedconst result = await rasterizeRecording(pool, input, outputPath, playerHtml, onProgress, {progress,log,signal: abort.signal,+ blockSource,})timings.setup_s = result.timings.setup_stimings.capture_s = result.timings.capture_sRasterizationMetrics.observeSetup('success', timings.setup_s)RasterizationMetrics.observeCapture('success', timings.capture_s)- const periods = videoTimestampsFromFrames(- result.inactivity_periods,- result.frame_session_ms,- result.output_fps,- result.pre_roll_frames- )-progress.phase = 'upload'onProgress()const uploadStart = process.hrtime()@@ -168,12 +170,7 @@ async function rasterizeRecordingActivity(const output: RasterizeRecordingOutput = {s3_uri: s3Uri,- video_duration_s: result.capture_duration_s,- playback_speed: result.playback_speed,- show_metadata_footer: !!input.show_metadata_footer,- footer_height_px: input.show_metadata_footer ? METADATA_FOOTER_HEIGHT_PX : 0,- truncated: result.truncated,- inactivity_periods: periods,+ ...renderOutputFields(result, input),file_size_bytes: stat.size,timings,}@@ -223,6 +220,7 @@ async function rasterizeRecordingActivity(ctx.cancellationSignal.removeEventListener('abort', onCancel)RasterizationMetrics.activityFinished()await fs.rm(outputPath, { force: true })+ await fs.rm(sourcePath, { force: true })}}diff --git a/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts b/nodejs/src/session-replay/recording-rasterizer/thumbnail.tsindex 9b32cadb0010..b1c7c0ce941d 100644--- a/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts+++ b/nodejs/src/session-replay/recording-rasterizer/thumbnail.ts@@ -7,7 +7,7 @@ import { promisify } from 'util'import { toFiniteNumber } from './capture/config'import { RasterizationError } from './errors'import { createLogger } from './logger'-import { downloadFromS3, uploadToS3 } from './storage'+import { downloadFromS3, parseS3Uri, uploadToS3 } from './storage'import type { ExtractThumbnailInput, ExtractThumbnailOutput } from './types'const execFileAsync = promisify(execFile)@@ -17,14 +17,6 @@ const log = createLogger()// is wedged on a corrupt file rather than working.const FFMPEG_TIMEOUT_MS = 60_000-function parseS3Uri(uri: string): { bucket: string; key: string } {- const match = /^s3:\/\/([^/]+)\/(.+)$/.exec(uri)- if (!match) {- throw new RasterizationError(`Not an S3 URI: ${uri}`, false, 'INVALID_INPUT')- }- return { bucket: match[1], key: match[2] }-}-export interface Rect {w: numberh: numberdiff --git a/nodejs/src/session-replay/recording-rasterizer/types.ts b/nodejs/src/session-replay/recording-rasterizer/types.tsindex ed6d40de2a93..11ea3bc9b3d6 100644--- a/nodejs/src/session-replay/recording-rasterizer/types.ts+++ b/nodejs/src/session-replay/recording-rasterizer/types.ts@@ -7,6 +7,8 @@ export interface RasterizeRecordingInput {// recording-api (the rasterizer cannot mint its own). Optional only during migration, before the// minting side has shipped.recording_api_token?: string+ // Renders this `[windowId, event]` JSONL object instead of fetching blocks from recording-api.+ source_s3_uri?: stringmax_virtual_time?: number // max virtual-time seconds before stopping capture (default: unlimited)playback_speed?: number // 1-360, defaults to 4start_offset_s?: number // seconds from session start to begin playbackdiff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 2becf5d81575..777bd208e2e5 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -176,3 +176,11 @@ if TEST or DEBUG:)else:DICTIONARY_STAGING_S3_ENDPOINT = os.getenv("DICTIONARY_STAGING_S3_ENDPOINT", "") or None++# Replay Vision labeling benchmark. Frozen cases are written under this bucket and prefix; an empty bucket+# disables the build. The prefix must sit outside the exports lifecycle rule, since a benchmark version is kept.+REPLAY_VISION_BENCHMARK_BUCKET = os.getenv("REPLAY_VISION_BENCHMARK_BUCKET", "")+REPLAY_VISION_BENCHMARK_PREFIX = os.getenv("REPLAY_VISION_BENCHMARK_PREFIX", "replay-vision-benchmark")+# The labeling suite's benchmark export API (MLHog labeling/replay/EXPORT.md), and a read-scoped `lbl_` token for it.+REPLAY_VISION_BENCHMARK_LABELING_URL = os.getenv("REPLAY_VISION_BENCHMARK_LABELING_URL", "")+REPLAY_VISION_BENCHMARK_LABELING_TOKEN = os.getenv("REPLAY_VISION_BENCHMARK_LABELING_TOKEN", "")diff --git a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.pyindex 5a073366db60..72bf1a75e1be 100644--- a/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py+++ b/posthog/temporal/session_replay/rasterize_recording/activities/rasterize.py@@ -52,37 +52,20 @@ def report_export_event(asset: ExportedAsset, event: str, **properties: Any) ->capture_export_event(asset, event, ph_background_capture(), **properties)-def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResult:- close_old_connections()-- asset = ExportedAsset.objects.select_related("team__organization", "created_by").get(pk=exported_asset_id)- try:- assert_export_authorization(asset)- except ValueError as error:- raise ApplicationError(str(error), non_retryable=True) from error- ctx = asset.export_context or {}-- session_id = ctx.get("session_recording_id")- if not session_id:- # 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 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")-- s3_key_prefix = f"{settings.OBJECT_STORAGE_EXPORTS_FOLDER}/{output_format}/team-{asset.team_id}/task-{asset.id}"-+def rasterization_input_from_context(+ ctx: dict[str, Any],+ *,+ team_id: int,+ session_id: str,+ s3_bucket: str,+ s3_key_prefix: str,+ output_format: str,+ recording_api_token: str = "",+) -> RasterizationActivityInput:+ """The render an export context describes, with the defaults and bounds every render gets.++ Shared with callers that render without an ExportedAsset, so their renders match production's.+ """# Callers may pass `timestamp`+`duration` or the native `start_offset_s`/`end_offset_s`.start_offset_s = ctx.get("start_offset_s") if ctx.get("start_offset_s") is not None else ctx.get("timestamp")duration = ctx.get("duration")@@ -111,17 +94,11 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResulplayback_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.- recording_api_token = (- mint_recording_api_token(asset.team_id, "read", ttl=_RASTERIZE_TOKEN_TTL) if recording_api_jwt_enabled() else ""- )-- activity_input = RasterizationActivityInput(- team_id=asset.team_id,+ return RasterizationActivityInput(+ team_id=team_id,session_id=session_id,recording_api_token=recording_api_token,- s3_bucket=settings.OBJECT_STORAGE_BUCKET,+ s3_bucket=s3_bucket,s3_key_prefix=s3_key_prefix,playback_speed=playback_speed,recording_fps=recording_fps,@@ -137,6 +114,54 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResulmax_virtual_time=ctx.get("max_virtual_time"),)++def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResult:+ close_old_connections()++ asset = ExportedAsset.objects.select_related("team__organization", "created_by").get(pk=exported_asset_id)+ try:+ assert_export_authorization(asset)+ except ValueError as error:+ raise ApplicationError(str(error), non_retryable=True) from error+ ctx = asset.export_context or {}++ session_id = ctx.get("session_recording_id")+ if not session_id:+ # 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 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")++ s3_key_prefix = f"{settings.OBJECT_STORAGE_EXPORTS_FOLDER}/{output_format}/team-{asset.team_id}/task-{asset.id}"++ # 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.+ recording_api_token = (+ mint_recording_api_token(asset.team_id, "read", ttl=_RASTERIZE_TOKEN_TTL) if recording_api_jwt_enabled() else ""+ )++ activity_input = rasterization_input_from_context(+ ctx,+ team_id=asset.team_id,+ session_id=session_id,+ s3_bucket=settings.OBJECT_STORAGE_BUCKET,+ s3_key_prefix=s3_key_prefix,+ output_format=output_format,+ recording_api_token=recording_api_token,+ )+fingerprint = compute_params_fingerprint(activity_input)cached = _try_synthesize_cached_output(asset, ctx, fingerprint)@@ -151,8 +176,8 @@ def build_rasterization_input(exported_asset_id: int) -> BuildRasterizationResulreport_export_event(asset,"export started",- playback_speed=playback_speed,- recording_fps=recording_fps,+ playback_speed=activity_input.playback_speed,+ recording_fps=activity_input.recording_fps,output_format=output_format,)diff --git a/posthog/temporal/session_replay/rasterize_recording/types.py b/posthog/temporal/session_replay/rasterize_recording/types.pyindex f4dbeb63763b..92f177c092e8 100644--- a/posthog/temporal/session_replay/rasterize_recording/types.py+++ b/posthog/temporal/session_replay/rasterize_recording/types.py@@ -23,16 +23,6 @@ RASTERIZE_WORKFLOW_TIMEOUT = RASTERIZE_RENDER_TIMEOUT * RASTERIZE_RENDER_MAX_ATTRASTERIZE_WORKFLOW_SINGLE_ATTEMPT_TIMEOUT = RASTERIZE_RENDER_TIMEOUT + timedelta(minutes=10)-class RasterizeRecordingInputs(BaseModel, frozen=True):- """Input to the RasterizeRecordingWorkflow."""-- exported_asset_id: int- product: Literal["session_replay", "replay_vision"] = "session_replay"- # Routes the render activity. None keeps the shared rasterization queue, so histories- # recorded before this field existed replay unchanged.- task_queue: str | None = None--class RasterizationActivityInput(BaseModel, frozen=True):"""Input sent to the Node.js rasterize-recording activity.@@ -46,6 +36,9 @@ class RasterizationActivityInput(BaseModel, frozen=True):# Defaults to "" so a workflow that recorded build_rasterization_input's result under an older# release (before this field existed) still deserializes on replay instead of failing validation.recording_api_token: str = ""+ # Renders this JSONL object instead of the team's recording. Internal callers only: build_rasterization_input+ # never reads it from export_context, which users can write through the exports API.+ source_s3_uri: str | None = Nones3_bucket: strs3_key_prefix: strplayback_speed: float = 4@@ -62,6 +55,25 @@ class RasterizationActivityInput(BaseModel, frozen=True):mouse_tail: bool = True+class RasterizeRecordingInputs(BaseModel, frozen=True):+ """Input to the RasterizeRecordingWorkflow: an ExportedAsset to render, or a render with none behind it."""++ exported_asset_id: int | None = None+ # A render the caller built itself, for recordings with no ExportedAsset (the Replay Vision labeling+ # benchmark). The workflow then skips the asset steps: preparing, finalizing and recording failures.+ render_input: RasterizationActivityInput | None = None+ product: Literal["session_replay", "replay_vision", "replay_vision_benchmark"] = "session_replay"+ # Routes the render activity. None keeps the shared rasterization queue, so histories+ # recorded before this field existed replay unchanged.+ task_queue: str | None = None++ @model_validator(mode="after")+ def _one_render_target(self) -> "RasterizeRecordingInputs":+ if (self.exported_asset_id is None) == (self.render_input is None):+ raise ValueError("pass exactly one of exported_asset_id and render_input")+ return self++class InactivityPeriod(BaseModel, frozen=True):ts_from_s: floatts_to_s: float | None = None@@ -116,7 +128,14 @@ class RecordRasterizationFailureInput(BaseModel, frozen=True):# Output destination fields — excluded so bucket/prefix changes don't invalidate caches.# recording_api_token is per-run and ephemeral, so it must never participate in the cache key.-_FINGERPRINT_EXCLUDE: set[str] = {"team_id", "session_id", "s3_bucket", "s3_key_prefix", "recording_api_token"}+FINGERPRINT_EXCLUDE: set[str] = {+ "team_id",+ "session_id",+ "source_s3_uri",+ "s3_bucket",+ "s3_key_prefix",+ "recording_api_token",+}# Bump when the renderer draws the same inputs differently, so videos cached from the old renderer are not reused.@@ -124,7 +143,7 @@ _RENDERER_VERSION = 2def compute_params_fingerprint(activity_input: "RasterizationActivityInput") -> str:- payload = f"v{_RENDERER_VERSION}:" + activity_input.model_dump_json(exclude=_FINGERPRINT_EXCLUDE)+ payload = f"v{_RENDERER_VERSION}:" + activity_input.model_dump_json(exclude=FINGERPRINT_EXCLUDE)return hashlib.sha256(payload.encode()).hexdigest()[:16]diff --git a/posthog/temporal/session_replay/rasterize_recording/workflow.py b/posthog/temporal/session_replay/rasterize_recording/workflow.pyindex 9d2bf5e06b94..d5379f2a227a 100644--- a/posthog/temporal/session_replay/rasterize_recording/workflow.py+++ b/posthog/temporal/session_replay/rasterize_recording/workflow.py@@ -45,6 +45,7 @@ from .types import (RASTERIZE_RENDER_TIMEOUT,BuildRasterizationResult,FinalizeRasterizationInput,+ RasterizationActivityInput,RasterizationActivityOutput,RasterizeRecordingInputs,RecordRasterizationFailureInput,@@ -93,8 +94,9 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):# Count runs, not attempts: only the final scheduled attempt is a failed run.if self._is_final_attempt():_record_outcome(RASTERIZATION_FAILED_COUNTER, inputs)- if wf.patched(_RECORD_FAILURE_PATCH):- await self._record_failure(inputs, exc, error_code)+ # Only an asset has somewhere to record the reason; a caller-built render reports its own.+ if inputs.exported_asset_id is not None and wf.patched(_RECORD_FAILURE_PATCH):+ await self._record_failure(inputs.exported_asset_id, exc, error_code)await self._maybe_bump_stuck_counter(error_code)raiseawait self._maybe_clear_stuck_counter()@@ -111,7 +113,7 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):max_attempts = cls._max_attempts()return max_attempts is not None and 0 < max_attempts <= wf.info().attempt- async def _record_failure(self, inputs: RasterizeRecordingInputs, exc: BaseException, error_code: str) -> None:+ async def _record_failure(self, exported_asset_id: int, exc: BaseException, error_code: str) -> None:"""Write the renderer's own reason onto the asset before the workflow fails.Swallows its own errors: losing the reason is worse than the render failing, but masking the@@ -122,7 +124,7 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):await wf.execute_activity(record_rasterization_failure,RecordRasterizationFailureInput(- exported_asset_id=inputs.exported_asset_id,+ exported_asset_id=exported_asset_id,error_code=error_code,error_message=truncate_for_temporal_payload(str(cause), MAX_ERROR_MESSAGE_CHARS),),@@ -180,6 +182,13 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):wf.logger.warning("rasterize.stuck_counter_clear_failed", extra={"error": str(exc)})async def _run(self, inputs: RasterizeRecordingInputs) -> RasterizationActivityOutput:+ if inputs.render_input is not None:+ # A caller-built render has no asset to prepare from or finalize onto.+ result = await self._render(inputs, inputs.render_input)+ self._phase = "done"+ return result++ assert inputs.exported_asset_id is not None # one of the two, per RasterizeRecordingInputsretry_policy = common.RetryPolicy(maximum_attempts=3)self._phase = "preparing"@@ -196,21 +205,7 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):assert prep.activity_input is not None # tagged-union invariant- self._phase = "rendering"- # Plain dict from Node.js across the cross-language boundary.- 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=inputs.task_queue or settings.RASTERIZATION_TASK_QUEUE,- start_to_close_timeout=RASTERIZE_RENDER_TIMEOUT,- heartbeat_timeout=dt.timedelta(seconds=30),- retry_policy=common.RetryPolicy(maximum_attempts=RASTERIZE_RENDER_MAX_ATTEMPTS),- )-- result = RasterizationActivityOutput.model_validate(raw_result)+ result = await self._render(inputs, prep.activity_input)self._phase = "finalizing"await wf.execute_activity(@@ -226,3 +221,21 @@ class RasterizeRecordingWorkflow(PostHogWorkflow):self._phase = "done"return result++ async def _render(+ self, inputs: RasterizeRecordingInputs, activity_input: RasterizationActivityInput+ ) -> RasterizationActivityOutput:+ self._phase = "rendering"+ # Plain dict from Node.js across the cross-language boundary.+ raw_result: dict[str, Any] = await wf.execute_activity(+ "rasterize-recording",+ 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=inputs.task_queue or settings.RASTERIZATION_TASK_QUEUE,+ start_to_close_timeout=RASTERIZE_RENDER_TIMEOUT,+ heartbeat_timeout=dt.timedelta(seconds=30),+ retry_policy=common.RetryPolicy(maximum_attempts=RASTERIZE_RENDER_MAX_ATTEMPTS),+ )+ return RasterizationActivityOutput.model_validate(raw_result)diff --git a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.pyindex 12ba1c06b493..fbc00848fe00 100644--- a/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py+++ b/posthog/temporal/tests/session_replay/rasterize_recording/test_workflow.py@@ -7,7 +7,7 @@ import temporalio.workflowfrom temporalio import activityfrom temporalio.api.enums.v1 import IndexedValueTypefrom temporalio.api.operatorservice.v1 import AddSearchAttributesRequest-from temporalio.client import WorkflowHistory+from temporalio.client import WorkflowFailureError, WorkflowHistoryfrom temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributesfrom temporalio.exceptions import (ActivityError,@@ -507,3 +507,52 @@ async def test_render_runs_on_the_requested_queue(route_elsewhere: bool):)assert rendered_on == [expected_queue]++[email protected]("render_fails", [False, True])+async def test_caller_built_render_skips_the_asset_steps(render_fails: bool):+ from django.conf import settings++ from posthog.temporal.session_replay.rasterize_recording.types import RasterizationActivityInput++ @activity.defn(name="rasterize-recording")+ async def render_mocked(_inputs: dict) -> dict:+ if render_fails:+ raise ApplicationError("no snapshots", type="NO_SNAPSHOTS", non_retryable=True)+ return {"s3_uri": "s3://bench/case/video.mp4", "video_duration_s": 1.0, "playback_speed": 8.0}++ render_input = RasterizationActivityInput(+ session_id="case-1",+ team_id=1,+ source_s3_uri="s3://bench/case/events.jsonl.zst",+ s3_bucket="bench",+ s3_key_prefix="case",+ )+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with (+ Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RasterizeRecordingWorkflow],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ),+ Worker(env.client, task_queue=settings.RASTERIZATION_TASK_QUEUE, activities=[render_mocked]),+ ):+ handle = await env.client.start_workflow(+ RasterizeRecordingWorkflow.run,+ RasterizeRecordingInputs(render_input=render_input, product="replay_vision_benchmark"),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ if render_fails:+ with pytest.raises(WorkflowFailureError):+ await handle.result()+ else:+ assert (await handle.result()).s3_uri == "s3://bench/case/video.mp4"+ history = await handle.fetch_history()++ # No asset to prepare from, finalize onto, or record a failure against.+ assert _scheduled_activities(history) == ["rasterize-recording"]diff --git a/products/replay_vision/backend/benchmark/__init__.py b/products/replay_vision/backend/benchmark/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/replay_vision/backend/benchmark/consensus.py b/products/replay_vision/backend/benchmark/consensus.pynew file mode 100644index 000000000000..b7624d9a7139--- /dev/null+++ b/products/replay_vision/backend/benchmark/consensus.py@@ -0,0 +1,194 @@+"""Collapse the labeling suite's answers for one (question, recording) cell into a single reference answer.++The consensus keeps the labeling suite's own answer shape, so a scorer reads a reference answer and a+labeler's answer the same way. Question types with no comparable value (free text, ranking,+correction) produce no consensus; the benchmark leaves them out.+"""++import statistics+from collections import Counter+from typing import Any++from pydantic import BaseModel++# A consensus needs at least two independent answers; one labeler is an opinion, not agreement.+MIN_LABELS = 2+# Spans from different labelers belong to the same moment when they overlap at all or sit this close.+SPAN_JOIN_TOLERANCE_MS = 2_000+++class Question(BaseModel, frozen=True):+ question_id: str+ version: int+ type: str+ # The labeling suite's question JSON: prompt, options, sub-questions and flags.+ definition: dict[str, Any]+++class Span(BaseModel, frozen=True):+ start_ms: int+ end_ms: int+++class CellConsensus(BaseModel, frozen=True):+ question_id: str+ question_version: int+ recording_id: str+ answer: dict[str, Any]+ # Share of labelers whose answer matches the consensus; None where answers have no single comparable value.+ agreement: float | None+ label_count: int+++def cell_consensus(question: Question, recording_id: str, labels: list[dict[str, Any]]) -> CellConsensus | None:+ if len(labels) < MIN_LABELS:+ return None+ result = _majority_answer(question, labels)+ if result is None:+ return None+ answer, agreement = result+ return CellConsensus(+ question_id=question.question_id,+ question_version=question.version,+ recording_id=recording_id,+ answer={"questionId": question.question_id, "type": question.type, **answer},+ agreement=agreement,+ label_count=len(labels),+ )+++def _majority_answer(question: Question, labels: list[dict[str, Any]]) -> tuple[dict[str, Any], float | None] | None:+ definition = question.definition+ if question.type == "binary":+ return _majority_value([label.get("choice") for label in labels], lambda choice: {"choice": choice})+ if question.type == "multiple_choice":+ if definition.get("optionScale"):+ return _median_ratings(definition["optionScale"], labels)+ if definition.get("multiple"):+ return _per_option_majority(definition, labels)+ choices = [_single_choice(label) for label in labels]+ if definition.get("ordinal"):+ return _median_choice(choices)+ return _majority_value(choices, lambda index: {"choiceIndices": [index]})+ if question.type == "itemized":+ return _span_consensus([_itemized_spans(label) for label in labels])+ if question.type == "timeline_marking":+ return _span_consensus([_marker_spans(label) for label in labels])+ return None+++def _majority_value(values: list[Any], build: Any) -> tuple[dict[str, Any], float] | None:+ answered = [value for value in values if value is not None]+ if len(answered) < MIN_LABELS:+ return None+ ranked = Counter(answered).most_common()+ if len(ranked) > 1 and ranked[0][1] == ranked[1][1]:+ return None+ value, count = ranked[0]+ return build(value), count / len(answered)+++def _single_choice(label: dict[str, Any]) -> int | None:+ indices = label.get("choiceIndices") or []+ return indices[0] if len(indices) == 1 else None+++def _median_choice(choices: list[int | None]) -> tuple[dict[str, Any], float] | None:+ answered = [choice for choice in choices if choice is not None]+ if len(answered) < MIN_LABELS:+ return None+ median = _settled_median(answered)+ if median is None:+ return None+ return {"choiceIndices": [median]}, sum(1 for choice in answered if choice == median) / len(answered)+++def _settled_median(values: list[int]) -> int | None:+ """The median when it is one of the values, None when it falls between two: a split, not an answer."""+ median = statistics.median(values)+ return int(median) if median == int(median) else None+++def _per_option_majority(+ definition: dict[str, Any], labels: list[dict[str, Any]]+) -> tuple[dict[str, Any], float] | None:+ option_count = len(definition.get("options", []))+ chosen = [set(label.get("choiceIndices") or []) for label in labels]+ majority = sorted(index for index in range(option_count) if sum(index in c for c in chosen) * 2 > len(chosen))+ # No option with a majority is disagreement, not a shared answer of "none", unless most chose none.+ if not majority and sum(not c for c in chosen) * 2 <= len(chosen):+ return None+ agreement = sum(1 for c in chosen if c == set(majority)) / len(chosen)+ return {"choiceIndices": majority}, agreement+++def _median_ratings(scale: dict[str, Any], labels: list[dict[str, Any]]) -> tuple[dict[str, Any], None] | None:+ by_option: dict[str, list[int]] = {}+ for label in labels:+ for option_id, rating in (label.get("ratings") or {}).items():+ # A missing, malformed or off-scale rating is no answer for that option, the way a span missing an edge is.+ if type(rating) is int and 1 <= rating <= scale.get("max", 0):+ by_option.setdefault(option_id, []).append(rating)+ ratings = {+ option_id: median+ for option_id, values in by_option.items()+ if len(values) >= MIN_LABELS and (median := _settled_median(values)) is not None+ }+ if not ratings:+ return None+ return {"ratings": ratings}, None+++def _span(edges: dict[str, Any]) -> list[Span]:+ """A span with both edges, or none: an answer missing one is dropped rather than failing the snapshot."""+ start, end = edges.get("startMs"), edges.get("endMs")+ # `type(...) is int` rather than isinstance, which would pass True and False as millisecond edges.+ return [Span(start_ms=start, end_ms=end)] if type(start) is int and type(end) is int else []+++def _itemized_spans(label: dict[str, Any]) -> list[Span]:+ spans: list[Span] = []+ for item in label.get("items") or []:+ for edges in item.get("spans") or [item]:+ spans.extend(_span(edges))+ return spans+++def _marker_spans(label: dict[str, Any]) -> list[Span]:+ return [span for marker in label.get("markers") or [] for span in _span(marker)]+++def _span_consensus(per_labeler: list[list[Span]]) -> tuple[dict[str, Any], float] | None:+ """Presence by majority, plus the moments at least two labelers marked.++ Each moment is a cluster of overlapping spans from two or more labelers, reported as the median of their+ edges. A moment only one labeler marked is left out: it may be real, but it is not agreed ground truth.+ """+ present = [len(spans) > 0 for spans in per_labeler]+ presence = _majority_value(present, lambda value: {"present": value})+ if presence is None:+ return None+ answer, agreement = presence+ tagged = sorted(+ ((span, labeler) for labeler, spans in enumerate(per_labeler) for span in spans),+ key=lambda pair: pair[0].start_ms,+ )+ clusters: list[list[tuple[Span, int]]] = []+ cluster_end = -1+ for span, labeler in tagged:+ if clusters and span.start_ms <= cluster_end + SPAN_JOIN_TOLERANCE_MS:+ clusters[-1].append((span, labeler))+ cluster_end = max(cluster_end, span.end_ms)+ else:+ clusters.append([(span, labeler)])+ cluster_end = span.end_ms+ moments = [+ {+ "startMs": round(statistics.median(span.start_ms for span, _ in cluster)),+ "endMs": round(statistics.median(span.end_ms for span, _ in cluster)),+ "labelers": len({labeler for _, labeler in cluster}),+ }+ for cluster in clusters+ if len({labeler for _, labeler in cluster}) >= MIN_LABELS+ ]+ return {**answer, "moments": moments if answer["present"] else []}, agreementdiff --git a/products/replay_vision/backend/benchmark/labeling_api.py b/products/replay_vision/backend/benchmark/labeling_api.pynew file mode 100644index 000000000000..3c7ad5f21eba--- /dev/null+++ b/products/replay_vision/backend/benchmark/labeling_api.py@@ -0,0 +1,187 @@+"""Read the labeling suite's benchmark export API, the one contract this benchmark has with MLHog.++The routes and their shapes are documented in MLHog's `labeling/replay/EXPORT.md`. Nothing here+knows the labeling database, the image ref formats or the v2 encryption; the playable route+returns a recording with all of that already resolved.+"""++import io+import time+import zlib+from collections import defaultdict+from collections.abc import Iterator+from contextlib import contextmanager+from typing import Any++from django.conf import settings++import requests+from pydantic import BaseModel++from posthog.dataclasses import frozen++from products.replay_vision.backend.benchmark.consensus import CellConsensus, Question, cell_consensus+from products.replay_vision.backend.benchmark.layout import BenchmarkCase++EXPORT_SCHEMA_VERSION = 1+_PAGE_SIZE = 200+# A playable recording is decoded and image-resolved on request, so a long one takes a while.+_TIMEOUT = (10, 300)+# The app caps playable exports in flight and answers the overflow with a 429, which clears once+# another export finishes, so a busy answer is waited out here rather than failing the case.+_BUSY_RETRIES = 4+_READ_CHUNK_BYTES = 1024 * 1024+_BUSY_BACKOFF_SECONDS = 5+++class ExportSnapshot(BaseModel, frozen=True):+ questions: list[Question]+ cells: list[CellConsensus]+ cases: list[BenchmarkCase]+++class GzipBody(io.RawIOBase):+ """A gzip response body, decoded as it is read, that fails on one ending before its trailer.++ The export ends a failed body early, and urllib3's own decoding would pass that off as a short recording.+ """++ def __init__(self, raw: Any) -> None:+ self._raw = raw+ self._decoder = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)+ self._pending = b""++ def readable(self) -> bool:+ return True++ def read(self, size: int | None = -1) -> bytes:+ wanted = -1 if size is None else size+ while (wanted < 0 or len(self._pending) < wanted) and not self._decoder.eof:+ chunk = self._raw.read(_READ_CHUNK_BYTES, decode_content=False)+ if not chunk:+ raise OSError("the playable export ended before its gzip trailer")+ self._pending += self._decoder.decompress(chunk)+ if wanted < 0:+ data, self._pending = self._pending, b""+ else:+ data, self._pending = self._pending[:wanted], self._pending[wanted:]+ return data+++@frozen+class PlayableRecording:+ # The JSONL body, decoded from the route's gzip as it is read.+ stream: GzipBody+ image_refs: int+ images_resolved: int+++class LabelingExportClient:+ def __init__(self, base_url: str, token: str) -> None:+ self.base = base_url.rstrip("/") + "/v1/admin/exports/benchmark"+ self.headers = {"authorization": f"Bearer {token}", "user-agent": "posthog-replay-vision-benchmark"}++ @classmethod+ def from_settings(cls) -> "LabelingExportClient":+ if not settings.REPLAY_VISION_BENCHMARK_LABELING_URL or not settings.REPLAY_VISION_BENCHMARK_LABELING_TOKEN:+ raise ValueError("REPLAY_VISION_BENCHMARK_LABELING_URL and _TOKEN must be set")+ return cls(settings.REPLAY_VISION_BENCHMARK_LABELING_URL, settings.REPLAY_VISION_BENCHMARK_LABELING_TOKEN)++ def _get(self, path: str, params: dict[str, str] | None = None, stream: bool = False) -> requests.Response:+ for attempt in range(_BUSY_RETRIES + 1):+ response = requests.get(+ f"{self.base}{path}", params=params, headers=self.headers, timeout=_TIMEOUT, stream=stream+ )+ if response.status_code != 429 or attempt == _BUSY_RETRIES:+ break+ response.close()+ time.sleep(_BUSY_BACKOFF_SECONDS * 2**attempt)+ response.raise_for_status()+ return response++ def _json(self, path: str, params: dict[str, str] | None = None) -> dict[str, Any]:+ body = self._get(path, params).json()+ if body.get("schemaVersion") != EXPORT_SCHEMA_VERSION:+ raise ValueError(+ f"labeling export serves schema {body.get('schemaVersion')}, expected {EXPORT_SCHEMA_VERSION}"+ )+ return body++ def snapshot(self) -> ExportSnapshot:+ questions = self._json("/questions")["questions"]+ recordings: list[dict[str, Any]] = []+ after: str | None = None+ while True:+ params = {"limit": str(_PAGE_SIZE)} | ({"after": after} if after else {})+ page = self._json("/recordings", params)+ recordings.extend(page["recordings"])+ after = page["next"]+ if after is None:+ return build_snapshot(questions, recordings)++ @contextmanager+ def playable(self, recording_id: str) -> Iterator[PlayableRecording]:+ """The recording as a stream, so a long one never sits whole in the worker's memory."""+ response = self._get(f"/recordings/{recording_id}/playable", stream=True)+ try:+ yield PlayableRecording(+ stream=GzipBody(response.raw),+ image_refs=int(response.headers.get("x-benchmark-image-refs", 0)),+ images_resolved=int(response.headers.get("x-benchmark-images-resolved", 0)),+ )+ finally:+ response.close()+++def build_snapshot(questions: list[dict[str, Any]], recordings: list[dict[str, Any]]) -> ExportSnapshot:+ """Consensus per (question, recording) cell for the v2 recordings, from answers to the question's current wording.++ An answer to an earlier version answered a different question, and one with no version predates the+ column, so neither can be pooled with the rest.+ """+ parsed = {+ row["questionId"]: Question(+ question_id=row["questionId"],+ version=row["version"],+ type=row["question"]["type"],+ definition=row["question"],+ )+ for row in questions+ }+ cells: list[CellConsensus] = []+ cases: list[BenchmarkCase] = []+ for recording in recordings:+ # A v1 recording's ids are pseudonyms, so no production inputs exist to scan it with.+ if recording["idKind"] != "real" or not (recording["teamRef"] or "").isdigit() or not recording["sessionRef"]:+ continue+ answers: dict[str, list[dict[str, Any]]] = defaultdict(list)+ for label in recording["labels"]:+ question = parsed.get(label["questionId"])+ if question is not None and label["questionVersion"] == question.version:+ answers[label["questionId"]].append(label["label"])+ recording_cells = [+ consensus+ for question_id in sorted(answers)+ if (+ consensus := cell_consensus(+ parsed[question_id],+ recording["recordingId"],+ answers[question_id],+ )+ )+ is not None+ ]+ if not recording_cells:+ continue+ cells.extend(recording_cells)+ cases.append(+ BenchmarkCase(+ case_id=recording["recordingId"],+ split=recording["split"],+ domain=recording["domain"],+ team_id=int(recording["teamRef"]),+ session_id=recording["sessionRef"],+ product_context=recording["siteBrief"] or "",+ )+ )+ return ExportSnapshot(questions=list(parsed.values()), cells=cells, cases=cases)diff --git a/products/replay_vision/backend/benchmark/layout.py b/products/replay_vision/backend/benchmark/layout.pynew file mode 100644index 000000000000..7d264c59f7e7--- /dev/null+++ b/products/replay_vision/backend/benchmark/layout.py@@ -0,0 +1,56 @@+"""Where a benchmark version's objects live. A version is written once and never edited; a refresh is a new version."""++from django.conf import settings++from pydantic import BaseModel, Field+++class BenchmarkCase(BaseModel, frozen=True):+ """One labeled recording to render, as listed in the version's `cases.jsonl`."""++ # The labeling suite's recording id, used as the case id throughout. It lands in object keys and workflow ids,+ # so only a UUID from the export is accepted.+ case_id: str = Field(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")+ split: str | None+ domain: str | None+ # The PostHog team and session: production's scan inputs are fetched by them, and a deletion reaches the case by them.+ team_id: int+ session_id: str+ product_context: str = ""+++class BenchmarkLayout:+ def __init__(self, version: str) -> None:+ self.bucket = settings.REPLAY_VISION_BENCHMARK_BUCKET+ self.root = f"{settings.REPLAY_VISION_BENCHMARK_PREFIX}/{version}"++ @property+ def manifest_key(self) -> str:+ return f"{self.root}/manifest.json"++ @property+ def questions_key(self) -> str:+ return f"{self.root}/questions.json"++ @property+ def labels_key(self) -> str:+ return f"{self.root}/labels.jsonl"++ @property+ def cases_key(self) -> str:+ return f"{self.root}/cases.jsonl"++ def case_prefix(self, case_id: str) -> str:+ return f"{self.root}/cases/{case_id}"++ def events_key(self, case_id: str) -> str:+ return f"{self.case_prefix(case_id)}/events.jsonl.zst"++ def inputs_key(self, case_id: str) -> str:+ return f"{self.case_prefix(case_id)}/inputs.json"++ def status_key(self, case_id: str) -> str:+ return f"{self.case_prefix(case_id)}/status.json"++ def events_uri(self, case_id: str) -> str:+ return f"s3://{self.bucket}/{self.events_key(case_id)}"diff --git a/products/replay_vision/backend/management/commands/build_replay_vision_benchmark.py b/products/replay_vision/backend/management/commands/build_replay_vision_benchmark.pynew file mode 100644index 000000000000..033fd3a0bb51--- /dev/null+++ b/products/replay_vision/backend/management/commands/build_replay_vision_benchmark.py@@ -0,0 +1,34 @@+from django.conf import settings+from django.core.management.base import BaseCommand, CommandParser++from asgiref.sync import async_to_sync++from posthog.temporal.common.client import sync_connect++from products.replay_vision.backend.temporal.benchmark_types import BuildBenchmarkInputs+from products.replay_vision.backend.temporal.constants import BUILD_BENCHMARK_WORKFLOW_NAME+++class Command(BaseCommand):+ help = "Build a frozen Replay Vision labeling benchmark version from the labeling suite's labels"++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("version", help="Version name, for example v1. A built version is never rewritten.")+ parser.add_argument("--recording-limit", type=int, default=None, help="Cap the version to this many recordings")+ parser.add_argument("--max-concurrent-renders", type=int, default=4)++ def handle(self, *args: object, **options: object) -> None:+ inputs = BuildBenchmarkInputs(+ version=str(options["version"]),+ recording_limit=options["recording_limit"],+ max_concurrent_renders=options["max_concurrent_renders"],+ )+ workflow_id = f"{BUILD_BENCHMARK_WORKFLOW_NAME}-{inputs.version}"+ client = sync_connect()+ async_to_sync(client.start_workflow)( # type: ignore[misc]+ BUILD_BENCHMARK_WORKFLOW_NAME, # type: ignore[arg-type]+ inputs, # type: ignore[arg-type]+ id=workflow_id,+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,+ )+ self.stdout.write(f"Started {workflow_id}")diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 1abe8ba2c764..3fa2048bfa94 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -46,11 +46,19 @@ from products.replay_vision.backend.temporal.activities import (upload_video_to_gemini_activity,upsert_scanner_schedule_activity,)+from products.replay_vision.backend.temporal.activities.benchmark import (+ load_benchmark_cases_activity,+ prepare_benchmark_case_activity,+ record_benchmark_case_activity,+ snapshot_benchmark_labels_activity,+ write_benchmark_manifest_activity,+)from products.replay_vision.backend.temporal.activities.refresh_search_suggestions import (list_stale_search_suggestions_activity,refresh_scanner_search_suggestions_activity,)from products.replay_vision.backend.temporal.backfill_workflow import BackfillScannerWorkflow+from products.replay_vision.backend.temporal.benchmark_workflow import BuildBenchmarkWorkflowfrom products.replay_vision.backend.temporal.estimates import RefreshScannerEstimatesWorkflowfrom products.replay_vision.backend.temporal.evaluation_workflow import EvaluatePromptSuggestionWorkflowfrom products.replay_vision.backend.temporal.gemini_cleanup_sweep import (@@ -74,6 +82,7 @@ from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkfloWORKFLOWS = [ApplyScannerWorkflow,BackfillScannerWorkflow,+ BuildBenchmarkWorkflow,EvaluatePromptSuggestionWorkflow,MeterScannerReadsWorkflow,ObservationMediaWorkflow,@@ -135,6 +144,11 @@ ACTIVITIES: list[Callable[..., Any]] = [sweep_gemini_files_activity,list_stale_search_suggestions_activity,refresh_scanner_search_suggestions_activity,+ snapshot_benchmark_labels_activity,+ load_benchmark_cases_activity,+ prepare_benchmark_case_activity,+ record_benchmark_case_activity,+ write_benchmark_manifest_activity,]__all__ = [diff --git a/products/replay_vision/backend/temporal/activities/benchmark.py b/products/replay_vision/backend/temporal/activities/benchmark.pynew file mode 100644index 000000000000..a8203d9a47bc--- /dev/null+++ b/products/replay_vision/backend/temporal/activities/benchmark.py@@ -0,0 +1,199 @@+"""Activities that build a labeling benchmark version: snapshot the labels, then prepare and record each case."""++import json+import hashlib+from typing import IO, cast++import zstandard+from temporalio import activity+from temporalio.exceptions import ApplicationError++from posthog.models import Team+from posthog.storage import object_storage+from posthog.sync import database_sync_to_async_pool+from posthog.temporal.session_replay.rasterize_recording.activities.rasterize import rasterization_input_from_context+from posthog.temporal.session_replay.rasterize_recording.types import FINGERPRINT_EXCLUDE, RasterizationActivityInput++from products.replay_vision.backend.benchmark.labeling_api import LabelingExportClient+from products.replay_vision.backend.benchmark.layout import BenchmarkCase, BenchmarkLayout+from products.replay_vision.backend.consent import is_ai_data_processing_approved+from products.replay_vision.backend.temporal.activities.ensure_session_asset import analysis_export_context+from products.replay_vision.backend.temporal.activities.fetch_session_events import fetch_session_payload+from products.replay_vision.backend.temporal.benchmark_types import (+ BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE,+ BENCHMARK_CASE_SKIPPED_ERROR_TYPE,+ LoadBenchmarkCasesInputs,+ LoadBenchmarkCasesOutput,+ PrepareBenchmarkCaseInputs,+ PrepareBenchmarkCaseOutput,+ RecordBenchmarkCaseInputs,+ SnapshotBenchmarkInputs,+ SnapshotBenchmarkOutput,+ WriteBenchmarkManifestInputs,+)+from products.replay_vision.backend.temporal.decorators import track_activity+from products.replay_vision.backend.temporal.errors import IneligibleSessionError+from products.replay_vision.backend.temporal.types import ScannerLlmInputs++# The rasterizer refuses a render without a positive team id; a source render reads no team data.+BENCHMARK_RENDER_TEAM_ID = 1+++def _layout(version: str) -> BenchmarkLayout:+ layout = BenchmarkLayout(version)+ if not layout.bucket:+ raise ValueError("REPLAY_VISION_BENCHMARK_BUCKET is not set")+ return layout+++def benchmark_render_input(case_id: str, layout: BenchmarkLayout) -> RasterizationActivityInput:+ """The render a production scan's analysis video gets, from the case's recording instead of recording-api."""+ return rasterization_input_from_context(+ analysis_export_context(case_id),+ team_id=BENCHMARK_RENDER_TEAM_ID,+ session_id=case_id,+ s3_bucket=layout.bucket,+ s3_key_prefix=layout.case_prefix(case_id),+ output_format="mp4",+ ).model_copy(update={"source_s3_uri": layout.events_uri(case_id)})+++def _write_jsonl(key: str, bucket: str, lines: list[str]) -> None:+ object_storage.write(key, "\n".join(lines) + "\n", bucket=bucket)+++def _read_cases(layout: BenchmarkLayout) -> list[str]:+ body = object_storage.read(layout.cases_key, bucket=layout.bucket, missing_ok=True) or ""+ return [line for line in body.splitlines() if line.strip()]+++def _snapshot(inputs: SnapshotBenchmarkInputs) -> SnapshotBenchmarkOutput:+ layout = _layout(inputs.version)+ if object_storage.head_object(layout.manifest_key, bucket=layout.bucket):+ raise ValueError(f"benchmark version {inputs.version} is already built; versions are never rewritten")+ # A build that stopped partway resumes on the snapshot it took, so its cases keep describing one moment.+ if existing := _read_cases(layout):+ return SnapshotBenchmarkOutput(case_count=len(existing))++ snapshot = LabelingExportClient.from_settings().snapshot()+ cases = snapshot.cases+ if inputs.recording_limit is not None:+ # Hash order rather than id order, so a small version is a sample, not the oldest recordings.+ cases = sorted(cases, key=lambda case: hashlib.sha256(case.case_id.encode()).hexdigest())+ cases = sorted(cases[: inputs.recording_limit], key=lambda case: case.case_id)+ kept = {case.case_id for case in cases}+ cells = [cell for cell in snapshot.cells if cell.recording_id in kept]++ object_storage.write(+ layout.questions_key,+ json.dumps([question.model_dump(mode="json") for question in snapshot.questions]),+ bucket=layout.bucket,+ )+ _write_jsonl(layout.labels_key, layout.bucket, [cell.model_dump_json() for cell in cells])+ # Written last, so a snapshot that stops partway leaves no cases for a resume to trust.+ _write_jsonl(layout.cases_key, layout.bucket, [case.model_dump_json() for case in cases])+ return SnapshotBenchmarkOutput(case_count=len(cases))+++@track_activity()+async def snapshot_benchmark_labels_activity(inputs: SnapshotBenchmarkInputs) -> SnapshotBenchmarkOutput:+ return await database_sync_to_async_pool(_snapshot)(inputs)+++def _load_cases(inputs: LoadBenchmarkCasesInputs) -> LoadBenchmarkCasesOutput:+ window = _read_cases(_layout(inputs.version))[inputs.offset : inputs.offset + inputs.limit]+ return LoadBenchmarkCasesOutput(cases=[BenchmarkCase.model_validate_json(line) for line in window])+++@track_activity()+async def load_benchmark_cases_activity(inputs: LoadBenchmarkCasesInputs) -> LoadBenchmarkCasesOutput:+ return await database_sync_to_async_pool(_load_cases)(inputs)+++def _skip(reason: str) -> ApplicationError:+ return ApplicationError(reason, type=BENCHMARK_CASE_SKIPPED_ERROR_TYPE, non_retryable=True)+++def _production_inputs(case: BenchmarkCase) -> ScannerLlmInputs:+ """The inputs a production scan of this session gets, from the same fetch; a session it would not scan is skipped."""+ # The same gate a production scan passes before anything leaves for Gemini.+ if not is_ai_data_processing_approved(case.team_id):+ raise _skip("no AI data processing consent")+ try:+ payload = fetch_session_payload(case.team_id, case.session_id)+ except IneligibleSessionError as error:+ raise _skip(f"ineligible: {error.kind}") from error+ except Team.DoesNotExist as error:+ raise _skip("team no longer exists") from error+ if payload is None:+ raise _skip("no analytics events")+ return payload+++def _already_built(layout: BenchmarkLayout, case: BenchmarkCase) -> bool:+ status = object_storage.read(layout.status_key(case.case_id), bucket=layout.bucket, missing_ok=True)+ return status is not None and json.loads(status).get("outcome") == "built"+++def _prepare_case(layout: BenchmarkLayout, case: BenchmarkCase) -> PrepareBenchmarkCaseOutput:+ # A resumed build keeps what an earlier run of this version rendered instead of rendering it again.+ if _already_built(layout, case):+ raise ApplicationError("already built", type=BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE, non_retryable=True)+ # Inputs first: a skipped session costs the labeling app nothing.+ inputs = _production_inputs(case)+ with LabelingExportClient.from_settings().playable(case.case_id) as playable:+ # The reader only calls read(), which GzipBody provides.+ with zstandard.ZstdCompressor().stream_reader(cast(IO[bytes], playable.stream)) as compressed:+ object_storage.write_stream(layout.events_key(case.case_id), compressed, bucket=layout.bucket)+ object_storage.write(layout.inputs_key(case.case_id), inputs.model_dump_json(), bucket=layout.bucket)+ return PrepareBenchmarkCaseOutput(+ render_input=benchmark_render_input(case.case_id, layout),+ image_refs=playable.image_refs,+ images_resolved=playable.images_resolved,+ )+++@track_activity()+async def prepare_benchmark_case_activity(inputs: PrepareBenchmarkCaseInputs) -> PrepareBenchmarkCaseOutput:+ return await database_sync_to_async_pool(_prepare_case)(_layout(inputs.version), inputs.case)+++def _record_case(inputs: RecordBenchmarkCaseInputs) -> None:+ layout = _layout(inputs.version)+ object_storage.write(+ layout.status_key(inputs.case_id), inputs.model_dump_json(exclude={"version"}), bucket=layout.bucket+ )+++@track_activity()+async def record_benchmark_case_activity(inputs: RecordBenchmarkCaseInputs) -> None:+ await database_sync_to_async_pool(_record_case)(inputs)+++def _write_manifest(inputs: WriteBenchmarkManifestInputs, built_at: str) -> None:+ layout = _layout(inputs.version)+ # The render every case got, without the parts that name one case.+ render_settings = benchmark_render_input("", layout).model_dump(+ exclude=FINGERPRINT_EXCLUDE, mode="json", exclude_none=True+ )+ manifest = {+ "version": inputs.version,+ "built_at": built_at,+ "case_count": inputs.case_count,+ "built": inputs.built,+ "failed": inputs.failed,+ "skipped": inputs.skipped,+ "render_settings": render_settings,+ }+ object_storage.write(layout.manifest_key, json.dumps(manifest), bucket=layout.bucket)+++@track_activity()+async def write_benchmark_manifest_activity(inputs: WriteBenchmarkManifestInputs) -> None:+ built_at = activity.info().current_attempt_scheduled_time.isoformat()+ await database_sync_to_async_pool(_write_manifest)(inputs, built_at)diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.pyindex 08402e60d23f..7dc69384a415 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py@@ -94,7 +94,7 @@ async def fetch_session_events_activity(inputs: FetchSessionEventsInputs) -> Nonif await redis_client.exists(redis_key):return- payload = await sync_to_async(_fetch_payload)(inputs.team_id, inputs.session_id)+ payload = await sync_to_async(fetch_session_payload)(inputs.team_id, inputs.session_id)if payload is None:raise IneligibleSessionError("No events to analyze",@@ -194,7 +194,7 @@ def _group_type_labels(team: Team) -> dict[int, str]:return {}-def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:+def fetch_session_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:# select_related saves the extra round trip when fetch_product_context reads team.project.team = Team.objects.select_related("project").get(pk=team_id)events_obj = SessionReplayEvents()diff --git a/products/replay_vision/backend/temporal/benchmark_types.py b/products/replay_vision/backend/temporal/benchmark_types.pynew file mode 100644index 000000000000..2980ee6a851c--- /dev/null+++ b/products/replay_vision/backend/temporal/benchmark_types.py@@ -0,0 +1,83 @@+"""Types for building a labeling benchmark version, split from `types.py` like `backfill_types.py`."""++from typing import Literal++from pydantic import BaseModel, Field++from posthog.temporal.session_replay.rasterize_recording.types import (+ RasterizationActivityInput,+ RasterizationActivityOutput,+)++from products.replay_vision.backend.benchmark.layout import BenchmarkCase++# The prepare activity's error type for a session production would not scan, which the build skips.+BENCHMARK_CASE_SKIPPED_ERROR_TYPE = "BenchmarkCaseSkipped"+# Its error type for a case an earlier run of the same version already built, which a resumed build counts as is.+BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE = "BenchmarkCaseAlreadyBuilt"++CaseOutcome = Literal["built", "failed", "skipped"]+++class BuildBenchmarkInputs(BaseModel, frozen=True):+ version: str = Field(pattern=r"^[a-z0-9][a-z0-9-]{0,62}$")+ # Caps the snapshot to this many recordings, picked deterministically, for a small first version.+ recording_limit: int | None = Field(default=None, ge=1)+ # Renders in flight at once. Benchmark renders share the rasterizer with customer scans.+ max_concurrent_renders: int = Field(default=4, ge=1, le=16)+ # Carried across continue-as-new; unset on the first run, which takes the snapshot.+ case_count: int | None = None+ offset: int = 0+ built: int = 0+ failed: int = 0+ skipped: int = 0+++class SnapshotBenchmarkInputs(BaseModel, frozen=True):+ version: str+ recording_limit: int | None = None+++class SnapshotBenchmarkOutput(BaseModel, frozen=True):+ case_count: int+++class LoadBenchmarkCasesInputs(BaseModel, frozen=True):+ version: str+ offset: int+ limit: int+++class LoadBenchmarkCasesOutput(BaseModel, frozen=True):+ cases: list[BenchmarkCase]+++class PrepareBenchmarkCaseInputs(BaseModel, frozen=True):+ version: str+ case: BenchmarkCase+++class PrepareBenchmarkCaseOutput(BaseModel, frozen=True):+ render_input: RasterizationActivityInput+ # Refs the recording carries, and images the export put back; the rest render as placeholders.+ image_refs: int+ images_resolved: int+++class RecordBenchmarkCaseInputs(BaseModel, frozen=True):+ version: str+ case_id: str+ outcome: CaseOutcome+ render: RasterizationActivityOutput | None = None+ # Why the case failed, or why production would not scan the session when it was skipped.+ reason: str | None = None+ image_refs: int = 0+ images_resolved: int = 0+++class WriteBenchmarkManifestInputs(BaseModel, frozen=True):+ version: str+ case_count: int+ built: int+ failed: int+ skipped: intdiff --git a/products/replay_vision/backend/temporal/benchmark_workflow.py b/products/replay_vision/backend/temporal/benchmark_workflow.pynew file mode 100644index 000000000000..749ab615a755--- /dev/null+++ b/products/replay_vision/backend/temporal/benchmark_workflow.py@@ -0,0 +1,177 @@+"""Build one labeling benchmark version: snapshot the labels, then prepare and render every labeled recording.++Each case renders through the rasterize workflow, the same path production renders take, at the lowest priority+so customer scans go first. A session production would not scan is skipped and a case that fails is recorded;+the version is built from the rest. The workflow continues as new after each batch, so history stays bounded+however many cases a version holds.+"""++import asyncio+import datetime as dt+from collections import Counter++from temporalio import (+ common,+ workflow as wf,+)+from temporalio.common import Priority, WorkflowIDReusePolicy+from temporalio.exceptions import ApplicationError++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.errors import unwrap_temporal_cause++with wf.unsafe.imports_passed_through():+ from django.conf import settings++ from posthog.temporal.session_replay.rasterize_recording.types import (+ RasterizationActivityOutput,+ RasterizeRecordingInputs,+ )++ from products.replay_vision.backend.benchmark.layout import BenchmarkCase+ from products.replay_vision.backend.temporal.activities.benchmark import (+ load_benchmark_cases_activity,+ prepare_benchmark_case_activity,+ record_benchmark_case_activity,+ snapshot_benchmark_labels_activity,+ write_benchmark_manifest_activity,+ )+ from products.replay_vision.backend.temporal.benchmark_types import (+ BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE,+ BENCHMARK_CASE_SKIPPED_ERROR_TYPE,+ BuildBenchmarkInputs,+ CaseOutcome,+ LoadBenchmarkCasesInputs,+ LoadBenchmarkCasesOutput,+ PrepareBenchmarkCaseInputs,+ PrepareBenchmarkCaseOutput,+ RecordBenchmarkCaseInputs,+ SnapshotBenchmarkInputs,+ SnapshotBenchmarkOutput,+ WriteBenchmarkManifestInputs,+ )+ from products.replay_vision.backend.temporal.constants import BUILD_BENCHMARK_WORKFLOW_NAME++# Cases per run before continue-as-new. Each case adds about a dozen history events.+CASES_PER_RUN = 200+# Temporal's lowest priority, so benchmark renders queue behind every customer render. The child's+# render activity inherits it.+BENCHMARK_RENDER_PRIORITY = Priority(priority_key=5)+# Rasterizer codes for a recording production gates as ineligible rather than failed: nothing to draw, or+# too large to render. The benchmark skips those the same way.+_INELIGIBLE_RENDER_TYPES = frozenset({"NO_SNAPSHOTS", "RECORDING_TOO_LARGE"})+# A render at the lowest priority waits behind any production backlog, and that wait counts against the child's+# execution timeout, so it gets hours rather than the single render attempt production callers budget for.+BENCHMARK_RENDER_TIMEOUT = dt.timedelta(hours=6)++_RETRY = common.RetryPolicy(maximum_attempts=3)+++def _skip_reason(error: BaseException) -> str | None:+ cause = error if isinstance(error, ApplicationError) else unwrap_temporal_cause(error)+ if cause is None:+ return None+ if cause.type == BENCHMARK_CASE_SKIPPED_ERROR_TYPE:+ return cause.message+ if cause.type in _INELIGIBLE_RENDER_TYPES:+ return f"render: {cause.type}"+ return None++[email protected](name=BUILD_BENCHMARK_WORKFLOW_NAME)+class BuildBenchmarkWorkflow(PostHogWorkflow):+ inputs_cls = BuildBenchmarkInputs++ @wf.run+ async def run(self, inputs: BuildBenchmarkInputs) -> None:+ if inputs.case_count is None:+ snapshot: SnapshotBenchmarkOutput = await wf.execute_activity(+ snapshot_benchmark_labels_activity,+ SnapshotBenchmarkInputs(version=inputs.version, recording_limit=inputs.recording_limit),+ start_to_close_timeout=dt.timedelta(minutes=30),+ retry_policy=_RETRY,+ )+ inputs = inputs.model_copy(update={"case_count": snapshot.case_count})+ assert inputs.case_count is not None++ batch: LoadBenchmarkCasesOutput = await wf.execute_activity(+ load_benchmark_cases_activity,+ LoadBenchmarkCasesInputs(version=inputs.version, offset=inputs.offset, limit=CASES_PER_RUN),+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=_RETRY,+ )+ slots = asyncio.Semaphore(inputs.max_concurrent_renders)+ outcomes = Counter(+ await asyncio.gather(*(self._build_case(inputs.version, case, slots) for case in batch.cases))+ )+ built = inputs.built + outcomes["built"]+ failed = inputs.failed + outcomes["failed"]+ skipped = inputs.skipped + outcomes["skipped"]++ next_offset = inputs.offset + len(batch.cases)+ if batch.cases and next_offset < inputs.case_count:+ wf.continue_as_new(+ inputs.model_copy(update={"offset": next_offset, "built": built, "failed": failed, "skipped": skipped})+ )++ await wf.execute_activity(+ write_benchmark_manifest_activity,+ WriteBenchmarkManifestInputs(+ version=inputs.version, case_count=inputs.case_count, built=built, failed=failed, skipped=skipped+ ),+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=_RETRY,+ )++ async def _build_case(self, version: str, case: BenchmarkCase, slots: asyncio.Semaphore) -> CaseOutcome:+ async with slots:+ outcome: CaseOutcome = "built"+ render: RasterizationActivityOutput | None = None+ reason: str | None = None+ image_refs = images_resolved = 0+ try:+ prepared: PrepareBenchmarkCaseOutput = await wf.execute_activity(+ prepare_benchmark_case_activity,+ PrepareBenchmarkCaseInputs(version=version, case=case),+ start_to_close_timeout=dt.timedelta(minutes=10),+ retry_policy=_RETRY,+ )+ image_refs, images_resolved = prepared.image_refs, prepared.images_resolved+ render = await wf.execute_child_workflow(+ "rasterize-recording",+ RasterizeRecordingInputs(render_input=prepared.render_input, product="replay_vision_benchmark"),+ result_type=RasterizationActivityOutput,+ id=f"{BUILD_BENCHMARK_WORKFLOW_NAME}-{version}-{case.case_id}",+ # Not replay-checked, like the rasterize workflow's own task queue setting.+ task_queue=settings.SESSION_REPLAY_TASK_QUEUE,+ retry_policy=common.RetryPolicy(maximum_attempts=1),+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ execution_timeout=BENCHMARK_RENDER_TIMEOUT,+ priority=BENCHMARK_RENDER_PRIORITY,+ )+ except Exception as error:+ cause = unwrap_temporal_cause(error)+ if cause is not None and cause.type == BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE:+ return "built"+ reason = _skip_reason(error)+ outcome = "skipped" if reason else "failed"+ reason = reason or str(cause or error)+ try:+ await wf.execute_activity(+ record_benchmark_case_activity,+ RecordBenchmarkCaseInputs(+ version=version,+ case_id=case.case_id,+ outcome=outcome,+ render=render,+ reason=reason,+ image_refs=image_refs,+ images_resolved=images_resolved,+ ),+ start_to_close_timeout=dt.timedelta(minutes=2),+ retry_policy=_RETRY,+ )+ except Exception:+ # One case whose status could not be written must not fail the batch and the renders beside it.+ return "failed"+ return outcomediff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex c61588011c92..5f459b51d9fd 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -5,6 +5,7 @@ from temporalio.common import Priority, RetryPolicyAPPLY_SCANNER_WORKFLOW_NAME = "replay-vision-apply-scanner"SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"+BUILD_BENCHMARK_WORKFLOW_NAME = "replay-vision-build-benchmark"# How long a cached admission budget admits without re-running the spend aggregates. Spend the# cache misses (settling receipts, evaluation reservations, failed-observation refunds) stays wrongdiff --git a/products/replay_vision/backend/tests/test_benchmark.py b/products/replay_vision/backend/tests/test_benchmark.pynew file mode 100644index 000000000000..7cfdbf432b92--- /dev/null+++ b/products/replay_vision/backend/tests/test_benchmark.py@@ -0,0 +1,315 @@+import io+import gzip+import uuid+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import temporalio.worker+from parameterized import parameterized+from temporalio import (+ activity,+ workflow as wf,+)+from temporalio.contrib.pydantic import pydantic_data_converter+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from posthog.temporal.session_replay.rasterize_recording.types import (+ RasterizationActivityInput,+ RasterizationActivityOutput,+ RasterizeRecordingInputs,+)++from products.replay_vision.backend.benchmark import labeling_api+from products.replay_vision.backend.benchmark.consensus import Question, cell_consensus+from products.replay_vision.backend.benchmark.labeling_api import LabelingExportClient, build_snapshot+from products.replay_vision.backend.benchmark.layout import BenchmarkCase+from products.replay_vision.backend.error_kinds import IneligibleSessionKind+from products.replay_vision.backend.temporal import benchmark_workflow+from products.replay_vision.backend.temporal.activities import benchmark as benchmark_activities+from products.replay_vision.backend.temporal.benchmark_types import (+ BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE,+ BENCHMARK_CASE_SKIPPED_ERROR_TYPE,+ BuildBenchmarkInputs,+ LoadBenchmarkCasesInputs,+ LoadBenchmarkCasesOutput,+ PrepareBenchmarkCaseInputs,+ PrepareBenchmarkCaseOutput,+ RecordBenchmarkCaseInputs,+ SnapshotBenchmarkInputs,+ SnapshotBenchmarkOutput,+ WriteBenchmarkManifestInputs,+)+from products.replay_vision.backend.temporal.benchmark_workflow import BuildBenchmarkWorkflow+from products.replay_vision.backend.temporal.constants import BUILD_BENCHMARK_WORKFLOW_NAME+from products.replay_vision.backend.temporal.errors import IneligibleSessionError+from products.replay_vision.backend.temporal.types import EventTable, ScannerLlmInputs, SessionMetadata++REC_1, REC_2, REC_3 = (f"00000000-0000-4000-8000-00000000000{i}" for i in range(1, 4))+CASE_IDS = [f"00000000-0000-4000-8000-0000000000a{i}" for i in range(6)]+++def _question(kind: str, **definition: Any) -> Question:+ return Question(question_id="q1", version=3, type=kind, definition=definition)+++def _span_label(*spans: tuple[int, int]) -> dict[str, Any]:+ return {"items": [{"itemId": str(i), "startMs": start, "endMs": end} for i, (start, end) in enumerate(spans)]}+++ [+ ("binary_majority", _question("binary"), [{"choice": True}] * 2 + [{"choice": False}], {"choice": True}),+ ("binary_tie_is_not_ground_truth", _question("binary"), [{"choice": True}, {"choice": False}], None),+ (+ "ordinal_takes_the_median",+ _question("multiple_choice", ordinal=True, options=[{}, {}, {}, {}]),+ [{"choiceIndices": [0]}, {"choiceIndices": [2]}, {"choiceIndices": [3]}],+ {"choiceIndices": [2]},+ ),+ (+ "multi_select_keeps_options_most_labelers_chose",+ _question("multiple_choice", multiple=True, options=[{}, {}, {}]),+ [{"choiceIndices": [0, 1]}, {"choiceIndices": [0]}, {"choiceIndices": [0, 2]}],+ {"choiceIndices": [0]},+ ),+ (+ "multi_select_disagreement_is_not_consensus",+ _question("multiple_choice", multiple=True, options=[{}, {}, {}]),+ [{"choiceIndices": [0, 1]}, {"choiceIndices": [2]}],+ None,+ ),+ (+ "multi_select_most_choosing_none_is_an_answer",+ _question("multiple_choice", multiple=True, options=[{}, {}, {}]),+ [{"choiceIndices": []}, {"choiceIndices": []}, {"choiceIndices": [1]}],+ {"choiceIndices": []},+ ),+ (+ "span_moment_needs_two_labelers",+ _question("itemized"),+ [_span_label((1_000, 4_000), (30_000, 31_000)), _span_label((1_500, 5_000)), {"items": []}],+ {"present": True, "moments": [{"startMs": 1_250, "endMs": 4_500, "labelers": 2}]},+ ),+ (+ "ordinal_split_between_two_values_is_not_consensus",+ _question("multiple_choice", ordinal=True, options=[{}, {}, {}, {}]),+ [{"choiceIndices": [0]}, {"choiceIndices": [3]}],+ None,+ ),+ (+ "span_with_a_boolean_edge_is_dropped",+ _question("itemized"),+ [_span_label((1_000, 4_000)), _span_label((1_500, 5_000)), {"items": [{"startMs": True, "endMs": 9}]}],+ {"present": True, "moments": [{"startMs": 1_250, "endMs": 4_500, "labelers": 2}]},+ ),+ (+ "rating_that_is_not_an_integer_or_is_off_scale_is_no_answer",+ _question("multiple_choice", optionScale={"max": 5}, options=[{"optionId": "a"}]),+ [+ {"ratings": {"a": 4}},+ {"ratings": {"a": 4}},+ {"ratings": {"a": None}},+ {"ratings": {"a": 9}},+ {"ratings": {"a": 9}},+ ],+ {"ratings": {"a": 4}},+ ),+ ("single_label_is_not_consensus", _question("binary"), [{"choice": True}], None),+ ("free_text_has_no_consensus", _question("freeform_long"), [{"response": "a"}, {"response": "a"}], None),+ ]+)+def test_majority_consensus(+ _name: str, question: Question, labels: list[dict[str, Any]], expected: dict[str, Any] | None+) -> None:+ consensus = cell_consensus(question, REC_1, labels)+ if expected is None:+ assert consensus is None+ else:+ assert consensus is not None+ assert {key: consensus.answer[key] for key in expected} == expected+++def _raw(body: bytes) -> MagicMock:+ stream = io.BytesIO(body)+ raw = MagicMock()+ raw.read.side_effect = lambda size, decode_content: stream.read(size)+ return raw+++def test_playable_refuses_a_body_cut_before_its_gzip_trailer() -> None:+ cut = MagicMock(status_code=200, raw=_raw(gzip.compress(b'{"type":4}\n' * 100)[:-8]), headers={})+ client = LabelingExportClient("https://labeling.example.com", "lbl_test")+ with patch.object(labeling_api.requests, "get", return_value=cut), client.playable(REC_1) as playable:+ with pytest.raises(OSError, match="gzip trailer"):+ playable.stream.read()+++def test_playable_waits_out_a_busy_labeling_app() -> None:+ busy = MagicMock(status_code=429)+ ready = MagicMock(status_code=200, raw=_raw(gzip.compress(b"{}\n")), headers={"x-benchmark-images-resolved": "3"})+ client = LabelingExportClient("https://labeling.example.com", "lbl_test")+ with (+ patch.object(labeling_api.requests, "get", side_effect=[busy, busy, ready]),+ patch.object(labeling_api.time, "sleep"),+ client.playable(REC_1) as playable,+ ):+ body = playable.stream.read()++ assert (body, playable.images_resolved) == (b"{}\n", 3)+ busy.raise_for_status.assert_not_called()+++def test_snapshot_keeps_v2_recordings_and_current_question_versions() -> None:+ questions = [{"questionId": "q1", "version": 2, "question": {"questionId": "q1", "type": "binary"}}]++ def answer(coder: int, version: int | None, choice: bool) -> dict[str, Any]:+ return {"questionId": "q1", "questionVersion": version, "coder": coder, "label": {"choice": choice}}++ recording = {+ "recordingId": REC_1,+ "split": "validation",+ "domain": "example.com",+ "teamRef": "2",+ "sessionRef": "s1",+ "idKind": "real",+ "siteBrief": None,+ # Two current answers say no; two answers to the old wording say yes and must not outvote them.+ "labels": [answer(0, 2, False), answer(1, 2, False), answer(2, 1, True), answer(3, None, True)],+ }+ unanswered_now = {**recording, "recordingId": REC_2, "labels": [answer(0, 1, True), answer(1, 1, True)]}+ # Answered like rec-1, but its pseudonymous ids join to no production inputs.+ v1 = {**recording, "recordingId": REC_3, "teamRef": "0123456789abcdef0123456789abcdef", "idKind": "pseudonym"}++ snapshot = build_snapshot(questions, [recording, unanswered_now, v1])++ assert [(cell.recording_id, cell.answer["choice"], cell.label_count) for cell in snapshot.cells] == [+ (REC_1, False, 2)+ ]+ assert [(case.case_id, case.team_id, case.session_id) for case in snapshot.cases] == [(REC_1, 2, "s1")]+++PRODUCTION_INPUTS = ScannerLlmInputs(+ session_id="sess-1",+ team_id=2,+ events=EventTable(columns=["event_uuid"], rows=[]),+ metadata=SessionMetadata(start_time="2026-09-01T00:00:00Z", end_time="2026-09-01T00:05:00Z", duration_seconds=300),+)+++ [+ ("no_consent", False, PRODUCTION_INPUTS, "no AI data processing consent"),+ (+ "production_would_not_scan_it",+ True,+ IneligibleSessionError("too short", kind=IneligibleSessionKind.TOO_SHORT),+ f"ineligible: {IneligibleSessionKind.TOO_SHORT}",+ ),+ ("no_analytics_events", True, None, "no analytics events"),+ ]+)+def test_a_session_without_production_inputs_is_skipped(+ _name: str, consented: bool, fetched: Any, expected_reason: str+) -> None:+ case = BenchmarkCase(case_id=REC_1, split="validation", domain=None, team_id=2, session_id="sess-1")+ with (+ patch.object(benchmark_activities, "is_ai_data_processing_approved", return_value=consented),+ patch.object(benchmark_activities, "fetch_session_payload", side_effect=[fetched]),+ pytest.raises(ApplicationError) as raised,+ ):+ benchmark_activities._production_inputs(case)++ assert (raised.value.type, raised.value.message) == (BENCHMARK_CASE_SKIPPED_ERROR_TYPE, expected_reason)++[email protected](name="rasterize-recording")+class _FakeRasterizeWorkflow:+ @wf.run+ async def run(self, inputs: RasterizeRecordingInputs) -> RasterizationActivityOutput:+ assert inputs.render_input is not None+ session_id = inputs.render_input.session_id+ if session_id == CASE_IDS[1]:+ raise ApplicationError("render crashed", type="RENDER_FAILED", non_retryable=True)+ if session_id == CASE_IDS[3]:+ raise ApplicationError("nothing to draw", type="NO_SNAPSHOTS", non_retryable=True)+ return RasterizationActivityOutput(+ s3_uri=f"s3://bench/{session_id}/video.mp4", video_duration_s=10, playback_speed=8+ )+++async def test_build_continues_past_failed_and_skipped_cases_and_counts_them() -> None:+ cases = [+ BenchmarkCase(case_id=case_id, split="validation", domain=None, team_id=2, session_id=f"s{i}")+ for i, case_id in enumerate(CASE_IDS)+ ]+ recorded: list[RecordBenchmarkCaseInputs] = []+ manifests: list[WriteBenchmarkManifestInputs] = []++ @activity.defn(name="snapshot_benchmark_labels_activity")+ async def snapshot(inputs: SnapshotBenchmarkInputs) -> SnapshotBenchmarkOutput:+ return SnapshotBenchmarkOutput(case_count=len(cases))++ @activity.defn(name="load_benchmark_cases_activity")+ async def load(inputs: LoadBenchmarkCasesInputs) -> LoadBenchmarkCasesOutput:+ return LoadBenchmarkCasesOutput(cases=cases[inputs.offset : inputs.offset + inputs.limit])++ @activity.defn(name="prepare_benchmark_case_activity")+ async def prepare(inputs: PrepareBenchmarkCaseInputs) -> PrepareBenchmarkCaseOutput:+ if inputs.case.case_id == CASE_IDS[2]:+ raise ApplicationError("ineligible: too_short", type=BENCHMARK_CASE_SKIPPED_ERROR_TYPE, non_retryable=True)+ if inputs.case.case_id == CASE_IDS[4]:+ raise ApplicationError("already built", type=BENCHMARK_CASE_ALREADY_BUILT_ERROR_TYPE, non_retryable=True)+ render_input = RasterizationActivityInput(+ session_id=inputs.case.case_id, team_id=1, s3_bucket="bench", s3_key_prefix=inputs.case.case_id+ )+ return PrepareBenchmarkCaseOutput(render_input=render_input, image_refs=1, images_resolved=1)++ @activity.defn(name="record_benchmark_case_activity")+ async def record(inputs: RecordBenchmarkCaseInputs) -> None:+ if inputs.case_id == CASE_IDS[5]:+ raise ApplicationError("bucket unavailable", non_retryable=True)+ recorded.append(inputs)++ @activity.defn(name="write_benchmark_manifest_activity")+ async def manifest(inputs: WriteBenchmarkManifestInputs) -> None:+ manifests.append(inputs)++ workflow_queue = str(uuid.uuid4())+ render_queue = str(uuid.uuid4())+ runner = temporalio.worker.UnsandboxedWorkflowRunner()+ with (+ patch.object(benchmark_workflow, "CASES_PER_RUN", 2),+ patch.object(benchmark_workflow.settings, "SESSION_REPLAY_TASK_QUEUE", render_queue),+ ):+ async with await WorkflowEnvironment.start_time_skipping(data_converter=pydantic_data_converter) as env:+ async with (+ Worker(+ env.client,+ task_queue=workflow_queue,+ workflows=[BuildBenchmarkWorkflow],+ activities=[snapshot, load, prepare, record, manifest],+ workflow_runner=runner,+ ),+ Worker(env.client, task_queue=render_queue, workflows=[_FakeRasterizeWorkflow], workflow_runner=runner),+ ):+ await env.client.execute_workflow(+ BUILD_BENCHMARK_WORKFLOW_NAME,+ BuildBenchmarkInputs(version="v1"),+ id=str(uuid.uuid4()),+ task_queue=workflow_queue,+ )++ by_case = {r.case_id: (r.outcome, r.reason) for r in recorded}+ assert by_case[CASE_IDS[0]] == ("built", None)+ assert by_case[CASE_IDS[1]][0] == "failed"+ # Skipped before rendering, and a recording production would gate as ineligible.+ assert by_case[CASE_IDS[2]] == ("skipped", "ineligible: too_short")+ assert by_case[CASE_IDS[3]] == ("skipped", "render: NO_SNAPSHOTS")+ # Built by an earlier run, so counted without a second render or record; a failed record fails one case.+ assert CASE_IDS[4] not in by_case and CASE_IDS[5] not in by_case+ assert [(m.case_count, m.built, m.failed, m.skipped) for m in manifests] == [(6, 2, 2, 2)]diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex e1afa5221f9c..8ff3b475d0a4 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1989,7 +1989,7 @@ class TestFetchSessionEventsActivity:"duration": 300,"active_seconds": 200,}- # Empty columns + no rows triggers `_fetch_payload` to return None.+ # Empty columns + no rows triggers `fetch_session_payload` to return None.mock_obj = self._make_session_replay_events_mock(metadata, [([], [])])with patch(diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 616f40bbd84e..89d082580f88 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -786,6 +786,8 @@ _POSTHOG_OWNED_BUCKET_SETTING_NAMES = ("OBJECT_STORAGE_BUCKET","OBJECT_STORAGE_EXTERNAL_WEB_ANALYTICS_BUCKET","QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET",+ # Holds decrypted recordings from many teams and may share a bucket the node role reads, so it is denied.+ "REPLAY_VISION_BENCHMARK_BUCKET","SESSION_RECORDING_V2_S3_BUCKET",)