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): drop a throwaway PNG encode and size the scrub sidecar's threads (#73643)

Robbiecd0e97c64975
diff --git a/Dockerfile.ml-mirror-image-scrub b/Dockerfile.ml-mirror-image-scrub
index 3b9129d5110e..7afd8859dd39 100644
--- a/Dockerfile.ml-mirror-image-scrub
+++ b/Dockerfile.ml-mirror-image-scrub
@@ -51,12 +51,25 @@ RUN groupadd -g 10001 posthog && \
useradd -u 10001 -g posthog -m -d /home/posthog posthog && \
chown -R posthog:posthog /code
-# One thread per native pool: the sidecar bounds parallelism by its request-concurrency ceiling
-# (IMAGE_SCRUB_CONCURRENCY), so per-op pools sized to host cores would oversubscribe a CPU-limited
-# pod. sharp is pinned at module load in src/blur.ts (sharp.concurrency(1) + cache(false), imported
-# by every scrub path); ORT is pinned per-session (ORT_THREADS).
+# Native pools are bounded so they cannot oversubscribe a CPU-limited pod. sharp is pinned to one
+# thread per operation at module load in src/blur.ts (sharp.concurrency(1) + cache(false), imported
+# by every scrub path), and OpenMP likewise. ORT is sized in src/cores.ts as cores/SCRUB_WORKERS,
+# since onnxruntime-node's run blocks its thread: each worker runs one inference at a time, so it is
+# threads times workers that has to fit the quota. With one worker per core that lands on 1 each.
ENV OMP_NUM_THREADS=1
+# libuv reads this when it first creates its thread pool and never resizes, which happens before any
+# entry-module code under a loader like tsx, so it cannot be set from JS. The pool is process-wide
+# and shared by every worker thread, and each worker's sharp stages queue onto it, so size it by
+# SCRUB_WORKERS (one core per worker) rather than by request concurrency. Below the worker count the
+# sharp stages re-serialise on a pod with more cores than this.
+ENV UV_THREADPOOL_SIZE=8
+
+# Each worker loads its own three ONNX sessions, zxing wasm module and V8 isolate, because sessions
+# cannot be shared across isolates. Memory therefore scales with SCRUB_WORKERS, which defaults to the
+# core count: size the pod's memory limit against cores, not against a single process, or a
+# many-core node OOM-kills the sidecar into a crash loop. Set SCRUB_WORKERS to cap it explicitly.
+
# Prove at build time that the models parse, the native/wasm runtimes load, and a scrub runs end to
# end — a broken model download or prebuilt-binary mismatch fails the image build, not the deploy.
# --network=none doubles as a guarantee that startup has no network dependency, which is also why
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignore b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignore
index 0da03257a7eb..37f0b13ac04c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignore
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignore
@@ -6,6 +6,8 @@ models/
test-data/
# Generated/transient
corpus/
+code-corpus/
+code-corpus-degraded/
out/
# tesseract.js downloads this language data at runtime
*.traineddata
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 a5b402e7ab6b..34a5c991a6ec 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
@@ -57,7 +57,11 @@ Production never imports from `dev/`.
```text
src/ (production — ships)
- main.ts entrypoint: load models -> start servers
+ main.ts entrypoint: start the worker pool -> start servers
+ pool.ts the inference workers: dispatch, per-job deadlines, replace the dead
+ scrub-worker.ts one worker thread: owns its ONNX sessions, scrubs one image at a time
+ worker-protocol.ts the job/reply messages crossing the thread boundary
+ cores.ts worker + ORT thread sizing from the cgroup CPU quota and memory limit
server.ts the /scrub + /metrics listeners; scrub implementation injected
config.ts env-driven runtime config
blur.ts baseline blur (kept in sync with rust/replay-anonymizer/src/blur.rs)
@@ -108,15 +112,41 @@ The face check re-runs YuNet at high sensitivity on the scrubbed output and asse
The suite **gates** on session replay's representative domain (crisp rendered-UI text + faces) and **reports** on a harder scanned-document set:
```text
-UI TEXT (gated): 12/12 clean, 0.0% leak [PASS] # rendered screenshots
-DOCUMENT TEXT (report): 18/20 clean, 5.2% worst [report] # faint fax/scan print, out of domain
-FACE: 88/88 faces redacted (100%)
+UI TEXT (gated): 31/31 clean, 0.0% leak [PASS] # rendered screenshots
+DOCUMENT TEXT (report): 19/20 clean, 2.7% worst [report] # faint fax/scan print, out of domain
+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
+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
+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.
+
## Models are baked into the image
The three ONNX models (safety gate, YuNet, DBNet) are `ADD`ed in `Dockerfile.ml-mirror-image-scrub` (repo root) from commit-pinned upstream URLs with BuildKit `--checksum` verification (same pins + sha256 checks as `dev/setup.ts` — keep them in sync).
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/leak-check.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/leak-check.ts
new file mode 100644
index 000000000000..31ba03197399
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/leak-check.ts
@@ -0,0 +1,61 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * OCR leak on a named set of images, for sweeping detector settings against the cases that fail.
+ * Same measurement as scrub-eval's text check, over an argument list instead of the whole corpus, so
+ * a threshold sweep costs seconds per setting rather than minutes.
+ *
+ * PROB_T=0.2 DILATE_X=12 tsx dev/leak-check.ts corpus/shot_desktop_3840x2160_dpr1_*.png
+ *
+ * OCR reads the ORIGINAL at its own size and the scrubbed output rescaled to match, so settings that
+ * shrink the output are not credited for text that merely became too small to read.
+ */
+import { readFile } from 'node:fs/promises'
+import { basename } from 'node:path'
+import sharp from 'sharp'
+import { type Worker, createWorker } from 'tesseract.js'
+
+import { advancedScrub, loadModels } from '../src/scrub.ts'
+
+const OCR_CONF = 60
+const OCR_MAX_LONG = 2200
+
+async function readableWords(tess: Worker, img: Buffer, W: number, H: number): Promise<number> {
+ const scale = Math.max(1, Math.min(2, OCR_MAX_LONG / Math.max(W, H)))
+ const big = await sharp(img)
+ .resize(Math.round(W * scale), Math.round(H * scale), { fit: 'fill' })
+ .png()
+ .toBuffer()
+ const { data } = await tess.recognize(big, {}, { blocks: true })
+ const words = (data.blocks ?? []).flatMap((b: any) =>
+ (b.paragraphs ?? []).flatMap((p: any) => (p.lines ?? []).flatMap((l: any) => l.words ?? []))
+ ) as { text: string; confidence: number }[]
+ return words.filter((w) => w.confidence >= OCR_CONF && /[A-Za-z0-9]{2,}/.test(w.text ?? '')).length
+}
+
+const files = process.argv.slice(2)
+const models = await loadModels()
+const tess = await createWorker('eng')
+let worst = 0
+let boxes = 0
+let ms = 0
+for (const f of files) {
+ const buf = await readFile(f)
+ const { width: W, height: H } = await sharp(buf).metadata()
+ const orig = await readableWords(tess, buf, W!, H!)
+ const { out, t } = await advancedScrub(buf, models, 'dbnet')
+ const resid = await readableWords(tess, out, W!, H!)
+ const leak = (100 * resid) / Math.max(1, orig)
+ worst = Math.max(worst, leak)
+ boxes += t.textBoxes
+ ms += t.totalMs
+ console.error(` ${basename(f).padEnd(40)} ${orig} -> ${resid} (${leak.toFixed(1)}%) boxes=${t.textBoxes}`)
+}
+await tess.terminate()
+console.log(
+ JSON.stringify({
+ label: process.env.SWEEP_LABEL ?? '',
+ worstLeakPct: Number(worst.toFixed(1)),
+ boxes,
+ meanMs: Number((ms / files.length).toFixed(0)),
+ })
+)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-code-corpus.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-code-corpus.ts
new file mode 100644
index 000000000000..7419a60c0ce5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-code-corpus.ts
@@ -0,0 +1,72 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Screenshots with real machine-decodable codes composited in, for testing the code detector's
+ * recall against its cost. The eval corpus has exactly one code in 113 images, which is enough to
+ * notice a total outage and nothing else.
+ *
+ * Codes are written by zxing's own encoder, so what the detector is asked to find is what a reader
+ * would actually decode. Sizes span the range a code appears at on screen, from a small inline
+ * ticket barcode to a full-panel provisioning QR.
+ *
+ * Output: ./code-corpus/*.png
+ */
+import { readFileSync } from 'node:fs'
+import { mkdir, writeFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import sharp from 'sharp'
+import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'
+
+const wasmFile = createRequire(`${process.cwd()}/`).resolve('zxing-wasm/writer/zxing_writer.wasm')
+const wasmBytes = readFileSync(wasmFile)
+prepareZXingModule({
+ overrides: {
+ wasmBinary: wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength),
+ },
+})
+
+const OUT = new URL('../code-corpus/', import.meta.url).pathname
+
+// The payloads a real replay would carry: a TOTP provisioning URI, a ticket, an account reference.
+const PAYLOADS: [string, 'QRCode' | 'DataMatrix' | 'Aztec' | 'Code128' | 'PDF417'][] = [
+ ['otpauth://totp/Acme:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Acme', 'QRCode'],
+ ['https://acme.example.com/invoice/2026-0042?token=b7f3a91c', 'QRCode'],
+ ['ACCT-0098761234', 'DataMatrix'],
+ ['TICKET-A1B2C3-SEAT-14F', 'Aztec'],
+ ['4242424242424242', 'Code128'],
+]
+
+/** Code side in pixels, as it would appear inside a 1920x1080-ish frame. */
+const SIDES = [96, 160, 280]
+
+async function main(): Promise<void> {
+ await mkdir(OUT, { recursive: true })
+ let n = 0
+ for (const [payload, format] of PAYLOADS) {
+ for (const side of SIDES) {
+ const { svg } = await writeBarcode(payload, { format })
+ const code = await sharp(Buffer.from(svg))
+ .resize(side, side, { fit: 'inside', kernel: 'nearest' })
+ .flatten({ background: '#fff' })
+ .png()
+ .toBuffer()
+ const { width, height } = await sharp(code).metadata()
+ // A plain page with the code placed off-centre, so detection is not helped by it being
+ // the only thing present or by sitting at a predictable origin.
+ const frame = await sharp({
+ create: { width: 1920, height: 1080, channels: 3, background: '#f3f4f6' },
+ })
+ .composite([{ input: code, left: 420, top: 260 }])
+ .png()
+ .toBuffer()
+ const file = `code_${format}_${side}px_${n++}.png`
+ await writeFile(OUT + file, frame)
+ console.log(` ${file} ${width}x${height} code in 1920x1080`)
+ }
+ }
+ console.log(`code corpus: ${n} images in ${OUT}`)
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts
index 1a2e83cea873..a15f41501dd1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts
@@ -10,7 +10,10 @@ import sharp from 'sharp'
const OUT = new URL('../corpus/', import.meta.url).pathname
-function screenshotSvg(w: number, h: number, seed: number): Buffer {
+/** textScale is the capture's device pixel ratio: a retina screenshot has twice the pixels AND twice
+ * the glyph height, while a large monitor at DPR 1 has the pixels without the glyphs, which is the
+ * case that stresses the SCRUB_MAX_PIXELS downscale hardest. */
+function screenshotSvg(w: number, h: number, seed: number, textScale = 1): Buffer {
const rows: string[] = []
const lines = [
'Dashboard Settings Profile Billing Log out',
@@ -22,19 +25,19 @@ function screenshotSvg(w: number, h: number, seed: number): Buffer {
'SSN 123-45-6789 DOB 1990-04-12 Acct 0098761234',
'Search results for "quarterly forecast q3 2026"',
]
- let y = 40
+ let y = 40 * textScale
for (let i = 0; i < 18; i++) {
const text = lines[(i + seed) % lines.length]
rows.push(
- `<text x="32" y="${y}" font-family="Arial" font-size="${14 + ((i + seed) % 6)}" fill="#1f2937">${text}</text>`
+ `<text x="${32 * textScale}" y="${y}" font-family="Arial" font-size="${(14 + ((i + seed) % 6)) * textScale}" fill="#1f2937">${text}</text>`
)
y += Math.floor(h / 20)
}
return Buffer.from(
`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">
<rect width="${w}" height="${h}" fill="#ffffff"/>
- <rect width="${w}" height="56" fill="#111827"/>
- <text x="32" y="36" font-family="Arial" font-size="22" fill="#ffffff">Acme Analytics</text>
+ <rect width="${w}" height="${56 * textScale}" fill="#111827"/>
+ <text x="${32 * textScale}" y="${36 * textScale}" font-family="Arial" font-size="${22 * textScale}" fill="#ffffff">Acme Analytics</text>
${rows.join('\n')}
</svg>`
)
@@ -57,21 +60,31 @@ async function main(): Promise<void> {
await mkdir(OUT, { recursive: true })
const manifest: { file: string; bytes: number; kind: string }[] = []
- const sizes: [number, number, string][] = [
- [1280, 720, 'desktop'],
- [1440, 900, 'desktop'],
- [375, 812, 'mobile'],
- [390, 844, 'mobile'],
+ // Spans both sides of SCRUB_MAX_PIXELS on purpose. Everything at or under 1440x900 stays under
+ // the cap and is never downscaled, so a corpus of only those says nothing about what the cap
+ // costs. The dpr-1 entries above 2 MP are the pessimistic shape: monitor-sized frames whose text
+ // is still 14-19px, so the downscale eats glyph height that was already marginal.
+ const sizes: [number, number, string, number][] = [
+ [1280, 720, 'desktop', 1],
+ [1440, 900, 'desktop', 1],
+ [1920, 1080, 'desktop', 1],
+ [2560, 1440, 'desktop', 1],
+ [3840, 2160, 'desktop', 1],
+ [2880, 1800, 'retina', 2],
+ [3840, 2160, 'retina', 2],
+ [375, 812, 'mobile', 1],
+ [390, 844, 'mobile', 1],
+ [750, 1624, 'mobile', 2],
]
let i = 0
- for (const [w, h, kind] of sizes) {
+ for (const [w, h, kind, dpr] of sizes) {
for (let k = 0; k < 3; k++) {
- const png = await sharp(screenshotSvg(w, h, i + k))
+ const png = await sharp(screenshotSvg(w, h, i + k, dpr))
.png()
.toBuffer()
- const file = `shot_${kind}_${w}x${h}_${k}.png`
+ const file = `shot_${kind}_${w}x${h}_dpr${dpr}_${k}.png`
await writeFile(OUT + file, png)
- manifest.push({ file, bytes: png.length, kind: `screenshot_${kind}` })
+ manifest.push({ file, bytes: png.length, kind: `screenshot_${kind}_dpr${dpr}` })
i++
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/one-shot.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/one-shot.ts
new file mode 100644
index 000000000000..54dbceaa6271
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/one-shot.ts
@@ -0,0 +1,14 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/** Scrub one file under whatever env this process was started with, and write the result.
+ *
+ * SCRUB_MAX_PIXELS=1000000 tsx dev/one-shot.ts corpus/shot.png out/a.png
+ */
+import { readFile, writeFile } from 'node:fs/promises'
+
+import { advancedScrub, loadModels } from '../src/scrub.ts'
+
+const [input, output] = process.argv.slice(2)
+const models = await loadModels()
+const { out, t } = await advancedScrub(await readFile(input), models, 'dbnet')
+await writeFile(output, out)
+console.log(`${output}: text=${t.textBoxes} faces=${t.faces} codes=${t.codes} ${t.totalMs.toFixed(0)}ms`)
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
new file mode 100644
index 000000000000..6a3cc9036a8a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/res-sweep.ts
@@ -0,0 +1,91 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * 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
+ * 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
+ *
+ * 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
+ * not it was redacted, which flatters exactly the settings under test.
+ */
+import { existsSync } from 'node:fs'
+import { readFile, readdir } from 'node:fs/promises'
+import { basename, join } from 'node:path'
+import sharp from 'sharp'
+
+import { advancedScrub, loadModels } from '../src/scrub.ts'
+import { SCRUB_MAX_PIXELS } from '../src/src-image.ts'
+
+const ROOT = new URL('..', import.meta.url).pathname
+
+async function listImages(dir: string): Promise<string[]> {
+ const p = join(ROOT, dir)
+ if (!existsSync(p)) {
+ return []
+ }
+ return (await readdir(p)).filter((f) => /\.(png|jpg|jpeg)$/i.test(f)).map((f) => join(p, f))
+}
+
+async function main(): Promise<void> {
+ const label = process.argv[2] ?? 'run'
+ const models = await loadModels()
+ const files = [
+ ...(await listImages(process.env.SWEEP_DIR ?? 'corpus')),
+ ...(process.env.SWEEP_DIR ? [] : await listImages('fixtures')),
+ ...(process.env.SWEEP_DIR ? [] : await listImages('test-data/text')),
+ ...(process.env.SWEEP_DIR ? [] : await listImages('test-data/faces')),
+ ]
+
+ // The first scrub of a process pays one-off native init, so spend it before timing anything.
+ if (files.length) {
+ await advancedScrub(await readFile(files[0]), models, 'dbnet')
+ }
+
+ const rows: Record<string, number | string>[] = []
+ for (const f of files) {
+ const buf = await readFile(f)
+ const meta = await sharp(buf).metadata()
+ const { out, t } = await advancedScrub(buf, models, 'dbnet')
+ const outMeta = await sharp(out).metadata()
+ rows.push({
+ file: basename(f),
+ srcMp: (meta.width! * meta.height!) / 1e6,
+ outMp: (outMeta.width! * outMeta.height!) / 1e6,
+ textBoxes: t.textBoxes,
+ faces: t.faces,
+ codes: t.codes,
+ outBytes: out.length,
+ totalMs: t.totalMs,
+ textMs: t.textMs,
+ faceMs: t.faceMs,
+ nsfwMs: t.nsfwMs,
+ codesMs: t.codesMs,
+ composeMs: t.composeMs,
+ encodeMs: t.encodeMs,
+ decodeMs: t.decodeMs,
+ })
+ const srcMp = (meta.width! * meta.height!) / 1e6
+ const outMp = (outMeta.width! * outMeta.height!) / 1e6
+ console.error(
+ ` ${basename(f).padEnd(44)} ${srcMp.toFixed(2)}MP -> ${outMp.toFixed(2)}MP ` +
+ `text=${t.textBoxes} faces=${t.faces} codes=${t.codes} ${t.totalMs.toFixed(0)}ms`
+ )
+ }
+
+ console.log(
+ JSON.stringify({
+ label,
+ scrubMaxPixels: SCRUB_MAX_PIXELS,
+ detFactor: process.env.DET_FACTOR ?? '0.75 (default)',
+ rows,
+ })
+ )
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
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
new file mode 100644
index 000000000000..0340fe8638bf
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/compose.test.ts
@@ -0,0 +1,85 @@
+import sharp from 'sharp'
+
+import { type StageTimings, compose } from './scrub.ts'
+
+function timings(): StageTimings {
+ return {
+ decodeMs: 0,
+ nsfwMs: 0,
+ faceMs: 0,
+ textMs: 0,
+ codesMs: 0,
+ composeMs: 0,
+ encodeMs: 0,
+ totalMs: 0,
+ blanked: false,
+ uniform: false,
+ faces: 0,
+ textBoxes: 0,
+ codes: 0,
+ format: 'png',
+ inputPixels: 0,
+ inputBytes: 0,
+ storedPixels: 0,
+ }
+}
+
+describe('compose', () => {
+ const W = 800
+ const H = 600
+ const box = { left: 201, top: 137, width: 197, height: 143 }
+
+ /** Thin dark strokes on white inside the box, so the mean-colour fill comes out light and any
+ * dark pixel in the result is content that escaped it rather than the fill itself. */
+ async function strokesOnWhite(): Promise<{
+ data: Buffer
+ W: number
+ H: number
+ format: string
+ inputPixels: number
+ }> {
+ // Flush to every edge of the box on purpose: a resize kernel reaching outward from the box
+ // boundary has to find content there, or the fixture cannot show the leak it exists to catch.
+ const strokes = []
+ for (let y = box.top; y < box.top + box.height; y += 24) {
+ strokes.push(`<rect x="${box.left}" y="${y}" width="${box.width}" height="5" fill="#000000"/>`)
+ }
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">
+ <rect width="${W}" height="${H}" fill="#ffffff"/>${strokes.join('')}</svg>`
+ // flatten to 3 channels exactly as decodeSrc does: Src is declared 3-channel, and an SVG
+ // renders with alpha, so skipping it hands compose a buffer it reads misaligned.
+ const { data, info } = await sharp(Buffer.from(svg))
+ .flatten({ background: '#fff' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ expect(info.channels).toBe(3)
+ return { data, W, H, format: 'png', inputPixels: W * H }
+ }
+
+ async function darkPixels(png: Buffer): Promise<number> {
+ const { data, info } = await sharp(png).raw().toBuffer({ resolveWithObject: true })
+ let dark = 0
+ for (let i = 0; i < data.length; i += info.channels) {
+ if (data[i] < 100) {
+ dark++
+ }
+ }
+ return dark
+ }
+
+ // Nothing else covers compose or the storage encode: no test reaches advancedScrub, since it
+ // needs the ONNX models. This is the only place a fill that stops surviving the encode would be
+ // caught, and the storage path resizes between the fill and the PNG.
+ //
+ // It does NOT pin the ordering of fill against resize, which is the subtler property: resizing
+ // first leaves a rim of what the box covered, because the kernel reaches past the box edge while
+ // the outward rounding covers only a pixel of rounding. That ordering is verified structurally
+ // (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))
+
+ expect(await darkPixels(out)).toBe(0)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts
index 6b0fb4080285..4fb55e2cddd7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/config.ts
@@ -1,3 +1,5 @@
+import { numFromEnv } from './env.ts'
+
export interface Config {
port: number
// Loopback-only /scrub must not be reachable off-pod, but Prometheus scrapes the pod IP, so /metrics + health
@@ -6,13 +8,24 @@ export interface Config {
maxConcurrency: number
// 413 above the ~10 MiB Kafka message ceiling — bigger is anomalous. The service owns its own memory bound.
maxBodyBytes: number
+ // How long one image may hold a worker, measured from dispatch, before that worker is treated as
+ // wedged and replaced. Sized against the caller that actually gives up first: ScrubClient's
+ // per-request timeout is SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_TIMEOUT_MS (10s), not the 120s
+ // whole-batch budget. Past that point the consumer has already destroyed the socket and is
+ // retrying, so the work is unwanted, and every extra second it runs holds one of maxConcurrency
+ // against requests that are still wanted. The slack over 10s is for the reply crossing back.
+ jobTimeoutMs: number
}
+// Validated like every other knob: a mistyped IMAGE_SCRUB_CONCURRENCY parsed to NaN leaves
+// `inFlight >= maxConcurrency` permanently false, which removes load shedding entirely rather than
+// failing loudly.
export function loadConfig(): Config {
return {
- port: Number(process.env.IMAGE_SCRUB_PORT ?? 9010),
- metricsPort: Number(process.env.IMAGE_SCRUB_METRICS_PORT ?? 9011),
- maxConcurrency: Number(process.env.IMAGE_SCRUB_CONCURRENCY ?? 8),
- maxBodyBytes: Number(process.env.IMAGE_SCRUB_MAX_BODY_BYTES ?? 20 * 1024 * 1024),
+ port: numFromEnv('IMAGE_SCRUB_PORT', 9010, 1, 65535),
+ metricsPort: numFromEnv('IMAGE_SCRUB_METRICS_PORT', 9011, 1, 65535),
+ maxConcurrency: numFromEnv('IMAGE_SCRUB_CONCURRENCY', 8, 1, 256),
+ maxBodyBytes: numFromEnv('IMAGE_SCRUB_MAX_BODY_BYTES', 20 * 1024 * 1024, 1024, 512 * 1024 * 1024),
+ jobTimeoutMs: numFromEnv('IMAGE_SCRUB_JOB_TIMEOUT_MS', 15_000, 1000, 600_000),
}
}
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
new file mode 100644
index 000000000000..2e65461f2b02
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.test.ts
@@ -0,0 +1,82 @@
+import { totalmem } from 'node:os'
+
+import { memoryLimitBytes, quotaCores, workersForMemoryLimit } from './cores.ts'
+
+const reader =
+ (files: Record<string, string>) =>
+ (path: string): string => {
+ const body = files[path]
+ if (body === undefined) {
+ throw new Error(`ENOENT: ${path}`)
+ }
+ return body
+ }
+
+describe('quotaCores', () => {
+ const V2 = '/sys/fs/cgroup/cpu.max'
+ const V1_QUOTA = '/sys/fs/cgroup/cpu/cpu.cfs_quota_us'
+ const V1_PERIOD = '/sys/fs/cgroup/cpu/cpu.cfs_period_us'
+
+ it.each([
+ ['cgroup v2, whole cores', { [V2]: '400000 100000\n' }, 4],
+ ['cgroup v2, fractional floors rather than rounds up', { [V2]: '3500 1000\n' }, 3],
+ ['cgroup v2, sub-core still yields one', { [V2]: '50000 100000\n' }, 1],
+ ['cgroup v1 when v2 is absent', { [V1_QUOTA]: '200000\n', [V1_PERIOD]: '100000\n' }, 2],
+ ])('reads %s', (_case, files, expected) => {
+ expect(quotaCores(reader(files))).toBe(expected)
+ })
+
+ it.each([
+ ['uncapped v2 reports max', { [V2]: 'max 100000\n' }],
+ ['uncapped v1 reports a negative quota', { [V1_QUOTA]: '-1\n', [V1_PERIOD]: '100000\n' }],
+ ['no cgroup files at all', {}],
+ ['a malformed single token', { [V2]: 'garbage\n' }],
+ ])('returns null when %s', (_case, files) => {
+ // null is what makes the caller fall back to a small constant. Returning a number here, or
+ // letting the host's core count through, is how a capped pod ends up oversubscribed.
+ expect(quotaCores(reader(files))).toBeNull()
+ })
+})
+
+describe('memoryLimitBytes', () => {
+ const V2 = '/sys/fs/cgroup/memory.max'
+ const V1 = '/sys/fs/cgroup/memory/memory.limit_in_bytes'
+
+ it('reads the v2 limit, and the v1 one when v2 is absent', () => {
+ expect(memoryLimitBytes(reader({ [V2]: '2147483648\n' }))).toBe(2147483648)
+ expect(memoryLimitBytes(reader({ [V1]: '2147483648\n' }))).toBe(2147483648)
+ })
+
+ it.each([
+ ['uncapped v2 reports max', { [V2]: 'max\n' }],
+ // cgroup v1 has no word for uncapped and reports a number near 2^63 instead. Taken at face
+ // value it divides into a worker count far past any real pod, which is the wrong direction to
+ // be wrong in: the cap exists to stop a many-core node OOM-killing the sidecar at startup.
+ ['uncapped v1 reports a sentinel near 2^63', { [V1]: '9223372036854771712\n' }],
+ ['no cgroup files at all', {}],
+ ['a malformed value', { [V2]: 'garbage\n' }],
+ ])('returns null when %s', (_case, files) => {
+ expect(memoryLimitBytes(reader(files))).toBeNull()
+ })
+
+ it('ignores a limit at or above the host, which is what an uncapped container reads', () => {
+ expect(memoryLimitBytes(reader({ [V2]: `${totalmem()}\n` }))).toBeNull()
+ })
+})
+
+describe('memoryBoundedWorkers', () => {
+ // The reserve stops the arithmetic handing every byte of the limit to workers, leaving the main
+ // thread and the overlap during a replacement unbudgeted. Note what this says about the deployed
+ // 4-core/2Gi shape: memory, not cores, is the binding constraint there, and a pod has to carry
+ // 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],
+ ['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) => {
+ 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
new file mode 100644
index 000000000000..53af8f4210f4
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/cores.ts
@@ -0,0 +1,175 @@
+import { readFileSync } from 'node:fs'
+import { availableParallelism, totalmem } from 'node:os'
+
+import { numFromEnv } from './env.ts'
+
+/** Max threads a single ONNX session may use. Matches the ceiling numFromEnv enforces below. */
+const ORT_THREADS_MAX = 32
+
+/** Assumed allotment when no quota is readable. Small on purpose: see the fallback in containerCores. */
+const NO_QUOTA_CORES = 4
+
+/** Enough to cover any pod this lane is deployed on; guards a bad env value from forking hundreds. */
+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.
+ *
+ * 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.
+ */
+const WORKER_MEMORY_BUDGET_BYTES = 896 * 1024 * 1024
+
+/**
+ * Held back from the worker budget for everything that is not a worker: the main thread's own heap,
+ * express and prom-client, and the overlap while a retiring worker's terminate() is still pending on
+ * a native call that cannot be interrupted, which is exactly when a replacement is being started.
+ * Without it the arithmetic hands every byte of the limit to workers and the guard cannot prevent
+ * the OOM it exists to prevent.
+ */
+const MAIN_THREAD_RESERVE_BYTES = 384 * 1024 * 1024
+
+/**
+ * Inference worker threads, one per core by default, capped by the memory limit.
+ *
+ * onnxruntime-node's `run` blocks the thread that calls it, so a single-threaded process can only
+ * ever have one inference executing however many requests are in flight. A thread each is what
+ * converts cores into concurrent scrubs.
+ *
+ * Cores alone would oversubscribe memory on a node whose CPU-to-memory ratio is higher than the
+ * pod's, and every worker's footprint is paid at startup while it loads its models: too many turns
+ * a healthy pod into an OOM crash loop that never serves a request.
+ */
+export const SCRUB_WORKERS = numFromEnv(
+ 'SCRUB_WORKERS',
+ Math.min(SCRUB_WORKERS_MAX, containerCores(), memoryBoundedWorkers()),
+ 1,
+ SCRUB_WORKERS_MAX
+)
+
+/**
+ * Heap ceiling handed to each worker, so V8 sizes its isolate against its share rather than against
+ * the whole container. Without it every worker independently believes it may grow into the entire
+ * limit, and N of them collectively promise N times what exists: the first one to actually take it
+ * gets the pod OOM-killed instead of hitting its own GC. Reported in MB, which is what
+ * worker_threads' resourceLimits expects.
+ */
+export const WORKER_HEAP_MB = Math.max(256, Math.floor(WORKER_MEMORY_BUDGET_BYTES / (1024 * 1024)) - 128)
+
+/**
+ * Intra-op threads for every ONNX session, defined once so the three models cannot drift apart.
+ *
+ * The default is clamped because `numFromEnv` validates the default as strictly as an env override:
+ * an unclamped `containerCores()` above the ceiling would throw at module load and refuse to start
+ * the sidecar, which is reachable whenever there is no quota to read and the host is large.
+ *
+ * The default divides by the worker count because each worker runs its own inference concurrently
+ * with the others, so the per-session pools multiply. Threads times workers is what has to fit the
+ * allotment: exceeding it is paid back as CFS throttling, which is the cost this sizing exists to
+ * avoid. An ORT_THREADS override is per session and is not divided, so it is a total only when
+ * SCRUB_WORKERS is 1.
+ */
+export const ORT_THREADS = numFromEnv(
+ 'ORT_THREADS',
+ Math.min(ORT_THREADS_MAX, Math.max(1, Math.floor(containerCores() / SCRUB_WORKERS))),
+ 1,
+ ORT_THREADS_MAX
+)
+
+/**
+ * Cores this process may actually use, as opposed to the ones it can see.
+ *
+ * `availableParallelism()` reports the host's CPUs and knows nothing about the cgroup quota, so a
+ * container limited to 4 cores on a 96-core node reports 96. Sizing a thread pool off that number
+ * oversubscribes by an order of magnitude, which costs more in context switching than the threads
+ * ever return.
+ */
+export function containerCores(): number {
+ const quota = quotaCores((path) => readFileSync(path, 'utf8'))
+ if (quota !== null) {
+ return quota
+ }
+ // Deliberately not availableParallelism(): a pod with CPU requests but no limit reads `max`, as
+ // does any runtime sharing the host's cgroup namespace, and the host's core count is the very
+ // number this exists to avoid. Guessing small costs some throughput on an uncapped pod; guessing
+ // the host's size costs an order of magnitude of oversubscription on a capped one.
+ return Math.min(NO_QUOTA_CORES, availableParallelism())
+}
+
+/** Workers the memory limit can hold once the main thread's reserve is set aside, or
+ * SCRUB_WORKERS_MAX when there is no limit to read: an unreadable limit must not cap the pool below
+ * what the cores support. */
+export function memoryBoundedWorkers(): number {
+ const limit = memoryLimitBytes((path) => readFileSync(path, 'utf8'))
+ return limit === null ? SCRUB_WORKERS_MAX : workersForMemoryLimit(limit)
+}
+
+/** Split out so the arithmetic is testable without a cgroup filesystem: getting it wrong is a silent
+ * under- or over-provision rather than an error. */
+export function workersForMemoryLimit(limitBytes: number): number {
+ return Math.max(1, Math.floor((limitBytes - MAIN_THREAD_RESERVE_BYTES) / WORKER_MEMORY_BUDGET_BYTES))
+}
+
+/**
+ * The container's memory limit in bytes, or null when the kernel reports no cap. Takes its reader
+ * for the same reason quotaCores does.
+ *
+ * cgroup v1 reports a sentinel near 2^63 rather than a word like `max` when uncapped, and that
+ * number divided by the per-worker budget is large enough to look like an unbounded allowance, so
+ * anything at or above the host's own memory is treated as no limit.
+ */
+export function memoryLimitBytes(read: (path: string) => string): number | null {
+ for (const path of ['/sys/fs/cgroup/memory.max', '/sys/fs/cgroup/memory/memory.limit_in_bytes']) {
+ try {
+ const raw = read(path).trim()
+ if (raw === 'max') {
+ return null
+ }
+ const bytes = Number(raw)
+ if (Number.isFinite(bytes) && bytes > 0 && bytes < totalmem()) {
+ return bytes
+ }
+ } catch {
+ // not this cgroup version, or not containerised
+ }
+ }
+ return null
+}
+
+/**
+ * The enforced quota in whole cores, or null when the kernel reports no cap. Takes its reader so the
+ * parsing is testable without a cgroup filesystem, which is most of where this can go wrong: the
+ * failure mode is a silently wrong thread count rather than an error.
+ */
+export function quotaCores(read: (path: string) => string): number | null {
+ // cgroup v2: "<quota> <period>", or "max <period>" when uncapped.
+ try {
+ const [quota, period] = read('/sys/fs/cgroup/cpu.max').trim().split(/\s+/)
+ if (quota !== 'max') {
+ return wholeCores(Number(quota) / Number(period))
+ }
+ } catch {
+ // not cgroup v2, or not containerised
+ }
+ // cgroup v1: a negative quota means uncapped.
+ try {
+ const quota = Number(read('/sys/fs/cgroup/cpu/cpu.cfs_quota_us'))
+ const period = Number(read('/sys/fs/cgroup/cpu/cpu.cfs_period_us'))
+ if (quota > 0 && period > 0) {
+ return wholeCores(quota / period)
+ }
+ } catch {
+ // not cgroup v1, or not containerised
+ }
+ return null
+}
+
+/** Floors so a fractional quota never yields more threads than the quota allows: exceeding it is
+ * paid back as CFS throttling, which is the cost this sizing exists to avoid. */
+function wholeCores(cores: number): number | null {
+ return Number.isFinite(cores) ? Math.max(1, Math.floor(cores)) : null
+}
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 9db40278830a..b86f888f0a5f 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
@@ -9,6 +9,7 @@
*/
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 Src, srcSharp } from './src-image.ts'
@@ -33,6 +34,17 @@ const DEFAULTS: Required<DetectOpts> = {
padY: numFromEnv('PAD_Y', 0.3, 0, 2),
}
+/** Unsharp radius applied to the detector's input. 0 disables it. Detection only: the stored image
+ * is never sharpened. */
+const DET_SHARPEN = numFromEnv('DET_SHARPEN', 1, 0, 10)
+
+/** Only sharpen once the model's input is this fraction of the ORIGINAL image's side or smaller,
+ * measured across both downscales together (the SCRUB_MAX_PIXELS cap and the detLimit budget).
+ * Sharpening restores edges a resample removed, so on a frame that was barely resampled there is
+ * nothing to restore and it only amplifies whatever noise the source already had, which costs
+ * recall on grainy scans. */
+const DET_SHARPEN_BELOW = numFromEnv('DET_SHARPEN_BELOW', 0.6, 0.05, 1)
+
const MEAN = [0.485, 0.456, 0.406]
const STD = [0.229, 0.224, 0.225]
@@ -42,15 +54,17 @@ export interface DbnetModel {
outputName: string
}
-// 1 intra-op thread by default so we scale by running many images in parallel (one core each).
-const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
-
export async function loadDbnet(modelPath: string): Promise<DbnetModel> {
const session = await ort.InferenceSession.create(modelPath, {
graphOptimizationLevel: 'all',
intraOpNumThreads: ORT_THREADS,
interOpNumThreads: 1,
executionMode: 'sequential',
+ // The arena allocator holds on to peak allocations for reuse, which on a pool of workers each
+ // running their own sessions is memory multiplied by the worker count: measured at 719MB per
+ // worker with it on against 570MB off, on a 2 MP frame. It buys no measurable CPU here
+ // (97.6% of baseline over the eval corpus, inside run-to-run noise), so the memory is free.
+ enableCpuMemArena: false,
})
return { session, inputName: session.inputNames[0], outputName: session.outputNames[0] }
}
@@ -66,7 +80,16 @@ async function preprocess(
const ratio = Math.min(1, Math.sqrt((detLimit * detLimit) / (W * H)))
const rw = roundTo32(W * ratio)
const rh = roundTo32(H * ratio)
- const { data } = await srcSharp(src).resize(rw, rh, { fit: 'fill' }).raw().toBuffer({ resolveWithObject: true })
+ // 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 sharpened = DET_SHARPEN > 0 && totalRatio < DET_SHARPEN_BELOW
+ const { data } = await (sharpened ? pipeline.sharpen({ sigma: DET_SHARPEN }) : pipeline)
+ .raw()
+ .toBuffer({ resolveWithObject: true })
const chw = new Float32Array(3 * rw * rh)
const plane = rw * rh
for (let i = 0, p = 0; i < data.length; i += 3, p++) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs
new file mode 100644
index 000000000000..cd571e3b5bb2
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs
@@ -0,0 +1,55 @@
+// Stand-in worker for pool.test.ts: speaks the same protocol without loading any model. Plain .mjs
+// so spawning it needs no TypeScript loader, which keeps the test measuring the pool rather than the
+// runner. The input bytes select the behaviour.
+import { existsSync, readFileSync, writeFileSync } from 'node:fs'
+import { parentPort, workerData } from 'node:worker_threads'
+
+// failReadyOnce makes a slot's SECOND life die before signalling ready, so the first replacement of
+// a dead worker fails and the pool has to keep retrying rather than lose the slot. The generation
+// count lives on disk because each life is a fresh worker with no memory of the last.
+if (workerData.failReadyOnce) {
+ const marker = `${workerData.failReadyOnce}.${workerData.index}`
+ const generation = existsSync(marker) ? Number(readFileSync(marker, 'utf8')) : 0
+ writeFileSync(marker, String(generation + 1))
+ if (generation === 1) {
+ process.exit(9)
+ }
+}
+
+parentPort.postMessage({ ready: true })
+
+parentPort.on('message', async (job) => {
+ const kind = Buffer.from(job.input).toString()
+ if (kind === 'crash') {
+ process.exit(7)
+ }
+ if (kind === 'hang') {
+ // Never replies, standing in for a thread stuck inside a native ORT or libvips call. Cannot be
+ // a real block (a busy loop or Atomics.wait) because then terminate() could not stop it either
+ // and the test would hang on cleanup rather than assert anything.
+ return
+ }
+ if (kind === 'undecodable') {
+ parentPort.postMessage({ id: job.id, failure: { message: 'bad bytes', undecodable: true } })
+ return
+ }
+ // Reports its own interval so the test can assert overlap directly rather than inferring
+ // concurrency from total elapsed time, which turns into a flake on a loaded runner.
+ const startedAt = performance.now()
+ await new Promise((resolve) => setTimeout(resolve, 25))
+ const finishedAt = performance.now()
+ // Buffer.from(string) under 4 KiB comes out of Node's shared pool, which is the BLANK_PNG shape:
+ // the backing ArrayBuffer is 8 KiB and is not transferable.
+ const out =
+ kind === 'pooled-buffer'
+ ? Buffer.from('blank')
+ : new Uint8Array(Buffer.from(`done:${kind}:w${workerData.index}`))
+ // No transfer list, mirroring the real worker: a pool-backed ArrayBuffer cannot be transferred,
+ // and attempting it would throw here rather than exercising the path under test.
+ parentPort.postMessage({ id: job.id, out, timings: { totalMs: finishedAt - startedAt, startedAt, finishedAt } })
+ if (kind === 'die-when-idle') {
+ // Answers first, then dies holding no job: the pool has nothing to fail and has to notice
+ // the loss on its own. Replacements get a different kind, so they stay healthy.
+ setTimeout(() => process.exit(11), 5)
+ }
+})
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 41c8eba8bf46..3574e741c12c 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,21 +1,49 @@
+/* eslint-disable no-console -- sidecar logs to stdout */
import { loadConfig } from './config.ts'
-import { ScrubMetrics } from './metrics.ts'
-import { advancedScrub, loadModels } from './scrub.ts'
+import { ORT_THREADS, SCRUB_WORKERS } from './cores.ts'
+import { ScrubMetrics, trackPool } from './metrics.ts'
+import { startPool } from './pool.ts'
import { startServer } from './server.ts'
+// Resolved here rather than in pool.ts: entry points run under tsx, where import.meta works, while
+// jest's CJS transform cannot load a src/ module that contains it (see the note in qr.ts).
+const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)
+
const cfg = loadConfig()
-// Models load before any listener exists, so the readiness probe can't pass until the scrub can run.
-const models = await loadModels()
+// 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)'}`
+)
+// 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
+// builds the pool before any entry-module code runs, so this can only say so.
+if (uvThreadpoolSize < SCRUB_WORKERS) {
+ console.error(
+ `[image-scrub] UV_THREADPOOL_SIZE=${uvThreadpoolSize} is below workers=${SCRUB_WORKERS}, so sharp stages ` +
+ `will serialise; raise it in the image and rebuild`
+ )
+}
+
+// Every worker loads its models before this resolves, so no listener exists until the whole pool can
+// scrub and the readiness probe cannot pass on a half-started pool.
+const pool = await startPool(SCRUB_WORKERS, WORKER_URL, cfg.jobTimeoutMs)
+trackPool(pool)
+
const { scrub, metrics } = startServer(
cfg.port,
cfg.metricsPort,
cfg.maxConcurrency,
cfg.maxBodyBytes,
- async (input) => {
- const { out, t } = await advancedScrub(input, models)
+ async (input, signal) => {
+ const { out, t } = await pool.scrub(input, signal)
ScrubMetrics.observeScrubOutcome(t)
return out
- }
+ },
+ () => pool.usableWorkers() > 0
)
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
@@ -26,8 +54,13 @@ for (const sig of ['SIGINT', 'SIGTERM'] as const) {
let remaining = 2
const exitWhenBothClosed = (): void => {
if (--remaining === 0) {
- clearTimeout(force)
- process.exit(0)
+ // The backstop stays armed across pool.close(): terminating a worker wedged inside a
+ // native ORT call is exactly the step that can hang, and clearing the timer first
+ // would disarm it for the only part of shutdown that needs it.
+ void pool.close().finally(() => {
+ clearTimeout(force)
+ process.exit(0)
+ })
}
}
for (const server of [scrub, metrics]) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts
new file mode 100644
index 000000000000..acf32610ecb4
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts
@@ -0,0 +1,57 @@
+import { ScrubMetrics, register } from './metrics.ts'
+import { type StageTimings } from './scrub.ts'
+
+function timings(over: Partial<StageTimings> = {}): StageTimings {
+ return {
+ decodeMs: 5,
+ nsfwMs: 0,
+ faceMs: 0,
+ textMs: 0,
+ codesMs: 0,
+ composeMs: 1,
+ encodeMs: 2,
+ totalMs: 8,
+ blanked: false,
+ uniform: false,
+ faces: 0,
+ textBoxes: 0,
+ codes: 0,
+ format: 'png',
+ inputPixels: 1000,
+ inputBytes: 500,
+ storedPixels: 1000,
+ ...over,
+ }
+}
+
+async function stageCount(stage: string): Promise<number> {
+ const metric = (await register.getMetricsAsJSON()).find(
+ (m) => m.name === 'ml_mirror_image_scrub_stage_duration_seconds'
+ )
+ const values = (metric as { values: { metricName?: string; labels: Record<string, string>; value: number }[] })
+ .values
+ return values.find((v) => v.metricName?.endsWith('_count') && v.labels.stage === stage)?.value ?? 0
+}
+
+describe('observeScrubOutcome', () => {
+ // A frame that returned early never ran the stages below its exit, so recording their zeros
+ // reports work that did not happen and pulls every one of those quantiles toward zero. The
+ // damage scales with how common the early exit is, so it lands hardest exactly when the
+ // dashboard is being used to judge whether the early exit is worth having.
+ it('records only the stages that ran', async () => {
+ ScrubMetrics.observeScrubOutcome(timings({ uniform: true }))
+
+ expect(await stageCount('decode')).toBe(1)
+ expect(await stageCount('encode')).toBe(1)
+ for (const skipped of ['nsfw', 'face', 'text', 'codes']) {
+ expect(await stageCount(skipped)).toBe(0)
+ }
+
+ ScrubMetrics.observeScrubOutcome(timings({ blanked: true, nsfwMs: 3 }))
+
+ expect(await stageCount('nsfw')).toBe(1)
+ for (const skipped of ['face', 'text', 'codes']) {
+ expect(await stageCount(skipped)).toBe(0)
+ }
+ })
+})
diff --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.ts
index 51ee0a3401c6..f5fd7b8287c3 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,4 +1,4 @@
-import { Counter, Histogram, Registry } from 'prom-client'
+import { Counter, Gauge, Histogram, Registry } from 'prom-client'
import { type StageTimings } from './scrub.ts'
@@ -37,13 +37,22 @@ const aborted = new Counter({
const duration = new Histogram({
name: 'ml_mirror_image_scrub_duration_seconds',
help: 'Scrub wall time',
- buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5],
+ // Out to 60s: under IMAGE_SCRUB_CONCURRENCY-way contention a single scrub's wall time runs to
+ // seconds, and a quantile whose true value sits in the +Inf bucket reports the highest finite
+ // edge instead. A ceiling that traffic actually reaches reads as a flat line at that ceiling.
+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 60],
+ registers: [register],
+})
+const inputBytes = new Histogram({
+ name: 'ml_mirror_image_scrub_input_bytes',
+ help: 'Encoded size of each image received. Its _sum is the denominator for uniform_frame_bytes_total',
+ buckets: [64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216],
registers: [register],
})
const outputBytes = new Histogram({
name: 'ml_mirror_image_scrub_output_bytes',
help: 'Scrubbed output size — a collapse toward zero flags an output regression',
- buckets: [64, 256, 1024, 4096, 16384, 65536],
+ buckets: [64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304],
registers: [register],
})
// The total duration above says the scrub is slow; these say which stage to attack. Every one of
@@ -52,7 +61,7 @@ const stageDuration = new Histogram({
name: 'ml_mirror_image_scrub_stage_duration_seconds',
help: 'Scrub wall time by stage. Sums to roughly the total, so the stage with the largest rate() share is where the CPU goes',
labelNames: ['stage'],
- buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2],
+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30],
registers: [register],
})
// Which decoder we actually pay for. Only formats with a multi-resolution decode (JPEG, WebP) can
@@ -64,9 +73,17 @@ const sourceFormat = new Counter({
labelNames: ['format'],
registers: [register],
})
+// The permanent record's own resolution, which SCRUB_OUT_MAX_PIXELS can now move independently of
+// the source. output_bytes alone cannot show it, being confounded by how compressible the content is.
+const storedMegapixels = new Histogram({
+ name: 'ml_mirror_image_scrub_stored_megapixels',
+ help: 'Megapixels of the image actually written, after any SCRUB_OUT_MAX_PIXELS downscale',
+ buckets: [0.05, 0.1, 0.25, 0.5, 1, 2, 2.56, 4, 8, 16],
+ registers: [register],
+})
const sourceMegapixels = new Histogram({
name: 'ml_mirror_image_scrub_source_megapixels',
- help: 'Source megapixels before the SCRUB_MAX_PIXELS downscale, by format. Mass above the 2.56 budget bucket is the only traffic a shrink-on-load path could speed up',
+ help: 'Source megapixels before the SCRUB_MAX_PIXELS downscale, by format. Mass above the SCRUB_MAX_PIXELS budget is the traffic that actually gets downscaled',
labelNames: ['format'],
buckets: [0.1, 0.25, 0.5, 1, 2, 2.56, 4, 8, 16, 50],
registers: [register],
@@ -79,6 +96,21 @@ const blanked = new Counter({
help: 'Images irreversibly replaced with a blank PNG by the NSFW/gore gate (alert on rate spikes)',
registers: [register],
})
+// Whether blank frames are worth catching earlier (in the Rust collector, before they reach Kafka
+// and S3 at all) is a question about volume, not about the scrub. These two answer it: the count
+// against scrubbed_total gives the share of calls, and the bytes against input_bytes_sum give the
+// share of topic and bucket volume, which is what an upstream skip would actually save. Both count
+// only what survives the dedup upstream, since a repeat of the same blank never reaches this service.
+const uniformFrames = new Counter({
+ name: 'ml_mirror_image_scrub_uniform_frames_total',
+ help: 'Frames of a single flat colour, where detection was skipped as provably vacuous',
+ registers: [register],
+})
+const uniformFrameBytes = new Counter({
+ name: 'ml_mirror_image_scrub_uniform_frame_bytes_total',
+ help: 'Encoded bytes of those frames: the scrub-topic and bucket volume an upstream blank skip would remove',
+ registers: [register],
+})
const facesRedacted = new Counter({
name: 'ml_mirror_image_scrub_faces_redacted_total',
help: 'Face regions solid-filled (alert on a sustained zero rate under traffic: detector outage)',
@@ -95,7 +127,58 @@ const codesRedacted = new Counter({
registers: [register],
})
+// Pool health. Throughput is the product of how many workers are alive and how long each job holds
+// one, and neither is visible from the request counters: a pod down to one worker still answers
+// every request, just eight times slower, which reads as the load easing off.
+const workerRestarts = new Counter({
+ name: 'ml_mirror_image_scrub_worker_restarts_total',
+ help: 'Replacement attempts after a worker died or wedged (a nonzero rate means jobs are being lost and capacity rebuilt)',
+ registers: [register],
+})
+// Separate from the attempt counter because a replacement that cannot start is retried, so the two
+// diverging is what distinguishes a pool rebuilding itself from one failing to.
+const workerRestartFailures = new Counter({
+ name: 'ml_mirror_image_scrub_worker_restart_failures_total',
+ help: 'Replacement attempts that failed to become ready and were themselves retried',
+ registers: [register],
+})
+interface PoolProbe {
+ usableWorkers(): number
+ queueDepth(): number
+}
+// Set after the pool starts, so the gauges have to reach for it at scrape time rather than close
+// over it at construction.
+let pool: PoolProbe | null = null
+
+/** Both values change with every job, far too often to push, so they are sampled when scraped. */
+export function trackPool(started: PoolProbe): void {
+ pool = started
+}
+
+new Gauge({
+ name: 'ml_mirror_image_scrub_workers_usable',
+ help: 'Inference workers alive and able to serve, against SCRUB_WORKERS. Counts busy ones too: it is capacity, not idleness',
+ registers: [register],
+ collect() {
+ if (pool) {
+ this.set(pool.usableWorkers())
+ }
+ },
+})
+new Gauge({
+ name: 'ml_mirror_image_scrub_queue_depth',
+ help: 'Jobs accepted but waiting for a free worker (sustained depth means the pod is undersized, not that a worker is stuck)',
+ registers: [register],
+ collect() {
+ if (pool) {
+ this.set(pool.queueDepth())
+ }
+ },
+})
+
export const ScrubMetrics = {
+ incWorkerRestart: () => workerRestarts.inc(),
+ incWorkerRestartFailure: () => workerRestartFailures.inc(),
incScrubbed: () => scrubbed.inc(),
incFailed: () => failed.inc(),
incUndecodable: () => undecodable.inc(),
@@ -108,6 +191,12 @@ export const ScrubMetrics = {
if (t.blanked) {
blanked.inc()
}
+ if (t.uniform) {
+ uniformFrames.inc()
+ uniformFrameBytes.inc(t.inputBytes)
+ }
+ inputBytes.observe(t.inputBytes)
+ storedMegapixels.observe(t.storedPixels / 1e6)
facesRedacted.inc(t.faces)
textBoxesRedacted.inc(t.textBoxes)
codesRedacted.inc(t.codes)
@@ -115,9 +204,16 @@ export const ScrubMetrics = {
sourceFormat.labels(t.format).inc()
sourceMegapixels.labels(t.format).observe(t.inputPixels / 1e6)
stageDuration.labels('decode').observe(t.decodeMs / 1000)
+ // Each early return skips the stages below it, and recording their zeros would drag those
+ // quantiles toward zero rather than describing the work they do. A uniform frame returns
+ // before the gate and every detector, still paying compose and encode; a blanked one returns
+ // after the gate but before detection and compose.
+ if (t.uniform) {
+ stageDuration.labels('compose').observe(t.composeMs / 1000)
+ stageDuration.labels('encode').observe(t.encodeMs / 1000)
+ return
+ }
stageDuration.labels('nsfw').observe(t.nsfwMs / 1000)
- // A blanked image returns before detection and compose, so recording their zeros would
- // drag those stages' quantiles toward zero rather than describing the work they do.
if (t.blanked) {
return
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts
new file mode 100644
index 000000000000..4b1ab40531d5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts
@@ -0,0 +1,174 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+
+import { UndecodableImageError } from './blur.ts'
+import { ScrubAbandonedError, type ScrubPool, type ScrubResult, startPool } from './pool.ts'
+
+// cwd-relative rather than import.meta, which jest's CJS transform cannot load (see qr.ts).
+const FAKE_WORKER = pathToFileURL(`${process.cwd()}/src/fake-scrub-worker.mjs`)
+
+/** The stand-in worker reports its own interval on top of the real timings, so the test can assert
+ * overlap rather than infer it from elapsed wall time, which only measures how loaded the runner is. */
+type TimedRun = ScrubResult['t'] & { startedAt: number; finishedAt: number }
+
+/** Replacement runs on a backoff timer, so tests wait for the pool to report the capacity back rather
+ * than for a duration that has to be re-tuned whenever that backoff changes. */
+async function untilUsable(pool: ScrubPool, workers: number): Promise<void> {
+ const giveUpAt = performance.now() + 10_000
+ while (pool.usableWorkers() !== workers) {
+ if (performance.now() > giveUpAt) {
+ throw new Error(`pool stuck at ${pool.usableWorkers()} usable workers, wanted ${workers}`)
+ }
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ }
+}
+
+function peakOverlap(results: ScrubResult[]): number {
+ const edges = results.flatMap((r) => [
+ { at: (r.t as TimedRun).startedAt, delta: 1 },
+ { at: (r.t as TimedRun).finishedAt, delta: -1 },
+ ])
+ edges.sort((a, b) => a.at - b.at || a.delta - b.delta)
+ let live = 0
+ let peak = 0
+ for (const edge of edges) {
+ live += edge.delta
+ peak = Math.max(peak, live)
+ }
+ return peak
+}
+
+describe('startPool', () => {
+ let pool: ScrubPool
+
+ afterEach(async () => {
+ await pool?.close()
+ })
+
+ it('runs a job on every worker at once instead of serialising them', async () => {
+ // The whole reason the pool exists: onnxruntime-node's run blocks its thread, so concurrency
+ // only comes from having several. If dispatch ever serialises, throughput collapses to one
+ // image at a time and nothing else in the suite would notice.
+ pool = await startPool(3, FAKE_WORKER)
+
+ const results = await Promise.all(['a', 'b', 'c'].map((k) => pool.scrub(Buffer.from(k))))
+
+ expect(peakOverlap(results)).toBe(3)
+ expect(results.map((r) => r.out.toString().split(':')[1])).toEqual(['a', 'b', 'c'])
+ })
+
+ it('never exceeds the worker count, queueing the rest', async () => {
+ // A job handed to a busy worker would be lost or would overwrite its in-flight reply, so the
+ // ceiling matters as much as the parallelism.
+ pool = await startPool(2, FAKE_WORKER)
+
+ const results = await Promise.all(Array.from({ length: 6 }, (_unused, i) => pool.scrub(Buffer.from(`q${i}`))))
+
+ expect(peakOverlap(results)).toBe(2)
+ expect(results.map((r) => r.out.toString().split(':')[1])).toEqual(['q0', 'q1', 'q2', 'q3', 'q4', 'q5'])
+ })
+
+ it('replaces a worker that dies while idle', async () => {
+ // A worker holding no job leaves nothing to reject, so a pool that only reacts to in-flight
+ // failures loses it silently and never recovers the capacity. The only visible symptom would
+ // be throughput quietly dropping, which is indistinguishable from the load easing off.
+ pool = await startPool(2, FAKE_WORKER)
+
+ // The worker answers before it dies, so wait for the loss itself and then for the recovery:
+ // scrub() returning says nothing about whether the death has happened yet.
+ await pool.scrub(Buffer.from('die-when-idle'))
+ await untilUsable(pool, 1)
+ await untilUsable(pool, 2)
+
+ const results = await Promise.all(['x', 'y'].map((k) => pool.scrub(Buffer.from(k))))
+ expect(peakOverlap(results)).toBe(2)
+ })
+
+ it('survives a reply whose buffer is pool-backed', async () => {
+ // A small Buffer shares Node's 8 KiB pool, and that pool ArrayBuffer cannot be transferred.
+ // BLANK_PNG is exactly this shape, so transferring the reply threw DataCloneError on the
+ // NSFW-gated path, killing the worker and turning a successful blank into a retriable 500.
+ pool = await startPool(1, FAKE_WORKER)
+
+ const result = await pool.scrub(Buffer.from('pooled-buffer'))
+
+ expect(result.out.length).toBeGreaterThan(0)
+ const again = await pool.scrub(Buffer.from('still-alive'))
+ expect(again.out.toString()).toMatch(/^done:still-alive/)
+ })
+
+ it('rebuilds an UndecodableImageError from the wire', async () => {
+ // Structured clone drops the prototype, and this class is what the HTTP layer keys the
+ // permanent 422 on. Lose it and every undecodable image becomes a retriable 500 that the
+ // consumer then attempts four times.
+ pool = await startPool(1, FAKE_WORKER)
+
+ await expect(pool.scrub(Buffer.from('undecodable'))).rejects.toBeInstanceOf(UndecodableImageError)
+ })
+
+ it('drops a queued job whose caller has hung up, without occupying a worker', async () => {
+ // The consumer gives up after 10s and retries, but its queue entry outlives it. Dispatching
+ // it anyway spends a full scrub on a response nobody reads, and the server holds one of its
+ // concurrency slots until that scrub settles, so a backlog of abandoned work sheds live
+ // requests with 503s while the pool is busy with dead ones.
+ pool = await startPool(1, FAKE_WORKER)
+ const hungUp = new AbortController()
+
+ // One worker, so everything after the first job waits in the queue behind it.
+ const running = pool.scrub(Buffer.from('first'))
+ const abandonedJob = pool.scrub(Buffer.from('abandoned'), hungUp.signal)
+ const wanted = pool.scrub(Buffer.from('wanted'))
+ hungUp.abort()
+
+ await expect(abandonedJob).rejects.toBeInstanceOf(ScrubAbandonedError)
+ expect((await running).out.toString()).toMatch(/^done:first/)
+ expect((await wanted).out.toString()).toMatch(/^done:wanted/)
+ })
+
+ it('keeps retrying a replacement that cannot start', async () => {
+ // spawn() writes its slot before it can know the worker is good, so an attempt that fails
+ // leaves one that is never usable and never retired. If the failure is not retried, nothing
+ // else ever will be: the slot is gone for the process's lifetime, the pod serves at reduced
+ // capacity, and liveness only fails at zero usable workers so nothing restarts it.
+ const dir = mkdtempSync(join(tmpdir(), 'scrub-pool-'))
+ try {
+ pool = await startPool(2, FAKE_WORKER, 5000, { failReadyOnce: join(dir, 'died') })
+ await untilUsable(pool, 2)
+
+ // Kill one worker. Its first replacement dies before signalling ready; the second must land.
+ await expect(pool.scrub(Buffer.from('crash'))).rejects.toThrow(/exited with code 7/)
+ await untilUsable(pool, 2)
+
+ const results = await Promise.all(['x', 'y'].map((k) => pool.scrub(Buffer.from(k))))
+ expect(peakOverlap(results)).toBe(2)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('reclaims a worker that never replies, and keeps serving afterwards', async () => {
+ // A thread stuck inside a native ORT or libvips call answers nothing and cannot be interrupted,
+ // so without a deadline the job never settles. The server only decrements its concurrency count
+ // when it does, which means one wedge permanently costs one of maxConcurrency: after enough of
+ // them the sidecar sheds every request with a 503 until the pod is restarted.
+ pool = await startPool(1, FAKE_WORKER, 100)
+
+ await expect(pool.scrub(Buffer.from('hang'))).rejects.toThrow(/timed out/)
+
+ await untilUsable(pool, 1)
+ const after = await pool.scrub(Buffer.from('after'))
+ expect(after.out.toString()).toMatch(/^done:after/)
+ })
+
+ it('fails the in-flight job when a worker dies, and keeps serving afterwards', async () => {
+ // Otherwise the request hangs until the consumer's timeout and the pool quietly shrinks.
+ pool = await startPool(2, FAKE_WORKER)
+
+ await expect(pool.scrub(Buffer.from('crash'))).rejects.toThrow(/exited with code 7/)
+
+ const after = await pool.scrub(Buffer.from('after'))
+ expect(after.out.toString()).toMatch(/^done:after/)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts
new file mode 100644
index 000000000000..8a0acfc54920
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts
@@ -0,0 +1,333 @@
+/* eslint-disable no-console -- sidecar logs to stdout */
+import { Worker } from 'node:worker_threads'
+
+import { UndecodableImageError } from './blur.ts'
+import { WORKER_HEAP_MB } from './cores.ts'
+import { ScrubMetrics } from './metrics.ts'
+import { type StageTimings } from './scrub.ts'
+import { type ScrubReply } from './worker-protocol.ts'
+
+const WORKER_READY_TIMEOUT_MS = 120_000
+const RESTART_BACKOFF_BASE_MS = 500
+const RESTART_BACKOFF_MAX_MS = 30_000
+/** How long a replacement must stay up before its slot's failure streak is forgiven. */
+const RESTART_HEALTHY_MS = 60_000
+/** How long a retired worker may take to terminate before that is worth a log line. */
+const TERMINATE_GRACE_MS = 30_000
+
+/** Nobody was waiting for this job by the time it could have run, so it was never dispatched. Not a
+ * failure of the scrub: the caller has already moved on. */
+export class ScrubAbandonedError extends Error {}
+
+export interface ScrubResult {
+ out: Buffer
+ t: StageTimings
+}
+
+export interface ScrubPool {
+ /** `signal` is the caller's, so a job whose requester has already hung up is dropped from the
+ * queue instead of being dispatched. A job already running cannot be cancelled: its worker is
+ * inside a native call that does not observe signals. */
+ scrub(input: Buffer, signal?: AbortSignal): Promise<ScrubResult>
+ /** Workers alive and able to serve, busy ones included. The liveness probe reads this: with
+ * inference off the main thread, a process whose workers are all dead still answers probes
+ * perfectly well. */
+ usableWorkers(): number
+ queueDepth(): number
+ close(): Promise<void>
+}
+
+interface Pending {
+ resolve: (r: ScrubResult) => void
+ reject: (e: Error) => void
+}
+
+interface Slot {
+ worker: Worker
+ /** The job this worker is running, since it takes exactly one at a time: `run` blocks its thread.
+ * `deadline` is armed here rather than at enqueue so it measures execution, not queue wait. */
+ job: { id: number; pending: Pending; deadline: NodeJS.Timeout } | null
+ /** False until the worker reports ready and again once retired. A worker that never finished
+ * starting will not answer, so dispatching to it strands the job until the consumer times out. */
+ usable: boolean
+ /** A crash raises both `error` and `exit`, so replacement has to be idempotent per slot. */
+ retired: boolean
+ /** When this worker became ready, so the restart backoff can tell a worker that recovered from
+ * one that is flapping. */
+ readyAt: number
+}
+
+/**
+ * A fixed set of inference workers, one job each at a time.
+ *
+ * Resolves only once every worker has loaded its models, so a worker that cannot start (a missing
+ * model, or a loader that does not reach worker threads) fails startup loudly rather than leaving
+ * the pool quietly short-handed. That matters because the listener is bound after this returns, so
+ * the readiness probe never passes on a broken pool.
+ *
+ * The worker URL is a parameter rather than resolved here because jest's CJS transform cannot load a
+ * module containing import.meta, the same constraint qr.ts documents. Entry points run under tsx,
+ * where it works.
+ */
+export async function startPool(
+ size: number,
+ workerUrl: URL,
+ jobTimeoutMs = 15_000,
+ workerData: Record<string, unknown> = {}
+): Promise<ScrubPool> {
+ const slots: Slot[] = []
+ const queue: { id: number; input: Buffer; pending: Pending; signal?: AbortSignal; queuedAt: number }[] = []
+ let nextJobId = 0
+ let closing = false
+ const restartFailures: number[] = []
+
+ const pump = (): void => {
+ if (closing) {
+ return
+ }
+ // Drop from the front anything nobody is waiting for any more, before looking for a worker.
+ // The consumer gives up on a request after 10s and retries, but its queue entry outlived it:
+ // the job would still be dispatched, occupy a worker for a full scrub, and hold one of the
+ // server's concurrency slots the whole time, so a backlog of abandoned work would shed live
+ // requests with 503s while the pool burned CPU on results nobody would read.
+ while (queue.length > 0 && abandoned(queue[0])) {
+ const dead = queue.shift()!
+ dead.pending.reject(new ScrubAbandonedError(`scrub job ${dead.id} was abandoned before it ran`))
+ }
+ for (const slot of slots) {
+ if (!slot?.usable || slot.job || queue.length === 0) {
+ continue
+ }
+ const next = queue.shift()!
+ // A worker wedged inside a native ONNX or libvips call answers nothing and cannot be
+ // interrupted, so without this the job never settles and the server never releases the
+ // concurrency slot it is holding. Armed here, at dispatch, because a deadline armed at
+ // enqueue charges queue wait to whichever worker happens to hold the job when it expires:
+ // under the overload that causes queueing that destroys healthy workers, which removes
+ // capacity and lengthens the queue further.
+ const deadline = setTimeout(() => {
+ retireAndReplace(slots.indexOf(slot), slot, new Error(`scrub job ${next.id} timed out`))
+ }, jobTimeoutMs)
+ deadline.unref()
+ slot.job = { id: next.id, pending: next.pending, deadline }
+ slot.worker.postMessage({ id: next.id, input: next.input })
+ }
+ }
+
+ /** Nobody is waiting: either the caller hung up, or it has been queued past the point where the
+ * caller's own timeout must already have fired even if we were never told. */
+ const abandoned = (job: { signal?: AbortSignal; queuedAt: number }): boolean =>
+ job.signal?.aborted === true || performance.now() - job.queuedAt > jobTimeoutMs
+
+ const spawn = async (index: number): Promise<void> => {
+ const worker = new Worker(workerUrl, {
+ workerData: { ...workerData, index },
+ resourceLimits: { maxOldGenerationSizeMb: WORKER_HEAP_MB },
+ })
+ const slot: Slot = { worker, job: null, usable: false, retired: false, readyAt: 0 }
+ slots[index] = slot
+
+ // An 'error' with no listener is rethrown as an uncaught exception, so one worker's failure
+ // would take the whole sidecar down. This sink covers the worker's entire life, including
+ // the window after the ready race stops listening and before the handlers below are attached.
+ worker.on('error', (error) => console.error(`[image-scrub] worker ${index}: ${String(error)}`))
+
+ // Startup failures reject rather than retire, so a worker that cannot load fails startPool
+ // instead of respawning forever against whatever is broken. All three exits are covered
+ // deliberately: a worker killed while loading models (an OOM, an external terminate) emits
+ // `exit` with no `error`, and waiting only on `error` would leave this promise unsettled, so
+ // startPool would never resolve, no listener would ever bind, and the pod would sit wedged
+ // with nothing logged.
+ await new Promise<void>((ready, failed) => {
+ const onReady = (msg: ScrubReply): void => {
+ if ('ready' in msg) {
+ cleanup()
+ ready()
+ }
+ }
+ const onError = (error: Error): void => {
+ cleanup()
+ failed(error)
+ }
+ const onExit = (code: number): void => {
+ cleanup()
+ failed(new Error(`scrub worker exited with code ${code} before it was ready`))
+ }
+ const timer = setTimeout(() => {
+ cleanup()
+ failed(new Error(`scrub worker did not become ready within ${WORKER_READY_TIMEOUT_MS}ms`))
+ }, WORKER_READY_TIMEOUT_MS)
+ const cleanup = (): void => {
+ clearTimeout(timer)
+ worker.off('message', onReady)
+ worker.off('error', onError)
+ worker.off('exit', onExit)
+ }
+ worker.on('message', onReady)
+ worker.once('error', onError)
+ worker.once('exit', onExit)
+ }).catch((error: unknown) => {
+ // Terminate before rethrowing: a worker that timed out is still running, and would go on
+ // to finish loading and idle forever holding three ONNX sessions and a thread.
+ void worker.terminate().catch(() => {})
+ throw error
+ })
+
+ worker.on('message', (msg: ScrubReply) => {
+ if ('ready' in msg) {
+ return
+ }
+ if (!slot.job || slot.job.id !== msg.id) {
+ // Should be unreachable: one job per slot, replies keyed by id. If it ever happens the
+ // job it belonged to never settles, which strands a concurrency slot in the server for
+ // the process's lifetime, so say so rather than drop it silently.
+ console.error(`[image-scrub] worker ${index} replied for job ${msg.id} with none in flight`)
+ return
+ }
+ const { pending, deadline } = slot.job
+ clearTimeout(deadline)
+ slot.job = null
+ // Only a worker that has been up a while counts as recovered. Resetting on the first
+ // reply would let a worker that alternates crash and success never accumulate failures,
+ // so the backoff below would never engage for exactly the flapping this guards against.
+ if (performance.now() - slot.readyAt > RESTART_HEALTHY_MS) {
+ restartFailures[index] = 0
+ }
+ if ('failure' in msg) {
+ const error = msg.failure.undecodable
+ ? new UndecodableImageError(msg.failure.message)
+ : new Error(msg.failure.message)
+ pending.reject(error)
+ } else {
+ pending.resolve({
+ out: Buffer.from(msg.out.buffer, msg.out.byteOffset, msg.out.byteLength),
+ t: msg.timings,
+ })
+ }
+ pump()
+ })
+
+ // A worker that dies takes any in-flight job with it, so fail that request rather than let it
+ // hang until the consumer's timeout. Replacement is unconditional: a worker that dies while
+ // idle carries no job to fail, and leaving it would shrink the pool with nothing to show it.
+ worker.on('error', (error) => retireAndReplace(index, slot, error))
+ worker.on('exit', (code) => retireAndReplace(index, slot, new Error(`scrub worker exited with code ${code}`)))
+ slot.readyAt = performance.now()
+ slot.usable = true
+ }
+
+ const retireAndReplace = (index: number, slot: Slot, error: Error): void => {
+ if (closing || slot.retired) {
+ return
+ }
+ slot.retired = true
+ slot.usable = false
+ if (slot.job) {
+ clearTimeout(slot.job.deadline)
+ slot.job.pending.reject(error)
+ }
+ slot.job = null
+
+ // Replace only once the old worker is actually gone. terminate() cannot interrupt a thread
+ // sitting inside a native ONNX or libvips call, and that is precisely the case the job
+ // deadline retires a worker for, so spawning on a timer regardless would add a worker while
+ // the one it replaces is still holding its isolate, its three sessions and a frame's buffers.
+ // A sender able to keep producing images that breach the deadline could then walk the pod
+ // past the memory its worker count was sized for, one live-but-retired worker at a time,
+ // until it OOMs. Waiting bounds the pool at its configured size: a wedged worker costs its
+ // own slot until the native call returns, which is the same capacity it was already failing
+ // to provide, and if every slot ends up wedged the liveness probe restarts the pod.
+ const terminated = slot.worker.terminate().catch(() => undefined)
+ const stillGoing = setTimeout(
+ () => console.error(`[image-scrub] worker ${index} has not terminated; its slot stays down until it does`),
+ TERMINATE_GRACE_MS
+ )
+ stillGoing.unref()
+ void terminated.then(() => {
+ clearTimeout(stillGoing)
+ scheduleReplacement(index, error)
+ })
+ }
+
+ /**
+ * Keep trying to rebuild this slot, on a backoff, until one attempt sticks.
+ *
+ * A replacement that itself fails to start is the same condition as a worker that died, and has
+ * to be retried the same way. Giving up after one attempt loses the slot for the process's
+ * lifetime: `spawn` writes its slot before it can know the worker is good, so a failed attempt
+ * leaves one that is never usable and never retired, which nothing else will ever replace. The
+ * pod then serves at reduced capacity indefinitely, and since the liveness probe only fails at
+ * zero usable workers nothing restarts it.
+ *
+ * The backoff exists because a worker that dies on every start (an OOM loading models, a corrupt
+ * model file) would otherwise respawn in a tight loop, spending the CPU the survivors need and
+ * burying the first failure in log noise.
+ */
+ const scheduleReplacement = (index: number, error: Error): void => {
+ if (closing) {
+ return
+ }
+ ScrubMetrics.incWorkerRestart()
+ const failures = (restartFailures[index] ?? 0) + 1
+ restartFailures[index] = failures
+ const delayMs = Math.min(RESTART_BACKOFF_MAX_MS, RESTART_BACKOFF_BASE_MS * 2 ** (failures - 1))
+ console.error(
+ `[image-scrub] worker ${index} lost (${failures} in a row), replacing in ${delayMs}ms: ${error.message}`
+ )
+ const timer = setTimeout(() => {
+ if (closing) {
+ return
+ }
+ spawn(index)
+ .then(pump)
+ .catch((e: unknown) => {
+ ScrubMetrics.incWorkerRestartFailure()
+ scheduleReplacement(index, e instanceof Error ? e : new Error(String(e)))
+ })
+ }, delayMs)
+ timer.unref()
+ }
+
+ await Promise.all(Array.from({ length: size }, (_unused, i) => spawn(i)))
+
+ return {
+ scrub(input: Buffer, signal?: AbortSignal): Promise<ScrubResult> {
+ if (closing) {
+ return Promise.reject(new Error('scrub pool is closing'))
+ }
+ if (signal?.aborted) {
+ return Promise.reject(new ScrubAbandonedError('scrub requested by a caller that had already hung up'))
+ }
+ return new Promise<ScrubResult>((resolve, reject) => {
+ queue.push({
+ id: nextJobId++,
+ input,
+ pending: { resolve, reject },
+ signal,
+ queuedAt: performance.now(),
+ })
+ pump()
+ })
+ },
+ usableWorkers(): number {
+ return slots.filter((s) => s?.usable).length
+ },
+ queueDepth(): number {
+ return queue.length
+ },
+ async close(): Promise<void> {
+ closing = true
+ for (const pendingJob of queue.splice(0)) {
+ pendingJob.pending.reject(new Error('scrub pool is closing'))
+ }
+ // Slots can be absent while a replacement is still waiting out its backoff.
+ for (const slot of slots) {
+ if (slot?.job) {
+ clearTimeout(slot.job.deadline)
+ slot.job.pending.reject(new Error('scrub pool is closing'))
+ }
+ }
+ await Promise.all(slots.filter(Boolean).map((s) => s.worker.terminate()))
+ },
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts
index c0af4c0a03de..44ccd13bdef4 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts
@@ -39,6 +39,11 @@ export async function detectCodes(src: Src): Promise<Box[]> {
// Structural ImageData (zxing dispatches on width/height/data); Node has no ImageData class, so
// colorSpace only exists to satisfy the DOM type.
const imageData = { data: rgba, width: W, height: H, colorSpace: 'srgb' } as ImageData
+ // tryHarder is the dominant cost here (roughly two thirds of this stage) and it stays on. It buys
+ // nothing on crisp on-screen codes, where dropping it finds the same 13 of 15 in dev/make-code-corpus,
+ // but a replay frame can hold a photographed code (a ticket on a phone, a webcam preview), and on
+ // camera-degraded versions of that same set it finds 13 of 15 against 8 without. Restricting
+ // formats is likewise a false economy: it drops a large Code128 that the full set decodes.
const results = await readBarcodes(imageData, { tryHarder: true, maxNumberOfSymbols: 32 })
const boxes: Box[] = []
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts
index 311cbc171366..234574459cd3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts
@@ -6,11 +6,10 @@
*/
import * as ort from 'onnxruntime-node'
-import { numFromEnv } from './env.ts'
+import { ORT_THREADS } from './cores.ts'
import { type Src, srcSharp } from './src-image.ts'
const SAFETY_SIZE = 224 // fixed model input; pixel values 0-255 (normalization is baked into the graph)
-const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
export interface SafetyModel {
session: ort.InferenceSession
@@ -24,6 +23,11 @@ export async function loadSafety(modelPath: string): Promise<SafetyModel> {
intraOpNumThreads: ORT_THREADS,
interOpNumThreads: 1,
executionMode: 'sequential',
+ // The arena allocator holds on to peak allocations for reuse, which on a pool of workers each
+ // running their own sessions is memory multiplied by the worker count: measured at 719MB per
+ // worker with it on against 570MB off, on a 2 MP frame. It buys no measurable CPU here
+ // (97.6% of baseline over the eval corpus, inside run-to-run noise), so the memory is free.
+ enableCpuMemArena: false,
})
return { session, inputName: session.inputNames[0], outputName: session.outputNames[0] }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts
new file mode 100644
index 000000000000..f26915a0c635
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts
@@ -0,0 +1,48 @@
+/**
+ * One inference worker: owns its own ONNX sessions and scrubs one image at a time.
+ *
+ * The whole scrub runs here rather than just the model calls, because onnxruntime-node's `run`
+ * blocks the thread it is called on, so leaving anything else on that thread only serialises it
+ * behind the inference. Sessions cannot be shared across isolates, so each worker loads its own.
+ */
+import { parentPort } from 'node:worker_threads'
+
+import { UndecodableImageError } from './blur.ts'
+import { advancedScrub, loadModels } from './scrub.ts'
+import { type ScrubJob, type ScrubReply } from './worker-protocol.ts'
+
+if (!parentPort) {
+ throw new Error('scrub-worker must be started as a worker thread')
+}
+const port = parentPort
+
+// Loaded before the ready signal, so the pool only reports itself up once every worker can scrub.
+const models = await loadModels()
+port.postMessage({ ready: true } satisfies ScrubReply)
+
+port.on('message', (job: ScrubJob) => {
+ const input = Buffer.from(job.input.buffer, job.input.byteOffset, job.input.byteLength)
+ // Catch rather than pass a rejection handler, so a throw while replying is reported as a failed
+ // job instead of becoming an unhandled rejection that takes the whole worker down with it.
+ advancedScrub(input, models)
+ .then(({ out, t }) => {
+ // Copied, never transferred: nothing this returns has a transferable backing store, so a
+ // transfer list throws DataCloneError on every reply rather than on some edge case.
+ // sharp hands back a napi external ArrayBuffer, which is not detachable even when it is
+ // exactly sized, and the safety gate's BLANK_PNG is carved from Node's shared 8 KiB
+ // buffer pool. A PNG-sized copy costs microseconds against a scrub, so there is nothing
+ // to reclaim by trying to be clever here.
+ port.postMessage({ id: job.id, out, timings: t } satisfies ScrubReply)
+ })
+ .catch((error: unknown) => {
+ // Structured clone drops the prototype, so the one distinction the HTTP layer acts on
+ // (422 permanent versus 500 retriable) has to travel as data rather than as a class.
+ port.postMessage({
+ id: job.id,
+ failure: {
+ message: error instanceof Error ? error.message : String(error),
+ undecodable: error instanceof UndecodableImageError,
+ },
+ } satisfies ScrubReply)
+ })
+})
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 a194463520a4..64f2bfd294a0 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,7 @@ 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 { type Src, decodeSrc, srcSharp } from './src-image.ts'
+import { SCRUB_OUT_MAX_PIXELS, type Src, decodeSrc, srcSharp } from './src-image.ts'
import { type YunetModel, detectFacesYunet, loadYunet } from './yunet.ts'
export type TextMode = 'heuristic' | 'dbnet'
@@ -47,6 +47,10 @@ export async function loadModels(
return { safety, dbnet, yunet }
}
+// For harnesses that load and drop models repeatedly (dev/bench.ts). The sidecar never calls it:
+// models live as long as the worker that loaded them, and every path that ends a worker has either
+// already lost the thread or cannot get a reply from it, so the isolate teardown after
+// worker.terminate() is what frees the sessions there.
export async function disposeModels(m: Models): Promise<void> {
await Promise.all([m.safety.session.release(), m.dbnet.session.release(), m.yunet.session.release()])
}
@@ -62,6 +66,8 @@ export interface StageTimings {
encodeMs: number
totalMs: number
blanked: boolean
+ /** Frame was a single flat colour, so detection was skipped as provably vacuous. */
+ uniform: boolean
faces: number
textBoxes: number
codes: number
@@ -69,6 +75,10 @@ export interface StageTimings {
* and only formats with a multi-resolution decode can be shrunk on load. */
format: string
inputPixels: number
+ /** Encoded size as received, which is what this image cost the topic and the bucket. */
+ inputBytes: number
+ /** Pixels actually written, which SCRUB_OUT_MAX_PIXELS can move independently of the source. */
+ storedPixels: number
}
const NSFW_THRESHOLD = numFromEnv('NSFW_THRESHOLD', 0.6, 0.05, 0.95) // NSFL+NSFW combined; deliberately loose, this is a safety net
@@ -125,11 +135,14 @@ export async function advancedScrub(
encodeMs: 0,
totalMs: 0,
blanked: false,
+ uniform: false,
faces: 0,
textBoxes: 0,
codes: 0,
format: 'unknown',
inputPixels: 0,
+ inputBytes: input.length,
+ storedPixels: 0,
}
const t0 = performance.now()
const tDec = performance.now()
@@ -146,6 +159,17 @@ export async function advancedScrub(
timings.format = src.format
timings.inputPixels = src.inputPixels
+ // A frame of one exact colour holds no text, face, code or anything the safety gate could trip
+ // on, so every model below can only return nothing. Replay captures plenty of them: blank page
+ // loads, transitions, cleared views. Ahead of the gate rather than after it because the gate is a
+ // 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)
+ timings.totalMs = performance.now() - t0
+ return { out, t: timings }
+ }
+
// 1. NSFW / gore gate FIRST: if it trips we skip all detection. Running it first (rather than
// overlapping detection) keeps each worker ~1 core, which packs better under multi-process
// scaling — the throughput-bound case. Set PARALLEL_DETECT=1 to overlap instead (lower latency
@@ -210,6 +234,27 @@ export async function advancedScrub(
return { out, t: timings }
}
+/** Whether every pixel is the same exact colour.
+ *
+ * Exact, and over the same buffer every detector is given, which is what makes skipping them sound:
+ * a frame that is one colour at that resolution cannot yield a detection at that resolution. Both
+ * obvious relaxations break that: a tolerance admits a faint watermark, and running it over a
+ * thumbnail admits a single 14px line once the downscale averages it into the background. Costs
+ * nothing on a frame with content, which differs from its first pixel within the first few, and a
+ * full pass only on frames it is about to save an entire detection round on. */
+export function isUniform(src: Src): boolean {
+ const d = src.data
+ const r = d[0]
+ const g = d[1]
+ const b = d[2]
+ for (let i = 3; i < d.length; i += 3) {
+ if (d[i] !== r || d[i + 1] !== g || d[i + 2] !== b) {
+ return false
+ }
+ }
+ return true
+}
+
/**
* Model-free text detector. Text has high local edge density, so: downscale to grayscale, compute
* a gradient map, tile it, and mark tiles whose mean gradient is high (but not saturated, which
@@ -288,12 +333,19 @@ async function detectTextRegions(input: Buffer, W: number, H: number): Promise<B
* pixels inside a box ever survive. A solid fill carries no glyph, face, or code-module structure
* (blur and mosaic are low-pass filters whose coarse structure an LLM or a re-run detector can
* still recover), so the same irreversible treatment covers all three classes. */
-async function compose(src: Src, W: number, H: number, boxes: Box[], timings: StageTimings): Promise<Buffer> {
+export async function compose(
+ src: Src,
+ W: number,
+ H: number,
+ boxes: Box[],
+ timings: StageTimings,
+ outMaxPixels: number = SCRUB_OUT_MAX_PIXELS
+): Promise<Buffer> {
const tC = performance.now()
if (boxes.length === 0) {
timings.composeMs = performance.now() - tC
const tE0 = performance.now()
- const out0 = await srcSharp(src).png({ compressionLevel: PNG_LEVEL }).toBuffer()
+ const out0 = await encodeStored(srcSharp(src), W, H, outMaxPixels, timings)
timings.encodeMs = performance.now() - tE0
return out0
}
@@ -341,14 +393,56 @@ async function compose(src: Src, W: number, H: number, boxes: Box[], timings: St
// Soften edges by blurring the COLOUR layer only (alpha stays hard, so nothing under a box is
// ever revealed; the blur just fades the fill into its background margin).
const redBlurred = EDGE_BLUR > 0 ? await sharp(red, raw3).blur(EDGE_BLUR).raw().toBuffer() : red
- const overlay = await sharp(redBlurred, raw3).joinChannel(alphaLayer, raw1).png().toBuffer()
+ // Raw, not PNG: composite reads a raw buffer directly, so encoding here would only be decoded
+ // again inside composite, costing a full-frame round-trip at sharp's default compression.
+ const overlay = await sharp(redBlurred, raw3).joinChannel(alphaLayer, raw1).raw().toBuffer()
timings.composeMs = performance.now() - tC
const tE = performance.now()
- const out = await srcSharp(src)
- .composite([{ input: overlay, left: 0, top: 0 }])
- .png({ compressionLevel: PNG_LEVEL })
- .toBuffer()
+ 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)
timings.encodeMs = performance.now() - tE
return out
}
+
+/**
+ * Encode at the storage budget, downscaling only after every fill is already in the pixels.
+ *
+ * Order matters here and is the whole reason this is a separate step. Resampling the frame first and
+ * filling the rescaled boxes afterwards leaves a rim of the content each box exists to destroy: a
+ * resize kernel reaches beyond the box edge, so destination pixels just outside it carry a weighted
+ * average that includes what was inside. Rounding the boxes outward covers one pixel of rounding,
+ * not the kernel's reach, and measured against a black block on white the residue runs to full
+ * intensity one pixel out at a mild downscale. Downscaling what is already redacted cannot leak,
+ * because the only thing left to smear is the solid fill.
+ *
+ * Sharp orders resize before composite within one pipeline regardless of call order, so the resize
+ * has to happen in a second pass over the composited pixels rather than chained onto the first.
+ */
+async function encodeStored(
+ redacted: sharp.Sharp,
+ W: number,
+ H: number,
+ outMaxPixels: number,
+ 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))
+ if (timings) {
+ timings.storedPixels = outW * outH
+ }
+ 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' })
+ .png({ compressionLevel: PNG_LEVEL })
+ .toBuffer()
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
index 8e02e287a71c..3e23d0fbd2fe 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
@@ -70,6 +70,30 @@ describe('image-scrub sidecar server', () => {
expect(res.status).toBe(404)
})
+ it('fails liveness once there is no scrub capacity left', async () => {
+ // Inference runs on worker threads, so a process that has lost all of them answers this
+ // listener as fast as a healthy one. Before that move a wedged inference blocked the event
+ // loop and the probe failed on its own; a static 200 would leave the kubelet with no way to
+ // tell a working pod from one that will never scrub again.
+ let hasCapacity = true
+ const probed = startServer(0, 0, 4, 1024, blurOnly, () => hasCapacity)
+ await once(probed.metrics, 'listening')
+ const probeBase = `http://127.0.0.1:${(probed.metrics.address() as AddressInfo).port}`
+ try {
+ expect((await fetch(`${probeBase}/_health`)).status).toBe(200)
+
+ hasCapacity = false
+ expect((await fetch(`${probeBase}/_health`)).status).toBe(503)
+ // Readiness holds, keeping the pod in the Service that Prometheus scrapes through.
+ expect((await fetch(`${probeBase}/_ready`)).status).toBe(200)
+ } finally {
+ for (const server of [probed.scrub, probed.metrics]) {
+ server.closeAllConnections()
+ server.close()
+ }
+ }
+ })
+
it('does not serve health or metrics on the scrub listener', async () => {
expect((await fetch(`${base}/_health`)).status).toBe(404)
expect((await fetch(`${base}/_ready`)).status).toBe(404)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
index c539d4b9d3e0..3aef4ce7e3d3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
@@ -4,12 +4,15 @@ import { type Server } from 'node:http'
import { UndecodableImageError } from './blur.ts'
import { ScrubMetrics, register } from './metrics.ts'
+import { ScrubAbandonedError } from './pool.ts'
class ConsumerHungUpError extends Error {}
/** The scrub implementation is injected (main.ts wires advancedScrub over its loaded models; tests
- * inject the model-free blur) so the HTTP plumbing stays testable without the ML runtime. */
-export type ScrubFn = (input: Buffer) => Promise<Buffer>
+ * inject the model-free blur) so the HTTP plumbing stays testable without the ML runtime. The
+ * signal carries the caller hanging up, which is what lets queued work be dropped rather than run
+ * for a response nobody will read. */
+export type ScrubFn = (input: Buffer, signal: AbortSignal) => Promise<Buffer>
export interface SidecarServers {
// /scrub, bound to loopback — the pod IP must never expose it.
@@ -23,13 +26,14 @@ export function startServer(
metricsPort: number,
maxConcurrency: number,
maxBodyBytes: number,
- scrubFn: ScrubFn
+ scrubFn: ScrubFn,
+ canScrub: () => boolean = () => true
): SidecarServers {
async function scrub(input: Buffer, signal: AbortSignal): Promise<Buffer> {
if (signal.aborted) {
throw new ConsumerHungUpError()
}
- return scrubFn(input)
+ return scrubFn(input, signal)
}
let inFlight = 0
@@ -96,7 +100,9 @@ export function startServer(
})
app.use((err: Error & { status?: number; type?: string }, _req: Request, res: Response, _next: NextFunction) => {
- if (err instanceof ConsumerHungUpError) {
+ // Both mean the caller stopped waiting: one noticed at the HTTP layer, the other in the pool
+ // when the job came up for dispatch. Neither is a scrub failure, so neither counts as one.
+ if (err instanceof ConsumerHungUpError || err instanceof ScrubAbandonedError) {
ScrubMetrics.incAborted()
return
}
@@ -130,7 +136,21 @@ export function startServer(
const obs = express()
obs.disable('x-powered-by')
obs.disable('etag')
- obs.get(['/_health', '/_ready'], (_req, res) => {
+ // Liveness, not readiness, is what asks whether any scrub capacity is left. Inference runs on
+ // worker threads, so a pod that has lost all of them answers this listener as fast as a healthy
+ // one: without this the kubelet would never restart it. Failing readiness instead would drop the
+ // pod out of the Service that Prometheus scrapes through, taking the metrics away at the one
+ // moment they explain what happened, and it would buy nothing back, since /scrub is loopback-only
+ // and reaches no Service. The probe's failureThreshold decides how long a pool rebuilding through
+ // its restart backoff is given before the pod is replaced.
+ obs.get('/_health', (_req, res) => {
+ if (!canScrub()) {
+ res.status(503).send('no scrub capacity')
+ return
+ }
+ res.status(200).send('ok')
+ })
+ obs.get('/_ready', (_req, res) => {
res.status(200).send('ok')
})
obs.get('/metrics', (_req, res, next) => {
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 aa4026cc1272..8017c4edda43 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
@@ -1,21 +1,71 @@
/**
- * Startup smoke test: loads the models and runs one scrub end to end. Run at image-build time (see
- * Dockerfile.ml-mirror-image-scrub) with networking disabled, so a missing/corrupt model, a
+ * Startup smoke test: starts the worker pool and runs two scrubs end to end. Run at image-build time
+ * (see Dockerfile.ml-mirror-image-scrub) with networking disabled, so a missing/corrupt model, a
* prebuilt-binary mismatch, or an accidental runtime network dependency fails the build instead of
* crash-looping the deploy.
+ *
+ * It goes through the pool rather than calling advancedScrub directly so the build also proves the
+ * runner's TypeScript loader reaches worker threads. Nothing else here would catch that, and its
+ * failure mode is a pod that never becomes ready.
+ *
+ * The input has to carry content, and the result is asserted rather than just checked for bytes.
+ * A flat frame takes the uniform fast path, which returns before the safety gate and all three
+ * detectors: with one the build would still pass while running no inference at all, so an ONNX
+ * binary that loads but cannot `run`, or a zxing wasm module that never instantiates, would reach
+ * 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 { advancedScrub, disposeModels, loadModels } from './scrub.ts'
+import { startPool } from './pool.ts'
-async function main(): Promise<void> {
- const models = await loadModels()
- const png = await sharp({ create: { width: 64, height: 64, channels: 3, background: '#fff' } })
+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()
- const { t } = await advancedScrub(png, models)
- await disposeModels(models)
- console.log(`smoke scrub OK (${Math.round(t.totalMs)}ms)`)
+}
+
+async function main(): Promise<void> {
+ const pool = await startPool(2, WORKER_URL)
+ const png = await contentPng()
+ // 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()
+
+ for (const [label, result] of [
+ ['first', first],
+ ['second', second],
+ ] as const) {
+ if (result.out.length === 0) {
+ throw new Error(`smoke scrub (${label}) produced empty output`)
+ }
+ if (result.t.uniform) {
+ throw new Error(`smoke scrub (${label}) took the uniform fast path, so no model ran`)
+ }
+ if (result.t.blanked) {
+ throw new Error(`smoke scrub (${label}) was blanked by the safety gate on a text fixture`)
+ }
+ if (result.t.textBoxes === 0) {
+ throw new Error(`smoke scrub (${label}) found no text in a fixture that is mostly text`)
+ }
+ }
+ console.log(
+ `smoke scrub OK (${Math.round(first.t.totalMs)}ms, ${Math.round(second.t.totalMs)}ms, ` +
+ `${first.t.textBoxes} text regions)`
+ )
}
main().catch((e) => {
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 54205a54895a..98cb310630f8 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
@@ -6,14 +6,24 @@ 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 — compose holds a few full-frame buffers, and bytes are
-// proportional to area, so the budget bounds the per-image working set (~8 MB/frame at 1600^2 vs
-// ~150 MB at the 50 MP decode limit); (2) fidelity honesty — text detection runs under the same
-// area budget (DET_CAP^2), 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
-// (skyscraper screenshots, infographics) keep legible native resolution instead of being squashed.
+// 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)
+
export interface Src {
data: Buffer
W: number
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/uniform.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/uniform.test.ts
new file mode 100644
index 000000000000..bcdae78e4b45
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/uniform.test.ts
@@ -0,0 +1,31 @@
+import { isUniform } from './scrub.ts'
+
+function frame(width: number, height: number, fill: [number, number, number]): Parameters<typeof isUniform>[0] {
+ const data = Buffer.alloc(width * height * 3)
+ for (let i = 0; i < data.length; i += 3) {
+ data[i] = fill[0]
+ data[i + 1] = fill[1]
+ data[i + 2] = fill[2]
+ }
+ return { data, W: width, H: height, format: 'png', inputPixels: width * height }
+}
+
+describe('isUniform', () => {
+ // Frames it reports as uniform skip detection entirely, so anything it wrongly accepts is text
+ // that never reaches DBNet. A tolerance, or the same check over a thumbnail, would accept a
+ // single line of 14px text in a 1080p frame once it averages into the background.
+ it.each([
+ ['one differing pixel in the middle', 1920 * 540 * 3 + 960 * 3],
+ ['one differing pixel in the last row', 1920 * 1079 * 3],
+ ['one differing pixel adjacent to the first', 3],
+ ])('rejects a frame with %s', (_case, offset) => {
+ const f = frame(1920, 1080, [255, 255, 255])
+ f.data[offset + 1] = 254
+
+ expect(isUniform(f)).toBe(false)
+ })
+
+ it('accepts a frame that is one exact colour', () => {
+ expect(isUniform(frame(1920, 1080, [243, 244, 246]))).toBe(true)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts
new file mode 100644
index 000000000000..632c83984c2d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts
@@ -0,0 +1,12 @@
+import { type StageTimings } from './scrub.ts'
+
+export interface ScrubJob {
+ id: number
+ input: Uint8Array
+}
+
+/** A worker sends `ready` once, then exactly one reply per job. */
+export type ScrubReply =
+ | { ready: true }
+ | { id: number; out: Uint8Array; timings: StageTimings }
+ | { id: number; failure: { message: string; undecodable: boolean } }
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 73a6c8e2e1cb..dda1b3a98643 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
@@ -7,6 +7,7 @@
*/
import * as ort from 'onnxruntime-node'
+import { ORT_THREADS } from './cores.ts'
import { numFromEnv } from './env.ts'
import { type Box } from './geometry.ts'
import { type Src, srcSharp } from './src-image.ts'
@@ -16,7 +17,6 @@ const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)
const NMS_IOU = 0.3
const STRIDES = [8, 16, 32]
const PAD = 0.25 // expand each detected face box so hairline/chin/ears are covered
-const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
export interface YunetModel {
session: ort.InferenceSession
@@ -29,6 +29,11 @@ export async function loadYunet(modelPath: string): Promise<YunetModel> {
intraOpNumThreads: ORT_THREADS,
interOpNumThreads: 1,
executionMode: 'sequential',
+ // The arena allocator holds on to peak allocations for reuse, which on a pool of workers each
+ // running their own sessions is memory multiplied by the worker count: measured at 719MB per
+ // worker with it on against 570MB off, on a 2 MP frame. It buys no measurable CPU here
+ // (97.6% of baseline over the eval corpus, inside run-to-run noise), so the memory is free.
+ enableCpuMemArena: false,
})
return { session, inputName: session.inputNames[0] }
}