:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): convert image-scrub pixels in the Rust addon (#106894)
Robbie1380ebbccc71
diff --git a/.dockerignore b/.dockerignoreindex 84920e8ab14e..a2f110e5b791 100644--- a/.dockerignore+++ b/.dockerignore@@ -98,6 +98,7 @@ nodejs/node_modules# artifacts out of the plugin-server build context.nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/node_modulesnodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/models+nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/nativenodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/corpusnodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/test-datanodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/outdiff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.jsindex 1ebbe9626f8a..2f42114eb202 100644--- a/.github/scripts/trunk-impacted-targets.js+++ b/.github/scripts/trunk-impacted-targets.js@@ -154,8 +154,9 @@ const SEMGREP = 'semgrep'const CARGO_LOCK = 'cargo-lock'// The nodejs lane on its own, for files whose only reader is the ingestion-// suite or an image built purely from nodejs/ sources. The rust and proto-// rules also use it to name that lane without dragging in the frontend.+// suite or an image built from nodejs/ sources and native bindings that claim+// this lane already. The rust and proto rules also use it to name that lane+// without dragging in the frontend.const NODE = 'node'// Suites that run the backend and the frontend together: E2E, Hog, and the@@ -277,7 +278,8 @@ const TRIPWIRE_RULES = [['.github/workflows/container-images-ci.yml', FULLSTACK],['.github/workflows/cd-sandbox-base-image.yml', FULLSTACK],['.github/workflows/ci-recording-rasterizer-container.yml', FULLSTACK],- // The ml-mirror-image-scrub sidecar is built from nodejs/ sources only.+ // The ml-mirror-image-scrub sidecar is built from nodejs/ sources and the replay-anonymizer addon,+ // and a change to that native binding claims the node lane too (NATIVE_BINDING_CONSUMER_LANES).['.github/workflows/ci-ml-mirror-image-scrub-container.yml', NODE],// The skills build renders templates that import product Python, and the// embedded-payload job runs the services/mcp generator that writes into@@ -595,7 +597,8 @@ const TRIPWIRE_RULES = [// Single-purpose images ahead of the fallback: each is read by exactly one// workflow or suite, whose rule above already carries the radius.// Dockerfile.llm-analytics is built only by its master-push CD workflow,- // Dockerfile.ml-mirror-image-scrub only from nodejs/ sources, and the+ // Dockerfile.ml-mirror-image-scrub only from nodejs/ sources and the+ // replay-anonymizer addon, whose changes already claim the node lane, and the// playwright and sandbox images host suites that run both language// families. Everything else at the root, the unified app image included,// backs E2E, hobby, and production, which is the app-image radius; no@@ -1508,7 +1511,10 @@ const RUST_DETERMINATOR = 'rust:determinator'// nodejs/package.json is the only dependent of the two binding packages// (@posthog/hogvm-node, @posthog/replay-anonymizer) today,// and the test suite re-derives that from pnpm-workspace.yaml so a second-// dependent fails there rather than silently going unclaimed here.+// dependent fails there rather than silently going unclaimed here. The+// image-scrub sidecar under nodejs/src/ingestion loads the replay-anonymizer+// addon too, built from the crate rather than installed from the package, and+// it sits in this same lane.const NATIVE_BINDING_CONSUMER_LANES = ['node:ingestion']// Every target this script can emit. A widening decision names this set insteaddiff --git a/.github/workflows/ci-ml-mirror-image-scrub-container.yml b/.github/workflows/ci-ml-mirror-image-scrub-container.ymlindex f7980e57fbd7..f334c62aaf1e 100644--- a/.github/workflows/ci-ml-mirror-image-scrub-container.yml+++ b/.github/workflows/ci-ml-mirror-image-scrub-container.yml@@ -39,9 +39,15 @@ jobs:id: filterwith:token: ${{ steps.app-token.outputs.token || github.token }}+ # The image and the unit tests both build the replay-anonymizer addon from these crates and the workspace files cargo reads.filters: |scrub_files:- 'nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/**'+ - 'rust/replay-anonymizer/**'+ - 'rust/replay-anonymizer-node/**'+ - 'rust/Cargo.toml'+ - 'rust/Cargo.lock'+ - 'rust/.cargo/config.toml'- 'Dockerfile.ml-mirror-image-scrub'- '.github/workflows/ci-ml-mirror-image-scrub-container.yml'@@ -50,7 +56,7 @@ jobs:name: Unit-test ml-mirror-image-scrubif: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && needs.changes.outputs.scrub_files == 'true'runs-on: ubuntu-24.04- timeout-minutes: 10+ timeout-minutes: 15permissions:contents: readdefaults:@@ -79,6 +85,15 @@ jobs:# jest runs through babel (no type errors), so tsc is the only thing that typechecks the worker.run: pnpm typecheck+ - name: Install Rust+ uses: dtolnay/rust-toolchain@3c5f7ea28cd621ae0bf5283f0e981fb97b8a7af9+ with:+ toolchain: 1.91.1++ - name: Build the native addon+ # src/pixel-convert.ts loads the addon at import, so every suite that reaches a detector needs it.+ run: pnpm build:native+- name: Run unit testsrun: pnpm test:unitdiff --git a/Dockerfile.ml-mirror-image-scrub b/Dockerfile.ml-mirror-image-scrubindex 48810f132b93..cb1ee520586c 100644--- a/Dockerfile.ml-mirror-image-scrub+++ b/Dockerfile.ml-mirror-image-scrub@@ -20,6 +20,20 @@# paths filtered in .github/workflows/ci-ml-mirror-image-scrub-container.yml change. Once a pinned# digest expires, running pods keep serving from their cached copy, so the loss only surfaces as new# nodes failing to pull.++# The replay-anonymizer Node addon, which src/pixel-convert.ts loads for the pixel layout conversions+# that build the model inputs. The crate is a member of the rust/ workspace, so cargo needs the whole+# workspace to resolve it, but it compiles only this crate and its dependencies. Bookworm on both+# stages, so the addon links against the glibc that the runtime stage ships.+FROM rust:1.91.1-slim-bookworm AS native-addon+WORKDIR /build/rust+COPY rust ./+RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \+ --mount=type=cache,target=/usr/local/cargo/git,sharing=locked \+ --mount=type=cache,id=ml-mirror-image-scrub-cargo-target,target=/build/rust/target,sharing=locked \+ cargo build --release --locked -p replay-anonymizer-node && \+ cp target/release/libreplay_anonymizer_node.so /build/replay-anonymizer.node+FROM node:24.13.0-bookworm-slimWORKDIR /code/appSHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]@@ -39,6 +53,7 @@ COPY nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/COPY nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src ./src# Tests co-locate in src/ but must not ship in the runtime image.RUN rm -f src/*.test.ts+COPY --from=native-addon /build/replay-anonymizer.node native/replay-anonymizer.node# The ONNX models (safety gate, face, text), pinned to immutable upstream refs and checksum-verified# by BuildKit; loadModels() reads them from WORKDIR-relative models/. Keep URLs + digests in syncdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignore b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/.gitignoreindex 37f0b13ac04c..98b6b749ef3c 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@@ -4,6 +4,8 @@ package-lock.json# Downloaded by `npm run setup` — not committed (see binaries/data decision in README).models/test-data/+# Built from rust/replay-anonymizer-node by `npm run build:native`+native/# Generated/transientcorpus/code-corpus/diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 20fd49408d34..406488946902 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@@ -118,16 +118,17 @@ The fill's edges are feathered by blurring the fill's _colour_ only, never the mAll model inference and image processing run in optimized native libraries.The TypeScript is orchestration plus lightweight output decoding (over small downscaled maps, not full images):-| Stage | Library | Native engine |-| -------------------------------------- | ------------------ | -------------------- |-| NSFW/gore classify (SwiftFormer) | `onnxruntime-node` | ONNX Runtime (C++) |-| Face detection (YuNet) | `onnxruntime-node` | ONNX Runtime (C++) |-| Text detection (DBNet / PP-OCRv6 tiny) | `onnxruntime-node` | ONNX Runtime (C++) |-| QR/barcode detection | `zxing-wasm` | zxing-cpp (C++/wasm) |-| resize / blur / composite / encode | `sharp` | libvips (C++) |+| Stage | Library | Native engine |+| -------------------------------------- | ----------------------- | -------------------- |+| NSFW/gore classify (SwiftFormer) | `onnxruntime-node` | ONNX Runtime (C++) |+| Face detection (YuNet) | `onnxruntime-node` | ONNX Runtime (C++) |+| Text detection (DBNet / PP-OCRv6 tiny) | `onnxruntime-node` | ONNX Runtime (C++) |+| QR/barcode detection | `zxing-wasm` | zxing-cpp (C++/wasm) |+| resize / blur / composite / encode | `sharp` | libvips (C++) |+| model input and zxing pixel layout | replay-anonymizer addon | Rust (neon) |We do not train anything and run no neural nets in JS.-The only hand-written JS is model-output decoding (DBNet threshold + dilation + connected components, YuNet anchor decode + NMS, tensor packing, mask fill), which runs over the small detection maps and is not the bottleneck.+The only hand-written JS is model-output decoding (DBNet threshold + dilation + connected components, YuNet anchor decode + NMS, mask fill), which runs over the small detection maps and is not the bottleneck.Everything model-shaped runs on ONE runtime (onnxruntime-node) on purpose: a second ML runtime would mean a second native-binary compatibility surface and a second set of failure modes (Node-version coupling, slow fallback backends).## Layout@@ -149,6 +150,7 @@ src/ (production — ships)yunet.ts YuNet face detector (ONNX)dbnet.ts DBNet text-region detector (ONNX)qr.ts QR/barcode detector (zxing-wasm, loaded from node_modules — no egress)+ pixel-convert.ts pixel layout conversions for the model inputs and zxing (Rust addon in native/)scale-plan.ts every resize decided in one pure function, before a pixel is readfloors.ts what each detector finds vs what a person can read, and where both were measuredsrc-image.ts decode the source once to raw RGB, to the size the plan asked for@@ -170,9 +172,12 @@ dev/ (non-production)text-det-setup.ts text-det-corpus.ts text-det-quantize.py text-det-dynamic-hw.py its models, labelled images and int8 buildsface-bench.ts face detector comparison: YuNet variants and input sizes, cost and per-face redaction recallcode-bench.ts code detector cost against zxing's input scale, and which codes stay decodable from the stored image+ build-native.ts build the replay-anonymizer Rust addon into native/ (npm run build:native)+ pixel-convert-bench.ts pixel-convert-reference.ts the addon's conversions timed against the TypeScript loops they replacedfixtures/ committed eval fixtures (e.g. a retina Wikipedia page: dense text + a face)models/ test-data/ corpus/ out/ downloaded/generated by setup (gitignored)+native/ the replay-anonymizer addon, built by npm run build:native (gitignored)```## Run@@ -180,7 +185,8 @@ models/ test-data/ corpus/ out/ downloaded/generated by setup (gitignored)```bashpnpm install --ignore-workspace # standalone package: own lockfile, outside the root workspacenpm run setup # download ONNX models + sample test images, generate the corpus-npm run test:unit # fast unit tests (no models/network)+npm run build:native # build the Rust addon into native/ (needs cargo); again after any rust/replay-anonymizer* change+npm run test:unit # fast unit tests (no models/network, but the addon)npm run eval # scrub-quality suite (text + face) over real imagesnpm run bench # latency + per-stage breakdownnpm run smoke # models load + one scrub end to end (what the image build runs)@@ -243,6 +249,17 @@ zxing's wasm loads from `node_modules`.A build-time smoke test (`src/smoke.ts`) then loads the models and runs one scrub with networking disabled, so a broken model, a native-binary mismatch, or an accidental runtime network dependency fails the image build instead of crash-looping the deploy.The sidecar makes no network fetches at startup.+## The native addon++The pixel layout conversions that build each model input and zxing's RGBA frame (`src/pixel-convert.ts`) run in the replay-anonymizer Rust addon (`rust/replay-anonymizer-node/src/pixels.rs`).+The worker allocates each destination typed array, and the addon borrows the source and the destination in place, so no pixel data crosses the boundary as a copy.+The output is the same, bit for bit, as the TypeScript loops that it replaced.+`src/pixel-convert.test.ts` checks that against those loops (`dev/pixel-convert-reference.ts`), and `dev/pixel-convert-bench.ts` times the two.++The image compiles the addon from `rust/` in a Rust stage of `Dockerfile.ml-mirror-image-scrub` and copies it to `native/`.+Every worker loads it at startup, so a missing or stale addon fails the smoke test and with it the image build.+On a dev machine, `npm run build:native` builds it into `native/`.+## ObservabilityBeyond the HTTP outcome counters (scrubbed/failed/undecodable/rejected/too-large/aborted, duration, output bytes), `/metrics` carries the outcome signals an anonymization control needs:diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/build-native.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/build-native.tsnew file mode 100644index 000000000000..10943d83aee8--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/build-native.ts@@ -0,0 +1,40 @@+/* eslint-disable no-console -- CLI output script: console output is the whole point */+/**+ * Builds the replay-anonymizer Rust addon and copies it to native/, where src/pixel-convert.ts loads+ * it from. The image builds the same crate in a Rust stage of Dockerfile.ml-mirror-image-scrub.+ *+ * Needs a Rust toolchain. Run it again after any change under rust/replay-anonymizer-node or+ * rust/replay-anonymizer, because the sidecar loads whatever binary native/ holds.+ */+import { execFileSync } from 'node:child_process'+import { copyFileSync, mkdirSync } from 'node:fs'+import { fileURLToPath } from 'node:url'++const RUST_WORKSPACE = fileURLToPath(new URL('../../../../../../../rust/', import.meta.url))+const NATIVE_DIR = fileURLToPath(new URL('../native/', import.meta.url))++interface CargoMessage {+ reason: string+ target?: { name: string }+ filenames?: string[]+}++const stdout = execFileSync(+ 'cargo',+ ['build', '--release', '--locked', '-p', 'replay-anonymizer-node', '--message-format=json-render-diagnostics'],+ { cwd: RUST_WORKSPACE, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 1 << 30 }+)+const library = stdout+ .toString()+ .split('\n')+ .filter((line) => line.startsWith('{'))+ .map((line) => JSON.parse(line) as CargoMessage)+ .filter((message) => message.reason === 'compiler-artifact' && message.target?.name === 'replay_anonymizer_node')+ .flatMap((message) => message.filenames ?? [])+ .find((file) => /\.(so|dylib)$/.test(file))+if (!library) {+ throw new Error('cargo reported no replay_anonymizer_node library')+}+mkdirSync(NATIVE_DIR, { recursive: true })+copyFileSync(library, `${NATIVE_DIR}replay-anonymizer.node`)+console.log(`copied ${library} to native/replay-anonymizer.node`)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.tsnew file mode 100644index 000000000000..df12383718a9--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-bench.ts@@ -0,0 +1,152 @@+/* eslint-disable no-console -- CLI output script: console output is the whole point */+/**+ * Pixel layout conversion cost: each TypeScript loop that src/pixel-convert.ts replaced against the+ * Rust addon, at the sizes production converts, and whether the two give the same bytes.+ *+ * tsx dev/pixel-convert-bench.ts [--iterations N] [--warmup N]+ *+ * Needs the addon in native/ (`npm run build:native`). Every case converts the same pseudo-random+ * frame with both implementations, alternating call by call so that clock and thermal drift land on+ * both, and reports the median call. Both write into a destination allocated once, so the times+ * leave out the allocation, which production makes the same way either side of the change.+ */+import { arch, cpus } from 'node:os'++import { type PerPlane, rgbToChw, rgbToNormalizedChw, rgbToRgba } from '../src/pixel-convert.ts'+import { mulberry32 } from './bench-common.ts'+import { dbnetChwTs, qrRgbaTs, safetyChwTs, yunetChwTs } from './pixel-convert-reference.ts'++const IMAGENET_MEAN: PerPlane = [0.485, 0.456, 0.406]+const IMAGENET_STD: PerPlane = [0.229, 0.224, 0.225]++type Destination = Float32Array | Uint8ClampedArray++// Methods rather than function properties, so that each case can narrow `out` to its own array type.+interface Case {+ conversion: string+ width: number+ height: number+ allocate(pixels: number): Destination+ ts(rgb: Buffer, out: Destination): void+ rust(rgb: Buffer, out: Destination): void+}++const planes = (pixels: number): Float32Array => new Float32Array(3 * pixels)+const rgbaBytes = (pixels: number): Uint8ClampedArray => new Uint8ClampedArray(4 * pixels)++const dbnet = {+ conversion: 'dbnet (normalized BGR)',+ allocate: planes,+ ts: (rgb: Buffer, chw: Float32Array) => dbnetChwTs(rgb, chw, IMAGENET_MEAN, IMAGENET_STD),+ rust: (rgb: Buffer, chw: Float32Array) => rgbToNormalizedChw(rgb, chw, 'bgr', IMAGENET_MEAN, IMAGENET_STD),+}+const qr = {+ conversion: 'qr (RGBA)',+ allocate: rgbaBytes,+ ts: (rgb: Buffer, rgba: Uint8ClampedArray) => qrRgbaTs(rgb, rgba),+ rust: (rgb: Buffer, rgba: Uint8ClampedArray) => rgbToRgba(rgb, rgba),+}++// The text canvases are two that the scale plan hands DBNet, YuNet takes a fixed 640x640 input,+// safety.ts resizes to 224x224, and the code frames are two sizes that zxing reads.+const CASES: Case[] = [+ { ...dbnet, width: 640, height: 384 },+ { ...dbnet, width: 928, height: 576 },+ {+ conversion: 'yunet (BGR)',+ width: 640,+ height: 640,+ allocate: planes,+ ts: (rgb, chw: Float32Array) => yunetChwTs(rgb, chw),+ rust: (rgb, chw: Float32Array) => rgbToChw(rgb, chw, 'bgr'),+ },+ {+ conversion: 'safety (RGB)',+ width: 224,+ height: 224,+ allocate: planes,+ ts: (rgb, chw: Float32Array) => safetyChwTs(rgb, chw),+ rust: (rgb, chw: Float32Array) => rgbToChw(rgb, chw, 'rgb'),+ },+ { ...qr, width: 638, height: 359 },+ { ...qr, width: 1181, height: 664 },+]++function arg(name: string): string | undefined {+ const i = process.argv.indexOf(`--${name}`)+ return i >= 0 ? process.argv[i + 1] : undefined+}++// A Buffer, like the raw output of sharp that production converts, so V8 compiles the TypeScript+// loops for the same receiver type that they see in production.+function randomRgb(pixels: number, seed: number): Buffer {+ const random = mulberry32(seed)+ const rgb = Buffer.alloc(3 * pixels)+ for (let i = 0; i < rgb.length; i++) {+ rgb[i] = random() * 256+ }+ return rgb+}++function timeMs(run: (rgb: Buffer, out: Destination) => void, rgb: Buffer, out: Destination): number {+ const start = performance.now()+ run(rgb, out)+ return performance.now() - start+}++function median(values: number[]): number {+ const sorted = [...values].sort((a, b) => a - b)+ const middle = sorted.length >> 1+ return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2+}++function main(): void {+ const iterations = Number(arg('iterations') ?? 200)+ const warmup = Number(arg('warmup') ?? 50)+ console.log(`node ${process.version} ${arch()} ${cpus()[0]?.model ?? 'unknown cpu'}`)+ console.log(`median of ${iterations} calls per implementation after ${warmup} warm-up calls\n`)+ console.log(+ 'conversion size pixels ts ms rust ms ts ns/px rust ns/px speedup same bytes'+ )+ let mismatches = 0+ for (const [index, c] of CASES.entries()) {+ const pixels = c.width * c.height+ const rgb = randomRgb(pixels, index + 1)+ const tsOut = c.allocate(pixels)+ const rustOut = c.allocate(pixels)+ for (let i = 0; i < warmup; i++) {+ c.ts(rgb, tsOut)+ c.rust(rgb, rustOut)+ }+ const tsMs: number[] = []+ const rustMs: number[] = []+ for (let i = 0; i < iterations; i++) {+ tsMs.push(timeMs(c.ts, rgb, tsOut))+ rustMs.push(timeMs(c.rust, rgb, rustOut))+ }+ const same = Buffer.from(tsOut.buffer).equals(Buffer.from(rustOut.buffer))+ if (!same) {+ mismatches+++ }+ const [ts, rust] = [median(tsMs), median(rustMs)]+ console.log(+ [+ c.conversion.padEnd(22),+ `${c.width}x${c.height}`.padStart(9),+ String(pixels).padStart(9),+ ts.toFixed(3).padStart(8),+ rust.toFixed(3).padStart(8),+ ((ts * 1e6) / pixels).toFixed(2).padStart(9),+ ((rust * 1e6) / pixels).toFixed(2).padStart(11),+ `${(ts / rust).toFixed(1)}x`.padStart(8),+ (same ? 'yes' : 'NO').padStart(11),+ ].join(' ')+ )+ }+ if (mismatches > 0) {+ console.error(`\n${mismatches} of ${CASES.length} conversions gave different bytes`)+ process.exitCode = 1+ }+}++main()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-reference.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-reference.tsnew file mode 100644index 000000000000..17c1ec8ad7a3--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/pixel-convert-reference.ts@@ -0,0 +1,46 @@+/**+ * The TypeScript loops that src/pixel-convert.ts replaced, as they ran at each call site. They are+ * the reference that the Rust conversions must match bit for bit (src/pixel-convert.test.ts), and+ * the baseline that dev/pixel-convert-bench.ts times them against. The only change from the call+ * sites is that the destination and the statistics come in as arguments.+ */++/** dbnet.ts: BGR planes with the statistics applied in plane order. */+export function dbnetChwTs(data: Uint8Array, chw: Float32Array, mean: readonly number[], std: readonly number[]): void {+ const plane = chw.length / 3+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {+ chw[p] = (data[i + 2] / 255 - mean[0]) / std[0]+ chw[plane + p] = (data[i + 1] / 255 - mean[1]) / std[1]+ chw[2 * plane + p] = (data[i] / 255 - mean[2]) / std[2]+ }+}++/** yunet.ts: BGR planes with the byte values unchanged. */+export function yunetChwTs(data: Uint8Array, chw: Float32Array): void {+ const plane = chw.length / 3+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {+ chw[p] = data[i + 2] // B+ chw[plane + p] = data[i + 1] // G+ chw[2 * plane + p] = data[i] // R+ }+}++/** safety.ts: RGB planes with the byte values unchanged. */+export function safetyChwTs(data: Uint8Array, chw: Float32Array): void {+ const plane = chw.length / 3+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {+ chw[p] = data[i]+ chw[plane + p] = data[i + 1]+ chw[2 * plane + p] = data[i + 2]+ }+}++/** qr.ts: RGBA with every pixel opaque. */+export function qrRgbaTs(data: Uint8Array, rgba: Uint8ClampedArray): void {+ for (let i = 0, o = 0; i < data.length; i += 3, o += 4) {+ rgba[o] = data[i]+ rgba[o + 1] = data[i + 1]+ rgba[o + 2] = data[i + 2]+ rgba[o + 3] = 255+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.jsonindex 3bd277a292bb..7017af9f3b99 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json@@ -12,6 +12,7 @@"format": "oxfmt -c .oxfmtrc.json","format:check": "oxfmt -c .oxfmtrc.json --check","setup": "tsx dev/setup.ts",+ "build:native": "tsx dev/build-native.ts","corpus": "tsx dev/make-corpus.ts","bench": "tsx dev/bench.ts","scale": "tsx dev/scale.ts",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.tsindex d763de240496..6a78427d9e06 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@@ -12,6 +12,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 PerPlane, rgbToNormalizedChw } from './pixel-convert.ts'import { type Dims } from './scale-plan.ts'import { type Src, srcSharp } from './src-image.ts'@@ -45,8 +46,8 @@ const DET_SHARPEN = numFromEnv('DET_SHARPEN', 1, 0, 10)* 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]+const MEAN: PerPlane = [0.485, 0.456, 0.406]+const STD: PerPlane = [0.229, 0.224, 0.225]export interface DbnetModel {session: ort.InferenceSession@@ -90,13 +91,8 @@ async function preprocess(.raw().toBuffer({ resolveWithObject: true })const chw = new Float32Array(3 * rw * rh)- const plane = rw * rh// PaddleOCR decodes with OpenCV, so the model takes BGR planes, with the statistics applied in that order.- for (let i = 0, p = 0; i < data.length; i += 3, p++) {- chw[p] = (data[i + 2] / 255 - MEAN[0]) / STD[0]- chw[plane + p] = (data[i + 1] / 255 - MEAN[1]) / STD[1]- chw[2 * plane + p] = (data[i] / 255 - MEAN[2]) / STD[2]- }+ rgbToNormalizedChw(data, chw, 'bgr', MEAN, STD)return { data: chw, rw, rh, sx: src.W / cw, sy: src.H / ch }}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.test.tsnew file mode 100644index 000000000000..a6f7b0601806--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.test.ts@@ -0,0 +1,190 @@+import { mulberry32 } from '../dev/bench-common.ts'+import { dbnetChwTs, qrRgbaTs, safetyChwTs, yunetChwTs } from '../dev/pixel-convert-reference.ts'+import { type PerPlane, rgbToChw, rgbToNormalizedChw, rgbToRgba } from './pixel-convert.ts'++const IMAGENET_MEAN: PerPlane = [0.485, 0.456, 0.406]+const IMAGENET_STD: PerPlane = [0.229, 0.224, 0.225]++type Destination = Float32Array | Uint8ClampedArray++// Methods rather than function properties, so that each entry can narrow `out` to its own array type.+interface Conversion {+ name: string+ valuesPerPixel: number+ bytesPerValue: number+ view(buffer: ArrayBuffer, byteOffset: number, length: number): Destination+ rust(rgb: Uint8Array, out: Destination): void+ ts(rgb: Uint8Array, out: Destination): void+}++const floatPlanes = {+ valuesPerPixel: 3,+ bytesPerValue: 4,+ view: (buffer: ArrayBuffer, byteOffset: number, length: number) => new Float32Array(buffer, byteOffset, length),+}++const CONVERSIONS: Conversion[] = [+ {+ name: 'dbnet',+ ...floatPlanes,+ rust: (rgb, chw: Float32Array) => rgbToNormalizedChw(rgb, chw, 'bgr', IMAGENET_MEAN, IMAGENET_STD),+ ts: (rgb, chw: Float32Array) => dbnetChwTs(rgb, chw, IMAGENET_MEAN, IMAGENET_STD),+ },+ {+ name: 'yunet',+ ...floatPlanes,+ rust: (rgb, chw: Float32Array) => rgbToChw(rgb, chw, 'bgr'),+ ts: (rgb, chw: Float32Array) => yunetChwTs(rgb, chw),+ },+ {+ name: 'safety',+ ...floatPlanes,+ rust: (rgb, chw: Float32Array) => rgbToChw(rgb, chw, 'rgb'),+ ts: (rgb, chw: Float32Array) => safetyChwTs(rgb, chw),+ },+ {+ name: 'qr',+ valuesPerPixel: 4,+ bytesPerValue: 1,+ view: (buffer, byteOffset, length) => new Uint8ClampedArray(buffer, byteOffset, length),+ rust: (rgb, rgba: Uint8ClampedArray) => rgbToRgba(rgb, rgba),+ ts: (rgb, rgba: Uint8ClampedArray) => qrRgbaTs(rgb, rgba),+ },+]++// One pixel, and counts either side of every vector width the kernels can use, so that each scalar+// tail runs.+const SMALL_PIXEL_COUNTS = [1, 2, 3, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 129, 255, 257, 1001]+// The sizes production converts: the safety input, two text canvases, the YuNet input, and two+// code-reader frames.+const PRODUCTION_SIZES = [+ [224, 224],+ [640, 384],+ [928, 576],+ [640, 640],+ [638, 359],+ [1181, 664],+]+const PIXEL_COUNTS = [...SMALL_PIXEL_COUNTS, ...PRODUCTION_SIZES.map(([width, height]) => width * height)]++function allocate(conversion: Conversion, pixels: number): Destination {+ const length = conversion.valuesPerPixel * pixels+ return conversion.view(new ArrayBuffer(length * conversion.bytesPerValue), 0, length)+}++function randomRgb(pixels: number, seed: number): Uint8Array {+ const random = mulberry32(seed)+ const words = new Uint32Array(Math.ceil((3 * pixels) / 4))+ for (let i = 0; i < words.length; i++) {+ words[i] = random() * 2 ** 32+ }+ return new Uint8Array(words.buffer, 0, 3 * pixels)+}++// Every channel steps through all 256 values with a different stride, so every entry of every+// plane's lookup table is read at least once.+function everyValueRgb(): Uint8Array {+ const rgb = new Uint8Array(3 * 256)+ for (let p = 0; p < 256; p++) {+ rgb[3 * p] = p+ rgb[3 * p + 1] = (7 * p + 85) % 256+ rgb[3 * p + 2] = (13 * p + 170) % 256+ }+ return rgb+}++function bytesOf(view: ArrayBufferView): Buffer {+ return Buffer.from(view.buffer, view.byteOffset, view.byteLength)+}++// Reports the first byte that differs rather than both arrays, which can hold millions of values.+function firstDifference(+ rust: ArrayBufferView,+ ts: ArrayBufferView+): { byte: number; rust: number; ts: number } | { rustBytes: number; tsBytes: number } | null {+ const [a, b] = [bytesOf(rust), bytesOf(ts)]+ if (a.length !== b.length) {+ return { rustBytes: a.length, tsBytes: b.length }+ }+ if (a.equals(b)) {+ return null+ }+ const byte = a.findIndex((value, index) => value !== b[index])+ return { byte, rust: a[byte], ts: b[byte] }+}++function compare(conversion: Conversion, rgb: Uint8Array): ReturnType<typeof firstDifference> {+ const pixels = rgb.length / 3+ const [rust, ts] = [allocate(conversion, pixels), allocate(conversion, pixels)]+ conversion.rust(rgb, rust)+ conversion.ts(rgb, ts)+ return firstDifference(rust, ts)+}++describe('pixel conversions', () => {+ test.each(CONVERSIONS)('$name matches the TypeScript it replaced, bit for bit', (conversion) => {+ const mismatches = [+ ...PIXEL_COUNTS.map((pixels) => ({ pixels, difference: compare(conversion, randomRgb(pixels, pixels)) })),+ { pixels: 'every value', difference: compare(conversion, everyValueRgb()) },+ ].filter(({ difference }) => difference !== null)++ expect(mismatches).toEqual([])+ })++ test.each([+ { mean: [0, 0, 0], std: [1, 1, 1] },+ { mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5] },+ { mean: [0.1234567, 0.7654321, 0.3333333], std: [0.0271828, 0.314159, 0.9999999] },+ ] as { mean: PerPlane; std: PerPlane }[])(+ 'normalized planes match the TypeScript for mean $mean and std $std',+ ({ mean, std }) => {+ for (const rgb of [randomRgb(1001, 1), everyValueRgb()]) {+ const [rust, ts] = [new Float32Array(rgb.length), new Float32Array(rgb.length)]+ rgbToNormalizedChw(rgb, rust, 'bgr', mean, std)+ dbnetChwTs(rgb, ts, mean, std)++ expect(firstDifference(rust, ts)).toBeNull()+ }+ }+ )++ test.each(CONVERSIONS)('$name reads and writes only inside the views it is given', (conversion) => {+ const pixels = 37+ const source = new Uint8Array(5 + 3 * pixels + 5)+ source.set(randomRgb(pixels, 3), 5)+ const rgb = source.subarray(5, 5 + 3 * pixels)+ const guardBytes = 16+ const length = conversion.valuesPerPixel * pixels+ const buffer = new ArrayBuffer(guardBytes + length * conversion.bytesPerValue + guardBytes)+ const whole = new Uint8Array(buffer).fill(0xa5)+ const out = conversion.view(buffer, guardBytes, length)+ const expected = allocate(conversion, pixels)++ conversion.rust(rgb, out)+ conversion.ts(rgb, expected)++ expect(firstDifference(out, expected)).toBeNull()+ expect([...whole.subarray(0, guardBytes), ...whole.subarray(guardBytes + out.byteLength)]).toEqual(+ Array.from({ length: 2 * guardBytes }, () => 0xa5)+ )+ })++ test.each(CONVERSIONS)('$name refuses a layout that does not fit', (conversion) => {+ const rgb = randomRgb(10, 5)++ expect(() => conversion.rust(rgb, allocate(conversion, 10).subarray(1))).toThrow(+ `destination length is ${conversion.valuesPerPixel * 10 - 1}, expected ${conversion.valuesPerPixel * 10}`+ )+ expect(() => conversion.rust(rgb.subarray(1), allocate(conversion, 10))).toThrow(+ 'rgb length 29 is not a whole number of pixels'+ )+ })++ test('refuses a destination that shares memory with its source', () => {+ const buffer = new ArrayBuffer(64)++ expect(() => rgbToRgba(new Uint8Array(buffer, 0, 30), new Uint8ClampedArray(buffer, 20, 40))).toThrow(+ 'the source and destination share memory'+ )+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.tsnew file mode 100644index 000000000000..0e67202368dc--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pixel-convert.ts@@ -0,0 +1,51 @@+/**+ * The pixel layout conversions that build the model inputs and zxing's RGBA frame, run in the+ * replay-anonymizer Rust addon (rust/replay-anonymizer-node/src/pixels.rs). The caller allocates+ * each destination and the addon borrows both typed arrays in place, so no pixel data is copied+ * across the boundary.+ */+import { createRequire } from 'node:module'+import { resolve } from 'node:path'++export type PlaneOrder = 'rgb' | 'bgr'+export type PerPlane = readonly [number, number, number]++interface PixelConvert {+ /** Interleaved RGB bytes to channel-major float planes with the byte values unchanged. */+ rgbToChw(rgb: Uint8Array, chw: Float32Array, order: PlaneOrder): void+ /** Interleaved RGB bytes to channel-major float planes of `(value / 255 - mean) / std`, with+ * `mean` and `std` in plane order. Each value is the one that expression gives in JS when it is+ * stored into a Float32Array. */+ rgbToNormalizedChw(rgb: Uint8Array, chw: Float32Array, order: PlaneOrder, mean: PerPlane, std: PerPlane): void+ /** Interleaved RGB bytes to interleaved RGBA bytes with every pixel opaque. */+ rgbToRgba(rgb: Uint8Array, rgba: Uint8ClampedArray): void+}++const FUNCTIONS = ['rgbToChw', 'rgbToNormalizedChw', 'rgbToRgba'] as const++// Resolved against the working directory like the models, because the image and the dev scripts+// both run from the package root. It is made absolute because jest's createRequire resolves a+// relative path from the parent of the directory that it is given.+const ADDON_PATH = resolve('native/replay-anonymizer.node')++function loadPixelConvert(): PixelConvert {+ let addon: Partial<PixelConvert>+ try {+ addon = createRequire(ADDON_PATH)(ADDON_PATH) as Partial<PixelConvert>+ } catch (error) {+ throw new Error(`cannot load the native addon at ${ADDON_PATH}; build it with \`npm run build:native\``, {+ cause: error,+ })+ }+ const missing = FUNCTIONS.filter((name) => typeof addon[name] !== 'function')+ if (missing.length > 0) {+ throw new Error(+ `the native addon at ${ADDON_PATH} has no ${missing.join(', ')}; rebuild it with \`npm run build:native\``+ )+ }+ return addon as PixelConvert+}++// Loaded at import so that a missing or stale addon fails worker startup, which fails the pool and+// the image build's smoke test, rather than the first scrub.+export const { rgbToChw, rgbToNormalizedChw, rgbToRgba } = loadPixelConvert()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.tsindex 3cb72b484efa..f6ac64a1d553 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts@@ -10,6 +10,7 @@ import { createRequire } from 'node:module'import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'import { type Box } from './geometry.ts'+import { rgbToRgba } from './pixel-convert.ts'import { type Src, srcSharp } from './src-image.ts'// zxing-wasm's default loader fetches its .wasm from a CDN on first use; hand it the binary that@@ -36,12 +37,7 @@ export async function detectCodes(src: Src, scale = 1): Promise<Box[]> {: await srcSharp(src).resize(width, height, { fit: 'fill' }).raw().toBuffer()// zxing takes RGBA ImageData; expand the shared raw RGB in one pass.const rgba = new Uint8ClampedArray(width * height * 4)- for (let i = 0, o = 0; i < data.length; i += 3, o += 4) {- rgba[o] = data[i]- rgba[o + 1] = data[i + 1]- rgba[o + 2] = data[i + 2]- rgba[o + 3] = 255- }+ rgbToRgba(data, rgba)// 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, height, colorSpace: 'srgb' } as ImageDatadiff --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.tsindex 234574459cd3..99ff64d9cb87 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@@ -7,6 +7,7 @@import * as ort from 'onnxruntime-node'import { ORT_THREADS } from './cores.ts'+import { rgbToChw } from './pixel-convert.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)@@ -43,13 +44,8 @@ export async function classifySafety(model: SafetyModel, src: Src): Promise<Safe.resize(SAFETY_SIZE, SAFETY_SIZE, { fit: 'fill' }).raw().toBuffer({ resolveWithObject: true })- const plane = SAFETY_SIZE * SAFETY_SIZE- const chw = new Float32Array(3 * plane)- for (let i = 0, p = 0; i < data.length; i += 3, p++) {- chw[p] = data[i]- chw[plane + p] = data[i + 1]- chw[2 * plane + p] = data[i + 2]- }+ const chw = new Float32Array(3 * SAFETY_SIZE * SAFETY_SIZE)+ rgbToChw(data, chw, 'rgb')const out = await model.session.run({[model.inputName]: new ort.Tensor('float32', chw, [1, 3, SAFETY_SIZE, SAFETY_SIZE]),})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.tsindex fca0fd12e1eb..e28da183ccec 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts@@ -10,6 +10,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 { rgbToChw } from './pixel-convert.ts'// Tiling bounds for extreme-aspect frames. A single letterboxed pass scales by 640/longSide, so on a// very tall/wide image a face (at most ~shortSide across) can land below the detector's smallest// stride. Above MAX_ASPECT the frame is cut along its long axis into windows of aspect TILE_ASPECT@@ -135,12 +136,7 @@ async function detectInWindow(// RGB(HWC, 0-255) -> BGR(CHW, float32, no normalization), as OpenCV's YuNet expects.const side = YUNET_SIDEconst chw = new Float32Array(3 * side * side)- const plane = side * side- for (let i = 0, p = 0; i < data.length; i += 3, p++) {- chw[p] = data[i + 2] // B- chw[plane + p] = data[i + 1] // G- chw[2 * plane + p] = data[i] // R- }+ rgbToChw(data, chw, 'bgr')const out = await model.session.run({ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, side, side]) })// Uniform inverse scale back to window coords, then offset to frame coords; boxes decoded in thediff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 09779617787f..15253c968fee 100644--- a/rust/replay-anonymizer-node/src/lib.rs+++ b/rust/replay-anonymizer-node/src/lib.rs@@ -6,11 +6,18 @@//! metadata come out — Rust owns the parse, the scrub, and the serialize, so no JSON crosses the FFI//! boundary as a string. Behavior is pinned by the shared JSON fixtures in the core crate's//! `tests/fixtures/`, which the Jest suite runs against through this addon.+//!+//! It also carries the image-scrub sidecar's pixel layout conversions (`pixels`), which fill model+//! inputs in place in typed arrays that the sidecar allocates.++mod pixels;use std::sync::RwLock;+use neon::context::Lock;use neon::prelude::*;use neon::types::buffer::TypedArray;+use pixels::{LayoutError, PlaneOrder};use posthog_replay_anonymizer::{is_public_host, politeness_key, snapshot, try_canonicalize, AllowLists, FailKind,ImageCollection, ImagePolicy, PhaseTimings, UrlCollection,@@ -273,6 +280,92 @@ fn try_canonicalize_url_ffi(mut cx: FunctionContext) -> JsResult<JsObject> {Ok(result)}+enum InPlaceFailure {+ SharedMemory,+ Layout(LayoutError),+}++/// Runs `kernel` over the memory of both typed arrays, borrowed in place through one VM lock. The+/// lock's ledger refuses a destination that overlaps the source, which would otherwise alias the+/// kernel's `&[u8]` with its `&mut` slice.+fn run_on_borrowed<D: TypedArray>(+ lock: &Lock<'_, FunctionContext<'_>>,+ source: &JsUint8Array,+ destination: &mut D,+ kernel: impl FnOnce(&[u8], &mut [D::Item]) -> Result<(), LayoutError>,+) -> Result<(), InPlaceFailure> {+ let source = source+ .try_borrow(lock)+ .map_err(|_| InPlaceFailure::SharedMemory)?;+ let mut destination = destination+ .try_borrow_mut(lock)+ .map_err(|_| InPlaceFailure::SharedMemory)?;+ kernel(&source, &mut destination).map_err(InPlaceFailure::Layout)+}++fn convert_in_place<'cx, D: TypedArray>(+ cx: &mut FunctionContext<'cx>,+ source: Handle<'cx, JsUint8Array>,+ mut destination: Handle<'cx, D>,+ kernel: impl FnOnce(&[u8], &mut [D::Item]) -> Result<(), LayoutError>,+) -> JsResult<'cx, JsUndefined> {+ let converted = run_on_borrowed(&cx.lock(), &source, &mut *destination, kernel);+ match converted {+ Ok(()) => Ok(cx.undefined()),+ Err(InPlaceFailure::SharedMemory) => {+ cx.throw_error("the source and destination share memory")+ }+ Err(InPlaceFailure::Layout(error)) => cx.throw_range_error(error.to_string()),+ }+}++fn plane_order_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<PlaneOrder> {+ let order = cx.argument::<JsString>(index)?.value(cx);+ match order.as_str() {+ "rgb" => Ok(PlaneOrder::Rgb),+ "bgr" => Ok(PlaneOrder::Bgr),+ _ => cx.throw_type_error(format!("plane order must be 'rgb' or 'bgr', got '{order}'")),+ }+}++fn per_plane_arg(cx: &mut FunctionContext, index: usize) -> NeonResult<[f64; 3]> {+ let values = cx.argument::<JsArray>(index)?;+ if values.len(cx) != 3 {+ return cx.throw_range_error("expected one value per plane");+ }+ let mut per_plane = [0.0; 3];+ for (plane, value) in (0u32..).zip(per_plane.iter_mut()) {+ *value = values.get::<JsNumber, _, _>(cx, plane)?.value(cx);+ }+ Ok(per_plane)+}++fn rgb_to_chw_ffi(mut cx: FunctionContext) -> JsResult<JsUndefined> {+ let rgb = cx.argument::<JsUint8Array>(0)?;+ let chw = cx.argument::<JsFloat32Array>(1)?;+ let order = plane_order_arg(&mut cx, 2)?;+ convert_in_place(&mut cx, rgb, chw, |rgb, chw| {+ pixels::rgb_to_chw(rgb, chw, order)+ })+}++fn rgb_to_normalized_chw_ffi(mut cx: FunctionContext) -> JsResult<JsUndefined> {+ let rgb = cx.argument::<JsUint8Array>(0)?;+ let chw = cx.argument::<JsFloat32Array>(1)?;+ let order = plane_order_arg(&mut cx, 2)?;+ let mean = per_plane_arg(&mut cx, 3)?;+ let std = per_plane_arg(&mut cx, 4)?;+ convert_in_place(&mut cx, rgb, chw, |rgb, chw| {+ pixels::rgb_to_normalized_chw(rgb, chw, order, mean, std)+ })+}++fn rgb_to_rgba_ffi(mut cx: FunctionContext) -> JsResult<JsUndefined> {+ let rgb = cx.argument::<JsUint8Array>(0)?;+ let rgba = cx.argument::<JsUint8Array>(1)?;+ convert_in_place(&mut cx, rgb, rgba, pixels::rgb_to_rgba)+}+#[neon::main]fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("initAnonymizer", init_anonymizer)?;@@ -280,5 +373,8 @@ fn main(mut cx: ModuleContext) -> NeonResult<()> {cx.export_function("politenessKey", politeness_key_ffi)?;cx.export_function("isPublicHost", is_public_host_ffi)?;cx.export_function("tryCanonicalizeUrl", try_canonicalize_url_ffi)?;+ cx.export_function("rgbToChw", rgb_to_chw_ffi)?;+ cx.export_function("rgbToNormalizedChw", rgb_to_normalized_chw_ffi)?;+ cx.export_function("rgbToRgba", rgb_to_rgba_ffi)?;Ok(())}diff --git a/rust/replay-anonymizer-node/src/pixels.rs b/rust/replay-anonymizer-node/src/pixels.rsnew file mode 100644index 000000000000..dbfe7e63dc0b--- /dev/null+++ b/rust/replay-anonymizer-node/src/pixels.rs@@ -0,0 +1,189 @@+//! Pixel layout conversions for the image-scrub sidecar: its model input tensors and zxing's RGBA+//! frame.+//!+//! Every kernel writes into a destination that the caller allocated, and allocates nothing itself,+//! so the Node binding can pass typed arrays that it borrowed in place and no pixel crosses the+//! boundary as a copy.++use std::fmt;++/// The source channel that each output plane takes, in plane order.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PlaneOrder {+ Rgb,+ Bgr,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LayoutError {+ PartialPixel { rgb_len: usize },+ DestinationLength { expected: usize, actual: usize },+}++impl fmt::Display for LayoutError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ LayoutError::PartialPixel { rgb_len } => {+ write!(f, "rgb length {rgb_len} is not a whole number of pixels")+ }+ LayoutError::DestinationLength { expected, actual } => {+ write!(f, "destination length is {actual}, expected {expected}")+ }+ }+ }+}++/// Interleaved RGB bytes to channel-major planes with the byte values unchanged (0 to 255).+pub fn rgb_to_chw(rgb: &[u8], chw: &mut [f32], order: PlaneOrder) -> Result<(), LayoutError> {+ let pixels = pixel_count(rgb, chw.len(), 3)?;+ match order {+ PlaneOrder::Rgb => fill_planes::<0, 1, 2>(rgb, chw, pixels, |_, value| f32::from(value)),+ PlaneOrder::Bgr => fill_planes::<2, 1, 0>(rgb, chw, pixels, |_, value| f32::from(value)),+ }+ Ok(())+}++/// Interleaved RGB bytes to channel-major planes of `(value / 255 - mean) / std`, with `mean` and+/// `std` given in plane order.+pub fn rgb_to_normalized_chw(+ rgb: &[u8],+ chw: &mut [f32],+ order: PlaneOrder,+ mean: [f64; 3],+ std: [f64; 3],+) -> Result<(), LayoutError> {+ let pixels = pixel_count(rgb, chw.len(), 3)?;+ let tables = normalization_tables(mean, std);+ let normalize = |plane: usize, value: u8| tables[plane][usize::from(value)];+ match order {+ PlaneOrder::Rgb => fill_planes::<0, 1, 2>(rgb, chw, pixels, normalize),+ PlaneOrder::Bgr => fill_planes::<2, 1, 0>(rgb, chw, pixels, normalize),+ }+ Ok(())+}++/// Interleaved RGB bytes to interleaved RGBA bytes with every pixel opaque.+pub fn rgb_to_rgba(rgb: &[u8], rgba: &mut [u8]) -> Result<(), LayoutError> {+ pixel_count(rgb, rgba.len(), 4)?;+ for (pixel, out) in rgb.chunks_exact(3).zip(rgba.chunks_exact_mut(4)) {+ out[0] = pixel[0];+ out[1] = pixel[1];+ out[2] = pixel[2];+ out[3] = u8::MAX;+ }+ Ok(())+}++fn pixel_count(+ rgb: &[u8],+ destination_len: usize,+ destination_values_per_pixel: usize,+) -> Result<usize, LayoutError> {+ if !rgb.len().is_multiple_of(3) {+ return Err(LayoutError::PartialPixel { rgb_len: rgb.len() });+ }+ let pixels = rgb.len() / 3;+ let expected = pixels * destination_values_per_pixel;+ if destination_len != expected {+ return Err(LayoutError::DestinationLength {+ expected,+ actual: destination_len,+ });+ }+ Ok(pixels)+}++// The source channels are const parameters so that LLVM sees a fixed stride-3 access pattern, which+// it vectorizes (with `ld3` on aarch64) instead of emitting one scalar load per byte.+#[inline(always)]+fn fill_planes<+ const FIRST_CHANNEL: usize,+ const SECOND_CHANNEL: usize,+ const THIRD_CHANNEL: usize,+>(+ rgb: &[u8],+ chw: &mut [f32],+ pixels: usize,+ convert: impl Fn(usize, u8) -> f32,+) {+ let (first_plane, rest) = chw.split_at_mut(pixels);+ let (second_plane, third_plane) = rest.split_at_mut(pixels);+ let planes = first_plane.iter_mut().zip(second_plane).zip(third_plane);+ for (pixel, ((first, second), third)) in rgb.chunks_exact(3).zip(planes) {+ *first = convert(0, pixel[FIRST_CHANNEL]);+ *second = convert(1, pixel[SECOND_CHANNEL]);+ *third = convert(2, pixel[THIRD_CHANNEL]);+ }+}++// Each entry evaluates the expression in f64 and rounds once to the nearest-even f32, which is what+// JS does when it computes the expression and stores it into a Float32Array. The sidecar needs its+// model inputs to match that bit for bit, and f32 arithmetic would differ in the last bit for some+// inputs.+fn normalization_tables(mean: [f64; 3], std: [f64; 3]) -> [[f32; 256]; 3] {+ let mut tables = [[0.0; 256]; 3];+ for value in 0..=u8::MAX {+ let scaled = f64::from(value) / 255.0;+ for ((table, mean), std) in tables.iter_mut().zip(mean).zip(std) {+ table[usize::from(value)] = ((scaled - mean) / std) as f32;+ }+ }+ tables+}++#[cfg(test)]+mod tests {+ use std::alloc::{GlobalAlloc, Layout, System};+ use std::cell::Cell;++ use super::*;++ struct CountingAllocator;++ thread_local! {+ static ALLOCATIONS: Cell<usize> = const { Cell::new(0) };+ }++ unsafe impl GlobalAlloc for CountingAllocator {+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {+ ALLOCATIONS.with(|count| count.set(count.get() + 1));+ System.alloc(layout)+ }++ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {+ System.dealloc(ptr, layout)+ }+ }++ #[global_allocator]+ static ALLOCATOR: CountingAllocator = CountingAllocator;++ fn allocations_during(run: impl FnOnce()) -> usize {+ let before = ALLOCATIONS.with(Cell::get);+ run();+ ALLOCATIONS.with(Cell::get) - before+ }++ #[test]+ fn kernels_write_in_place_without_allocating() {+ let pixels = 1001;+ let rgb: Vec<u8> = (0..pixels * 3).map(|i| (i * 7 % 256) as u8).collect();+ let mut chw = vec![0.0f32; pixels * 3];+ let mut rgba = vec![0u8; pixels * 4];++ let allocations = allocations_during(|| {+ rgb_to_chw(&rgb, &mut chw, PlaneOrder::Bgr).unwrap();+ rgb_to_normalized_chw(+ &rgb,+ &mut chw,+ PlaneOrder::Bgr,+ [0.485, 0.456, 0.406],+ [0.229, 0.224, 0.225],+ )+ .unwrap();+ rgb_to_rgba(&rgb, &mut rgba).unwrap();+ });++ assert_eq!(allocations, 0);+ }+}