: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
test(replay): add the harnesses the scrub's constants were measured with (#73722)
Robbie545e844b9702
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.tsnew file mode 100644index 000000000000..9783a9686d04--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts@@ -0,0 +1,141 @@+/* eslint-disable no-console -- CLI output script: console output is the whole point */+/**+ * Detection floors for faces and codes, against the floor at which each still carries information in+ * the stored artifact. The text version of this lives in glyph-floor.ts; the same question has to be+ * asked separately for each detector, because their inputs are sized on different rules: DBNet scales+ * with the frame, YuNet letterboxes into a fixed 640 square, and zxing works on the frame directly.+ *+ * For each subject size it reports two things:+ * detected – the production detector finds it at the detection resolution+ * survives – the same subject is still machine-recoverable from the downscaled artifact+ *+ * `survives` is the attacker's side of the trade. For codes it is exact: zxing either decodes the+ * stored image or it does not, and a code it cannot decode carries nothing. For faces it is a proxy:+ * a face YuNet can still find in the artifact is one a re-identification attempt has something to+ * work with, which is stricter than a human recognising it and so errs the safe way.+ *+ * Any row that is `survives` but not `detected` is a leak: present in what we keep, missed by what+ * redacts it.+ */+import { readFileSync } from 'node:fs'+import { readFile, readdir } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { join } from 'node:path'+import sharp from 'sharp'+import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'++import { detectCodes } from '../src/qr.ts'+import { limitsFromEnv, planScales } from '../src/scale-plan.ts'+import { type Src } from '../src/src-image.ts'+import { detectFacesYunet, loadYunet } from '../src/yunet.ts'++const wasmFile = createRequire(`${process.cwd()}/`).resolve('zxing-wasm/writer/zxing_writer.wasm')+const wasmBytes = readFileSync(wasmFile)+prepareZXingModule({+ overrides: {+ wasmBinary: wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength),+ },+})++const FRAME_W = 1920+const FRAME_H = 1080+// From the planner, not hardcoded: the sibling benchmark was fixed for exactly this, having measured+// a pipeline that no longer shipped and reported a ratio it was not running at. The floors these runs+// produce feed bindingRatio(), so a harness that drifts from production invalidates them silently.+const LIMITS = limitsFromEnv()+const PLAN = planScales({ width: FRAME_W, height: FRAME_H }, LIMITS)+const DETECT_PX = PLAN.frame.width * PLAN.frame.height+const STORE_PX = PLAN.stored.width * PLAN.stored.height++async function place(subject: Buffer, sidePx: number): Promise<Buffer> {+ const scaled = await sharp(subject).resize(sidePx, sidePx, { fit: 'inside' }).toBuffer()+ return sharp({ create: { width: FRAME_W, height: FRAME_H, channels: 3, background: '#f3f4f6' } })+ .composite([{ input: scaled, left: 420, top: 260 }])+ .png()+ .toBuffer()+}++/**+ * The frame at an exact pixel budget, as raw pixels rather than through decodeSrc.+ *+ * decodeSrc re-applies SCRUB_MAX_PIXELS, so handing it an already-scaled PNG downscales twice and+ * the run silently measures a different ratio than the one it prints: at the shipped defaults a+ * "0.9 MP" detection frame arrived at 0.45 MP, making this benchmark report 3x while measuring 2.12x.+ */+async function atScale(frame: Buffer, targetPx: number): Promise<Src> {+ const scale = Math.sqrt(targetPx / (FRAME_W * FRAME_H))+ const W = Math.max(1, Math.round(FRAME_W * scale))+ const H = Math.max(1, Math.round(FRAME_H * scale))+ const { data } = await sharp(frame)+ .resize(W, H, { fit: 'fill' })+ .flatten({ background: '#ffffff' })+ .raw()+ .toBuffer({ resolveWithObject: true })+ return { data, W, H, format: 'raw', inputPixels: FRAME_W * FRAME_H }+}++async function faceFloors(): Promise<void> {+ const yunet = await loadYunet('models/yunet.onnx')+ const dir = 'test-data/faces'+ const files = (await readdir(dir)).filter((f) => /\.(png|jpg|jpeg)$/i.test(f)).slice(0, 6)+ console.log('\n FACES — subject placed at N px in a 1920x1080 frame\n')+ console.log(+ ` ${'face px'.padStart(8)}${'in artifact'.padStart(13)}${'detected'.padStart(10)}${'survives'.padStart(10)} verdict`+ )+ for (const sidePx of [24, 32, 48, 64, 96, 128, 192]) {+ let detected = 0+ let survives = 0+ for (const f of files) {+ const frame = await place(await readFile(join(dir, f)), sidePx)+ const det = await atScale(frame, DETECT_PX)+ const art = await atScale(frame, STORE_PX)+ if ((await detectFacesYunet(yunet, det, det.W, det.H)).length > 0) {+ detected+++ }+ if ((await detectFacesYunet(yunet, art, art.W, art.H, { scoreMin: 0.6 })).length > 0) {+ survives+++ }+ }+ const inArtifact = sidePx * Math.sqrt(STORE_PX / (FRAME_W * FRAME_H))+ const leak = survives > detected+ console.log(+ ` ${String(sidePx).padStart(8)}${inArtifact.toFixed(1).padStart(13)}${`${detected}/${files.length}`.padStart(10)}${`${survives}/${files.length}`.padStart(10)} ${leak ? 'LEAK: survives but missed' : survives === 0 ? 'gone from the artifact' : 'detected'}`+ )+ }+}++async function codeFloors(): Promise<void> {+ console.log('\n CODES — QR placed at N px in a 1920x1080 frame\n')+ console.log(+ ` ${'code px'.padStart(8)}${'in artifact'.padStart(13)}${'detected'.padStart(10)}${'decodable'.padStart(11)} verdict`+ )+ const { svg } = await writeBarcode('otpauth://totp/Acme:[email protected]?secret=JBSWY3DPEHPK3PXP', {+ format: 'QRCode',+ })+ const code = await sharp(Buffer.from(svg)).png().toBuffer()+ for (const sidePx of [48, 64, 96, 128, 192, 280]) {+ const frame = await place(code, sidePx)+ const det = await atScale(frame, DETECT_PX)+ const art = await atScale(frame, STORE_PX)+ const detected = (await detectCodes(det)).length > 0+ const decodable = (await detectCodes(art)).length > 0+ const inArtifact = sidePx * Math.sqrt(STORE_PX / (FRAME_W * FRAME_H))+ console.log(+ ` ${String(sidePx).padStart(8)}${inArtifact.toFixed(1).padStart(13)}${(detected ? 'yes' : 'no').padStart(10)}${(decodable ? 'yes' : 'no').padStart(11)} ${decodable && !detected ? 'LEAK: decodable but missed' : decodable ? 'detected' : 'gone from the artifact'}`+ )+ }+}++async function main(): Promise<void> {+ console.log(+ ` detection at ${DETECT_PX / 1e6} MP, artifact at ${STORE_PX / 1e6} MP ` ++ `(ratio ${Math.sqrt(DETECT_PX / STORE_PX).toFixed(2)}x per axis)`+ )+ await faceFloors()+ await codeFloors()+}++main().catch((e) => {+ console.error(e)+ process.exit(1)+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.tsnew file mode 100644index 000000000000..bdbe1c81796f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/glyph-floor.ts@@ -0,0 +1,95 @@+/* eslint-disable no-console -- CLI output script: console output is the whole point */+/**+ * Where detection fails against where legibility fails, as a function of glyph height.+ *+ * Megapixels are the wrong variable: 16pt text is the same physical size whether the frame is 0.6 MP+ * or 20 MP, so what decides whether DBNet finds it is how many pixels the glyph occupies by the time+ * the model sees it. This sweeps that directly, holding the frame size constant and varying only the+ * rendered size, then reports two thresholds:+ *+ * detection floor – below this, DBNet stops returning a box over the text+ * legibility floor – below this, OCR stops reading it+ *+ * The gap between them is the danger zone: text that is missed and still readable. Detection failing+ * BELOW legibility is the safe ordering; the reverse means small text leaks intact.+ *+ * OCR is a conservative stand-in for a human, and conservative in the unhelpful direction: tesseract+ * gives up before a person does, so a glyph it cannot read may still be readable, and the real+ * legibility floor sits at or below what this prints.+ */+import sharp from 'sharp'+import { createWorker } from 'tesseract.js'++import { detectTextDbnet, loadDbnet } from '../src/dbnet.ts'+import { limitsFromEnv, planScales } from '../src/scale-plan.ts'+import { decodeSrc } from '../src/src-image.ts'++const FRAME_W = 1280+const FRAME_H = 720+const PHRASE = 'Account 4242 4242 4242 4242'+const SIZES = [4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 20, 24, 32]++/** Rows of the same phrase at one size, spread down the frame so a single miss is not luck. */+function frameAt(fontPx: number): Promise<Buffer> {+ const rows = []+ for (let i = 0; i < 6; i++) {+ rows.push(+ `<text x="40" y="${60 + i * Math.max(fontPx * 2, 40)}" font-family="Arial" font-size="${fontPx}" fill="#111827">${PHRASE}</text>`+ )+ }+ return sharp(+ Buffer.from(+ `<svg xmlns="http://www.w3.org/2000/svg" width="${FRAME_W}" height="${FRAME_H}">` ++ `<rect width="${FRAME_W}" height="${FRAME_H}" fill="#ffffff"/>${rows.join('')}</svg>`+ )+ )+ .png()+ .toBuffer()+}++async function main(): Promise<void> {+ const dbnet = await loadDbnet('models/dbnet_det.onnx')+ const tess = await createWorker('eng')+ // Measured against the rendered frame through the real pipeline, not from the detection budget+ // alone. decodeSrc applies SCRUB_MAX_PIXELS first, so a glyph passes through two reductions+ // before the model sees it; taking only the second overstated this column by about 10% and the+ // floors quoted from it are what DETECT_OVER_STORE is derived from.+ const limits = limitsFromEnv()+ const probePlan = planScales({ width: FRAME_W, height: FRAME_H }, limits)+ const atModel = probePlan.text.content.width / FRAME_W+ console.log(+ `frame ${FRAME_W}x${FRAME_H} -> decoded ${probePlan.frame.width}x${probePlan.frame.height} -> ` ++ `model ${probePlan.text.content.width}px wide; glyphs reach DBNet at ${atModel.toFixed(3)}x\n`+ )+ console.log(+ ` ${'font px'.padStart(8)}${'at model'.padStart(10)}${'boxes'.padStart(7)}${'OCR words'.padStart(11)} verdict`+ )++ for (const fontPx of SIZES) {+ const png = await frameAt(fontPx)+ const src = await decodeSrc(png)+ const boxes = await detectTextDbnet(dbnet, src, planScales({ width: src.W, height: src.H }, limits).text)+ const { data } = await tess.recognize(png, {}, { blocks: true })+ const words = (data.blocks ?? []).flatMap((b: any) =>+ (b.paragraphs ?? []).flatMap((p: any) => (p.lines ?? []).flatMap((l: any) => l.words ?? []))+ ) as { text: string; confidence: number }[]+ const readable = words.filter((w) => w.confidence >= 60 && /[A-Za-z0-9]{2,}/.test(w.text ?? '')).length+ const found = boxes.length > 0+ const verdict = found+ ? readable > 0+ ? 'detected + readable'+ : 'detected, already illegible'+ : readable > 0+ ? 'MISSED BUT READABLE'+ : 'missed, illegible anyway'+ console.log(+ ` ${String(fontPx).padStart(8)}${(fontPx * atModel).toFixed(1).padStart(10)}${String(boxes.length).padStart(7)}${String(readable).padStart(11)} ${verdict}`+ )+ }+ await tess.terminate()+}++main().catch((e) => {+ console.error(e)+ process.exit(1)+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/mem-probe.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/mem-probe.tsnew file mode 100644index 000000000000..897a79ece6b0--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/mem-probe.ts@@ -0,0 +1,43 @@+/* eslint-disable no-console -- CLI output script: console output is the whole point */+/**+ * Resident memory per worker, which is what WORKER_MEMORY_BUDGET_BYTES in src/cores.ts has to be set+ * from. That constant decides how many workers a pod runs, so guessing it low sizes the pool into an+ * OOM crash loop and guessing it high leaves cores idle.+ *+ * tsx dev/mem-probe.ts <workers> [image]+ *+ * Peak RSS with every worker scrubbing at once, because that is the moment a pod dies: the models+ * and isolate are a small part of it, and the transient a scrub holds is most of it. Measure at the+ * SCRUB_MAX_PIXELS cap, where the transient plateaus.+ *+ * Measured on a 2026 dev machine at the then-current 2.56 MP cap: 278 MB/worker on a 0.33 MP frame,+ * 719 MB on 2 MP, 776 MB at the cap with the ONNX arena disabled (838 MB with it on). Re-run it+ * after any change to the cap, the arena setting, or what compose holds.+ */+import { readFile } from 'node:fs/promises'++import { startPool } from './pool-url.ts'++const rssMb = (): number => Math.round(process.memoryUsage.rss() / 1024 / 1024)++async function main(): Promise<void> {+ const size = Number(process.argv[2] ?? 1)+ const image = await readFile(process.argv[3] ?? 'corpus/shot_desktop_1920x1080_dpr1_0.png')+ const before = rssMb()+ const pool = await startPool(size)+ const loaded = rssMb()+ // All at once: a worker's peak overlaps its siblings' in production, and it is the sum the+ // kernel's OOM killer looks at.+ await Promise.all(Array.from({ length: size }, () => pool.scrub(image)))+ const peak = rssMb()+ await pool.close()+ console.log(+ ` workers=${String(size).padStart(2)} baseline ${before}MB after load ${loaded}MB peak ${peak}MB ` ++ `-> ${((peak - before) / size).toFixed(0)}MB/worker`+ )+}++main().catch((e) => {+ console.error(e)+ process.exit(1)+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pool-url.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pool-url.tsnew file mode 100644index 000000000000..259561aea2f4--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pool-url.ts@@ -0,0 +1,8 @@+/** Starting a pool needs the worker's URL, which only an entry point can resolve: import.meta works+ * under tsx but not under jest's CJS transform, which is why startPool takes it as a parameter+ * rather than resolving it itself (see the note in src/pool.ts). Dev scripts share it here. */+import { type ScrubPool, startPool as start } from '../src/pool.ts'++export function startPool(size: number): Promise<ScrubPool> {+ return start(size, new URL('../src/scrub-worker.ts', import.meta.url))+}