: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(image-scrub): add a stored long-side setting to the scrub sidecar (#116879)
Nicholas Waltzc2c7a073108c
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 79ee08031f10..1c913cf5b57b 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@@ -233,12 +233,36 @@ zxing reads the frame at exactly `ratio` times the stored scale, because its cosDBNet reads exactly `ratio` times the stored size too, cut down from its canvas budget whenever that makes its padded canvas smaller.`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.**-It is what gets stored, and everything else follows from it: the frame budget is `stored x ratio^2`, because the detectors have to see enough to keep the rule.-Setting the frame budget independently is what let two individually-reasonable settings combine into a pipeline that under-redacted, so `SCRUB_MAX_PIXELS` still exists as an override but is derived by default.+### Stored size++The guarantee is the ratio, not a small stored image.+Whatever is still legible in the artifact was large enough for a detector to find and fill, at any stored size.+A larger stored size keeps more scene detail for training and costs detector time, because the detectors grow with it.++**`SCRUB_STORED_MAX_SIDE` sets the stored size, and is the knob most people should touch.**+Up to the face tiling aspect (3:1) it caps the long side of what gets stored, and everything else follows from it: the face detector's input and the text canvas grow to `side x ratio`, and the frame budget to `stored x ratio^2`.+It takes 0 (off) or a value from 16 to 1024.++| Source | Unset (0) | 384 |+| --------- | --------- | ------- |+| 1920x1080 | 161x90 | 384x216 |+| 1280x720 | 161x90 | 323x181 |+| 390x844 | 74x161 | 98x213 |+| 400x300 | 100x75 | 100x75 |-Storing 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.+- Unset, the face detector runs at 640 px, which caps every stored image at about 161 px on its long side.+- An image smaller than about `side x ratio` stores at `1/ratio` of its size, whatever the side.+- Past 3:1 the side is not a cap, because capping a banner's long side would crush its short one. The face detector's input binds instead, as it does unset: the long side stays near the side up to 6:1, then the short side holds at about `side / 6` and the long side grows with the aspect (384 stores an 8:1 source at 517x64, and 20:1 at 1292x64).+- Above 640 px the face detector also runs a second pass at 640, since its floors were measured there and a close-up face at the larger input reaches the model bigger than anything checked. The pass is skipped where 640 would not shrink the window, and the two passes' boxes are merged as a union, so neither can remove a box the other found.++Before raising it in a deployment:++- Raise the container's memory, or the pool runs fewer workers. The model in `src/cores.ts` gives about 955 MB per worker at 384 instead of 514 MB. `dev/mem-probe.ts` measured 755 MB at 384 and 4.5 GB at 1024 on frames at the cap, inside the model's 955 MB and 5.0 GB.+- Check detection recall at the new sizes with `dev/scrub-eval.ts`.+- Watch `ml_mirror_image_scrub_duration_seconds` and `ml_mirror_image_scrub_stage_duration_seconds`, split by `ml_mirror_image_scrub_plan_info`, which carries the sizes each pod runs with.++`SCRUB_OUT_MAX_PIXELS` bounds the stored area (default `side^2`, or 50,000 when no side is set).+Setting the frame budget independently is what let two individually-reasonable settings combine into a pipeline that under-redacted, so `SCRUB_MAX_PIXELS` still exists as an override but is derived by default.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.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.tsindex 9ef69927b20d..e7e0a9981a29 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts@@ -11,7 +11,7 @@* models/candidates/yunet_n_dynamic.onnx out/face-calibration models/candidates/yunet_n_dynamic_int8.onnx* ORT_THREADS=1 tsx dev/face-bench.ts [--detectors a,b] [--sets a,b] [--limit N] [--label name]*- * Production reads each frame at min(1, 640 / long side) with the dynamic-shape YuNet export, on a+ * Production reads each frame at min(1, inputSide / long side), inputSide 640 by default, with the dynamic-shape YuNet export, on a* canvas that pads only to the model's stride, which is the scale the plan counts for the face stage.* The fixed-shape builds take only a 640x640 input, so their "fixed" entries letterbox: a frame* smaller than 640 is enlarged and a 16:9 frame is padded with black to a square, and neither buys@@ -36,7 +36,7 @@ import sharp, { type OverlayOptions } from 'sharp'import { numFromEnv } from '../src/env.ts'import { FACE_FLOOR } from '../src/floors.ts'import { type Box } from '../src/geometry.ts'-import { FACE_INPUT_SIDE, limitsFromEnv, planScales } from '../src/scale-plan.ts'+import { limitsFromEnv, planScales } from '../src/scale-plan.ts'import { type Src, decodeSrc, probeDims, srcSharp } from '../src/src-image.ts'import { type YunetModel, detectFacesYunet, detectionWindowsForTest, loadYunet } from '../src/yunet.ts'import { coverage, mulberry32 } from './bench-common.ts'@@ -96,7 +96,7 @@ interface GtImage {interface DetectorSpec {name: stringfile: string- /** native: production's input, the frame at min(1, 640/long), stride-padded. fixed: the 640x640 letterbox. */+ /** native: production's input, the frame at min(1, inputSide/long), stride-padded. fixed: the 640x640 letterbox. */input: 'fixed' | 'native'}@@ -353,7 +353,7 @@ function iou(a: Box, b: Box): number {function inputScale(input: DetectorSpec['input'], win: Box): number {const long = Math.max(win.width, win.height)- return input === 'fixed' ? FIXED_SIDE / long : Math.min(1, FACE_INPUT_SIDE / long)+ return input === 'fixed' ? FIXED_SIDE / long : Math.min(1, limitsFromEnv().faceInputSide / long)}// --dump-calibration builds its tensors here too, so that the int8 builds calibrate on the inputs the native variants see.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 a65de50e2cd2..53ada5037845 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 reads at most a 640px long side and never enlarges, and zxing reads the frame at the plan's+ * with the frame, YuNet reads at most its input side (640 px unless SCRUB_STORED_MAX_SIDE raises it) and never+ * enlarges, and zxing reads the frame at the plan's* code scale.** For each subject size it reports two things:@@ -26,7 +27,7 @@ import sharp from 'sharp'import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'import { detectCodes } from '../src/qr.ts'-import { FACE_INPUT_SIDE, limitsFromEnv, planScales } from '../src/scale-plan.ts'+import { limitsFromEnv, planScales } from '../src/scale-plan.ts'import { type Src } from '../src/src-image.ts'import { detectFacesYunet, loadYunet } from '../src/yunet.ts'@@ -81,7 +82,7 @@ async function atScale(frame: Buffer, targetPx: number): Promise<Src> {// A re-identification attempt can enlarge the stored image, and YuNet never enlarges a small input itself, so the survival check reads the stored image at YuNet's longest side.async function enlargedForReader(art: Src): Promise<Src> {- const scale = FACE_INPUT_SIDE / Math.max(art.W, art.H)+ const scale = LIMITS.faceInputSide / Math.max(art.W, art.H)const W = Math.round(art.W * scale)const H = Math.round(art.H * scale)const { data } = await sharp(art.data, { raw: { width: art.W, height: art.H, channels: 3 } })diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.tsindex df12383718a9..31d57880e5d5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.ts@@ -47,7 +47,7 @@ const qr = {rust: (rgb: Buffer, rgba: Uint8ClampedArray) => rgbToRgba(rgb, rgba),}-// The text canvases are two that the scale plan hands DBNet, YuNet takes a fixed 640x640 input,+// The text canvases are two that the scale plan hands DBNet, YuNet takes its default 640x640 input,// safety.ts resizes to 224x224, and the code frames are two sizes that zxing reads.const CASES: Case[] = [{ ...dbnet, width: 640, height: 384 },diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.tsindex 6c65a1847845..9cad6ae51767 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'import { loadConfig } from './config.ts'import { ORT_THREADS, SCRUB_WORKERS } from './cores.ts'import { bindingRatio } from './floors.ts'-import { ScrubMetrics, trackPool } from './metrics.ts'+import { ScrubMetrics, recordPlanInfo, trackPool } from './metrics.ts'import { startPool } from './pool.ts'import { limitsFromEnv } from './scale-plan.ts'import { startServer } from './server.ts'@@ -17,6 +17,7 @@ const SVG_RASTERIZER_PATH = fileURLToPath(new URL('./svg-rasterizer-process.mjs'const cfg = loadConfig()const SCRUB_LIMITS = limitsFromEnv()+recordPlanInfo(SCRUB_LIMITS)// Thread sizing is derived (workers and ORT threads from the cgroup quota) or set outside the process// (UV_THREADPOOL_SIZE in the Dockerfile), so log what this process actually resolved: a pool sized// wrong shows up as latency rather than as an error, with no other way to tell from a running pod.@@ -25,6 +26,7 @@ console.log(`[image-scrub] concurrency=${cfg.maxConcurrency} workers=${SCRUB_WORKERS} ortThreads=${ORT_THREADS} ` +`uvThreadpoolSize=${process.env.UV_THREADPOOL_SIZE ?? '4 (libuv default)'} ` +`framePixels=${SCRUB_LIMITS.framePixels} storedPixels=${SCRUB_LIMITS.storedPixels} ` ++ `storedMaxSide=${SCRUB_LIMITS.storedMaxSide} faceInputSide=${SCRUB_LIMITS.faceInputSide} ` +`ratio=${(bindingRatio() * SCRUB_LIMITS.safetyFactor).toFixed(2)}x`)// The pool is process-wide and every worker's sharp stages queue onto it, so below the worker countdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.tsindex 790611a219ce..71a45c2a36a0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts@@ -1,6 +1,7 @@import { Counter, Gauge, Histogram, Registry } from 'prom-client'import { type UndecodableImageReason } from './image-input.ts'+import { type PlanLimits } from './scale-plan.ts'import { type StageTimings } from './scrub.ts'export const register = new Registry()@@ -169,6 +170,25 @@ const workerRestartFailures = new Counter({help: 'Replacement attempts that failed to become ready and were themselves retried',registers: [register],})+// Which sizing a pod runs, so scrub latency and CPU can be split by it while a stored-side change rolls out.+const planInfo = new Gauge({+ name: 'ml_mirror_image_scrub_plan_info',+ help: 'The scale plan this process runs with, as labels; the value is always 1',+ labelNames: ['stored_max_side', 'face_input_side', 'frame_pixels', 'text_canvas_pixels'],+ registers: [register],+})++export function recordPlanInfo(limits: PlanLimits): void {+ planInfo+ .labels(+ String(limits.storedMaxSide),+ String(limits.faceInputSide),+ String(limits.framePixels),+ String(limits.textCanvasPixels)+ )+ .set(1)+}+interface PoolProbe {usableWorkers(): numberqueueDepth(): numberdiff --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 d34abbe6b6a7..5e1871137b49 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@@ -1,17 +1,37 @@import { FLOORS, bindingRatio, requiredRatio } from './floors.ts'-import { type PlanLimits, faceInputScale, fitToCanvas, planScales, scaleToArea } from './scale-plan.ts'+import { type PlanLimits, faceInputScale, fitToCanvas, limitsFromEnv, planScales, scaleToArea } from './scale-plan.ts'const LIMITS: PlanLimits = {framePixels: 450_000,textCanvasPixels: 736 * 736,storedPixels: 50_000,faceInputSide: 640,+ storedMaxSide: 0,faceTileAbove: 3,faceTileAspect: 6,stride: 32,safetyFactor: 1.3,}+function limitsWithStoredSide(side: number): PlanLimits {+ const saved = process.env.SCRUB_STORED_MAX_SIDE+ process.env.SCRUB_STORED_MAX_SIDE = String(side)+ try {+ return limitsFromEnv()+ } finally {+ if (saved === undefined) {+ delete process.env.SCRUB_STORED_MAX_SIDE+ } else {+ process.env.SCRUB_STORED_MAX_SIDE = saved+ }+ }+}++const LIMIT_SETS: [string, PlanLimits][] = [+ ['the default limits', LIMITS],+ ['a 384px stored side', limitsWithStoredSide(384)],+]+describe('scale-plan', () => {// The four rules the plan exists to keep, asserted over the shape classes that have each broken// one of them in production or review. Every case here is a real defect that shipped or nearly did.@@ -28,66 +48,93 @@ describe('scale-plan', () => {['a degenerate column', 10, 100_000],]- it.each(SHAPES)('never upscales any stage for %s', (_case, width, height) => {- const plan = planScales({ width, height }, LIMITS)-- expect(plan.frame.width).toBeLessThanOrEqual(width)- expect(plan.frame.height).toBeLessThanOrEqual(height)- expect(plan.text.content.width).toBeLessThanOrEqual(plan.frame.width)- 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)+ describe.each(LIMIT_SETS)('with %s', (_limitsName, limits) => {+ it.each(SHAPES)('never upscales any stage for %s', (_case, width, height) => {+ const plan = planScales({ width, height }, limits)++ expect(plan.frame.width).toBeLessThanOrEqual(width)+ expect(plan.frame.height).toBeLessThanOrEqual(height)+ expect(plan.text.content.width).toBeLessThanOrEqual(plan.frame.width)+ 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) => {+ // An axis that scales below one pixel floors to one, which leaves the other at full length+ // and the product above the budget by any factor: a 1x50,000,000 source planned ten times it.+ // The per-worker memory model is derived from this budget, so an unbounded frame is an OOM.+ const { frame } = planScales({ width, height }, limits)++ expect(frame.width * frame.height).toBeLessThanOrEqual(limits.framePixels)+ })++ it.each(SHAPES)('bounds the allocated tensor for %s', (_case, width, height) => {+ // Rule 2: a budget on content area does not bound the tensor once a collapsed axis is padded+ // up to the stride. A 100 KB PNG allocated fifteen times the budget this way.+ const { canvas } = planScales({ width, height }, limits).text++ expect(canvas.width * canvas.height).toBeLessThanOrEqual(limits.textCanvasPixels)+ expect(canvas.width % limits.stride).toBe(0)+ expect(canvas.height % limits.stride).toBe(0)+ })++ it.each(SHAPES)('keeps the canvas covering its content for %s', (_case, width, height) => {+ const { content, canvas } = planScales({ width, height }, limits).text++ expect(canvas.width).toBeGreaterThanOrEqual(content.width)+ expect(canvas.height).toBeGreaterThanOrEqual(content.height)+ })++ it.each(SHAPES)('holds the ratio against EVERY detector for %s', (_case, width, height) => {+ // Rule 4, and the finding that motivated the weakest-detector rule: deriving from the text+ // detector alone gave faces 2.15x on an ordinary 1080p frame while the docs promised 3x.+ const plan = planScales({ width, height }, limits)+ const required = bindingRatio()++ 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.scale+ const 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)+ }+ })})- it.each(SHAPES)('keeps the frame inside its own budget for %s', (_case, width, height) => {- // An axis that scales below one pixel floors to one, which leaves the other at full length- // and the product above the budget by any factor: a 1x50,000,000 source planned ten times it.- // The per-worker memory model is derived from this budget, so an unbounded frame is an OOM.- const { frame } = planScales({ width, height }, LIMITS)-- expect(frame.width * frame.height).toBeLessThanOrEqual(LIMITS.framePixels)+ it('is the tightest subject that sets the ratio', () => {+ // Whichever subject has least room decides, so adding a detector can only tighten it.+ expect(bindingRatio()).toBe(Math.max(...Object.values(FLOORS).map(requiredRatio)))+ expect(requiredRatio(FLOORS.text)).toBeCloseTo(4.3 / 3, 5)})- it.each(SHAPES)('bounds the allocated tensor for %s', (_case, width, height) => {- // Rule 2: a budget on content area does not bound the tensor once a collapsed axis is padded- // up to the stride. A 100 KB PNG allocated fifteen times the budget this way.- const { canvas } = planScales({ width, height }, LIMITS).text+ it.each([+ ['a 1080p desktop frame', 1920, 1080],+ ['a 4K desktop frame', 3840, 2160],+ ])('stores %s at the configured side, with detectors grown to keep the ratio', (_case, width, height) => {+ const limits = limitsWithStoredSide(384)+ const plan = planScales({ width, height }, limits)- expect(canvas.width * canvas.height).toBeLessThanOrEqual(LIMITS.textCanvasPixels)- expect(canvas.width % LIMITS.stride).toBe(0)- expect(canvas.height % LIMITS.stride).toBe(0)+ expect(Math.max(plan.stored.width, plan.stored.height)).toBe(384)+ expect(limits.faceInputSide).toBeGreaterThanOrEqual(384 * bindingRatio() * limits.safetyFactor)})- it.each(SHAPES)('keeps the canvas covering its content for %s', (_case, width, height) => {- const { content, canvas } = planScales({ width, height }, LIMITS).text+ it.each([+ ['a wide banner', 8000, 60],+ ['a tall strip', 60, 8000],+ ])('keeps the default stored size for %s past the tiling aspect', (_case, width, height) => {+ const capped = planScales({ width, height }, limitsWithStoredSide(384)).stored+ const unset = planScales({ width, height }, LIMITS).stored- expect(canvas.width).toBeGreaterThanOrEqual(content.width)- expect(canvas.height).toBeGreaterThanOrEqual(content.height)- })-- it.each(SHAPES)('holds the ratio against EVERY detector for %s', (_case, width, height) => {- // Rule 4, and the finding that motivated the weakest-detector rule: deriving from the text- // detector alone gave faces 2.15x on an ordinary 1080p frame while the docs promised 3x.- const plan = planScales({ width, height }, LIMITS)- const required = bindingRatio()-- 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.scale- const 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)- }+ expect(Math.min(capped.width, capped.height)).toBeGreaterThanOrEqual(Math.min(unset.width, unset.height))})- it('is the tightest subject that sets the ratio', () => {- // Whichever subject has least room decides, so adding a detector can only tighten it.- expect(bindingRatio()).toBe(Math.max(...Object.values(FLOORS).map(requiredRatio)))- expect(requiredRatio(FLOORS.text)).toBeCloseTo(4.3 / 3, 5)+ it.each([1, 15, 2048])('refuses a stored side of %p', (side) => {+ expect(() => limitsWithStoredSide(side)).toThrow('SCRUB_STORED_MAX_SIDE')})it('respects the stored budget when that is the tighter bound', () => {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 5c9accfd41d0..0171fdf30d56 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@@ -13,8 +13,9 @@* 1. Never upscale. Enlarging pixels adds nothing and softens the edges detection depends on.* 2. Bound the work by the tensor, not by the frame. A budget on frame area does not bound the* tensor once a collapsed axis is padded up to the encoder's stride.- * 3. Store small. The final 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.+ * 3. Store the size the operator chose. SCRUB_STORED_MAX_SIDE sets it; unset, the default detector+ * sizes allow about 161 px on the long side. Rule 4, not a small size, keeps what was not+ * redacted unreadable.* 4. Keep the ratio. Every detector must see a subject at least `ratio` times larger than the* stored image keeps it, so anything still readable was large enough to have been found.*/@@ -54,6 +55,8 @@ export interface PlanLimits {storedPixels: number/** The longest side YuNet reads a frame or tile at. */faceInputSide: number+ /** Longest side the stored image may have, or 0 for no bound beyond the area budget. */+ storedMaxSide: number/** Stride the text encoder needs its input to be a multiple of. */stride: number/** Margin over the measured floors. 1 means exactly what the measurement supports. */@@ -66,14 +69,15 @@ const atLeastOne = (n: number): number => Math.max(1, Math.floor(n))* disagree, which is how a legal stored size produced an illegal frame size. */const MIN_FRAME_PIXELS = 96 * 96-/** The face detector's input size and tiling rule, owned here because the plan has to model them. yunet.ts imports- * these rather than declaring its own, so the model and the plan cannot disagree. */-export const FACE_INPUT_SIDE = 640+/** The face detector's tiling rule and smallest input size, owned here because the plan has to model them. yunet.ts+ * reads its input size from `limitsFromEnv()` rather than declaring its own, so the model and the plan cannot disagree. */+export const DEFAULT_FACE_INPUT_SIDE = 640export const FACE_TILE_ABOVE = 3export const FACE_TILE_ASPECT = 6/**- * Most inferences one image may spend on faces.+ * Most windows one image may spend on faces, per pass: an input side above 640 also runs a 640 pass,+ * so the inference count is up to twice this.** Tiling covers a long frame with overlapping windows, and the count grows with the aspect ratio,* which the frame's AREA budget does not bound: a 400000x4 source plans a 280149x2 frame and asks for@@ -214,7 +218,12 @@ export function planScales(source: Dims, limits: PlanLimits): ScalePlan {const weakest = Math.min(textScale, faceScale, 1)const ratio = bindingRatio() * limits.safetyFactor- const stored = applyScale(frame, Math.min(1, weakest / ratio, scaleToArea(frame, limits.storedPixels)))+ // A frame past the tiling aspect is a banner or a strip: capping its long side would crush the short one to a+ // pixel or two, so it keeps the stored size the defaults give it.+ const long = Math.max(frame.width, frame.height)+ const capsSide = limits.storedMaxSide > 0 && long / Math.min(frame.width, frame.height) <= limits.faceTileAbove+ const sideScale = capsSide ? limits.storedMaxSide / long : 1+ const stored = applyScale(frame, Math.min(1, weakest / ratio, scaleToArea(frame, limits.storedPixels), sideScale))// 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)@@ -235,13 +244,32 @@ export function planScales(source: Dims, limits: PlanLimits): ScalePlan {* to see enough to keep the ratio, and the frame has to carry enough for the detectors. Exposing the* others as independent knobs is what let a pair of individually-reasonable settings combine into a* pipeline that under-redacted.+ *+ * `SCRUB_STORED_MAX_SIDE` sets the stored size by its long side. The face detector's input and the+ * text canvas then grow to `side x ratio`, because at their defaults the face input caps every+ * stored image at about 161 px whatever the area budget allows.*/export function limitsFromEnv(): PlanLimits {- const storedPixels = numFromEnv('SCRUB_OUT_MAX_PIXELS', 50_000, 16 * 16, LIMIT_INPUT_PIXELS)+ const storedMaxSide = numFromEnv('SCRUB_STORED_MAX_SIDE', 0, 0, 1024)+ if (storedMaxSide > 0 && storedMaxSide < 16) {+ throw new Error(`SCRUB_STORED_MAX_SIDE must be 0 or in [16, 1024], got ${storedMaxSide}`)+ }const safetyFactor = numFromEnv('SCRUB_SAFETY_FACTOR', 1.3, 1, 4)+ const ratio = bindingRatio() * safetyFactor+ const stride = 32+ const faceInputSide =+ storedMaxSide > 0+ ? Math.max(DEFAULT_FACE_INPUT_SIDE, upToStride(Math.ceil(storedMaxSide * ratio), stride))+ : DEFAULT_FACE_INPUT_SIDE+ const storedPixels = numFromEnv(+ 'SCRUB_OUT_MAX_PIXELS',+ storedMaxSide > 0 ? storedMaxSide * storedMaxSide : 50_000,+ 16 * 16,+ LIMIT_INPUT_PIXELS+ )// The frame has to carry the ratio for the tightest subject, with the margin, or no detector can// satisfy it however the later stages are sized.- const needed = storedPixels * (bindingRatio() * safetyFactor) ** 2+ const needed = storedPixels * ratio ** 2return {// Clamped at BOTH ends: numFromEnv validates a default as strictly as an override, so a// legal storedPixels must never derive an illegal framePixels and hand the operator a refusal@@ -253,12 +281,18 @@ export function limitsFromEnv(): PlanLimits {MIN_FRAME_PIXELS,LIMIT_INPUT_PIXELS),- textCanvasPixels: numFromEnv('DET_CANVAS_PIXELS', 736 * 736, 256 * 256, 4096 * 4096),+ textCanvasPixels: numFromEnv(+ 'DET_CANVAS_PIXELS',+ Math.min(4096 * 4096, Math.max(736 * 736, faceInputSide * faceInputSide)),+ 256 * 256,+ 4096 * 4096+ ),storedPixels,- faceInputSide: FACE_INPUT_SIDE,+ faceInputSide,+ storedMaxSide,faceTileAbove: FACE_TILE_ABOVE,faceTileAspect: FACE_TILE_ASPECT,- stride: 32,+ stride,safetyFactor,}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet-windows.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet-windows.test.tsindex 895e876a25a3..ce57b018b05a 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet-windows.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet-windows.test.ts@@ -1,7 +1,37 @@import { FACE_MAX_WINDOWS } from './scale-plan.ts'-import { detectionWindowsForTest } from './yunet.ts'+import { detectionWindowsForTest, faceInputSides, mergePasses, passesForWindow } from './yunet.ts'describe('detectionWindows', () => {+ it.each([+ [640, [640]],+ [1536, [1536, 640]],+ ])('keeps the measured 640 face pass when the input is %p', (inputSide, sides) => {+ // YuNet's floors were measured at 640; a larger input alone could miss a close-up face it was never checked on.+ expect(faceInputSides(inputSide)).toEqual(sides)+ })++ it.each([+ ['a window within 640 runs once', 400, 300, [1536]],+ ['a window of exactly 640 runs once', 640, 360, [1536]],+ ['a window the 640 pass shrinks runs at each', 1280, 720, [1536, 640]],+ ])('%s', (_case, width, height, sides) => {+ expect(passesForWindow({ left: 0, top: 0, width, height }, [1536, 640])).toEqual(sides)+ })++ it('keeps a face box from one pass that a tighter, higher-scoring box from another pass overlaps', () => {+ const tight = { left: 110, top: 110, width: 80, height: 80 }+ const wide = { left: 100, top: 100, width: 120, height: 120 }+ expect(mergePasses([[{ b: tight, s: 0.95 }], [{ b: wide, s: 0.75 }]])).toEqual([tight, wide])+ expect(+ mergePasses([+ [+ { b: tight, s: 0.95 },+ { b: wide, s: 0.75 },+ ],+ ])+ ).toEqual([tight])+ })+// A window starting off the edge is not an error anywhere downstream: face boxes are translated// by its offset, so they land at negative coordinates and are clamped away. Face redaction goes// silently off for the whole shape class, which is why this needs a test rather than a readerdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.tsindex 6891ca7c0e65..cc63de613434 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts@@ -11,7 +11,8 @@ import { ORT_THREADS } from './cores.ts'import { numFromEnv } from './env.ts'import { type Box } from './geometry.ts'import { rgbToChw } from './pixel-convert.ts'-// Tiling bounds for extreme-aspect frames. A single pass scales by 640/longSide, so on a+// Tiling bounds for extreme-aspect frames, with figures for the default 640 input (a larger input+// scales them up). A single pass scales by 640/longSide, so on a// very tall/wide image a face (at most ~shortSide across) can land below the detector's smallest// stride. Above MAX_ASPECT the frame is cut along its long axis into windows of aspect TILE_ASPECT// (overlapping by one shortSide, so a face — at most one shortSide across — is always fully inside@@ -21,10 +22,26 @@ import { rgbToChw } from './pixel-convert.ts'// Kept in step with PlanLimits.faceTileAbove / faceTileAspect: the planner needs the same rule to// know how much of a long frame this stage really sees, and two copies of it is the drift the// planner exists to remove.-import { FACE_INPUT_SIDE, FACE_TILE_ABOVE, FACE_TILE_ASPECT, faceWindowLong } from './scale-plan.ts'+import {+ DEFAULT_FACE_INPUT_SIDE,+ FACE_TILE_ABOVE,+ FACE_TILE_ASPECT,+ faceWindowLong,+ limitsFromEnv,+} from './scale-plan.ts'import { type Src, srcSharp } from './src-image.ts'const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)+const FACE_INPUT_SIDES = faceInputSides(limitsFromEnv().faceInputSide)++/**+ * The input sizes faces are detected at. YuNet's measured floors come from 640, and a close-up face at a larger input+ * reaches the model bigger than anything it was checked against, so a larger input adds a 640 pass rather than+ * replacing it.+ */+export function faceInputSides(inputSide: number): number[] {+ return inputSide > DEFAULT_FACE_INPUT_SIDE ? [inputSide, DEFAULT_FACE_INPUT_SIDE] : [inputSide]+}const NMS_IOU = 0.3const STRIDES = [8, 16, 32]const LARGEST_STRIDE = 32@@ -112,16 +129,48 @@ function detectionWindows(W: number, H: number): Window[] {return windows}+const windowScale = (win: Window, inputSide: number): number => Math.min(1, inputSide / Math.max(win.width, win.height))++/** A window already within the smaller side reaches the model at full size on every pass. */+export function passesForWindow(win: Window, inputSides: number[]): number[] {+ const scales = new Set<number>()+ return inputSides.filter((side) => {+ const scale = windowScale(win, side)+ if (scales.has(scale)) {+ return false+ }+ scales.add(scale)+ return true+ })+}++type Candidate = { b: Box; s: number }++/** Scores from different input sizes are not comparable, so a box from one pass never suppresses another pass's. */+export function mergePasses(passes: Candidate[][]): Box[] {+ return passes.flatMap((cand) => {+ const sorted = [...cand].sort((a, b) => b.s - a.s)+ const keep: Box[] = []+ for (const { b } of sorted) {+ if (!keep.some((k) => iou(k, b) > NMS_IOU)) {+ keep.push(b)+ }+ }+ return keep+ })+}+async function detectInWindow(model: YunetModel,src: Src,W: number,H: number,win: Window,- scoreMin: number-): Promise<{ b: Box; s: number }[]> {+ scoreMin: number,+ inputSide: number+): Promise<Candidate[]> {// Padding rather than resizing to reach the stride, because resizing up enlarges real pixels (rule 1 in scale-plan.ts).- const scale = Math.min(1, FACE_INPUT_SIDE / Math.max(win.width, win.height))+ const scale = windowScale(win, inputSide)const dw = Math.max(1, Math.round(win.width * scale))const dh = Math.max(1, Math.round(win.height * scale))const cw = upToStride(dw)@@ -143,7 +192,7 @@ async function detectInWindow(// padding scale past the window edge and get clamped away.const sx = win.width / dwconst sy = win.height / dh- const cand: { b: Box; s: number }[] = []+ const cand: Candidate[] = []for (const s of STRIDES) {const cls = out[`cls_${s}`].data as Float32Arrayconst obj = out[`obj_${s}`].data as Float32Array@@ -184,18 +233,13 @@ export async function detectFacesYunet(opts: FaceOpts = {}): Promise<Box[]> {const scoreMin = opts.scoreMin ?? SCORE_MIN- const cand: { b: Box; s: number }[] = []- for (const win of detectionWindows(W, H)) {- cand.push(...(await detectInWindow(model, src, W, H, win, scoreMin)))- }-- // greedy NMS over all windows (overlap regions produce duplicates for the same face)- cand.sort((a, b) => b.s - a.s)- const keep: Box[] = []- for (const { b } of cand) {- if (!keep.some((k) => iou(k, b) > NMS_IOU)) {- keep.push(b)+ const windows = detectionWindows(W, H)+ const passes: Candidate[][] = FACE_INPUT_SIDES.map(() => [])+ for (const win of windows) {+ for (const inputSide of passesForWindow(win, FACE_INPUT_SIDES)) {+ const pass = passes[FACE_INPUT_SIDES.indexOf(inputSide)]+ pass.push(...(await detectInWindow(model, src, W, H, win, scoreMin, inputSide)))}}- return keep+ return mergePasses(passes)}