: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(ai-research-v4): store remote svg images in the v4 fetcher (#124849)
Nicholas Waltz9d0e42969759
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.test.tsindex aac181b2bc1f..a4b51491583f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.test.ts@@ -154,7 +154,7 @@ describe('HttpImageFetcher', () => {it.each([['a type that is not an image', 'text/html', PNG, 'not_image'],- ['a type outside the raster set', 'image/svg+xml', PNG, 'not_image'],+ ['an SVG, which the store validates as a document', 'image/svg+xml', PNG, 'ok'],['the BMP format', 'image/bmp', Buffer.from('BM'), 'not_image'],['the AVIF format', 'image/avif', Buffer.from('\x00\x00\x00\x18ftypavif', 'binary'), 'not_image'],['a payload that is not the declared format', 'image/gif', PNG, 'ok'],diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.tsindex 573b510d783c..aa42c215544b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/image-fetch-v4/image-fetcher.ts@@ -9,15 +9,13 @@ import { REQUEST_IDENTITY_HEADERS } from './request-identity'import { WebBotAuthRequestSigner } from './web-bot-auth'/**- * The raster formats that the fetch lane accepts.+ * The formats that the fetch lane accepts. The store keeps the bytes as fetched, so an SVG stays an SVG document. An SVG+ * is text that can carry the page's own data, and redaction downstream of the dataset handles it.*- * SVG is absent on purpose. It is a text format that can carry the page's own data, so its redaction- * belongs on the inline path rather than on an image model.- *- * AVIF is absent because the image store validates only PNG, JPEG, GIF and WebP bytes+ * AVIF is absent because the image store validates only the formats in `SUPPORTED_IMAGE_MEDIA_TYPES`* (`image-transport.ts`), so it would reject every AVIF image that this lane fetched.*/-const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] as const+const ALLOWED_CONTENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml'] as constexport type ImageContentType = (typeof ALLOWED_CONTENT_TYPES)[number]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.tsindex a32d12104549..3dd9efcdefa5 100644--- 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@@ -19,6 +19,7 @@ const imageHeaders = {'image/jpeg': Buffer.from([0xff, 0xd8, 0xff, 0xe0]),'image/gif': Buffer.from('GIF89a', 'ascii'),'image/webp': Buffer.from('RIFF\x04\x00\x00\x00WEBP', 'binary'),+ 'image/svg+xml': Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>', 'utf8'),} satisfies Record<(typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number], Buffer>describe('image transport', () => {@@ -26,6 +27,34 @@ describe('image transport', () => {expect(imageBytesMatchMediaType(imageHeaders[contentType], contentType)).toBe(true)})+ const utf16 = (text: string, bigEndian: boolean): Buffer => {+ const body = Buffer.from(text, 'utf16le')+ return Buffer.concat([Buffer.from(bigEndian ? [0xfe, 0xff] : [0xff, 0xfe]), bigEndian ? body.swap16() : body])+ }+ const W3C_DOCTYPE =+ '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'++ test.each([+ ['a prolog before the root', `\uFEFF<?xml version="1.0"?>\n<!-- icon -->\n${W3C_DOCTYPE}\n<svg>`, true],+ ['a UTF-16LE document', utf16('<?xml version="1.0" encoding="UTF-16"?><svg/>', false), true],+ ['a UTF-16BE document', utf16('<svg/>', true), true],+ ['a prefixed root bound to the SVG namespace', '<s:svg xmlns:s="http://www.w3.org/2000/svg"/>', true],+ ['a prefixed root bound to another namespace', '<s:svg xmlns:s="http://example.com/ns"/>', false],+ ['an HTML page', '<!DOCTYPE html><html><svg></svg></html>', false],+ ['a root that only starts with svg', '<svgx/>', false],+ ['an unclosed comment', '<!-- <svg/>', false],+ ['a doctype with an internal subset', '<!DOCTYPE svg [<!ENTITY a "b">]><svg/>', false],+ [+ 'a quoted literal that hides a subset',+ '<!DOCTYPE svg SYSTEM "><svg " [<!ENTITY x "s">]><svg>&x;</svg>',+ false,+ ],+ ['a doctype that names another DTD', '<!DOCTYPE svg SYSTEM "https://example.com/evil.dtd"><svg/>', false],+ ])('reads %s as SVG or not', (_case, document, isSvg) => {+ const bytes = typeof document === 'string' ? Buffer.from(document, 'utf8') : document+ expect(imageBytesMatchMediaType(bytes, 'image/svg+xml')).toBe(isSvg)+ })+test.each([['gzip', gzipSync],['deflate', deflateSync],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.tsindex f99df31d18b3..adf3d0641a5c 100644--- 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@@ -7,7 +7,14 @@ 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+/** Keep in step with `FETCHED_IMAGE_TYPES` in `replay-core-v4/src/url_policy.rs`, which tells the recorder what this lane stores. */+export const SUPPORTED_IMAGE_MEDIA_TYPES = [+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ 'image/svg+xml',+] as constexport type SupportedImageMediaType = (typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number]@@ -149,9 +156,85 @@ export function imageBytesMatchMediaType(bytes: Buffer, contentType: SupportedIm}case 'image/webp':return bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP'+ case 'image/svg+xml':+ return isSvgDocument(bytes)}}+/** A prolog longer than this is not read, so a body of comments cannot make the check scan the whole image. */+const MAX_SVG_PROLOG_BYTES = 64 * 1024++/** The DTDs the W3C publishes for SVG. A doctype may name one of them, which many editors write, and no other. */+const W3C_SVG_DTD = /^https?:\/\/www\.w3\.org\/Graphics\/SVG\/1\.[01]\/DTD\/svg1[01](?:-(?:tiny|basic))?\.dtd$/++/**+ * A doctype with no internal subset, and at most an external identifier whose system literal is a W3C SVG DTD. The+ * literals match as whole tokens, so a `>` or `<svg` inside one cannot end the doctype or pass as the root.+ */+const SVG_DOCTYPE =+ /^<!DOCTYPE\s+[^\s>[]+(?:\s+(?:SYSTEM\s+("[^"]*"|'[^']*')|PUBLIC\s+(?:"[^"]*"|'[^']*')\s+("[^"]*"|'[^']*')))?\s*>/++/** The prolog and root as text, in the encoding a byte order mark names. The stored bytes stay as fetched. */+function svgHead(bytes: Buffer): string {+ const head = bytes.subarray(0, MAX_SVG_PROLOG_BYTES)+ if (head[0] === 0xff && head[1] === 0xfe) {+ return head.subarray(2).toString('utf16le')+ }+ if (head[0] === 0xfe && head[1] === 0xff) {+ const body = Buffer.from(head.subarray(2, 2 + ((head.length - 2) & ~1)))+ return body.swap16().toString('utf16le')+ }+ return head.toString('utf8').replace(/^\uFEFF/, '')+}++/**+ * Whether the bytes are an XML document with an SVG root. SVG has no signature, so the check skips what may come+ * before the root: a byte order mark, whitespace, the XML declaration and other processing instructions, comments and+ * one doctype of the shape `SVG_DOCTYPE` allows, because a parser downstream could resolve the entities of any other.+ * A prefixed root must bind its prefix to the SVG namespace.+ */+function isSvgDocument(bytes: Buffer): boolean {+ const text = svgHead(bytes)+ let position = 0+ for (;;) {+ while (position < text.length && /\s/.test(text[position])) {+ position+++ }+ if (text.startsWith('<!DOCTYPE', position)) {+ const doctype = SVG_DOCTYPE.exec(text.slice(position))+ const system = (doctype?.[1] ?? doctype?.[2])?.slice(1, -1)+ if (!doctype || (system !== undefined && !W3C_SVG_DTD.test(system))) {+ return false+ }+ position += doctype[0].length+ continue+ }+ const skipped = [+ ['<?', '?>'],+ ['<!--', '-->'],+ ].find(([open]) => text.startsWith(open, position))+ if (!skipped) {+ break+ }+ const end = text.indexOf(skipped[1], position + skipped[0].length)+ if (end < 0) {+ return false+ }+ position = end + skipped[1].length+ }+ const root = /^<(?:([A-Za-z_][\w.-]*):)?svg[\s/>]/.exec(text.slice(position, position + 256))+ if (!root) {+ return false+ }+ if (root[1] === undefined) {+ return true+ }+ const tagEnd = text.indexOf('>', position)+ const tag = text.slice(position, tagEnd < 0 ? undefined : tagEnd)+ const prefix = root[1].replace(/[.-]/g, '\\$&')+ return new RegExp(`\\sxmlns:${prefix}\\s*=\\s*["']http://www\\.w3\\.org/2000/svg["']`).test(tag)+}+export async function prepareFetchedImage(bytes: Buffer,contentType: string | undefined,diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.mdindex 2202acd7b70d..fcc93e201614 100644--- a/products/ai_training/docs/replay-data.md+++ b/products/ai_training/docs/replay-data.md@@ -578,6 +578,8 @@ The topics hold jobs for 24 hours, because jobs carry raw URLs.The v4 image fetcher is its own copy of the v3 fetcher under `ai-research/image-fetch-v4/`, with the v3 fetch policy, its own consumer groups, its own `AI_RESEARCH_V4_IMAGE_FETCH_*` settings and a share of the v3 per-host limits. It shares no code or table with v3.It applies the recorder's URL policy through `@posthog/ai-research-v4-native`, an addon over `replay_core_v4::url_policy`, so it canonicalizes a URL, groups it by registrable domain and refuses private hosts exactly as the recorder does.It stores each image, sealed and unscrubbed, under `images/url/`, and it does not send images to the scrub lane.+It stores PNG, JPEG, GIF, WebP and SVG as fetched. It does not rasterize an SVG; redaction downstream of the dataset handles SVG text.+The response must have one of these media types and bytes of that format: a signature for a raster image, or an SVG root element for SVG. An SVG may carry a byte order mark, comments, processing instructions and a doctype before its root. The doctype may name no internal subset and no external DTD other than a W3C SVG DTD, so that a parser downstream cannot resolve entities from the document. It refuses AVIF and every other type.The fetcher keeps a crawl history per URL reference, so per team and month, in its own DynamoDB table `ai-research-v4-image-fetch-history`, with the v3 fetch interval and conditional requests. The table also holds its robots.txt and tdmrep cache:diff --git a/rust/ai-research/replay-core-v4/src/url_policy.rs b/rust/ai-research/replay-core-v4/src/url_policy.rsindex f39f95ba33fc..fe0fe5495a5f 100644--- a/rust/ai-research/replay-core-v4/src/url_policy.rs+++ b/rust/ai-research/replay-core-v4/src/url_policy.rs@@ -363,7 +363,13 @@ pub fn is_remote(url: &str) -> bool {}/// The media types the image fetcher stores, the `ALLOWED_CONTENT_TYPES` of `image-fetch-v4/image-fetcher.ts`.-pub const FETCHED_IMAGE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];+pub const FETCHED_IMAGE_TYPES: [&str; 5] = [+ "image/png",+ "image/jpeg",+ "image/gif",+ "image/webp",+ "image/svg+xml",+];/// Whether a `<source type>` names a type the fetcher stores, ignoring parameters such as `codecs`.pub fn is_fetched_image_type(source_type: &str) -> bool {diff --git a/rust/ai-research/replay-recorder-v4/src/write.rs b/rust/ai-research/replay-recorder-v4/src/write.rsindex 451a16ce382b..cd5932694044 100644--- a/rust/ai-research/replay-recorder-v4/src/write.rs+++ b/rust/ai-research/replay-recorder-v4/src/write.rs@@ -805,15 +805,17 @@ mod tests {"https://cdn.example.com/a.png",);let source = |id: i64, attributes: serde_json::Value| json!({"type": 2, "tagName": "source", "attributes": attributes, "childNodes": [], "id": id});- // The scan leaves an SVG inline, so the browser can load it from the block.let (bare, typeless) = ("https://cdn.example.com/b.avif","https://cdn.example.com/c.webp",);+ // The scan leaves an SVG inline, so the browser can load it from the block. The fetcher stores a remote SVG.let svg ="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%2F%3E";+ let remote_svg = "https://cdn.example.com/a.svg";let picture = json!({"type": 2, "tagName": "picture", "attributes": {}, "id": 2, "childNodes": [source(6, json!({"type": "image/svg+xml", "srcset": format!("{svg} 1x")})),+ source(7, json!({"type": "image/svg+xml", "srcset": format!("{remote_svg} 1x")})),source(3, json!({"type": "image/avif", "srcset": format!("{avif} 1x")})),// A bare srcset equal to the img's src below: only the srcset empties.source(8, json!({"type": "image/avif", "srcset": bare})),@@ -851,6 +853,10 @@ mod tests {lines.contains(&format!(r#""srcset":"{svg} 1x""#)),"{lines}");+ assert!(+ lines.contains(&format!(r#""srcset":"{} 1x""#, reference(remote_svg))),+ "{lines}"+ );assert!(lines.contains(&format!(r#""srcset":"{} 1x""#, reference(webp))),"{lines}"