Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ai-research): store fetched images raw for the v4 dataset (#117982)

Nicholas Waltz95f444156192
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-sink.ts
new file mode 100644
index 000000000000..1922ad21b318
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-sink.ts
@@ -0,0 +1,16 @@
+import type { FetchCandidate } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record'
+import type { ImageFetchResult } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
+
+/**
+ * Where the lane stores each fetched image. The image counts as handled only once the sink resolves: a rejection keeps
+ * the URL unfinished, so it is fetched again.
+ *
+ * S3 expires an object by its creation time, so the lane refreshes an image that went `refreshIntervalMs` without one,
+ * and the image lives as long as the data that references it.
+ */
+export interface RefreshingImageSink {
+ readonly refreshIntervalMs: number
+ publishImage(candidate: FetchCandidate, result: ImageFetchResult): Promise<void>
+ /** Resets the age of the stored image of a reference, with no origin request. Resolves to false if none is stored. */
+ refreshImage(candidate: FetchCandidate): Promise<boolean>
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.test.ts
new file mode 100644
index 000000000000..a32d12104549
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.test.ts
@@ -0,0 +1,117 @@
+import { brotliCompressSync, deflateSync, gzipSync, zstdCompressSync } from 'node:zlib'
+
+import {
+ MAX_UNCOMPRESSED_IMAGE_BYTES,
+ SUPPORTED_IMAGE_MEDIA_TYPES,
+ imageBytesMatchMediaType,
+ prepareFetchedImage,
+} from './image-transport'
+
+const AVIF_HEADER = Buffer.concat([
+ Buffer.from([0x00, 0x00, 0x00, 0x18]),
+ Buffer.from('ftypavif', 'ascii'),
+ Buffer.alloc(4),
+ Buffer.from('avifmif1', 'ascii'),
+])
+
+const imageHeaders = {
+ 'image/png': Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ 'image/jpeg': Buffer.from([0xff, 0xd8, 0xff, 0xe0]),
+ 'image/gif': Buffer.from('GIF89a', 'ascii'),
+ 'image/webp': Buffer.from('RIFF\x04\x00\x00\x00WEBP', 'binary'),
+} satisfies Record<(typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number], Buffer>
+
+describe('image transport', () => {
+ test.each(SUPPORTED_IMAGE_MEDIA_TYPES)('accepts %s bytes that match the Kafka content-type', (contentType) => {
+ expect(imageBytesMatchMediaType(imageHeaders[contentType], contentType)).toBe(true)
+ })
+
+ test.each([
+ ['gzip', gzipSync],
+ ['deflate', deflateSync],
+ ['br', brotliCompressSync],
+ ['zstd', zstdCompressSync],
+ ] as const)('decodes %s response bytes before validating the image', async (contentEncoding, compress) => {
+ const png = imageHeaders['image/png']
+
+ await expect(prepareFetchedImage(compress(png), 'image/png', contentEncoding)).resolves.toEqual(png)
+ })
+
+ it('decodes stacked content codings in reverse application order', async () => {
+ const png = imageHeaders['image/png']
+ const encoded = brotliCompressSync(gzipSync(png))
+
+ await expect(prepareFetchedImage(encoded, 'image/png', 'gzip, br')).resolves.toEqual(png)
+ })
+
+ it('rejects more than four content coding layers', async () => {
+ await expect(
+ prepareFetchedImage(
+ imageHeaders['image/png'],
+ 'image/png',
+ 'identity, identity, identity, identity, identity'
+ )
+ ).rejects.toMatchObject({
+ reason: 'content_encoding_too_deep',
+ message: 'content-encoding exceeds 4 codings',
+ })
+ })
+
+ it('stops decompression when the decoded bytes cross the 20 MiB cap', async () => {
+ const compressed = gzipSync(Buffer.alloc(MAX_UNCOMPRESSED_IMAGE_BYTES + 1))
+
+ await expect(prepareFetchedImage(compressed, 'image/png', 'gzip')).rejects.toMatchObject({
+ reason: 'decoded_too_large',
+ message: `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`,
+ })
+ })
+
+ it.each([
+ ['an unsupported content coding', imageHeaders['image/png'], 'compress', 'unsupported_content_encoding'],
+ ['a malformed content coding list', imageHeaders['image/png'], 'gzip,', 'malformed_content_encoding'],
+ ['compressed bytes that are malformed', Buffer.from('not gzip'), 'gzip', 'decompression_failed'],
+ ] as const)('labels %s', async (_case, bytes, contentEncoding, reason) => {
+ await expect(prepareFetchedImage(bytes, 'image/png', contentEncoding)).rejects.toMatchObject({ reason })
+ })
+
+ // A truncated body would otherwise store the prefix of an image, which still starts with a valid signature.
+ test.each([
+ ['gzip', gzipSync],
+ ['deflate', deflateSync],
+ ['br', brotliCompressSync],
+ ['zstd', zstdCompressSync],
+ ] as const)('rejects a %s body cut short', async (contentEncoding, compress) => {
+ const png = Buffer.concat([imageHeaders['image/png'], Buffer.from('png body '.repeat(8))])
+ const compressed = compress(png)
+
+ for (const length of [compressed.length - 1, Math.floor(compressed.length / 2)]) {
+ await expect(
+ prepareFetchedImage(compressed.subarray(0, length), 'image/png', contentEncoding)
+ ).rejects.toMatchObject({ reason: 'decompression_failed' })
+ }
+ })
+
+ it('rejects a zstd body with a second frame, which the decoder would drop', async () => {
+ const png = imageHeaders['image/png']
+ const encoded = Buffer.concat([zstdCompressSync(png), zstdCompressSync(Buffer.from('tail'))])
+
+ await expect(prepareFetchedImage(encoded, 'image/png', 'zstd')).rejects.toMatchObject({
+ reason: 'decompression_failed',
+ })
+ })
+
+ it('rejects bytes that do not match the declared media type', async () => {
+ await expect(prepareFetchedImage(imageHeaders['image/jpeg'], 'image/png', undefined)).rejects.toMatchObject({
+ reason: 'content_type_mismatch',
+ message: 'image bytes do not match content-type image/png',
+ })
+ })
+
+ it.each([
+ ['a missing content-type', imageHeaders['image/png'], undefined, 'missing_content_type'],
+ ['a BMP content-type', Buffer.from('BM', 'ascii'), 'image/bmp', 'unsupported_content_type'],
+ ['an AVIF content-type', AVIF_HEADER, 'image/avif', 'unsupported_content_type'],
+ ] as const)('labels %s', async (_case, bytes, contentType, reason) => {
+ await expect(prepareFetchedImage(bytes, contentType, undefined)).rejects.toMatchObject({ reason })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.ts
new file mode 100644
index 000000000000..f99df31d18b3
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-transport.ts
@@ -0,0 +1,185 @@
+import { Readable, Transform } from 'node:stream'
+import { createBrotliDecompress, createGunzip, createInflate, createZstdDecompress } from 'node:zlib'
+
+export const MAX_UNCOMPRESSED_IMAGE_BYTES = 20 * 1024 * 1024
+export const CONTENT_TYPE_HEADER = 'content-type'
+export const CONTENT_ENCODING_HEADER = 'content-encoding'
+
+const MAX_CONTENT_ENCODING_LAYERS = 4
+
+export const SUPPORTED_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const
+
+export type SupportedImageMediaType = (typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number]
+
+export type ImageTransportRejectionReason =
+ | 'content_encoding_too_deep'
+ | 'malformed_content_encoding'
+ | 'unsupported_content_encoding'
+ | 'decompression_failed'
+ | 'decoded_too_large'
+ | 'missing_content_type'
+ | 'unsupported_content_type'
+ | 'content_type_mismatch'
+
+export class InvalidImageTransportError extends Error {
+ public constructor(
+ public readonly reason: ImageTransportRejectionReason,
+ message: string
+ ) {
+ super(message)
+ }
+}
+
+const decoderFactories: Record<string, () => Transform> = {
+ gzip: createGunzip,
+ deflate: createInflate,
+ br: createBrotliDecompress,
+ zstd: createZstdDecompress,
+}
+
+function parseContentEncodings(contentEncoding: string | undefined): string[] {
+ if (contentEncoding === undefined) {
+ return []
+ }
+ const encodings = contentEncoding.split(',').map((encoding) => encoding.trim().toLowerCase())
+ if (encodings.length > MAX_CONTENT_ENCODING_LAYERS) {
+ throw new InvalidImageTransportError(
+ 'content_encoding_too_deep',
+ `content-encoding exceeds ${MAX_CONTENT_ENCODING_LAYERS} codings`
+ )
+ }
+ if (encodings.some((encoding) => encoding.length === 0)) {
+ throw new InvalidImageTransportError('malformed_content_encoding', 'content-encoding contains an empty coding')
+ }
+ return encodings.filter((encoding) => encoding !== 'identity')
+}
+
+const ZSTD_FRAME_MAGIC = 0xfd2fb528
+
+/**
+ * Node's zstd decoder ends without an error on a truncated frame, and it drops every frame after the first. Both give a
+ * prefix of the image. So this walks the frame and block headers of RFC 8878 and accepts exactly one frame that ends
+ * at the last byte, as the Rust recorder's `unzstd` does.
+ */
+function isSingleCompleteZstdFrame(bytes: Buffer): boolean {
+ if (bytes.length < 5 || bytes.readUInt32LE(0) !== ZSTD_FRAME_MAGIC) {
+ return false
+ }
+ const descriptor = bytes[4]
+ const singleSegment = (descriptor & 0x20) !== 0
+ const contentSizeFlag = descriptor >> 6
+ const windowBytes = singleSegment ? 0 : 1
+ const dictionaryBytes = [0, 1, 2, 4][descriptor & 0x03]
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 2 ** contentSizeFlag
+ let offset = 5 + windowBytes + dictionaryBytes + contentSizeBytes
+ for (let last = false; !last; ) {
+ if (offset + 3 > bytes.length) {
+ return false
+ }
+ const header = bytes.readUIntLE(offset, 3)
+ offset += 3
+ last = (header & 1) === 1
+ const blockType = (header >> 1) & 3
+ if (blockType === 3) {
+ return false
+ }
+ // An RLE block stores one byte however long its output is.
+ offset += blockType === 1 ? 1 : header >>> 3
+ }
+ offset += (descriptor & 0x04) !== 0 ? 4 : 0
+ return offset === bytes.length
+}
+
+async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer> {
+ const decoderFactory = decoderFactories[encoding]
+ if (!decoderFactory) {
+ throw new InvalidImageTransportError(
+ 'unsupported_content_encoding',
+ `unsupported content-encoding: ${encoding}`
+ )
+ }
+ if (encoding === 'zstd' && !isSingleCompleteZstdFrame(bytes)) {
+ throw new InvalidImageTransportError('decompression_failed', 'invalid zstd content: not one complete frame')
+ }
+
+ const input = Readable.from([bytes])
+ const decoder = decoderFactory()
+ const chunks: Buffer[] = []
+ let outputBytes = 0
+ input.pipe(decoder)
+
+ try {
+ for await (const chunk of decoder) {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ if (outputBytes + buffer.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {
+ throw new InvalidImageTransportError(
+ 'decoded_too_large',
+ `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`
+ )
+ }
+ chunks.push(buffer)
+ outputBytes += buffer.length
+ }
+ } catch (error) {
+ if (error instanceof InvalidImageTransportError) {
+ throw error
+ }
+ throw new InvalidImageTransportError('decompression_failed', `invalid ${encoding} content: ${String(error)}`)
+ } finally {
+ input.destroy()
+ decoder.destroy()
+ }
+
+ return Buffer.concat(chunks, outputBytes)
+}
+
+export function isSupportedImageMediaType(contentType: string): contentType is SupportedImageMediaType {
+ return SUPPORTED_IMAGE_MEDIA_TYPES.includes(contentType as SupportedImageMediaType)
+}
+
+export function imageBytesMatchMediaType(bytes: Buffer, contentType: SupportedImageMediaType): boolean {
+ switch (contentType) {
+ case 'image/png':
+ return bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
+ case 'image/jpeg':
+ return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
+ case 'image/gif': {
+ const signature = bytes.toString('ascii', 0, 6)
+ return signature === 'GIF87a' || signature === 'GIF89a'
+ }
+ case 'image/webp':
+ return bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'
+ }
+}
+
+export async function prepareFetchedImage(
+ bytes: Buffer,
+ contentType: string | undefined,
+ contentEncoding: string | undefined
+): Promise<Buffer> {
+ if (!contentType) {
+ throw new InvalidImageTransportError('missing_content_type', 'unsupported content-type: missing')
+ }
+ if (!isSupportedImageMediaType(contentType)) {
+ throw new InvalidImageTransportError('unsupported_content_type', `unsupported content-type: ${contentType}`)
+ }
+ if (bytes.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {
+ throw new InvalidImageTransportError(
+ 'decoded_too_large',
+ `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`
+ )
+ }
+
+ let decoded = bytes
+ const encodings = parseContentEncodings(contentEncoding)
+ for (const encoding of encodings.reverse()) {
+ decoded = await decodeWithLimit(decoded, encoding)
+ }
+ if (!imageBytesMatchMediaType(decoded, contentType)) {
+ throw new InvalidImageTransportError(
+ 'content_type_mismatch',
+ `image bytes do not match content-type ${contentType}`
+ )
+ }
+ return decoded
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.test.ts
new file mode 100644
index 000000000000..df7eaff8910c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.test.ts
@@ -0,0 +1,139 @@
+import { CopyObjectCommand, PutObjectCommand, S3ServiceException } from '@aws-sdk/client-s3'
+import { createDecipheriv } from 'node:crypto'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import type { TeamMonthKey } from '~/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys'
+import type { FetchCandidate } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record'
+import type { ImageFetchResult } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
+
+import { RawImageStore } from './raw-image-store'
+
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from('png body')])
+const REF = 'imageurl:v4:7:2026-10:abcdefghijklmnopqrstuv'
+const KEY = Buffer.alloc(32, 9)
+const STORED: TeamMonthKey = { status: 'ok', key: KEY }
+
+function open(frame: Buffer): { aad: any; body: Buffer } {
+ const length = frame.readUInt16BE(6)
+ const aad = frame.subarray(8, 8 + length)
+ const nonce = frame.subarray(8 + length, 20 + length)
+ const sealed = frame.subarray(20 + length)
+ const decipher = createDecipheriv('aes-256-gcm', KEY, nonce, { authTagLength: 16 })
+ decipher.setAAD(aad)
+ decipher.setAuthTag(sealed.subarray(sealed.length - 16))
+ const body = Buffer.concat([decipher.update(sealed.subarray(0, sealed.length - 16)), decipher.final()])
+ return { aad: parseJSON(aad.toString()), body }
+}
+
+const NOT_FOUND = new S3ServiceException({ name: 'NoSuchKey', $fault: 'client', $metadata: { httpStatusCode: 404 } })
+
+function store(key: TeamMonthKey, s3Error?: Error) {
+ const puts: (PutObjectCommand | CopyObjectCommand)[] = []
+ const s3 = {
+ send: jest.fn((command: PutObjectCommand | CopyObjectCommand) => {
+ puts.push(command)
+ return s3Error ? Promise.reject(s3Error) : Promise.resolve({})
+ }),
+ }
+ return { sink: new RawImageStore({ get: () => Promise.resolve(key) }, s3 as any, 'images-v4', 10), puts }
+}
+
+const IMAGE_URL = 'https://images.example.com/logo.png'
+
+const candidate = (ref = REF): FetchCandidate => ({
+ originalRef: ref,
+ currentUrl: IMAGE_URL,
+ host: 'images.example.com',
+ origin: 'https://images.example.com',
+ registrableDomain: 'example.com',
+ remainingHops: 10,
+ notBeforeMs: 0,
+ firstSeenAtMs: 0,
+ fetchCount: 0,
+ republishCount: 0,
+ lastRepublishReason: null,
+})
+const fetched = (bytes = PNG): ImageFetchResult => ({
+ outcome: 'ok',
+ redirects: 0,
+ currentUrl: IMAGE_URL,
+ status: 200,
+ bytes,
+ contentType: 'image/png',
+})
+
+describe('RawImageStore', () => {
+ it('stores the image sealed under its team month key, over any earlier object of its reference', async () => {
+ const { sink, puts } = store(STORED)
+ await sink.publishImage(candidate(), fetched())
+
+ expect(puts).toHaveLength(1)
+ expect(puts[0]).toBeInstanceOf(PutObjectCommand)
+ const { Bucket, Key, IfNoneMatch, Body, ContentType } = (puts[0] as PutObjectCommand).input
+ expect([Bucket, Key, IfNoneMatch]).toEqual([
+ 'images-v4',
+ 'images/url/month=2026-10/7/abcdefghijklmnopqrstuv',
+ undefined,
+ ])
+ const { aad, body } = open(Body as Buffer)
+ expect(body).toEqual(PNG)
+ expect(aad).toEqual({
+ v: 4,
+ context: { teamId: 7, keyMonth: '2026-10', kind: 'image-url', codec: 'none', ref: REF },
+ })
+
+ // The refresh copies the object onto itself, which resets the creation time the lifecycle counts from.
+ await expect(sink.refreshImage(candidate())).resolves.toBe(true)
+ expect(puts[1]).toBeInstanceOf(CopyObjectCommand)
+ expect((puts[1] as CopyObjectCommand).input).toEqual({
+ Bucket,
+ Key,
+ CopySource: 'images-v4/images/url/month%3D2026-10/7/abcdefghijklmnopqrstuv',
+ MetadataDirective: 'REPLACE',
+ ContentType,
+ })
+ })
+
+ it('resolves to false when it refreshes a reference that has no object', async () => {
+ const { sink, puts } = store(STORED, NOT_FOUND)
+ await expect(sink.refreshImage(candidate())).resolves.toBe(false)
+ expect(puts).toHaveLength(1)
+ })
+
+ it.each([
+ ['a tombstoned team month', { status: 'deleted' }, candidate(), fetched()],
+ ['a team month without a key row', { status: 'missing' }, candidate(), fetched()],
+ ['a body that is not the image it claims to be', STORED, candidate(), fetched(Buffer.from('<html>'))],
+ [
+ 'a reference from another dataset',
+ STORED,
+ candidate('imageurl:v3:7:2026-10:abcdefghijklmnopqrstuv'),
+ fetched(),
+ ],
+ ] as const)('resolves without a new object for %s', async (_name, key, job, result) => {
+ const { sink, puts } = store(key)
+ await expect(sink.publishImage(job, result)).resolves.toBeUndefined()
+ expect(puts).toHaveLength(0)
+ })
+
+ it('holds a further image back while the write limit is full, so a slow S3 does not pile up images in memory', async () => {
+ let finishWrite!: () => void
+ const s3 = {
+ send: jest.fn(() => new Promise((resolve) => (finishWrite = () => resolve({})))),
+ }
+ const keyReads = jest.fn(() => Promise.resolve(STORED))
+ const sink = new RawImageStore({ get: keyReads }, s3 as any, 'images-v4', 1)
+
+ const first = sink.publishImage(candidate(), fetched())
+ const second = sink.publishImage(candidate(), fetched())
+ await new Promise((resolve) => setImmediate(resolve))
+ expect([s3.send.mock.calls.length, keyReads.mock.calls.length]).toEqual([1, 1])
+
+ finishWrite()
+ await first
+ await new Promise((resolve) => setImmediate(resolve))
+ finishWrite()
+ await second
+ expect(s3.send).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.ts
new file mode 100644
index 000000000000..d5d3cd670f89
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/raw-image-store.ts
@@ -0,0 +1,148 @@
+import { CopyObjectCommand, PutObjectCommand, S3Client, S3ServiceException } from '@aws-sdk/client-s3'
+import { Counter } from 'prom-client'
+
+import { ConcurrencyController } from '~/common/utils/concurrencyController'
+import { sealV4Frame } from '~/ingestion/pipelines/sessionreplay/ai-research/v4-keys/frame'
+import type { TeamMonthKeys } from '~/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys'
+import type { FetchCandidate } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record'
+import type { ImageFetchResult } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
+import { ImageFetchProcessingMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/processing-metrics'
+
+import type { RefreshingImageSink } from './image-sink'
+import { InvalidImageTransportError, prepareFetchedImage } from './image-transport'
+import { parseV4UrlRef } from './v4-url-ref'
+
+const S3_WRITE_TIMEOUT_MS = 30_000
+/** The `images-v4` lifecycle is 98 days: the 90-day raw window plus this interval and one day. */
+const REFRESH_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000
+const CONTENT_TYPE = 'application/octet-stream'
+
+const storedImages = new Counter({
+ name: 'ai_research_v4_image_fetch_stored_images_total',
+ help: 'Fetched images the v4 lane handled, by outcome.',
+ labelNames: ['outcome'],
+})
+
+/**
+ * Stores each fetched image sealed and unscrubbed in `images-v4`, under the team month key of its reference. The v4
+ * dataset is anonymized downstream, so unlike the v3 lane this sink never sends an image to the scrub lane.
+ *
+ * S3 expires an object by its creation time, and blocks that reference an image are written all month. So a new fetch
+ * overwrites the object of its reference, and `refreshImage` copies it onto itself to reset its age.
+ */
+export class RawImageStore implements RefreshingImageSink {
+ public readonly refreshIntervalMs = REFRESH_INTERVAL_MS
+ private readonly writes: ConcurrencyController
+
+ constructor(
+ private readonly keys: Pick<TeamMonthKeys, 'get'>,
+ private readonly s3: Pick<S3Client, 'send'>,
+ private readonly bucket: string,
+ maxConcurrentWrites: number
+ ) {
+ if (!Number.isInteger(maxConcurrentWrites) || maxConcurrentWrites < 1) {
+ throw new Error('the v4 image store needs a positive write limit')
+ }
+ this.writes = new ConcurrencyController(maxConcurrentWrites)
+ }
+
+ /** Bounds images held in memory while S3 is slow. */
+ public async publishImage(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {
+ await ImageFetchProcessingMetrics.runLimited(this.writes, 'image_publish_admission', 'image_publish_delivery', {
+ debugTag: candidate.registrableDomain,
+ fn: () => this.store(candidate, result),
+ })
+ }
+
+ public async refreshImage(candidate: FetchCandidate): Promise<boolean> {
+ const ref = parseV4UrlRef(candidate.originalRef)
+ if (!ref) {
+ storedImages.labels('foreign_ref').inc()
+ return false
+ }
+ return await ImageFetchProcessingMetrics.runLimited(
+ this.writes,
+ 'image_publish_admission',
+ 'image_publish_delivery',
+ {
+ debugTag: candidate.registrableDomain,
+ fn: () => this.copyOntoItself(imageObjectKey(ref)),
+ }
+ )
+ }
+
+ private async copyOntoItself(objectKey: string): Promise<boolean> {
+ try {
+ await this.s3.send(
+ new CopyObjectCommand({
+ Bucket: this.bucket,
+ Key: objectKey,
+ // S3 URL-decodes CopySource (unlike Key), so path segments must be percent-encoded.
+ CopySource: `${this.bucket}/${objectKey.split('/').map(encodeURIComponent).join('/')}`,
+ MetadataDirective: 'REPLACE',
+ ContentType: CONTENT_TYPE,
+ }),
+ { abortSignal: AbortSignal.timeout(S3_WRITE_TIMEOUT_MS) }
+ )
+ } catch (error) {
+ // The fetch stored nothing for this reference, for example because the body was not an image.
+ if (error instanceof S3ServiceException && error.$metadata.httpStatusCode === 404) {
+ storedImages.labels('refresh_not_stored').inc()
+ return false
+ }
+ throw error
+ }
+ storedImages.labels('refreshed').inc()
+ return true
+ }
+
+ private async store(candidate: FetchCandidate, result: ImageFetchResult): Promise<void> {
+ const ref = parseV4UrlRef(candidate.originalRef)
+ // A throw keeps the URL unfinished, and these inputs come back the same on every fetch.
+ if (!ref) {
+ storedImages.labels('foreign_ref').inc()
+ return
+ }
+ if (!result.bytes) {
+ storedImages.labels('invalid').inc()
+ return
+ }
+ const { teamId, keyMonth } = ref
+ let image: Buffer
+ try {
+ image = await prepareFetchedImage(result.bytes, result.contentType, result.contentEncoding)
+ } catch (error) {
+ // A body that is not the image it claims to be is handled: fetching it again returns the same body.
+ if (error instanceof InvalidImageTransportError) {
+ storedImages.labels('invalid').inc()
+ return
+ }
+ throw error
+ }
+ const key = await this.keys.get(teamId, keyMonth)
+ if (key.status !== 'ok') {
+ storedImages.labels(key.status === 'deleted' ? 'deleted' : 'missing_key').inc()
+ return
+ }
+ const frame = sealV4Frame(
+ key.key,
+ { teamId, keyMonth, kind: 'image-url', codec: 'none', ref: candidate.originalRef },
+ image
+ )
+ await this.s3.send(
+ new PutObjectCommand({
+ Bucket: this.bucket,
+ Key: imageObjectKey(ref),
+ Body: frame,
+ ContentType: CONTENT_TYPE,
+ }),
+ { abortSignal: AbortSignal.timeout(S3_WRITE_TIMEOUT_MS) }
+ )
+ storedImages.labels('stored').inc()
+ }
+}
+
+/** One object per reference. The month is the reference's key month, not the day it was fetched. */
+function imageObjectKey(ref: { teamId: number; keyMonth: string; hash: string }): string {
+ return `images/url/month=${ref.keyMonth}/${ref.teamId}/${ref.hash}`
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.test.ts
new file mode 100644
index 000000000000..f51c2c2bb368
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.test.ts
@@ -0,0 +1,23 @@
+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'
+
+import { parseV4UrlRef } from './v4-url-ref'
+
+describe('parseV4UrlRef', () => {
+ const hash = 'a'.repeat(22)
+
+ it('parses a month-scoped v4 URL ref that no v2 or v3 reader takes', () => {
+ const ref = `imageurl:v4:7:2026-10:${hash}`
+ expect(parseV4UrlRef(ref)).toEqual({ teamId: 7, keyMonth: '2026-10', hash })
+ expect(parseImageRef(ref)).toBeNull()
+ })
+
+ it.each([
+ ['a v3 ref', `imageurl:v3:7:2026-10:${hash}`],
+ ['a content ref', `image:v4:7:2026-10:${hash}`],
+ ['a month that does not exist', `imageurl:v4:7:2026-13:${hash}`],
+ ['a day-scoped ref', `imageurl:v4:7:2026-10-15:${hash}`],
+ ['a team id of zero', `imageurl:v4:0:2026-10:${hash}`],
+ ])('refuses %s', (_name, ref) => {
+ expect(parseV4UrlRef(ref)).toBeNull()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.ts
new file mode 100644
index 000000000000..059f79f02b38
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/v4-url-ref.ts
@@ -0,0 +1,14 @@
+/** Image URL references of the v4 dataset. */
+
+function isRawTeamId(value: unknown): boolean {
+ return typeof value === 'string' && /^[1-9][0-9]{0,15}$/.test(value) && Number.isSafeInteger(Number(value))
+}
+
+/** Parses `imageurl:v4:{team}:{YYYY-MM}:{hash}`. `parseImageRef` refuses it, so no v2 or v3 reader takes one. */
+export function parseV4UrlRef(s: string): { teamId: number; keyMonth: string; hash: string } | null {
+ const match = /^imageurl:v4:([1-9][0-9]{0,15}):([0-9]{4}-(?:0[1-9]|1[0-2])):([A-Za-z0-9_-]{22})$/.exec(s)
+ if (!match || !isRawTeamId(match[1])) {
+ return null
+ }
+ return { teamId: Number(match[1]), keyMonth: match[2], hash: match[3] }
+}