Skip to content

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

perf(replay): tie the scrub's detection resolution to what it stores (#73687)

Robbie1b7381290f60
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.md
index 34a5c991a6ec..f14009489c62 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
@@ -16,8 +16,7 @@ It runs a simple http server, receives an image and replies with the scrubbed im
Given an image, `advancedScrub` (`src/scrub.ts`):
-1. **Downscale**: every frame is capped at the `SCRUB_MAX_PIXELS` area budget (default 1600², aspect preserved) inside the decode.
- This bounds the per-image memory working set, and — since text detection runs under the same area budget — the stored output never carries resolution the detectors didn't certify as clean.
+1. **Plan the sizes**: `planScales` (`src/scale-plan.ts`) decides every resize from the source dimensions alone, before a pixel is read — the decoded frame, what each detector sees, and what gets stored.
An area budget rather than a long-side cap, so tall pages keep legible native resolution instead of being squashed.
Faces are detected on a letterboxed (never squashed) 640×640 input; frames beyond 3:1 aspect are tiled along their long axis (overlapping windows) so a face on a tall page stays above the detector's minimum size instead of shrinking past it.
2. **NSFW/gore gate**: if the image is explicit or gory (NSFL + NSFW probability over `NSFW_THRESHOLD`), it collapses to a 1x1 blank.
@@ -69,7 +68,9 @@ src/ (production — ships)
yunet.ts YuNet face detector (ONNX)
dbnet.ts DBNet text-region detector (ONNX)
qr.ts QR/barcode detector (zxing-wasm, loaded from node_modules — no egress)
- src-image.ts decode the source once to raw RGB (area-capped), shared across stages
+ scale-plan.ts every resize decided in one pure function, before a pixel is read
+ floors.ts what each detector finds vs what a person can read, and where both were measured
+ src-image.ts decode the source once to raw RGB, to the size the plan asked for
geometry.ts shared Box type + grid rounding
safety.ts NSFW/gore gate (SwiftFormer image-safety classifier, ONNX)
smoke.ts image-build-time smoke test: models load + one scrub, with networking disabled
@@ -118,7 +119,7 @@ FACE: 89/89 faces redacted (100%)
```
The corpus spans 0.3 to 8.3 megapixels at both device pixel ratios, which matters: it used to top out
-at 1440x900, entirely under the `SCRUB_MAX_PIXELS` cap, so nothing in it was ever downscaled on the
+at 1440x900, entirely under the frame budget, so nothing in it was ever downscaled on the
way to detection and the suite could not see what that cap costs. Adding monitor-sized frames
immediately failed the gate at a 14.3% leak on 4K captures taken at device pixel ratio 1, where 14px
text reaches DBNet at about 6px after both downscales. `DET_SHARPEN` closes that, and the numbers
@@ -126,26 +127,25 @@ above are with it on.
Faint, low-contrast scanned-fax lines occasionally survive.
That is contrast-limited not size-limited, so resolution alone won't catch every faded line, and it is outside the rendered-UI domain and within the "best-effort, not catastrophic if a little gets through" bar.
-Raise `DET_FACTOR` (env, default 0.75 of the long side) toward 1.0 to spend more CPU on text recall.
-
-### Resolution knobs
-
-`SCRUB_MAX_PIXELS` is what the **detectors** see, and lowering it is a redaction change rather than a
-cost one: at 1 MP the detection budget hits its 736 floor and a 4K frame yields zero text boxes, so
-the scrub becomes a no-op that returns a downscaled copy with everything still legible.
-`SCRUB_OUT_MAX_PIXELS` is what gets **stored**, applied after detection has run, so it costs no
-recall and is a question about what a downstream model needs to read. It defaults to
-`SCRUB_MAX_PIXELS`, meaning no downscale.
-
-### Probes
-
-The liveness probe answers 503 once no worker can scrub, which is what restores the signal that
-moving inference onto worker threads removed: a wedged synchronous inference used to block the event
-loop and fail the probe by itself. Readiness deliberately stays green so the pod keeps its place in
-the Service that Prometheus scrapes through, since `/scrub` is loopback-only and reaches no Service.
-That requires `livenessProbe` to point at `/_health` and `readinessProbe` at `/_ready`, which is how
-the lane's chart wires them; a deployment that points readiness at `/_health` would drop the pod out
-of the scrape at exactly the moment its metrics explain what happened.
+Raising `SCRUB_SAFETY_FACTOR` spends more CPU on recall: it enlarges the frame every detector sees, since the frame budget is derived from it.
+
+## Resolution
+
+One rule sets every size: **each detector must see a subject at least `ratio` times larger, per axis, than the stored image keeps it.**
+Anything 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.
+`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.
+
+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.
+
+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.
## Models are baked into the image
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/res-sweep.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/res-sweep.ts
index 6a3cc9036a8a..711ad3da51f8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/res-sweep.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/res-sweep.ts
@@ -2,10 +2,10 @@
/**
* One resolution setting, measured over every local image: what the detectors find and what it cost.
*
- * SCRUB_MAX_PIXELS and DET_FACTOR are read once at module load, so a sweep runs this process per
+ * limitsFromEnv().framePixels and DET_FACTOR are read once at module load, so a sweep runs this process per
* setting rather than looping inside one. Prints a JSON line per run for diffing across them.
*
- * SCRUB_MAX_PIXELS=1000000 DET_FACTOR=0.75 tsx dev/res-sweep.ts naive-1mp
+ * SCRUB_OUT_MAX_PIXELS=25000 tsx dev/res-sweep.ts smaller-artifact
*
* Box counts are the direct read on detection recall. The eval's OCR leak percentage is end-to-end
* but confounded here: a smaller output makes residual text harder for tesseract to read whether or
@@ -16,8 +16,8 @@ import { readFile, readdir } from 'node:fs/promises'
import { basename, join } from 'node:path'
import sharp from 'sharp'
+import { limitsFromEnv } from '../src/scale-plan.ts'
import { advancedScrub, loadModels } from '../src/scrub.ts'
-import { SCRUB_MAX_PIXELS } from '../src/src-image.ts'
const ROOT = new URL('..', import.meta.url).pathname
@@ -78,8 +78,7 @@ async function main(): Promise<void> {
console.log(
JSON.stringify({
label,
- scrubMaxPixels: SCRUB_MAX_PIXELS,
- detFactor: process.env.DET_FACTOR ?? '0.75 (default)',
+ scrubMaxPixels: limitsFromEnv().framePixels,
rows,
})
)
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.snap
new file mode 100644
index 000000000000..a52bebc98cac
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap
@@ -0,0 +1,100 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`scale geometry, as it currently behaves a 4K desktop frame 1`] = `
+{
+ "frame": "1181x664",
+ "stored": "161x90",
+ "textCanvas": "928x576",
+ "textContent": "928x551",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a 1080p desktop frame 1`] = `
+{
+ "frame": "1181x664",
+ "stored": "161x90",
+ "textCanvas": "928x576",
+ "textContent": "928x551",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a banner past the tiling threshold 1`] = `
+{
+ "frame": "8000x60",
+ "stored": "1789x13",
+ "textCanvas": "8000x64",
+ "textContent": "8000x60",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a degenerate column 1`] = `
+{
+ "frame": "8x88590",
+ "stored": "1x1936",
+ "textCanvas": "32x16928",
+ "textContent": "6x16928",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a degenerate strip 1`] = `
+{
+ "frame": "88590x8",
+ "stored": "1936x1",
+ "textCanvas": "16928x32",
+ "textContent": "16928x6",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a mobile portrait frame 1`] = `
+{
+ "frame": "390x844",
+ "stored": "74x161",
+ "textCanvas": "416x864",
+ "textContent": "390x844",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a retina laptop frame 1`] = `
+{
+ "frame": "1120x700",
+ "stored": "161x100",
+ "textCanvas": "864x608",
+ "textContent": "864x581",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a small sprite under every cap 1`] = `
+{
+ "frame": "200x200",
+ "stored": "50x50",
+ "textCanvas": "224x224",
+ "textContent": "200x200",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a square at the cap 1`] = `
+{
+ "frame": "671x671",
+ "stored": "161x161",
+ "textCanvas": "672x672",
+ "textContent": "671x671",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a tiny favicon 1`] = `
+{
+ "frame": "32x32",
+ "stored": "8x8",
+ "textCanvas": "32x32",
+ "textContent": "32x32",
+}
+`;
+
+exports[`scale geometry, as it currently behaves a wide banner 1`] = `
+{
+ "frame": "2048x219",
+ "stored": "251x26",
+ "textCanvas": "2048x224",
+ "textContent": "2048x219",
+}
+`;
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
index 0340fe8638bf..f0889aed056e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
@@ -1,5 +1,6 @@
import sharp from 'sharp'
+import { limitsFromEnv, planScales } from './scale-plan.ts'
import { type StageTimings, compose } from './scrub.ts'
function timings(): StageTimings {
@@ -77,9 +78,23 @@ describe('compose', () => {
// (encodeStored can only receive already-composited pixels) and empirically against a solid
// block, where the residue reached full intensity one pixel out at a 0.957 downscale. Through
// compose it is not separable from the fill itself, whose colour is the region's own mean.
- it.each([1, 0.957, 0.5, 0.25])('keeps a filled region covered at storage scale %s', async (fraction) => {
- const out = await compose(await strokesOnWhite(), W, H, [box], timings(), Math.round(W * H * fraction))
+ // Parameterised over caps that actually bind. The resolution invariant clamps the stored size to
+ // at most a third of what the detector saw, so any cap above that produces the same output and
+ // the case is inert: asserting the dimensions keeps the parameter honest rather than letting it
+ // silently stop varying anything, which is what happened when the clamp was introduced.
+ it.each([
+ ['a cap above the invariant, which clamps it', W * H],
+ ['a cap at the invariant', Math.round((W * H) / 9)],
+ ['a cap below the invariant', Math.round((W * H) / 25)],
+ ['a very small cap', 5_000],
+ ])('keeps a filled region covered with %s', async (_case, storedPixels) => {
+ const src = await strokesOnWhite()
+ const expected = planScales({ width: W, height: H }, { ...limitsFromEnv(), storedPixels }).stored
+ const out = await compose(src, W, H, [box], timings(), expected)
+
+ const meta = await sharp(out).metadata()
+ expect({ width: meta.width, height: meta.height }).toEqual(expected)
expect(await darkPixels(out)).toBe(0)
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.test.ts
index 2e65461f2b02..04ede9532c09 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.test.ts
@@ -71,12 +71,12 @@ describe('memoryBoundedWorkers', () => {
// roughly 4Gi before four workers fit. Sizing by cores alone would have put four workers in 2Gi,
// which measurement says needs about 3.1Gi at peak.
it.each([
- ['2Gi', 2 * 1024 ** 3, 1],
- ['3Gi', 3 * 1024 ** 3, 3],
- ['4Gi', 4 * 1024 ** 3, 4],
+ ['2Gi', 2 * 1024 ** 3, 3],
+ ['3Gi', 3 * 1024 ** 3, 5],
+ ['4Gi', 4 * 1024 ** 3, 7],
['1Gi, below one worker plus the reserve', 1024 ** 3, 1],
['256Mi, below even the reserve', 256 * 1024 ** 2, 1],
- ])('allows %s to hold %d workers', (_case, limit, expected) => {
+ ])('allows %s to hold %s workers', (_case, limit, expected) => {
expect(workersForMemoryLimit(limit)).toBe(expected)
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.ts
index 53af8f4210f4..cdcd07b75b8a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.ts
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'
import { availableParallelism, totalmem } from 'node:os'
import { numFromEnv } from './env.ts'
+import { limitsFromEnv } from './scale-plan.ts'
/** Max threads a single ONNX session may use. Matches the ceiling numFromEnv enforces below. */
const ORT_THREADS_MAX = 32
@@ -13,16 +14,21 @@ const NO_QUOTA_CORES = 4
const SCRUB_WORKERS_MAX = 32
/**
- * Memory to assume each worker needs, measured rather than assumed: peak RSS with every worker
- * scrubbing at once, divided by the worker count, on frames at the SCRUB_MAX_PIXELS cap where it
- * plateaus. That came to 776 MB per worker (278 MB on a 0.33 MP frame, 719 MB on 2 MP, 776 MB at the
- * cap), of which about 76 MB is the isolate and its three ONNX sessions and the rest is the transient
- * a scrub holds. This is that with headroom.
+ * Memory to assume each worker needs, derived from the frame budget it will hold rather than fixed,
+ * because most of a worker's peak is the transient a scrub holds and that scales with frame area.
+ * A fixed number goes stale the moment SCRUB_MAX_PIXELS moves, in whichever direction is unsafe.
*
- * The earlier figure here was 512 MB, back-solved from the deployed pod's cores-to-memory ratio
- * rather than from any measurement, and it was low enough to have sized the pool into an OOM.
+ * Measured with dev/mem-probe.ts, peak RSS with every worker scrubbing at once on frames at the cap:
+ *
+ * cap 0.45 MP -> ~300 MB/worker cap 2.56 MP -> ~700-780 MB/worker
+ *
+ * which is about 240 MB fixed (the isolate, three ONNX sessions, a zxing wasm instance) plus about
+ * 240 MB per megapixel of cap. Rounded up on both terms, since sizing this low crash-loops a pod and
+ * sizing it high only leaves cores idle.
*/
-const WORKER_MEMORY_BUDGET_BYTES = 896 * 1024 * 1024
+const WORKER_FIXED_BYTES = 288 * 1024 * 1024
+const WORKER_BYTES_PER_MEGAPIXEL = 288 * 1024 * 1024
+const WORKER_MEMORY_BUDGET_BYTES = WORKER_FIXED_BYTES + (WORKER_BYTES_PER_MEGAPIXEL * limitsFromEnv().framePixels) / 1e6
/**
* Held back from the worker budget for everything that is not a worker: the main thread's own heap,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts
index b86f888f0a5f..93e9f9abf00a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts
@@ -11,11 +11,11 @@ import * as ort from 'onnxruntime-node'
import { ORT_THREADS } from './cores.ts'
import { numFromEnv } from './env.ts'
-import { type Box, roundTo32 } from './geometry.ts'
+import { type Box } from './geometry.ts'
+import { type Dims } from './scale-plan.ts'
import { type Src, srcSharp } from './src-image.ts'
export interface DetectOpts {
- detLimit?: number // detection budget SIDE: the model input is capped at detLimit^2 px (aspect preserved). Bigger = catches smaller text, slower.
probThreshold?: number // per-pixel text probability cutoff
boxScoreMin?: number // mean probability over a component's core pixels to keep it
minAreaPx?: number // min component size in model-resolution px
@@ -25,7 +25,6 @@ export interface DetectOpts {
}
const DEFAULTS: Required<DetectOpts> = {
- detLimit: numFromEnv('DET_LIMIT', 640, 256, 4096),
probThreshold: numFromEnv('PROB_T', 0.3, 0.05, 0.9),
boxScoreMin: numFromEnv('BOX_SCORE', 0.5, 0.05, 0.95),
minAreaPx: numFromEnv('MIN_AREA', 16, 1, 1024),
@@ -71,21 +70,20 @@ export async function loadDbnet(modelPath: string): Promise<DbnetModel> {
async function preprocess(
src: Src,
- W: number,
- H: number,
- detLimit: number
+ text: { content: Dims; canvas: Dims }
): Promise<{ data: Float32Array; rw: number; rh: number; sx: number; sy: number }> {
- // Area budget (detLimit^2), aspect preserved: same tensor-size bound as a detLimit-square, but a
- // tall page keeps its native text size instead of being squashed below detectability.
- const ratio = Math.min(1, Math.sqrt((detLimit * detLimit) / (W * H)))
- const rw = roundTo32(W * ratio)
- const rh = roundTo32(H * ratio)
+ const { width: cw, height: ch } = text.content
+ const { width: rw, height: rh } = text.canvas
// A resample is a low-pass filter, and glyph edges are the high frequencies DB scores. Restoring
// some of that edge contrast before the model sees it is the cheapest lever on small text.
// Measured against the ORIGINAL rather than the decoded frame, because both downscales cost edge
// detail and a 4K screenshot has been through both by the time it arrives here.
- const totalRatio = Math.sqrt((rw * rh) / src.inputPixels)
- const pipeline = srcSharp(src).resize(rw, rh, { fit: 'fill' })
+ const totalRatio = Math.sqrt((cw * ch) / src.inputPixels)
+ // Padding is mid-grey rather than black or white: a flat extreme against a light or dark frame
+ // edge is itself a strong edge, which is what the DB head scores.
+ const pipeline = srcSharp(src)
+ .resize(cw, ch, { fit: 'fill' })
+ .extend({ right: rw - cw, bottom: rh - ch, background: '#808080' })
const sharpened = DET_SHARPEN > 0 && totalRatio < DET_SHARPEN_BELOW
const { data } = await (sharpened ? pipeline.sharpen({ sigma: DET_SHARPEN }) : pipeline)
.raw()
@@ -97,7 +95,7 @@ async function preprocess(
chw[plane + p] = (data[i + 1] / 255 - MEAN[1]) / STD[1]
chw[2 * plane + p] = (data[i + 2] / 255 - MEAN[2]) / STD[2]
}
- return { data: chw, rw, rh, sx: W / rw, sy: H / rh }
+ return { data: chw, rw, rh, sx: src.W / cw, sy: src.H / ch }
}
/** Horizontal dilation by radius k via per-row prefix sums; bridges inter-word gaps on a line. */
@@ -209,14 +207,13 @@ function postprocess(
export async function detectTextDbnet(
model: DbnetModel,
src: Src,
- W: number,
- H: number,
+ text: { content: Dims; canvas: Dims },
opts: DetectOpts = {}
): Promise<Box[]> {
const o: Required<DetectOpts> = { ...DEFAULTS, ...opts }
- const { data, rw, rh, sx, sy } = await preprocess(src, W, H, o.detLimit)
+ const { data, rw, rh, sx, sy } = await preprocess(src, text)
const tensor = new ort.Tensor('float32', data, [1, 3, rh, rw])
const out = await model.session.run({ [model.inputName]: tensor })
const prob = out[model.outputName].data as Float32Array
- return postprocess(prob, rw, rh, sx, sy, W, H, o)
+ return postprocess(prob, rw, rh, sx, sy, src.W, src.H, o)
}
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.ts
new file mode 100644
index 000000000000..2f43e63dceb1
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts
@@ -0,0 +1,91 @@
+/**
+ * What each detector can find, against what a person can still take out of the stored image.
+ *
+ * These two numbers are the whole basis of the scrub's sizing. Everything downstream is arithmetic
+ * on them: the detectors have to see each subject large enough to find it, and the stored image has
+ * to be small enough that anything they missed carries nothing. The gap between the pair is the
+ * margin, and the tightest subject decides the pipeline.
+ *
+ * Both are stated at a stage's OWN input, in that stage's own units, because that is what its
+ * benchmark measures and converting them to a shared unit is where the errors have crept in before.
+ */
+
+export interface Floor {
+ /** Size at which the detector reliably finds the subject, at the detector's own input. */
+ detectedAt: number
+ /** Size at which a person can still take PII from the subject, in the STORED image. */
+ readableAt: number
+ unit: string
+ /** How both numbers were obtained, so a reader can re-run rather than trust them. */
+ measuredBy: string
+}
+
+/**
+ * Text is the binding subject and the best measured.
+ *
+ * Detection: `tsx dev/glyph-floor.ts` sweeps rendered size against a fixed frame. DBNet starts finding
+ * text at about 4.9px and has every line by 7px, at the model input.
+ *
+ * Readability: rendered samples at a range of sizes, judged by eye. 4px is readable and 3px is not,
+ * so 3px is the largest size that carries nothing, which is the conservative end of that boundary. Tesseract gives up at 8-9px and is not the bar: a person reads
+ * well past where OCR does, and using OCR as the proxy hid a live leak once already.
+ */
+export const TEXT_FLOOR: Floor = {
+ detectedAt: 7,
+ readableAt: 3,
+ unit: 'font-size px (ink is about 0.72x this)',
+ measuredBy: 'dev/glyph-floor.ts, plus a human judgement on rendered samples',
+}
+
+/**
+ * Faces, from `dev/floors.ts`. Both numbers are converted from the sweep's source-pixel column, and
+ * the arithmetic is written out because getting these two into the same frame is exactly where the
+ * previous version went wrong: it paired a figure measured at the detection frame with one measured
+ * in the artifact and called the ratio 43/21.
+ *
+ * The sweep runs at 0.9 MP detection and 0.1 MP storage from a 1920x1080 source, so a face of S
+ * source px reaches YuNet at S x sqrt(0.9/2.07) x (640/1265) = 0.333 S, and is kept in the artifact
+ * at S x sqrt(0.1/2.07) = 0.220 S.
+ *
+ * Every face is found at 192 source px, which is 64px at YuNet's input. A face is still findable in
+ * the artifact at 96 source px, which is 21px there. The readable figure uses YuNet-on-the-artifact
+ * as the stand-in for re-identification, which is stricter than a person recognising someone.
+ */
+export const FACE_FLOOR: Floor = {
+ detectedAt: 64,
+ readableAt: 21,
+ unit: "face px, detected at YuNet's own input, readable in the stored image",
+ measuredBy: 'dev/floors.ts: a face placed at 24-192px in a 1920x1080 source',
+}
+
+/**
+ * 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.
+ *
+ * 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.
+ */
+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',
+}
+
+export const FLOORS = { text: TEXT_FLOOR, face: FACE_FLOOR, code: CODE_FLOOR } as const
+export type Subject = keyof typeof FLOORS
+
+/** How much larger a subject must be at this detector than in the artifact, for anything readable to
+ * have been detectable. */
+export function requiredRatio(floor: Floor): number {
+ return floor.detectedAt / floor.readableAt
+}
+
+/**
+ * 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.
+ */
+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/geometry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts
index 37639334d94c..3520bc255b5f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts
@@ -6,6 +6,3 @@ export interface Box {
}
// ONNX detectors need input dims on a 32-px grid; floor at 32.
-export function roundTo32(n: number): number {
- return Math.max(32, Math.round(n / 32) * 32)
-}
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.ts
index 3574e741c12c..9378bbde9afc 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
@@ -1,8 +1,10 @@
/* eslint-disable no-console -- sidecar logs to stdout */
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 { startPool } from './pool.ts'
+import { limitsFromEnv } from './scale-plan.ts'
import { startServer } from './server.ts'
// Resolved here rather than in pool.ts: entry points run under tsx, where import.meta works, while
@@ -10,13 +12,16 @@ import { startServer } from './server.ts'
const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)
const cfg = loadConfig()
+const SCRUB_LIMITS = limitsFromEnv()
// 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.
const uvThreadpoolSize = Number(process.env.UV_THREADPOOL_SIZE ?? 4)
console.log(
`[image-scrub] concurrency=${cfg.maxConcurrency} workers=${SCRUB_WORKERS} ortThreads=${ORT_THREADS} ` +
- `uvThreadpoolSize=${process.env.UV_THREADPOOL_SIZE ?? '4 (libuv default)'}`
+ `uvThreadpoolSize=${process.env.UV_THREADPOOL_SIZE ?? '4 (libuv default)'} ` +
+ `framePixels=${SCRUB_LIMITS.framePixels} storedPixels=${SCRUB_LIMITS.storedPixels} ` +
+ `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 count
// those stages re-serialise however many workers there are. It cannot be fixed from here: libuv
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.ts
new file mode 100644
index 000000000000..92e710d451e9
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.characterisation.test.ts
@@ -0,0 +1,37 @@
+import { limitsFromEnv, planScales } from './scale-plan.ts'
+
+/**
+ * What the geometry does today, pinned before it is rewritten.
+ *
+ * Not an assertion that these numbers are right: several are the subject of open findings. They are
+ * here so a rewrite has to be deliberate about every shape it changes, rather than discovering the
+ * change in production. Delete a row only alongside the reason it moved.
+ */
+describe('scale geometry, as it currently behaves', () => {
+ /** The whole chain for one source, now a single call rather than five modules to reconstruct. */
+ function plan(sourceW: number, sourceH: number) {
+ const p = planScales({ width: sourceW, height: sourceH }, limitsFromEnv())
+ return {
+ frame: `${p.frame.width}x${p.frame.height}`,
+ 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}`,
+ }
+ }
+
+ it.each([
+ ['a 1080p desktop frame', 1920, 1080],
+ ['a 4K desktop frame', 3840, 2160],
+ ['a retina laptop frame', 2880, 1800],
+ ['a mobile portrait frame', 390, 844],
+ ['a small sprite under every cap', 200, 200],
+ ['a tiny favicon', 32, 32],
+ ['a wide banner', 2048, 219],
+ ['a banner past the tiling threshold', 8000, 60],
+ ['a degenerate strip', 100000, 10],
+ ['a degenerate column', 10, 100000],
+ ['a square at the cap', 671, 671],
+ ])('%s', (_case, W, H) => {
+ expect(plan(W, H)).toMatchSnapshot()
+ })
+})
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.ts
new file mode 100644
index 000000000000..7293adc6ae00
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts
@@ -0,0 +1,126 @@
+import { FLOORS, bindingRatio, requiredRatio } from './floors.ts'
+import { type PlanLimits, faceInputScale, fitToCanvas, planScales, scaleToArea } from './scale-plan.ts'
+
+const LIMITS: PlanLimits = {
+ framePixels: 450_000,
+ textCanvasPixels: 736 * 736,
+ storedPixels: 50_000,
+ faceInputSide: 640,
+ faceTileAbove: 3,
+ faceTileAspect: 6,
+ stride: 32,
+ safetyFactor: 1.3,
+}
+
+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.
+ const SHAPES: [string, number, number][] = [
+ ['a 1080p desktop frame', 1920, 1080],
+ ['a 4K desktop frame', 3840, 2160],
+ ['a retina laptop frame', 2880, 1800],
+ ['a mobile portrait frame', 390, 844],
+ ['a sprite under every budget', 200, 200],
+ ['a favicon', 32, 32],
+ ['a wide banner', 2048, 219],
+ ['a banner past the face tiling threshold', 8000, 60],
+ ['a degenerate strip', 100_000, 10],
+ ['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)
+ })
+
+ 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 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)
+ }
+ })
+
+ 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(7 / 3, 5)
+ })
+
+ it('respects the stored budget when that is the tighter bound', () => {
+ // Two independent bounds: the ratio, and an operator's cap. The smaller wins.
+ const tight = planScales({ width: 1920, height: 1080 }, { ...LIMITS, storedPixels: 2_000 })
+
+ expect(tight.stored.width * tight.stored.height).toBeLessThanOrEqual(2_000)
+ })
+
+ it('lets a fixed-input detector enlarge a frame smaller than its square', () => {
+ // The one allowed upscale: the size belongs to the model, and filling the square is what
+ // maximises the subject at it. Only the reduction matters for the ratio, hence the cap at 1.
+ expect(faceInputScale({ width: 200, height: 100 }, 640, 3, 6)).toBe(1)
+ expect(faceInputScale({ width: 1280, height: 720 }, 640, 3, 6)).toBeCloseTo(0.5, 5)
+ })
+
+ it('never returns a zero dimension', () => {
+ // A degenerate axis floors to one pixel rather than vanishing: a zero-width buffer is a crash
+ // several stages down, far from the shape that caused it.
+ const plan = planScales({ width: 100_000, height: 3 }, LIMITS)
+
+ for (const d of [plan.frame, plan.text.content, plan.text.canvas, plan.stored]) {
+ expect(d.width).toBeGreaterThanOrEqual(1)
+ expect(d.height).toBeGreaterThanOrEqual(1)
+ }
+ })
+
+ it('scales to an area budget without exceeding it', () => {
+ expect(scaleToArea({ width: 2000, height: 1000 }, 500_000)).toBeCloseTo(0.5, 5)
+ expect(scaleToArea({ width: 100, height: 100 }, 500_000)).toBe(1)
+ })
+
+ it('fits a collapsed axis by shrinking the long one', () => {
+ const { canvas } = fitToCanvas({ width: 212_132, height: 2 }, 736 * 736, 32)
+
+ expect(canvas.width * canvas.height).toBeLessThanOrEqual(736 * 736)
+ expect(canvas.height).toBe(32)
+ })
+})
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.ts
new file mode 100644
index 000000000000..1d51de6c29e8
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
@@ -0,0 +1,239 @@
+/**
+ * Every resize the scrub performs, decided in one place, before any pixel is touched.
+ *
+ * The sizing used to be spread across five modules: the decode capped area, the text detector picked
+ * a budget and quantised it, the face detector letterboxed into a fixed square, and the storage step
+ * divided by a ratio. Each was locally sensible and every serious defect found in review lived in
+ * the seams between them, because no single place knew all of it. This is that place. It is pure
+ * arithmetic on dimensions, so the whole geometry can be asserted for any shape class without a
+ * model, an image, or a millisecond of inference.
+ *
+ * The rules it encodes, in full:
+ *
+ * 1. Never upscale. Enlarging pixels adds nothing and softens the edges detection depends on. The
+ * one exception is a detector whose input size is fixed by its model, which is a property of the
+ * model rather than a choice, and is marked as such.
+ * 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.
+ * 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.
+ */
+import { LIMIT_INPUT_PIXELS } from './blur.ts'
+import { numFromEnv } from './env.ts'
+import { bindingRatio } from './floors.ts'
+
+export interface Dims {
+ width: number
+ height: number
+}
+
+export interface ScalePlan {
+ /** The frame every stage shares, decoded once. */
+ frame: Dims
+ /** What DBNet sees: content, and the stride-padded canvas that is actually allocated. */
+ 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. */
+ code: { scale: number }
+ /** What gets written, and is the only copy that exists. */
+ stored: Dims
+}
+
+export interface PlanLimits {
+ /** Aspect past which the face detector tiles rather than letterboxing the whole frame, and the
+ * aspect of each tile. The planner has to know these: modelling the detector as a single
+ * letterbox understates how much of a long frame it really sees. */
+ faceTileAbove: number
+ faceTileAspect: number
+ /** Area budget for the decoded frame. */
+ framePixels: number
+ /** Area budget for the text detector's padded canvas. */
+ textCanvasPixels: number
+ /** Upper bound on the stored image; the ratio may make it smaller still. */
+ storedPixels: number
+ /** The fixed square YuNet's build requires. */
+ faceInputSide: 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. */
+ safetyFactor: number
+}
+
+const atLeastOne = (n: number): number => Math.max(1, Math.floor(n))
+
+/** Floor for the decoded frame, named once so the derived default and its own validation cannot
+ * disagree, which is how a legal stored size produced an illegal frame size. */
+const MIN_FRAME_PIXELS = 96 * 96
+
+/** The face detector's tiling rule, owned here because the plan has to model it. yunet.ts imports
+ * these rather than declaring its own, so the model and the plan cannot disagree. */
+export const FACE_TILE_ABOVE = 3
+export const FACE_TILE_ASPECT = 6
+
+/**
+ * Most inferences one image may spend on faces.
+ *
+ * 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
+ * 28,015 inferences from about 100 KB of PNG. Past the cap the windows widen instead of multiplying,
+ * so coverage is kept and the subject shrinks at the model, which is the same trade the area budget
+ * makes everywhere else.
+ */
+export const FACE_MAX_WINDOWS = 12
+
+/** Window length along the long axis, given the tiling rule and the inference cap. Shared by the
+ * planner and the detector so one rule produces both the plan and the work. */
+export function faceWindowLong(long: number, short: number, tileAbove: number, tileAspect: number): number {
+ if (long / short <= tileAbove) {
+ return long
+ }
+ // Each window past the first advances by (windowLong - short), so covering `long` within the cap
+ // needs at least this much window. Ceiled to an integer: this length becomes a crop rectangle,
+ // and sharp rejects a fractional one, so a fraction here is a 500 on every extreme-aspect image
+ // rather than a rounding difference. Up rather than down, so the cap still holds.
+ const toFitCap = Math.ceil((long - short) / FACE_MAX_WINDOWS + short)
+ return Math.min(long, Math.max(tileAspect * short, toFitCap))
+}
+
+/** Scale that fits `dims` inside an area budget, never above 1 because rule 1 forbids upscaling. */
+export function scaleToArea(dims: Dims, budgetPixels: number): number {
+ return Math.min(1, Math.sqrt(budgetPixels / (dims.width * dims.height)))
+}
+
+export function applyScale(dims: Dims, scale: number): Dims {
+ return { width: atLeastOne(dims.width * scale), height: atLeastOne(dims.height * scale) }
+}
+
+/**
+ * Scale into an area budget and stay there.
+ *
+ * `applyScale` alone does not: an axis that scales below one pixel is floored to one, which leaves
+ * the other axis at its full scaled length and the product above the budget by any factor. A
+ * 1x50,000,000 source, a few hundred KB of PNG, plans a 1x4,796,123 frame at ten times the budget,
+ * and the per-worker memory model is derived from that budget. Clamp the long axis against the
+ * floored short one.
+ */
+export function fitToArea(dims: Dims, budgetPixels: number): Dims {
+ const scaled = applyScale(dims, scaleToArea(dims, budgetPixels))
+ if (scaled.width * scaled.height <= budgetPixels) {
+ return scaled
+ }
+ return scaled.width >= scaled.height
+ ? { ...scaled, width: atLeastOne(budgetPixels / scaled.height) }
+ : { ...scaled, height: atLeastOne(budgetPixels / scaled.width) }
+}
+
+const upToStride = (n: number, stride: number): number => Math.max(stride, Math.ceil(n / stride) * stride)
+
+/**
+ * Content dimensions and the stride-padded canvas around them, with the CANVAS bounded rather than
+ * the content.
+ *
+ * Padding rather than resizing to reach the stride, because resizing up enlarges real pixels and
+ * resizing down discards rows, which on a short banner is a large fraction of it. But padding a
+ * collapsed axis multiplies the area back: a 212132x2 frame pads to 212160x32, so an area budget on
+ * the content alone lets a 100 KB source allocate a multi-megapixel tensor. Shrink the long axis
+ * against the short one's padded size until the canvas itself fits.
+ */
+export function fitToCanvas(dims: Dims, budgetPixels: number, stride: number): { content: Dims; canvas: Dims } {
+ let content = fitToArea(dims, budgetPixels)
+ let canvas = { width: upToStride(content.width, stride), height: upToStride(content.height, stride) }
+ for (let guard = 0; guard < 4 && canvas.width * canvas.height > budgetPixels; guard++) {
+ if (canvas.width >= canvas.height) {
+ const width = Math.max(stride, Math.floor(budgetPixels / canvas.height / stride) * stride)
+ content = { ...content, width: Math.min(content.width, width) }
+ canvas = { ...canvas, width: upToStride(content.width, stride) }
+ } else {
+ const height = Math.max(stride, Math.floor(budgetPixels / canvas.width / stride) * stride)
+ content = { ...content, height: Math.min(content.height, height) }
+ canvas = { ...canvas, height: upToStride(content.height, stride) }
+ }
+ }
+ return { content, canvas }
+}
+
+/**
+ * How much of the frame the face detector sees.
+ *
+ * Scaling the long side to fill the square maximises the subject at the model, which is what recall
+ * wants, so enlarging a frame smaller than the square is deliberate and allowed by rule 1: the size
+ * is the model's, not ours. What matters here is only the reduction, since that is what narrows the
+ * ratio.
+ *
+ * It tiles rather than letterboxing once a frame is longer than `tileAbove`, so the scale is set by
+ * the TILE and not by the whole frame. Modelling it as a single letterbox understated the scale on
+ * every long frame, and because the stored size is derived from the weakest detector that understating
+ * crushed the artifact: an 8000x60 banner planned a 1px-tall image where the real geometry supports
+ * nineteen, for a guarantee that never asked for it.
+ */
+export function faceInputScale(dims: Dims, side: number, tileAbove: number, tileAspect: number): number {
+ const long = Math.max(dims.width, dims.height)
+ const short = Math.min(dims.width, dims.height)
+ return Math.min(1, side / faceWindowLong(long, short, tileAbove, tileAspect))
+}
+
+/**
+ * The plan for one source image.
+ *
+ * The stored size is derived from the WEAKEST detector rather than any single one: a guarantee that
+ * holds for the text detector and not the face detector is not a guarantee. Every reduction between
+ * the source and each detector is already folded into its scale, so the ratio is enforced against
+ * what each model really saw rather than against the budgets that were asked for.
+ */
+export function planScales(source: Dims, limits: PlanLimits): ScalePlan {
+ const frame = fitToArea(source, limits.framePixels)
+ const text = fitToCanvas(frame, limits.textCanvasPixels, limits.stride)
+ const faceScale = faceInputScale(frame, limits.faceInputSide, limits.faceTileAbove, limits.faceTileAspect)
+
+ // Each detector's scale relative to the frame, so they are comparable.
+ const textScale = Math.min(text.content.width / frame.width, text.content.height / frame.height)
+ 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)))
+ return {
+ frame,
+ text,
+ face: { scale: faceScale },
+ code: { scale: 1 },
+ stored,
+ }
+}
+
+/**
+ * The limits this deployment runs with.
+ *
+ * Only the stored size is an operator's choice. Everything else follows from it: the detectors have
+ * 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.
+ */
+export function limitsFromEnv(): PlanLimits {
+ const storedPixels = numFromEnv('SCRUB_OUT_MAX_PIXELS', 50_000, 16 * 16, LIMIT_INPUT_PIXELS)
+ const safetyFactor = numFromEnv('SCRUB_SAFETY_FACTOR', 1.3, 1, 4)
+ // 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
+ return {
+ // 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
+ // naming a variable they never set. Only the upper end was clamped, so every stored size
+ // under about 1000 px crash-looped the sidecar before it bound a listener.
+ framePixels: numFromEnv(
+ 'SCRUB_MAX_PIXELS',
+ Math.max(MIN_FRAME_PIXELS, Math.min(LIMIT_INPUT_PIXELS, Math.ceil(needed))),
+ MIN_FRAME_PIXELS,
+ LIMIT_INPUT_PIXELS
+ ),
+ textCanvasPixels: numFromEnv('DET_CANVAS_PIXELS', 736 * 736, 256 * 256, 4096 * 4096),
+ storedPixels,
+ faceInputSide: 640,
+ faceTileAbove: FACE_TILE_ABOVE,
+ faceTileAspect: FACE_TILE_ASPECT,
+ stride: 32,
+ safetyFactor,
+ }
+}
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.ts
index 64f2bfd294a0..a5920fe0c488 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
@@ -18,7 +18,8 @@ import { numFromEnv } from './env.ts'
import { type Box } from './geometry.ts'
import { detectCodes } from './qr.ts'
import { type SafetyModel, classifySafety, loadSafety } from './safety.ts'
-import { SCRUB_OUT_MAX_PIXELS, type Src, decodeSrc, srcSharp } from './src-image.ts'
+import { type Dims, type ScalePlan, limitsFromEnv, planScales } from './scale-plan.ts'
+import { type Src, decodeSrc, probeDims, srcSharp } from './src-image.ts'
import { type YunetModel, detectFacesYunet, loadYunet } from './yunet.ts'
export type TextMode = 'heuristic' | 'dbnet'
@@ -107,17 +108,6 @@ function clampBox(b: Box, W: number, H: number): Box | null {
// --- input preparation --------------------------------------------------------------------------
/** Adaptive DBNet detection budget: big enough to resolve small text on retina shots, capped for cost.
* The returned value is the budget SIDE — dbnet caps its input at detLimit^2 px, aspect preserved. */
-// Detection budget as a fraction of the image's own scale (sqrt of its area). 0.75 clears all crisp
-// rendered UI (session replay's actual domain) cheaply; raise toward 1.0 for faint/small
-// scanned-document print (more CPU), lower for more throughput. Faint low-contrast text is
-// contrast- not size-limited, so resolution alone won't catch every faded fax line.
-const DET_FACTOR = numFromEnv('DET_FACTOR', 0.75, 0.1, 1)
-const DET_CAP = numFromEnv('DET_CAP', 1600, 256, 4096) // cap so retina screenshots don't explode
-function adaptiveDetLimit(W: number, H: number): number {
- const target = Math.round((Math.sqrt(W * H) * DET_FACTOR) / 32) * 32
- return Math.max(736, Math.min(DET_CAP, target))
-}
-
/** Whole worker job for one image, advanced path. Detection is parallelized when PARALLEL_DETECT=1:
* the three ORT sessions run on onnxruntime's background threads. */
export async function advancedScrub(
@@ -149,8 +139,12 @@ export async function advancedScrub(
// Decode the PNG ONCE; every stage re-wraps these raw pixels. The decode is the only stage that
// consumes untrusted bytes, so its failures are permanent-for-these-bytes (422/skip), never 500.
let src: Src
+ let plan: ScalePlan
try {
- src = await decodeSrc(input)
+ const meta = await probeDims(input)
+ // One decision, before any pixel is read: every stage below takes its size from here.
+ plan = planScales(meta, limitsFromEnv())
+ src = await decodeSrc(input, plan.frame)
} catch (e) {
throw e instanceof UndecodableImageError ? e : new UndecodableImageError(String(e))
}
@@ -165,7 +159,10 @@ export async function advancedScrub(
// fixed-cost inference on every frame, which makes it the largest single thing this skips.
if (isUniform(src)) {
timings.uniform = true
- const out = await compose(src, W, H, [], timings)
+ // Stored at the planned size like any other frame. Sizing it by its own dimensions instead
+ // would make a blank frame the one image kept at full resolution, which is a surprising
+ // exception to carry for no benefit: a flat colour is as recognisable small as large.
+ const out = await compose(src, W, H, [], timings, plan.stored)
timings.totalMs = performance.now() - t0
return { out, t: timings }
}
@@ -186,9 +183,8 @@ export async function advancedScrub(
// 2. Face (YuNet) + text (DBNet) on native ORT, codes (zxing) on wasm. Serial by default
// (1 core/worker); parallel opt-in.
- const det = adaptiveDetLimit(W, H)
const runText = (): Promise<Box[]> =>
- textMode === 'dbnet' ? detectTextDbnet(m.dbnet, src, W, H, { detLimit: det }) : detectTextRegions(input, W, H)
+ textMode === 'dbnet' ? detectTextDbnet(m.dbnet, src, plan.text) : detectTextRegions(input, W, H)
let faceBoxes: Box[]
let textBoxes: Box[]
let codeBoxes: Box[]
@@ -229,7 +225,7 @@ export async function advancedScrub(
}
const fillBoxes = [...faceBoxes, ...textBoxes.map(expandText).filter((b): b is Box => b !== null), ...codeBoxes]
- const out = await compose(src, W, H, fillBoxes, timings)
+ const out = await compose(src, W, H, fillBoxes, timings, plan.stored)
timings.totalMs = performance.now() - t0
return { out, t: timings }
}
@@ -339,13 +335,15 @@ export async function compose(
H: number,
boxes: Box[],
timings: StageTimings,
- outMaxPixels: number = SCRUB_OUT_MAX_PIXELS
+ /** Where the plan says this image is stored. Passed in rather than derived here, because the size
+ * is a property of the whole pipeline's geometry and not of the compose step. */
+ stored: Dims
): Promise<Buffer> {
const tC = performance.now()
if (boxes.length === 0) {
timings.composeMs = performance.now() - tC
const tE0 = performance.now()
- const out0 = await encodeStored(srcSharp(src), W, H, outMaxPixels, timings)
+ const out0 = await encodeStored(srcSharp(src), W, H, stored, timings)
timings.encodeMs = performance.now() - tE0
return out0
}
@@ -402,7 +400,7 @@ export async function compose(
const redacted = srcSharp(src).composite([
{ input: overlay, raw: { width: W, height: H, channels: 4 }, left: 0, top: 0 },
])
- const out = await encodeStored(redacted, W, H, outMaxPixels, timings)
+ const out = await encodeStored(redacted, W, H, stored, timings)
timings.encodeMs = performance.now() - tE
return out
}
@@ -425,21 +423,16 @@ async function encodeStored(
redacted: sharp.Sharp,
W: number,
H: number,
- outMaxPixels: number,
+ stored: Dims,
timings?: StageTimings
): Promise<Buffer> {
- if (W * H <= outMaxPixels) {
- if (timings) {
- timings.storedPixels = W * H
- }
- return redacted.png({ compressionLevel: PNG_LEVEL }).toBuffer()
- }
- const scale = Math.sqrt(outMaxPixels / (W * H))
- const outW = Math.max(1, Math.round(W * scale))
- const outH = Math.max(1, Math.round(H * scale))
+ const { width: outW, height: outH } = stored
if (timings) {
timings.storedPixels = outW * outH
}
+ if (outW >= W && outH >= H) {
+ return redacted.png({ compressionLevel: PNG_LEVEL }).toBuffer()
+ }
const { data, info } = await redacted.raw().toBuffer({ resolveWithObject: true })
return sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } })
.resize(outW, outH, { fit: 'fill' })
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
index 8017c4edda43..8243dd1192be 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
@@ -15,32 +15,80 @@
* production. Text is the assertion because it exercises the longest path, DBNet through to the
* composite, and it is the detector whose output the scrub mostly consists of.
*/
-import sharp from 'sharp'
-
import { startPool } from './pool.ts'
const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)
-/** Dark text on light, big enough to detect at any DET_FACTOR, plus a filled block so the composite
- * has more than one region to merge. */
-function contentPng(): Promise<Buffer> {
- return sharp(
- Buffer.from(
- `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360">
- <rect width="640" height="360" fill="#ffffff"/>
- <rect x="24" y="24" width="240" height="64" fill="#111827"/>
- <text x="32" y="180" font-family="Arial" font-size="34" fill="#111827">Account 0098761234</text>
- <text x="32" y="240" font-family="Arial" font-size="34" fill="#111827">[email protected]</text>
- </svg>`
- )
- )
- .png()
- .toBuffer()
-}
+/**
+ * A rendered fixture, embedded as bytes rather than drawn here.
+ *
+ * Drawing text at build time needs a font, and the runtime image has no fontconfig: an SVG with a
+ * `font-family` renders as an empty frame there, so the assertions below all fail on a scrub that is
+ * working perfectly. Rendering once on a machine that has fonts and shipping the pixels keeps the
+ * check honest without adding a font package to the image for the sake of one test.
+ *
+ * 320x180 with two lines of 22px text and a filled block, which reaches the detector well above its
+ * measured floor at any plan the sidecar ships with.
+ */
+const TEXT_FIXTURE_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAUAAAAC0CAMAAADSOgUjAAAC/VBMVEX///8SGSiQk5oxN0TAwcX8/Pynqq8RGCdBRlL+/v55fYVgZW/29veW' +
+ 'mqAYHi0qMD4TGinv8PG0t7vb3N4VHCp1eYL09PX9/f0jKTfu7/D6+vv4+fmSlZwWHSs2PEmeoacgJjX5+voUGyqrrbMXHSyAhIxeYmx+goqm' +
+ 'qa/T1Nf7+/x6foeIjJONkJhWW2Y9Q08kKjglKzna290aIS9kaXL39/cYHy5scHknLjve3+G6vMAfJjTs7e6Tlp3q6uzY2dvz8/QcIzEhJzVx' +
+ 'dX5FS1bh4uTm5+jAwsa5u7/19fZpbXfw8fEmLTry8vOxs7hwdH2qrbKvsbYbIjCgo6nOz9KlqK6wsrdZXmi4ur/k5eYeJTPq6+zd3uGEh4+C' +
+ 'ho1ARVFcYGtobHbo6Orn5+mjpasuNEF2eoKytbrW19pQVWApMD3CxMiipKplanPKy8/l5udSV2KKjpWPkplXXGcmLDooLzzc3d9CR1OVmJ6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(2, WORKER_URL)
- const png = await contentPng()
+ const png = TEXT_FIXTURE_PNG
// Two at once, so the build fails if a second worker cannot start or the pool mis-routes replies.
const [first, second] = await Promise.all([pool.scrub(png), pool.scrub(png)])
await pool.close()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts
index 98cb310630f8..ed8aeb4c6d82 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts
@@ -3,26 +3,7 @@
import sharp from 'sharp'
import { LIMIT_INPUT_PIXELS } from './blur.ts'
-import { numFromEnv } from './env.ts'
-
-// Every frame is downscaled (aspect preserved) to this pixel-AREA budget inside the decode,
-// unconditionally. Two reasons: (1) memory, because compose holds a few full-frame buffers and bytes
-// are proportional to area, so the budget bounds the per-image working set; (2) fidelity honesty,
-// because text detection runs under the same area budget, so storing pixels above it would preserve
-// exactly the detail the detectors never certified as clean. An area budget rather than a long-side
-// cap so tall pages keep legible native resolution instead of being squashed.
-//
-// Lowering this is a redaction-recall change, not a cost one: adaptiveDetLimit derives its input
-// side from the already-downscaled frame and floors at 736, so any budget at or below 1 MP pins
-// detection at that floor and shrinks text relative to it. Re-run `npm run eval` and compare box
-// counts, not just leak percentage, before moving it.
-export const SCRUB_MAX_PIXELS = numFromEnv('SCRUB_MAX_PIXELS', 1600 * 1600, 96 * 96, LIMIT_INPUT_PIXELS)
-
-// Area budget for the STORED image, applied after detection has run at SCRUB_MAX_PIXELS. Storage
-// resolution and detection resolution are separate questions: what a downstream model needs to read
-// a session is not what DBNet needs to find 14px text, and tying them together means every pixel
-// saved in storage is paid for in recall. Defaults to SCRUB_MAX_PIXELS, which is no downscale at all.
-export const SCRUB_OUT_MAX_PIXELS = numFromEnv('SCRUB_OUT_MAX_PIXELS', SCRUB_MAX_PIXELS, 96 * 96, LIMIT_INPUT_PIXELS)
+import { type Dims, limitsFromEnv, planScales } from './scale-plan.ts'
export interface Src {
data: Buffer
@@ -33,14 +14,30 @@ export interface Src {
inputPixels: number
}
-export async function decodeSrc(input: Buffer): Promise<Src> {
+/** Source dimensions from the header alone, so the plan can be made before any pixel is decoded. */
+export async function probeDims(input: Buffer): Promise<Dims> {
+ const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()
+ if (!meta.width || !meta.height) {
+ throw new Error('image has invalid dimensions')
+ }
+ return { width: meta.width, height: meta.height }
+}
+
+/**
+ * Decode to the frame the plan asked for.
+ *
+ * The target comes in rather than being computed here: every stage's size is one decision made in
+ * scale-plan.ts before any pixel is read, so a reader never has to reconstruct the geometry from the
+ * modules that happen to apply it.
+ */
+export async function decodeSrc(input: Buffer, frame?: Dims): Promise<Src> {
const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()
if (!meta.width || !meta.height) {
throw new Error('image has invalid dimensions')
}
- const scale = Math.min(1, Math.sqrt(SCRUB_MAX_PIXELS / (meta.width * meta.height)))
- const targetW = Math.max(1, Math.round(meta.width * scale))
- const targetH = Math.max(1, Math.round(meta.height * scale))
+ const target = frame ?? planScales({ width: meta.width, height: meta.height }, limitsFromEnv()).frame
+ const targetW = target.width
+ const targetH = target.height
// flatten, NOT removeAlpha: removeAlpha discards the alpha channel but keeps the RGB underneath,
// so content hidden under fully transparent pixels (invisible in the replay) would surface in
// the scrubbed output. Flatten composites over a background, destroying hidden RGB.
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.ts
new file mode 100644
index 000000000000..895e876a25a3
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet-windows.test.ts
@@ -0,0 +1,59 @@
+import { FACE_MAX_WINDOWS } from './scale-plan.ts'
+import { detectionWindowsForTest } from './yunet.ts'
+
+describe('detectionWindows', () => {
+ // 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 reader
+ // noticing. Aspect ratios between MAX_ASPECT and TILE_ASPECT are the gap: the frame is longer
+ // than a single pass allows but SHORTER than one tile.
+ it.each([
+ ['just over the tiling threshold', 901, 300],
+ ['a 4:1 banner', 1200, 300],
+ ['a 4:1 banner rotated', 300, 1200],
+ ['exactly at the tile aspect', 1800, 300],
+ ['beyond the tile aspect', 2400, 300],
+ ['an ordinary frame', 1920, 1080],
+ ])('keeps every window inside %s', (_case, W, H) => {
+ const windows = detectionWindowsForTest(W, H)
+
+ expect(windows.length).toBeGreaterThan(0)
+ for (const w of windows) {
+ // These become sharp crop rectangles, which reject fractions. A fractional window is a
+ // 500 on every image of that shape, which the consumer retries and then replays as a
+ // failed batch, so it has to be caught here rather than in production.
+ expect(Number.isInteger(w.left)).toBe(true)
+ expect(Number.isInteger(w.top)).toBe(true)
+ expect(Number.isInteger(w.width)).toBe(true)
+ expect(Number.isInteger(w.height)).toBe(true)
+ expect(w.left).toBeGreaterThanOrEqual(0)
+ expect(w.top).toBeGreaterThanOrEqual(0)
+ expect(w.left + w.width).toBeLessThanOrEqual(W)
+ expect(w.top + w.height).toBeLessThanOrEqual(H)
+ }
+ })
+
+ it.each([
+ ['a moderately long banner', 8000, 60],
+ ['a degenerate strip', 88_590, 8],
+ ['an extreme strip', 280_149, 2],
+ ])('bounds how many inferences %s costs', (_case, W, H) => {
+ // The window count grows with the aspect ratio, which the frame's AREA budget does not bound:
+ // a 400000x4 source asked for 28,015 face inferences from about 100 KB of PNG, which pins a
+ // worker for minutes and trips its deadline. Past the cap the windows widen rather than
+ // multiply, so the frame is still covered end to end.
+ const windows = detectionWindowsForTest(W, H)
+
+ expect(windows.length).toBeLessThanOrEqual(FACE_MAX_WINDOWS + 1)
+ expect(Math.max(...windows.map((w) => Math.max(w.left + w.width, w.top + w.height)))).toBe(Math.max(W, H))
+ })
+
+ it('covers the whole long side across its windows', () => {
+ // Overlap is deliberate (one short-side of it), so a face cannot straddle two windows and be
+ // missed by both. Gaps would be a silent miss in the same way.
+ const windows = detectionWindowsForTest(2400, 300)
+
+ expect(Math.min(...windows.map((w) => w.left))).toBe(0)
+ expect(Math.max(...windows.map((w) => w.left + w.width))).toBe(2400)
+ })
+})
diff --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.ts
index dda1b3a98643..fca0fd12e1eb 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
@@ -10,6 +10,17 @@ import * as ort from 'onnxruntime-node'
import { ORT_THREADS } from './cores.ts'
import { numFromEnv } from './env.ts'
import { type Box } from './geometry.ts'
+// Tiling bounds for extreme-aspect frames. A single letterboxed 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
+// some window): each window then scales by 640/(TILE_ASPECT*shortSide), keeping any face at least
+// ~640/TILE_ASPECT/(shortSide/faceSize) px. TILE_ASPECT=6 keeps a face spanning the full short side
+// at >=107px and a quarter-width face at >=27px, both comfortably detectable.
+// 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_TILE_ABOVE, FACE_TILE_ASPECT, faceWindowLong } from './scale-plan.ts'
import { type Src, srcSharp } from './src-image.ts'
const YUNET_SIDE = 640 // this YuNet build has a FIXED 640x640 input (dynamic dims are rejected)
@@ -51,15 +62,8 @@ export interface FaceOpts {
scoreMin?: number // lower = more sensitive (the verification pass uses this to catch lingering faces)
}
-// Tiling bounds for extreme-aspect frames. A single letterboxed 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
-// some window): each window then scales by 640/(TILE_ASPECT*shortSide), keeping any face at least
-// ~640/TILE_ASPECT/(shortSide/faceSize) px. TILE_ASPECT=6 keeps a face spanning the full short side
-// at >=107px and a quarter-width face at >=27px, both comfortably detectable.
-const MAX_ASPECT = 3
-const TILE_ASPECT = 6
+const MAX_ASPECT = FACE_TILE_ABOVE
+const TILE_ASPECT = FACE_TILE_ASPECT
interface Window {
left: number
@@ -68,17 +72,31 @@ interface Window {
height: number
}
+/** Exposed for tests: a window that starts off the edge silently disables face redaction for a
+ * whole class of frame shapes, and nothing downstream errors when it happens. */
+export function detectionWindowsForTest(W: number, H: number): Window[] {
+ return detectionWindows(W, H)
+}
+
function detectionWindows(W: number, H: number): Window[] {
const long = Math.max(W, H)
const short = Math.min(W, H)
if (long / short <= MAX_ASPECT) {
return [{ left: 0, top: 0, width: W, height: H }]
}
- const windowLong = TILE_ASPECT * short
- const stride = windowLong - short // overlap of one shortSide: no face can straddle two windows undetected
+ // Never longer than the frame: for an aspect between MAX_ASPECT and TILE_ASPECT the frame is
+ // SHORTER than a full tile, so an unclamped windowLong made `long - windowLong` negative and
+ // every window started off the left (or top) edge. Face boxes are translated by that offset, so
+ // at an aspect just over MAX_ASPECT the shift approached the whole long side and no box survived
+ // the width check: face redaction was silently off for every frame between 3:1 and 6:1.
+ // From the planner, so the work done here and the scale the plan assumed cannot disagree, and so
+ // the inference count is bounded: it grows with the aspect ratio, which the area budget does not
+ // constrain, and an unbounded count is a worker pinned by one small crafted image.
+ const windowLong = faceWindowLong(long, short, MAX_ASPECT, TILE_ASPECT)
+ const stride = Math.max(1, windowLong - short) // overlap of one shortSide: no face can straddle two windows undetected
const windows: Window[] = []
for (let pos = 0; ; pos += stride) {
- const start = Math.min(pos, long - windowLong)
+ const start = Math.max(0, Math.min(pos, long - windowLong))
windows.push(
W >= H
? { left: start, top: 0, width: Math.min(windowLong, long), height: H }