: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): read codes at the scale plan's ratio (#106776)
Robbiee797202515de
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex eacf6cfc212a..1c5da1effdba 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md@@ -103,7 +103,8 @@ Given an image, `advancedScrub` (`src/scrub.ts`):4. **Face redaction**: every detected face (YuNet) is filled with its **mean colour**.5. **Text redaction**: every detected text region (DBNet) gets the same fill, with a margin scaled to the box height (= font size).We detect _where_ text is and never read it.-6. **Code redaction**: every decodable QR/barcode (zxing) gets the same fill — a TOTP provisioning QR or ticket barcode is machine-readable PII that the face/text detectors can't see.+6. **Code redaction**: every QR/barcode that zxing decodes gets the same fill — a TOTP provisioning QR or ticket barcode is machine-readable PII that the face/text detectors can't see.+ zxing reads the frame at the plan's code scale, which finds every code still decodable from the stored image.The goal is to protect data labellers and reduce PII exposure.It does not need to be perfect; the self-verifying test (below) keeps it honest.@@ -221,7 +222,8 @@ One rule sets every size: **each detector must see a subject at least `ratio` tiAnything still readable in the artifact was therefore large enough to have been found and filled.`ratio` is derived rather than chosen, from measured floors in `src/floors.ts` — what each detector reliably finds, against what a person can still read out of the stored image.-Faces bind at 64/21 ≈ 3.05; text is 7/3 ≈ 2.33; codes constrain nothing, since a code degraded past decoding carries nothing.+Faces bind at 64/21 ≈ 3.05; codes need 3, and text 7/3 ≈ 2.33.+zxing reads the frame at exactly `ratio` times the stored scale, because its cost grows with the pixels it reads and no model fixes its input size.`SCRUB_SAFETY_FACTOR` (default 1.3) is margin on top, because both floors came from one font at near-black on white and low-contrast text moves the detection floor the wrong way.**`SCRUB_OUT_MAX_PIXELS` (default 50,000) is the only knob most people should touch.**@@ -231,7 +233,7 @@ Setting the frame budget independently is what let two individually-reasonable sStoring small is deliberate and is most of the guarantee. The downstream consumer identifies what kind of site a session is on, so it needs scene structure and not legibility — text being unreadable in the artifact is the point, not a cost.At the defaults a 1080p capture is stored at about 161x90.-Re-derive the floors with `tsx dev/glyph-floor.ts` (text) and `tsx dev/floors.ts` (faces and codes); both read their geometry from `limitsFromEnv()` so they cannot drift from what ships.+Re-derive the floors with `tsx dev/glyph-floor.ts` (text), `tsx dev/floors.ts` (faces) and `tsx dev/code-bench.ts` (codes); all three read their geometry from `limitsFromEnv()` so they cannot drift from what ships.## Models are baked into the imagediff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.tsindex 5126ed322006..268122973500 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts@@ -8,16 +8,17 @@* --limit keeps the first N frame, code, size and degradation combinations. --shard k/n renders and* checks every nth of those, starting at k, so n processes together cover the whole set once.*- * zxing reads the full frame today. A code only leaks if a reader can decode it from the stored- * image, and the stored image is several times smaller than the frame, so zxing may not need the- * whole frame to find every code that could leak. Each generated image is checked twice: zxing on the- * unredacted stored image (at 1x, 2x and 3x, since an attacker can upscale) decides whether the code- * could leak, and zxing on the frame at each scale decides whether the scrub would have covered it.+ * A code only leaks if a reader can decode it from the stored image, and the stored image is several+ * times smaller than the frame, so zxing does not need the whole frame to find every code that could+ * leak. Each generated image is checked twice: zxing on the unredacted stored image (at 1x, 2x and+ * 3x, since an attacker can upscale) decides whether the code could leak, and zxing on the frame at+ * each scale decides whether the scrub would have covered it. Each scale's time includes the resize+ * to it, which production pays too.** Scales are either a fraction of the frame (fN), a multiple of the stored image's scale (sN), or- * "plan": the multiple the scale plan already requires of every detector (binding ratio times the- * safety factor). None is ever above the frame. The sN points answer the ratio question directly: the smallest multiple at- * which every leakable code is still covered is the ratio codes need.+ * "plan": the scale src/scale-plan.ts gives zxing in production. None is ever above the frame. The sN+ * points answer the ratio question directly: the smallest multiple at which every leakable code is+ * still covered is the ratio codes need, which src/floors.ts records as CODE_FLOOR.*/import { readFileSync } from 'node:fs'import { mkdir, writeFile } from 'node:fs/promises'@@ -26,7 +27,6 @@ import { join } from 'node:path'import sharp from 'sharp'import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'-import { bindingRatio } from '../src/floors.ts'import { detectCodes } from '../src/qr.ts'import { limitsFromEnv, planScales } from '../src/scale-plan.ts'import { type Src, decodeSrc } from '../src/src-image.ts'@@ -239,21 +239,14 @@ async function main(): Promise<void> {const points: [string, number][] = [...FRAME_SCALES.map((f): [string, number] => [`f${f}`, f]),...STORED_MULTIPLES.map((m): [string, number] => [`s${m}`, Math.min(1, m * storedScale)]),- ['plan', Math.min(1, bindingRatio() * limits.safetyFactor * storedScale)],+ ['plan', plan.code.scale],]for (const [point, scale] of points) {const w = Math.max(1, Math.round(src.W * scale))const h = Math.max(1, Math.round(src.H * scale))- const input = await scaled(src, w, h)const t0 = performance.now()- const boxes = await detectCodes(input)+ const boxes = await detectCodes(src, scale)const ms = performance.now() - t0- const back = boxes.map((b) => ({- left: Math.floor((b.left * src.W) / w),- top: Math.floor((b.top * src.H) / h),- width: Math.ceil((b.width * src.W) / w),- height: Math.ceil((b.height * src.H) / h),- }))const codeSideAtZxing = s.codeSide * fx * (w / src.W)results.push({file: s.file,@@ -266,7 +259,7 @@ async function main(): Promise<void> {zxingPixels: w * h,modulePxAtZxing: codeSideAtZxing / s.modules,ms,- coverage: coverage(back, gt),+ coverage: coverage(boxes, gt),})}if ((i + 1) % 50 === 0) {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.tsindex a35cc886c71c..4c11fb5b0217 100644--- 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.ts@@ -3,7 +3,8 @@* 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.+ * with the frame, YuNet letterboxes into a fixed 640 square, and zxing reads the frame at the plan's+ * code scale.** For each subject size it reports two things:* detected – the production detector finds it at the detection resolution@@ -121,7 +122,7 @@ async function codeFloors(): Promise<void> {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 detected = (await detectCodes(det, PLAN.code.scale)).length > 0const decodable = (await detectCodes(art)).length > 0const inArtifact = sidePx * Math.sqrt(STORE_PX / (FRAME_W * FRAME_H))console.log(diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snapindex a52bebc98cac..856f9a17b4a6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap@@ -2,6 +2,7 @@exports[`scale geometry, as it currently behaves a 4K desktop frame 1`] = `{+ "codeScale": "0.540","frame": "1181x664","stored": "161x90","textCanvas": "928x576",@@ -11,6 +12,7 @@ exports[`scale geometry, as it currently behaves a 4K desktop frame 1`] = `exports[`scale geometry, as it currently behaves a 1080p desktop frame 1`] = `{+ "codeScale": "0.540","frame": "1181x664","stored": "161x90","textCanvas": "928x576",@@ -20,6 +22,7 @@ exports[`scale geometry, as it currently behaves a 1080p desktop frame 1`] = `exports[`scale geometry, as it currently behaves a banner past the tiling threshold 1`] = `{+ "codeScale": "1.000","frame": "8000x60","stored": "1789x13","textCanvas": "8000x64",@@ -29,6 +32,7 @@ exports[`scale geometry, as it currently behaves a banner past the tiling threshexports[`scale geometry, as it currently behaves a degenerate column 1`] = `{+ "codeScale": "0.495","frame": "8x88590","stored": "1x1936","textCanvas": "32x16928",@@ -38,6 +42,7 @@ exports[`scale geometry, as it currently behaves a degenerate column 1`] = `exports[`scale geometry, as it currently behaves a degenerate strip 1`] = `{+ "codeScale": "0.495","frame": "88590x8","stored": "1936x1","textCanvas": "16928x32",@@ -47,6 +52,7 @@ exports[`scale geometry, as it currently behaves a degenerate strip 1`] = `exports[`scale geometry, as it currently behaves a mobile portrait frame 1`] = `{+ "codeScale": "0.756","frame": "390x844","stored": "74x161","textCanvas": "416x864",@@ -56,6 +62,7 @@ exports[`scale geometry, as it currently behaves a mobile portrait frame 1`] = `exports[`scale geometry, as it currently behaves a retina laptop frame 1`] = `{+ "codeScale": "0.570","frame": "1120x700","stored": "161x100","textCanvas": "864x608",@@ -65,6 +72,7 @@ exports[`scale geometry, as it currently behaves a retina laptop frame 1`] = `exports[`scale geometry, as it currently behaves a small sprite under every cap 1`] = `{+ "codeScale": "1.000","frame": "200x200","stored": "50x50","textCanvas": "224x224",@@ -74,6 +82,7 @@ exports[`scale geometry, as it currently behaves a small sprite under every capexports[`scale geometry, as it currently behaves a square at the cap 1`] = `{+ "codeScale": "1.000","frame": "671x671","stored": "161x161","textCanvas": "672x672",@@ -83,6 +92,7 @@ exports[`scale geometry, as it currently behaves a square at the cap 1`] = `exports[`scale geometry, as it currently behaves a tiny favicon 1`] = `{+ "codeScale": "1.000","frame": "32x32","stored": "8x8","textCanvas": "32x32",@@ -92,6 +102,7 @@ exports[`scale geometry, as it currently behaves a tiny favicon 1`] = `exports[`scale geometry, as it currently behaves a wide banner 1`] = `{+ "codeScale": "0.486","frame": "2048x219","stored": "251x26","textCanvas": "2048x224",diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.tsindex 2f43e63dceb1..f375230a8836 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts@@ -59,18 +59,20 @@ export const FACE_FLOOR: Floor = {}/**- * Codes are the loosest by a wide margin, and the only subject whose two numbers are both source px:- * zxing runs on the frame directly, so there is no separate input scale to convert through.+ * Codes, in multiples of a code's size in the stored image, which is the unit `dev/code-bench.ts`+ * sweeps zxing's input in. The formats need different pixel sizes, both to be found and to be read,+ * so no single pair of pixel sizes holds for all of them.*- * Detected from 96 source px; not decodable out of the artifact until 280. Requiring detection to be- * 96/280 as large as readability is no constraint at all, since that is below 1: a code degraded past- * decoding carries nothing, which makes this subject self-limiting.+ * A code counts as readable when zxing decodes it from the stored image at 1x, 2x or 3x, since an+ * attacker can upscale. zxing finds every such code once it reads the frame at 3 times the stored+ * scale. At 2 times it misses two, both Aztec.*/export const CODE_FLOOR: Floor = {- detectedAt: 96,- readableAt: 280,- unit: 'code px in the SOURCE, both columns, since zxing works on the frame directly',- measuredBy: 'dev/floors.ts: a QR placed at 48-280px in a 1920x1080 source',+ detectedAt: 3,+ readableAt: 1,+ unit: "multiples of a code's size in the stored image",+ measuredBy:+ 'dev/code-bench.ts: six codes in five formats, six frame shapes, seven sizes, with blur, rotation and JPEG',}export const FLOORS = { text: TEXT_FLOOR, face: FACE_FLOOR, code: CODE_FLOOR } as const@@ -84,7 +86,7 @@ export function requiredRatio(floor: Floor): number {/*** The ratio the whole pipeline has to satisfy: the tightest subject, since the guarantee is only as- * good as the detector with the least room. Text is currently the binding one at 2.33.+ * good as the detector with the least room.*/export function bindingRatio(): number {return Math.max(...Object.values(FLOORS).map(requiredRatio))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.tsindex 802f7c35dded..cd84dc645c60 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts@@ -9,6 +9,8 @@ import sharp from 'sharp'import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'import { detectCodes } from './qr.ts'+import { type Dims, limitsFromEnv, planScales } from './scale-plan.ts'+import { type Src, decodeSrc, srcSharp } from './src-image.ts'const writerWasm = readFileSync(require.resolve('zxing-wasm/writer/zxing_writer.wasm'))prepareZXingModule({@@ -17,42 +19,90 @@ prepareZXingModule({},})+/** What dev/code-bench.ts counts as a leak: zxing decodes the stored image as it is, or upscaled the way an attacker would. */+async function decodableFromStoredImage(src: Src, stored: Dims): Promise<boolean> {+ const art = await srcSharp(src).resize(stored.width, stored.height, { fit: 'fill' }).raw().toBuffer()+ for (const factor of [1, 2, 3]) {+ const [W, H] = [stored.width * factor, stored.height * factor]+ const data = await sharp(art, { raw: { width: stored.width, height: stored.height, channels: 3 } })+ .resize(W, H, { kernel: 'cubic' })+ .raw()+ .toBuffer()+ if ((await detectCodes({ data, W, H, format: 'raw', inputPixels: W * H })).length > 0) {+ return true+ }+ }+ return false+}+describe('detectCodes', () => {- it('returns an in-bounds padded box covering a QR composited at a known location', async () => {- const qr = await writeBarcode('otpauth://totp/test?secret=JBSWY3DPEHPK3PXP', {- format: 'QRCode',- scale: 4,- })- const qrPng = Buffer.from(await qr.image!.arrayBuffer())- const { width: qrW, height: qrH } = await sharp(qrPng).metadata()- const [frameW, frameH, qrLeft, qrTop] = [800, 600, 500, 300]+ it.each([1, 0.75])(+ 'returns an in-bounds padded box covering a QR at a known location, read at %s of the frame',+ async (scale) => {+ const qr = await writeBarcode('otpauth://totp/test?secret=JBSWY3DPEHPK3PXP', {+ format: 'QRCode',+ scale: 4,+ })+ const qrPng = Buffer.from(await qr.image!.arrayBuffer())+ const { width: qrW, height: qrH } = await sharp(qrPng).metadata()+ const [frameW, frameH, qrLeft, qrTop] = [800, 600, 500, 300]- const { data, info } = await sharp({- create: { width: frameW, height: frameH, channels: 3, background: '#fff' },- })- .composite([{ input: qrPng, left: qrLeft, top: qrTop }])- .removeAlpha()- .raw()- .toBuffer({ resolveWithObject: true })-- const boxes = await detectCodes({- data,- W: info.width,- H: info.height,- format: 'raw',- inputPixels: info.width * info.height,+ const { data, info } = await sharp({+ create: { width: frameW, height: frameH, channels: 3, background: '#fff' },+ })+ .composite([{ input: qrPng, left: qrLeft, top: qrTop }])+ .removeAlpha()+ .raw()+ .toBuffer({ resolveWithObject: true })++ const boxes = await detectCodes(+ { data, W: info.width, H: info.height, format: 'raw', inputPixels: info.width * info.height },+ scale+ )++ expect(boxes).toHaveLength(1)+ const b = boxes[0]+ expect(b.left).toBeGreaterThanOrEqual(0)+ expect(b.top).toBeGreaterThanOrEqual(0)+ expect(b.left + b.width).toBeLessThanOrEqual(frameW)+ expect(b.top + b.height).toBeLessThanOrEqual(frameH)+ // the padded box must fully cover the QR itself+ expect(b.left).toBeLessThanOrEqual(qrLeft)+ expect(b.top).toBeLessThanOrEqual(qrTop)+ expect(b.left + b.width).toBeGreaterThanOrEqual(qrLeft + qrW!)+ expect(b.top + b.height).toBeGreaterThanOrEqual(qrTop + qrH!)+ }+ )++ it('covers an Aztec code the stored image keeps decodable, read at the planned scale of a 1080p frame', async () => {+ const source = { width: 1920, height: 1080 }+ const plan = planScales(source, limitsFromEnv())+ // Aztec sets CODE_FLOOR, and at this size the stored image of a 1080p capture still decodes it.+ const [side, left, top] = [360, 1100, 380]+ const code = await writeBarcode('TICKET-A1B2C3-SEAT-14F', { format: 'Aztec', scale: 1 })+ const codePng = await sharp(Buffer.from(await code.image!.arrayBuffer()))+ .resize(side, side, { kernel: 'nearest' })+ .png()+ .toBuffer()+ const png = await sharp({+ create: { width: source.width, height: source.height, channels: 3, background: '#f3f4f6' },})+ .composite([{ input: codePng, left, top }])+ .png()+ .toBuffer()+ const src = await decodeSrc(png, plan.frame)++ expect(await decodableFromStoredImage(src, plan.stored)).toBe(true)- expect(boxes).toHaveLength(1)- const b = boxes[0]- expect(b.left).toBeGreaterThanOrEqual(0)- expect(b.top).toBeGreaterThanOrEqual(0)- expect(b.left + b.width).toBeLessThanOrEqual(frameW)- expect(b.top + b.height).toBeLessThanOrEqual(frameH)- // the padded box must fully cover the QR itself- expect(b.left).toBeLessThanOrEqual(qrLeft)- expect(b.top).toBeLessThanOrEqual(qrTop)- expect(b.left + b.width).toBeGreaterThanOrEqual(qrLeft + qrW!)- expect(b.top + b.height).toBeGreaterThanOrEqual(qrTop + qrH!)+ const boxes = await detectCodes(src, plan.code.scale)+ const [fx, fy] = [src.W / source.width, src.H / source.height]+ const covered = boxes.some(+ (b) =>+ b.left <= left * fx &&+ b.top <= top * fy &&+ b.left + b.width >= (left + side) * fx &&+ b.top + b.height >= (top + side) * fy+ )+ expect(covered).toBe(true)})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.tsindex 44ccd13bdef4..3cb72b484efa 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts@@ -10,7 +10,7 @@ import { createRequire } from 'node:module'import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'import { type Box } from './geometry.ts'-import { type Src } from './src-image.ts'+import { type Src, srcSharp } from './src-image.ts'// zxing-wasm's default loader fetches its .wasm from a CDN on first use; hand it the binary that// shipped in node_modules instead, so the worker needs no runtime egress and always runs the build@@ -26,10 +26,16 @@ prepareZXingModule({const PAD = 0.15 // expand each hit so quiet zones / clipped modules are covered-export async function detectCodes(src: Src): Promise<Box[]> {- const { data, W, H } = src+/** Reads the frame at `scale` of its size and returns boxes in frame coordinates. */+export async function detectCodes(src: Src, scale = 1): Promise<Box[]> {+ const width = Math.max(1, Math.round(src.W * scale))+ const height = Math.max(1, Math.round(src.H * scale))+ const data =+ width === src.W && height === src.H+ ? src.data+ : await srcSharp(src).resize(width, height, { fit: 'fill' }).raw().toBuffer()// zxing takes RGBA ImageData; expand the shared raw RGB in one pass.- const rgba = new Uint8ClampedArray(W * H * 4)+ const rgba = new Uint8ClampedArray(width * height * 4)for (let i = 0, o = 0; i < data.length; i += 3, o += 4) {rgba[o] = data[i]rgba[o + 1] = data[i + 1]@@ -38,7 +44,7 @@ export async function detectCodes(src: Src): Promise<Box[]> {}// Structural ImageData (zxing dispatches on width/height/data); Node has no ImageData class, so// colorSpace only exists to satisfy the DOM type.- const imageData = { data: rgba, width: W, height: H, colorSpace: 'srgb' } as ImageData+ const imageData = { data: rgba, width, height, colorSpace: 'srgb' } as ImageData// tryHarder is the dominant cost here (roughly two thirds of this stage) and it stays on. It buys// nothing on crisp on-screen codes, where dropping it finds the same 13 of 15 in dev/make-code-corpus,// but a replay frame can hold a photographed code (a ticket on a phone, a webcam preview), and on@@ -46,21 +52,23 @@ export async function detectCodes(src: Src): Promise<Box[]> {// formats is likewise a false economy: it drops a large Code128 that the full set decodes.const results = await readBarcodes(imageData, { tryHarder: true, maxNumberOfSymbols: 32 })+ const toFrameX = src.W / width+ const toFrameY = src.H / heightconst boxes: Box[] = []for (const r of results) {const p = r.position- const xs = [p.topLeft.x, p.topRight.x, p.bottomLeft.x, p.bottomRight.x]- const ys = [p.topLeft.y, p.topRight.y, p.bottomLeft.y, p.bottomRight.y]+ const xs = [p.topLeft.x, p.topRight.x, p.bottomLeft.x, p.bottomRight.x].map((x) => x * toFrameX)+ const ys = [p.topLeft.y, p.topRight.y, p.bottomLeft.y, p.bottomRight.y].map((y) => y * toFrameY)const minX = Math.min(...xs)const maxX = Math.max(...xs)const minY = Math.min(...ys)const maxY = Math.max(...ys)const px = (maxX - minX) * PADconst py = (maxY - minY) * PAD- const left = Math.max(0, Math.round(minX - px))- const top = Math.max(0, Math.round(minY - py))- const right = Math.min(W, Math.round(maxX + px))- const bottom = Math.min(H, Math.round(maxY + py))+ const left = Math.max(0, Math.floor(minX - px))+ const top = Math.max(0, Math.floor(minY - py))+ const right = Math.min(src.W, Math.ceil(maxX + px))+ const bottom = Math.min(src.H, Math.ceil(maxY + py))if (right - left >= 2 && bottom - top >= 2) {boxes.push({ left, top, width: right - left, height: bottom - top })}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.characterisation.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.characterisation.test.tsindex 92e710d451e9..f22ec80e090f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.characterisation.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.characterisation.test.ts@@ -16,6 +16,7 @@ describe('scale geometry, as it currently behaves', () => {textContent: `${p.text.content.width}x${p.text.content.height}`,textCanvas: `${p.text.canvas.width}x${p.text.canvas.height}`,stored: `${p.stored.width}x${p.stored.height}`,+ codeScale: p.code.scale.toFixed(3),}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.tsindex 7293adc6ae00..2ad09fb59631 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts@@ -37,6 +37,7 @@ describe('scale-plan', () => {expect(plan.text.content.height).toBeLessThanOrEqual(plan.frame.height)expect(plan.stored.width).toBeLessThanOrEqual(plan.frame.width)expect(plan.stored.height).toBeLessThanOrEqual(plan.frame.height)+ expect(plan.code.scale).toBeLessThanOrEqual(1)})it.each(SHAPES)('keeps the frame inside its own budget for %s', (_case, width, height) => {@@ -73,11 +74,13 @@ describe('scale-plan', () => {const textSeen = Math.min(plan.text.content.width, plan.text.content.height)const faceSeen = Math.min(plan.frame.width, plan.frame.height) * plan.face.scale+ const codeSeen = Math.min(plan.frame.width, plan.frame.height) * plan.code.scaleconst kept = Math.min(plan.stored.width, plan.stored.height)// A stored axis floored to one pixel cannot express a ratio; such a frame carries no text.if (kept > 1) {expect(textSeen / kept).toBeGreaterThanOrEqual(required)expect(faceSeen / kept).toBeGreaterThanOrEqual(required)+ expect(codeSeen / kept).toBeGreaterThanOrEqual(required)}})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.tsindex 1d51de6c29e8..9e1979d8d2fc 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts@@ -36,7 +36,7 @@ export interface ScalePlan {text: { content: Dims; canvas: Dims }/** What YuNet sees. Its input is a fixed square, so this is how much of the frame reaches it. */face: { scale: number }- /** What zxing sees. It works on the frame directly. */+ /** What zxing sees, as a fraction of the frame. */code: { scale: number }/** What gets written, and is the only copy that exists. */stored: Dims@@ -175,6 +175,10 @@ export function faceInputScale(dims: Dims, side: number, tileAbove: number, tilereturn Math.min(1, side / faceWindowLong(long, short, tileAbove, tileAspect))}+// A resize has a fixed cost that a small reduction does not win back in zxing time, so zxing reads the frame as it+// is unless the plan takes it below this. Reading more than the ratio asks for cannot break rule 4.+const CODE_RESIZE_BELOW = 0.85+/*** The plan for one source image.*@@ -194,11 +198,15 @@ export function planScales(source: Dims, limits: PlanLimits): ScalePlan {const ratio = bindingRatio() * limits.safetyFactorconst stored = applyScale(frame, Math.min(1, weakest / ratio, scaleToArea(frame, limits.storedPixels)))+ // zxing's cost grows with the pixels it reads and no model fixes its input, so it gets exactly the ratio. That is+ // measured against the stored axes as kept, because flooring an axis to a whole pixel keeps more than was asked.+ const keptScale = Math.max(stored.width / frame.width, stored.height / frame.height)+ const codeScale = Math.min(1, ratio * keptScale)return {frame,text,face: { scale: faceScale },- code: { scale: 1 },+ code: { scale: codeScale < CODE_RESIZE_BELOW ? codeScale : 1 },stored,}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.tsindex 82cfe7361024..cd2fbfc4af2b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts@@ -194,7 +194,7 @@ export async function advancedScrub(;[faceBoxes, textBoxes, codeBoxes] = await Promise.all([detectFacesYunet(m.yunet, src, W, H),runText(),- detectCodes(src),+ detectCodes(src, plan.code.scale),])timings.faceMs = timings.textMs = timings.codesMs = performance.now() - tD} else {@@ -205,7 +205,7 @@ export async function advancedScrub(textBoxes = await runText()timings.textMs = performance.now() - tTconst tQ = performance.now()- codeBoxes = await detectCodes(src)+ codeBoxes = await detectCodes(src, plan.code.scale)timings.codesMs = performance.now() - tQ}timings.faces = faceBoxes.length