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.

feat(replay): scrub images on a parallel worker pool in the anonymizer (#73175)

Robbie378ba1e22e44
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 96e6c5097cc8..e3f08c0bfbcf 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -5750,6 +5750,12 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72167d68f5fce3b8655487b8038691a3c9984ee769590f93f2a631f4ad64e4f5"
+[[package]]
+name = "jpeg-decoder"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
+
[[package]]
name = "js-source-scopes"
version = "0.7.1"
@@ -8175,6 +8181,7 @@ dependencies = [
"base64 0.22.1",
"flate2",
"image",
+ "jpeg-decoder",
"libdeflater",
"lz4",
"memchr",
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index 2626a44d325e..b9223ddb6b2d 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -11,7 +11,7 @@ use std::sync::RwLock;
use neon::prelude::*;
use neon::types::buffer::TypedArray;
-use posthog_replay_anonymizer::{snapshot, AllowLists, FailKind, PhaseTimings};
+use posthog_replay_anonymizer::{snapshot, AllowLists, FailKind, ImagePolicy, PhaseTimings};
use serde::Deserialize;
// The fail-closed contract depends on `catch_unwind` containing panics on untrusted input. Under
@@ -22,6 +22,28 @@ compile_error!(
"replay-anonymizer-node requires panic=unwind: catch_unwind is the fail-closed guard"
);
+/// Deferred-parallel image scrubbing is the production default; `REPLAY_ANONYMIZER_PARALLEL_IMAGES=0`
+/// (or `false`) is the rollback lever to the inline path. Worker count comes from
+/// `REPLAY_ANONYMIZER_IMAGE_THREADS` (see the core crate's `images` module).
+static IMAGE_POLICY: std::sync::OnceLock<ImagePolicy> = std::sync::OnceLock::new();
+
+fn image_policy() -> ImagePolicy {
+ *IMAGE_POLICY.get_or_init(|| {
+ // Forgiving parse: this is an incident rollback lever, so common falsy spellings count.
+ let disabled = std::env::var("REPLAY_ANONYMIZER_PARALLEL_IMAGES").is_ok_and(|v| {
+ matches!(
+ v.trim().to_ascii_lowercase().as_str(),
+ "0" | "false" | "off" | "no"
+ )
+ });
+ if disabled {
+ ImagePolicy::Inline
+ } else {
+ ImagePolicy::Parallel
+ }
+ })
+}
+
// The allow lists are immutable per process; set once at startup via `initAnonymizer`.
static ALLOW: RwLock<Option<AllowLists>> = RwLock::new(None);
@@ -86,7 +108,10 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
let scrubbed = snapshot::anonymize_kafka_payload_timed(
allow,
&mut payload,
- snapshot::AnonymizeOpts::default(),
+ snapshot::AnonymizeOpts {
+ image_policy: image_policy(),
+ ..Default::default()
+ },
Some(&timings),
);
timings.scrub_finished();
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 6f4a61ded819..59e1477cfdb5 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -24,6 +24,7 @@ libdeflater = { workspace = true }
lz4 = { workspace = true }
memchr = "2"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp"] }
+jpeg-decoder = { version = "0.3", default-features = false }
serde = { workspace = true }
serde_json = { workspace = true }
simd-json = { version = "0.15", features = ["serde_impl"] }
diff --git a/rust/replay-anonymizer/src/assets.rs b/rust/replay-anonymizer/src/assets.rs
index 5071cf10fbfd..ef39bb52b76c 100644
--- a/rust/replay-anonymizer/src/assets.rs
+++ b/rust/replay-anonymizer/src/assets.rs
@@ -6,8 +6,9 @@ use std::borrow::Cow;
use simd_json::borrowed::{Object, Value};
-use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::blur::is_image_data_uri;
use crate::context::Ctx;
+use crate::images::ImageFallback;
use crate::json::{as_str, string_value};
use crate::url::scrub_url;
@@ -43,9 +44,7 @@ pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str)
if !is_image_data_uri(&value) {
return false;
}
- let blurred = ctx
- .blur_data_uri(&value)
- .unwrap_or_else(blank_image_data_uri);
+ let blurred = ctx.scrub_image(&value, ImageFallback::Blank);
attrs.insert(Cow::Owned(name.to_string()), string_value(blurred));
true
}
@@ -61,9 +60,7 @@ pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {
};
acted = true;
if is_image_data_uri(&existing) {
- let blurred = ctx
- .blur_data_uri(&existing)
- .unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
+ let blurred = ctx.scrub_image(&existing, ImageFallback::Placeholder);
attrs.insert(Cow::Borrowed(*key), string_value(blurred));
} else {
// Stashed under a namespaced attr that won't collide with an app `data-original-*`.
diff --git a/rust/replay-anonymizer/src/blur.rs b/rust/replay-anonymizer/src/blur.rs
index 2c5b6e0f9232..26ef1991630c 100644
--- a/rust/replay-anonymizer/src/blur.rs
+++ b/rust/replay-anonymizer/src/blur.rs
@@ -14,6 +14,54 @@ const MAX_LONG_SIDE: f32 = 96.0;
const MAX_IMAGE_SIDE: u32 = 16_384;
const MAX_IMAGE_ALLOC_BYTES: u64 = 256 * 1024 * 1024;
+const JPEG_MAGIC: &[u8] = &[0xFF, 0xD8, 0xFF];
+
+/// Decode a JPEG at a reduced DCT scale — the blur target is <= MAX_LONG_SIDE px, so the decoder
+/// can skip most IDCT work (it picks the smallest of 1/8..1 still at or above the request).
+/// Returns the decoded image plus the ORIGINAL dimensions, so the caller sizes the thumbnail off
+/// the true aspect, not the scaled decode. `None` falls back to the full-resolution path
+/// (non-JPEG bytes, oversize dimensions, or a pixel format the fast path doesn't map).
+fn decode_scaled_jpeg(bytes: &[u8]) -> Option<(DynamicImage, (u32, u32))> {
+ if !bytes.starts_with(JPEG_MAGIC) {
+ return None;
+ }
+ let mut decoder = jpeg_decoder::Decoder::new(std::io::Cursor::new(bytes));
+ decoder.read_info().ok()?;
+ let info = decoder.info()?;
+ // Baseline only: progressive (and lossless) frames buffer FULL-resolution coefficient planes
+ // inside decode() regardless of the requested scale, and jpeg-decoder has no allocation-limit
+ // API — a tiny crafted progressive header declaring 16k x 16k would force gigabytes. The
+ // fallback path enforces MAX_IMAGE_ALLOC_BYTES via image::Limits and rejects such files.
+ if info.coding_process != jpeg_decoder::CodingProcess::DctSequential {
+ return None;
+ }
+ let (w, h) = (u32::from(info.width), u32::from(info.height));
+ if w == 0 || h == 0 || w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE {
+ return None;
+ }
+ // Belt for the sequential path's own buffers: stay well under the fallback's allocation cap.
+ if u64::from(w) * u64::from(h) * 4 > MAX_IMAGE_ALLOC_BYTES {
+ return None;
+ }
+ decoder
+ .scale(MAX_LONG_SIDE as u16, MAX_LONG_SIDE as u16)
+ .ok()?;
+ let pixels = decoder.decode().ok()?;
+ let scaled = decoder.info()?;
+ let (sw, sh) = (u32::from(scaled.width), u32::from(scaled.height));
+ let img = match scaled.pixel_format {
+ jpeg_decoder::PixelFormat::RGB24 => {
+ image::RgbImage::from_raw(sw, sh, pixels).map(DynamicImage::ImageRgb8)
+ }
+ jpeg_decoder::PixelFormat::L8 => {
+ image::GrayImage::from_raw(sw, sh, pixels).map(DynamicImage::ImageLuma8)
+ }
+ // CMYK32 / L16 are rare; the generic decoder handles them at full resolution.
+ _ => None,
+ }?;
+ Some((img, (w, h)))
+}
+
fn decode_limited(bytes: &[u8]) -> Option<DynamicImage> {
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_IMAGE_SIDE);
@@ -70,8 +118,14 @@ pub fn blur_image_data_uri(s: &str) -> Option<String> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(payload.as_bytes())
.ok()?;
- let img = decode_limited(&bytes)?; // can't read the header / exceeds limits -> None
- let (w, h) = img.dimensions();
+ let (img, (w, h)) = match decode_scaled_jpeg(&bytes) {
+ Some(scaled) => scaled,
+ None => {
+ let img = decode_limited(&bytes)?; // can't read the header / exceeds limits -> None
+ let dims = img.dimensions();
+ (img, dims)
+ }
+ };
let (tw, th) = target_dims(w, h);
// Downsample (fit: fill) then Gaussian blur, mirroring the TS pipeline order.
let out = img
@@ -151,6 +205,39 @@ mod tests {
assert_eq!(decoded.dimensions(), (12, 6));
}
+ #[test]
+ fn scaled_jpeg_decode_sizes_the_thumbnail_off_the_original_dims() {
+ // 1024x512 decodes at a reduced DCT scale; the thumbnail must still come out at
+ // target_dims(1024, 512) = (96, 48), not 0.12x of the scaled decode.
+ for gray in [false, true] {
+ let rgb = image::RgbImage::from_fn(1024, 512, |x, y| {
+ image::Rgb([(x % 251) as u8, (y % 241) as u8, 90])
+ });
+ let img = if gray {
+ image::DynamicImage::ImageLuma8(image::DynamicImage::ImageRgb8(rgb).to_luma8())
+ } else {
+ image::DynamicImage::ImageRgb8(rgb)
+ };
+ let mut buf = Vec::new();
+ img.write_to(
+ &mut std::io::Cursor::new(&mut buf),
+ image::ImageFormat::Jpeg,
+ )
+ .unwrap();
+ let uri = format!(
+ "data:image/jpeg;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(&buf)
+ );
+ let out = blur_image_data_uri(&uri).expect("blur should succeed for a valid jpeg");
+ let (_, b64) = split_data_uri(&out).unwrap();
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(&b64)
+ .unwrap();
+ let decoded = image::load_from_memory(&bytes).unwrap();
+ assert_eq!(decoded.dimensions(), (96, 48), "gray={gray}");
+ }
+ }
+
#[test]
fn blur_rejects_non_image_data_uri() {
assert!(blur_image_data_uri("data:text/plain;base64,aGVsbG8=").is_none());
diff --git a/rust/replay-anonymizer/src/bytewalk.rs b/rust/replay-anonymizer/src/bytewalk.rs
index 1464312306d3..f6e1ebc64336 100644
--- a/rust/replay-anonymizer/src/bytewalk.rs
+++ b/rust/replay-anonymizer/src/bytewalk.rs
@@ -14,7 +14,7 @@
//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.
use crate::assets::{is_media_src_attr, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC};
-use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::blur::is_image_data_uri;
use crate::context::Ctx;
use crate::css;
use crate::dom::{
@@ -22,6 +22,7 @@ use crate::dom::{
ParentKind, TagKind,
};
use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL};
+use crate::images::ImageFallback;
use crate::scan::{self, Span};
use crate::text::{redact_emails, scrub_text};
use crate::url::scrub_url;
@@ -837,7 +838,7 @@ impl<'c, 'a> Walker<'c, 'a> {
if !is_image_data_uri(s) {
return None;
}
- Some(w.ctx.blur_data_uri(s).unwrap_or_else(blank_image_data_uri))
+ Some(w.ctx.scrub_image(s, ImageFallback::Blank))
});
}
if name == "style" || name == css::INLINED_STYLESHEET_ATTR {
@@ -895,10 +896,7 @@ impl<'c, 'a> Walker<'c, 'a> {
let end = scan::skip_string(bytes, vstart).ok()?;
let existing = scan::unescape(bytes, (vstart, end)).ok()?;
if is_image_data_uri(&existing) {
- let blurred = self
- .ctx
- .blur_data_uri(&existing)
- .unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
+ let blurred = self.ctx.scrub_image(&existing, ImageFallback::Placeholder);
scan::write_json_string(&blurred, out);
} else {
let scrubbed = scrub_url(self.ctx, &existing).unwrap_or_else(|| existing.into_owned());
diff --git a/rust/replay-anonymizer/src/canvas.rs b/rust/replay-anonymizer/src/canvas.rs
index eb728dba8480..f29e74d612f5 100644
--- a/rust/replay-anonymizer/src/canvas.rs
+++ b/rust/replay-anonymizer/src/canvas.rs
@@ -5,8 +5,9 @@
use base64::Engine;
use simd_json::borrowed::{Object, Value};
-use crate::blur::{blank_image_data_uri, is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};
+use crate::blur::{is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};
use crate::context::Ctx;
+use crate::images::ImageFallback;
use crate::json::{
as_array, as_array_mut, as_object, as_object_mut, as_str, as_u32, as_usize, key, string_value,
};
@@ -79,7 +80,7 @@ fn blur_canvas_arg(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
match value {
Value::String(s) => {
if is_image_data_uri(s) {
- let b = ctx.blur_data_uri(s).unwrap_or_else(blank_image_data_uri);
+ let b = ctx.scrub_image(s, ImageFallback::Blank);
*value = string_value(b);
return true;
}
@@ -103,7 +104,7 @@ fn blur_canvas_arg(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
// URL that may itself carry PII.
if let Some(src) = obj.get("src").and_then(as_str).map(str::to_string) {
if is_image_data_uri(&src) {
- let b = ctx.blur_data_uri(&src).unwrap_or_else(blank_image_data_uri);
+ let b = ctx.scrub_image(&src, ImageFallback::Blank);
obj.insert(key("src"), string_value(b));
return true;
}
@@ -169,14 +170,13 @@ fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
None => return false,
};
let original = format!("data:{mime};base64,{base64}");
- let (new_b64, new_type) = match ctx
- .blur_data_uri(&original)
- .and_then(|b| split_data_uri(&b))
- {
- Some((m, b64)) => (b64, m),
- // Fail-safe: a blank pixel (matches the TS synchronous neutralization).
- None => (BLANK_PNG_BASE64.to_string(), "image/png".to_string()),
- };
+ // scrub_image never fails outward (fallbacks are baked in), so the split always succeeds; the
+ // stated fallback keeps the fail-safe explicit if the URI shape ever changes.
+ let (new_b64, new_type) =
+ match split_data_uri(&ctx.scrub_image(&original, ImageFallback::Blank)) {
+ Some((m, b64)) => (b64, m),
+ None => (BLANK_PNG_BASE64.to_string(), "image/png".to_string()),
+ };
if let Some(ab) = blob
.get_mut("data")
.and_then(as_array_mut)
diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rs
index 21a9c016ec9d..271a9f22bb96 100644
--- a/rust/replay-anonymizer/src/context.rs
+++ b/rust/replay-anonymizer/src/context.rs
@@ -11,7 +11,9 @@ use std::collections::HashMap;
use anyhow::{bail, Result};
use crate::allow_lists::AllowLists;
-use crate::blur::{blur_image_data_uri, pixelate_raw_rgba};
+use crate::assets::PLACEHOLDER_SRC;
+use crate::blur::{blank_image_data_uri, blur_image_data_uri, pixelate_raw_rgba};
+use crate::images::{ImageFallback, ImagePolicy, ImageQueue};
use crate::timings::PhaseTimings;
/// Cumulative decompressed-bytes budget across all cv payloads in one message: the per-payload
@@ -19,7 +21,8 @@ use crate::timings::PhaseTimings;
/// fields can't decompress gigabytes serially. Real messages total under 10 MB.
const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;
-/// Scrub context: the allow lists, the cv decompression budget, and the blur memo.
+/// Scrub context: the allow lists, the cv decompression budget, the blur memo, and the image
+/// scrub policy (inline blur, or deferred onto the shared worker pool).
pub struct Ctx<'a> {
pub allow: &'a AllowLists,
pub cv_budget: Cell<usize>,
@@ -27,20 +30,71 @@ pub struct Ctx<'a> {
// value: the blurred result, or `None` when blurring failed (caller falls back to a blank pixel).
blur_cache: RefCell<HashMap<String, Option<String>>>,
timings: Option<&'a PhaseTimings>,
+ image_policy: ImagePolicy,
+ images: ImageQueue,
}
impl<'a> Ctx<'a> {
pub fn new(allow: &'a AllowLists) -> Self {
- Self::with_timings(allow, None)
+ Self::with_options(allow, None, ImagePolicy::Inline)
}
pub fn with_timings(allow: &'a AllowLists, timings: Option<&'a PhaseTimings>) -> Self {
+ Self::with_options(allow, timings, ImagePolicy::Inline)
+ }
+
+ // pub(crate): the token-patch barriers live only in the kafka snapshot pipeline, so a
+ // caller-built Parallel Ctx on the other entry points would emit unresolved tokens.
+ pub(crate) fn with_options(
+ allow: &'a AllowLists,
+ timings: Option<&'a PhaseTimings>,
+ image_policy: ImagePolicy,
+ ) -> Self {
Self {
allow,
cv_budget: Cell::new(CV_MESSAGE_DECOMPRESSION_BUDGET),
blur_cache: RefCell::new(HashMap::new()),
timings,
+ image_policy,
+ images: ImageQueue::default(),
+ }
+ }
+
+ /// Scrub one image data URI per the policy: the blurred URI (inline), or a token the patch
+ /// pass later replaces (parallel). Failures resolve to `fallback` either way. A message that
+ /// exhausts the queued-bytes budget degrades to inline for the remainder — bounded memory,
+ /// identical output.
+ pub(crate) fn scrub_image(&self, original: &str, fallback: ImageFallback) -> String {
+ if self.image_policy == ImagePolicy::Parallel {
+ if let Some(token) = self.images.submit(
+ original,
+ fallback,
+ true,
+ crate::images::MAX_QUEUED_URI_BYTES,
+ ) {
+ return token;
+ }
+ }
+ match (self.blur_data_uri(original), fallback) {
+ (Some(blurred), _) => blurred,
+ (None, ImageFallback::Blank) => blank_image_data_uri(),
+ (None, ImageFallback::Placeholder) => PLACEHOLDER_SRC.to_string(),
+ }
+ }
+
+ pub(crate) fn has_pending_images(&self) -> bool {
+ self.images.has_pending()
+ }
+
+ /// Replace any outstanding image tokens in serialized output, waiting for their jobs. Must run
+ /// wherever bytes become immutable: before a cv payload compresses, and on the final lines.
+ /// Worker-side blur time lands in the timings sink here, as jobs are claimed.
+ pub(crate) fn patch_pending_images(&self, buf: Vec<u8>) -> Vec<u8> {
+ let out = self.images.patch(buf);
+ if let Some(t) = self.timings {
+ self.images.drain_blur_time_into(t);
}
+ out
}
fn timed<T>(&self, op: &'static str, f: impl FnOnce() -> T) -> T {
diff --git a/rust/replay-anonymizer/src/css.rs b/rust/replay-anonymizer/src/css.rs
index c7923053dcc7..1508210dd801 100644
--- a/rust/replay-anonymizer/src/css.rs
+++ b/rust/replay-anonymizer/src/css.rs
@@ -5,8 +5,9 @@ use std::borrow::Cow;
use simd_json::borrowed::{Object, Value};
-use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::blur::is_image_data_uri;
use crate::context::Ctx;
+use crate::images::ImageFallback;
use crate::json::{as_array_mut, as_object_mut, as_str, string_value};
// rrweb inlines a same-origin/CORS-readable `<link rel="stylesheet">` into this attribute
@@ -82,9 +83,7 @@ pub(crate) fn rewrite(ctx: &Ctx<'_>, css: &str) -> Option<String> {
out.push_str(&css[last..start]);
// Blur (or fall back to a blank pixel) and re-wrap; no async placeholder needed since we
// resolve the image inline, so the final string matches the TS post-blur state.
- let replacement = ctx
- .blur_data_uri(&css[m.data_start..m.data_end])
- .unwrap_or_else(blank_image_data_uri);
+ let replacement = ctx.scrub_image(&css[m.data_start..m.data_end], ImageFallback::Blank);
out.push_str("url(");
if let Some(q) = m.quote {
out.push(q as char);
diff --git a/rust/replay-anonymizer/src/cv.rs b/rust/replay-anonymizer/src/cv.rs
index 47a6fa3125d0..b615df7fb279 100644
--- a/rust/replay-anonymizer/src/cv.rs
+++ b/rust/replay-anonymizer/src/cv.rs
@@ -49,14 +49,23 @@ fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<(Vec<u8>, bool)> {
Ok((out, was_zstd))
}
-fn compress_bytes(json: &[u8]) -> Result<String> {
+/// Compress a scrubbed cv payload, patching any deferred-image tokens first — after this the bytes
+/// are opaque to the final patch pass over the block lines.
+fn compress_bytes(ctx: &Ctx<'_>, json: &[u8]) -> Result<String> {
+ let patched;
+ let json = if ctx.has_pending_images() {
+ patched = ctx.patch_pending_images(json.to_vec());
+ patched.as_slice()
+ } else {
+ json
+ };
Ok(bytes_to_latin1(
&compression::compress_cv(json).context("compress cv payload")?,
))
}
-fn compress_value(value: &Value<'_>) -> Result<String> {
- compress_bytes(value.encode().as_bytes())
+fn compress_value(ctx: &Ctx<'_>, value: &Value<'_>) -> Result<String> {
+ compress_bytes(ctx, value.encode().as_bytes())
}
/// Scrub a `cv`-compressed FullSnapshot `data` value (a compressed latin-1 string, gzip or zstd)
@@ -77,11 +86,11 @@ pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Re
if was_zstd {
return Ok(false);
}
- *data = string_value(compress_bytes(&scratch)?);
+ *data = string_value(compress_bytes(ctx, &scratch)?);
return Ok(true);
}
Some(true) => {
- *data = string_value(compress_bytes(&walked)?);
+ *data = string_value(compress_bytes(ctx, &walked)?);
return Ok(true);
}
None => {}
@@ -91,7 +100,7 @@ pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Re
reject_if_too_deep(&scratch, "cv payload")?;
let mut payload = parse_untrusted(&mut scratch).context("parse cv payload")?;
scrub_full_snapshot(ctx, &mut payload);
- let recompressed = compress_value(&payload)?;
+ let recompressed = compress_value(ctx, &payload)?;
*data = string_value(recompressed);
Ok(true)
}
@@ -165,7 +174,7 @@ pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> Result
}
for (sub_key, json) in recompress {
- data.insert(key(sub_key), string_value(compress_bytes(&json)?));
+ data.insert(key(sub_key), string_value(compress_bytes(ctx, &json)?));
}
Ok(changed)
diff --git a/rust/replay-anonymizer/src/images.rs b/rust/replay-anonymizer/src/images.rs
new file mode 100644
index 000000000000..2292f2180f33
--- /dev/null
+++ b/rust/replay-anonymizer/src/images.rs
@@ -0,0 +1,426 @@
+//! Deferred image scrubbing: the walk swaps each image data URI for a token and queues the
+//! decode+blur+encode on a small shared worker pool, so pixel work overlaps the rest of the walk.
+//! Serialized output is patched wherever it becomes immutable — before each cv payload compresses,
+//! and over the final block lines.
+//!
+//! Dedup is preserved: the job map is keyed on the original URI per message (the same role the
+//! inline blur memo plays), so a recurring image submits one job and every occurrence patches to
+//! the same result. Fail-safe matches the inline path: a failed or panicked job patches to the
+//! occurrence's fallback (blank pixel or media placeholder), carried in the token.
+//!
+//! Tokens are plain base64-alphabet text (`xph<marker><id><fallback>`), optionally wrapped as a
+//! `data:image/png;base64,…` URI, so they survive JSON serialization byte-for-byte; the marker is
+//! random per process, so real payload bytes cannot collide with a live token.
+
+use std::cell::{Cell, RefCell};
+use std::collections::hash_map::RandomState;
+use std::collections::HashMap;
+use std::hash::{BuildHasher, Hasher};
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::sync::{mpsc, Arc, LazyLock, Mutex};
+use std::time::Instant;
+
+use crate::assets::PLACEHOLDER_SRC;
+use crate::blur::{blur_image_data_uri, BLANK_PNG_BASE64};
+use crate::timings::PhaseTimings;
+
+/// How images found during the walk are scrubbed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ImagePolicy {
+ /// Blur synchronously on the walk thread (the original behavior).
+ #[default]
+ Inline,
+ /// Queue blurs on the shared worker pool and patch tokens into the serialized output.
+ Parallel,
+}
+
+/// What a failed blur resolves to; chosen per occurrence, matching the inline call sites.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ImageFallback {
+ /// Blank 1x1 PNG (inline images, canvas args, css).
+ Blank,
+ /// The media placeholder SVG (media `src`-style attributes).
+ Placeholder,
+}
+
+const DATA_URI_PREFIX: &[u8] = b"data:image/png;base64,";
+const ID_HEX_LEN: usize = 8;
+
+/// Cap on the URI bytes one message may have queued: each job clones its data URI, so an
+/// image-stuffed message would otherwise retain a second copy of its whole payload while the
+/// fixed-size pool catches up. Past the cap, `submit` declines and the caller blurs inline —
+/// slower, bounded, identical output. Global memory stays bounded at (concurrent messages x cap).
+pub(crate) const MAX_QUEUED_URI_BYTES: usize = 32 * 1024 * 1024;
+
+/// Cap on distinct queued images per message: the byte budget alone under-counts tiny URIs, whose
+/// per-job overhead (job struct, result channel, map entries) dominates their payload. Real
+/// messages hold at most dozens of distinct images — repeats dedup — so past this the caller
+/// scrubs inline. With bounded scrub concurrency this also bounds the global channel depth.
+pub(crate) const MAX_QUEUED_IMAGES_PER_MESSAGE: u32 = 512;
+
+/// Generous ceiling on one blur job (worst real decodes are hundreds of ms); see `resolve`.
+const IMAGE_JOB_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
+
+/// Random 128 bits per process: payload bytes can't be crafted (or fluked, at any volume) to
+/// collide with a live token — a false match needs this exact 35-char ASCII run in the payload.
+static TOKEN_MARKER: LazyLock<String> = LazyLock::new(|| {
+ let state = RandomState::new();
+ let mut a = state.build_hasher();
+ a.write_u32(std::process::id());
+ let mut b = state.build_hasher();
+ b.write_u64(a.finish());
+ b.write_u32(std::process::id());
+ format!("xph{:016x}{:016x}", a.finish(), b.finish())
+});
+
+fn worker_count() -> usize {
+ std::env::var("REPLAY_ANONYMIZER_IMAGE_THREADS")
+ .ok()
+ .and_then(|v| v.parse::<usize>().ok())
+ .unwrap_or_else(|| {
+ std::thread::available_parallelism()
+ .map(|n| n.get().min(4))
+ .unwrap_or(2)
+ })
+ .clamp(1, 64)
+}
+
+struct Job {
+ uri: String,
+ result_tx: mpsc::SyncSender<JobResult>,
+}
+
+struct JobResult {
+ /// PNG base64 (no `data:` prefix); `None` = the image could not be blurred.
+ b64: Option<String>,
+ elapsed_ns: u64,
+}
+
+/// One shared pool for the whole process: total blur parallelism stays bounded no matter how many
+/// messages scrub concurrently on the libuv threadpool. `None` when no worker could be spawned —
+/// submission then declines and every image scrubs inline instead.
+static POOL: LazyLock<Option<mpsc::Sender<Job>>> = LazyLock::new(|| {
+ let (tx, rx) = mpsc::channel::<Job>();
+ let rx = Arc::new(Mutex::new(rx));
+ let mut spawned = 0usize;
+ for i in 0..worker_count() {
+ let rx = Arc::clone(&rx);
+ let spawn_result = std::thread::Builder::new()
+ .name(format!("replay-img-scrub-{i}"))
+ .spawn(move || loop {
+ let job = match rx.lock() {
+ Ok(guard) => match guard.recv() {
+ Ok(job) => job,
+ Err(_) => break,
+ },
+ Err(_) => break,
+ };
+ let start = Instant::now();
+ // A panic on a hostile image fails that one job closed, not the worker.
+ let b64 = catch_unwind(AssertUnwindSafe(|| blur_image_data_uri(&job.uri)))
+ .unwrap_or(None)
+ .and_then(|uri| {
+ uri.strip_prefix("data:image/png;base64,")
+ .map(str::to_string)
+ });
+ let elapsed_ns = u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX - 1);
+ // The queue side may already have given up on this job; a send error is fine.
+ job.result_tx.send(JobResult { b64, elapsed_ns }).ok();
+ });
+ if spawn_result.is_ok() {
+ spawned += 1;
+ }
+ }
+ (spawned > 0).then_some(tx)
+});
+
+enum JobState {
+ Pending(mpsc::Receiver<JobResult>),
+ /// Resolved blur output (PNG base64) plus the worker-side elapsed time, `0` once reported.
+ Resolved(Option<String>),
+}
+
+/// Per-message queue: URI-keyed dedup plus id-keyed job states for the patch pass.
+#[derive(Default)]
+pub struct ImageQueue {
+ ids_by_uri: RefCell<HashMap<String, u32>>,
+ jobs: RefCell<HashMap<u32, JobState>>,
+ next_id: Cell<u32>,
+ queued_uri_bytes: Cell<usize>,
+ /// Worker-side blur time and job count, accumulated as results are claimed.
+ pub(crate) blur_ns: Cell<u64>,
+ pub(crate) blur_count: Cell<u32>,
+}
+
+impl ImageQueue {
+ /// Submits (or dedups) a blur job and returns the occurrence's token, `data:`-wrapped when the
+ /// call site substitutes a full URI. `None` = the per-message byte budget is spent and the
+ /// caller must scrub this occurrence inline.
+ pub(crate) fn submit(
+ &self,
+ uri: &str,
+ fallback: ImageFallback,
+ wrapped: bool,
+ max_queued_uri_bytes: usize,
+ ) -> Option<String> {
+ let known = self.ids_by_uri.borrow().get(uri).copied();
+ let id = if let Some(id) = known {
+ id
+ } else {
+ let queued = self.queued_uri_bytes.get().saturating_add(uri.len());
+ if queued > max_queued_uri_bytes || self.next_id.get() >= MAX_QUEUED_IMAGES_PER_MESSAGE
+ {
+ return None;
+ }
+ let (result_tx, result_rx) = mpsc::sync_channel(1);
+ // A missing or wedged pool declines instead of panicking; the caller scrubs inline.
+ POOL.as_ref()?
+ .send(Job {
+ uri: uri.to_string(),
+ result_tx,
+ })
+ .ok()?;
+ self.queued_uri_bytes.set(queued);
+ let id = self.next_id.get();
+ self.next_id.set(id + 1);
+ self.ids_by_uri.borrow_mut().insert(uri.to_string(), id);
+ self.jobs
+ .borrow_mut()
+ .insert(id, JobState::Pending(result_rx));
+ id
+ };
+ let fb = match fallback {
+ ImageFallback::Blank => 'b',
+ ImageFallback::Placeholder => 'p',
+ };
+ let core = format!("{}{id:08x}{fb}", &*TOKEN_MARKER);
+ Some(if wrapped {
+ format!(
+ "{}{core}",
+ std::str::from_utf8(DATA_URI_PREFIX).expect("static prefix is utf-8")
+ )
+ } else {
+ core
+ })
+ }
+
+ /// Move blur time accumulated by claimed jobs into the timings sink (idempotent via reset).
+ pub(crate) fn drain_blur_time_into(&self, timings: &PhaseTimings) {
+ let (ns, count) = (self.blur_ns.replace(0), self.blur_count.replace(0));
+ if count > 0 {
+ timings.add_blur(ns, count);
+ }
+ }
+
+ /// Whether any jobs were queued for this message (tokens may be present in output).
+ pub(crate) fn has_pending(&self) -> bool {
+ !self.jobs.borrow().is_empty()
+ }
+
+ /// Blocks until the job's result is in (the patch barrier); `None` = blur failed.
+ fn resolve(&self, id: u32) -> Option<String> {
+ let mut jobs = self.jobs.borrow_mut();
+ let state = jobs.get_mut(&id)?;
+ if let JobState::Pending(rx) = state {
+ // Bounded wait: a wedged worker fails this image closed instead of stalling the
+ // partition; a straggler's late result lands in the buffered channel and is dropped.
+ let result = match rx.recv_timeout(IMAGE_JOB_TIMEOUT) {
+ Ok(r) => r,
+ Err(_) => JobResult {
+ b64: None,
+ elapsed_ns: 0,
+ },
+ };
+ self.blur_ns
+ .set(self.blur_ns.get().saturating_add(result.elapsed_ns));
+ self.blur_count.set(self.blur_count.get().saturating_add(1));
+ *state = JobState::Resolved(result.b64);
+ }
+ match state {
+ JobState::Resolved(b64) => b64.clone(),
+ JobState::Pending(_) => unreachable!("state was just resolved"),
+ }
+ }
+
+ /// Replaces every token in `buf` with its blur result (waiting for stragglers), returning the
+ /// input untouched when nothing was queued or nothing matches. Call wherever serialized bytes
+ /// become immutable: before a cv payload compresses, and on the final block lines.
+ pub(crate) fn patch(&self, buf: Vec<u8>) -> Vec<u8> {
+ if !self.has_pending() {
+ return buf;
+ }
+ let needle = TOKEN_MARKER.as_bytes();
+ let token_len = needle.len() + ID_HEX_LEN + 1;
+ let mut out: Option<Vec<u8>> = None;
+ let mut copied_to = 0usize;
+ let mut search_from = 0usize;
+ while let Some(rel) = memchr::memmem::find(&buf[search_from..], needle) {
+ let start = search_from + rel;
+ if start + token_len > buf.len() {
+ break;
+ }
+ let Some(id) =
+ parse_hex_id(&buf[start + needle.len()..start + needle.len() + ID_HEX_LEN])
+ else {
+ search_from = start + needle.len();
+ continue;
+ };
+ let fallback = match buf[start + token_len - 1] {
+ b'b' => ImageFallback::Blank,
+ b'p' => ImageFallback::Placeholder,
+ _ => {
+ search_from = start + needle.len();
+ continue;
+ }
+ };
+ if !self.jobs.borrow().contains_key(&id) {
+ // Marker collision with real payload bytes; astronomically unlikely — leave as-is.
+ search_from = start + needle.len();
+ continue;
+ }
+ let wrapped = start >= DATA_URI_PREFIX.len()
+ && &buf[start - DATA_URI_PREFIX.len()..start] == DATA_URI_PREFIX;
+ let span_start = if wrapped {
+ start - DATA_URI_PREFIX.len()
+ } else {
+ start
+ };
+ let span_end = start + token_len;
+ let replacement: String = match (self.resolve(id), fallback) {
+ (Some(b64), _) => {
+ if wrapped {
+ format!("data:image/png;base64,{b64}")
+ } else {
+ b64
+ }
+ }
+ (None, ImageFallback::Placeholder) => PLACEHOLDER_SRC.to_string(),
+ (None, ImageFallback::Blank) => {
+ if wrapped {
+ format!("data:image/png;base64,{BLANK_PNG_BASE64}")
+ } else {
+ BLANK_PNG_BASE64.to_string()
+ }
+ }
+ };
+ let out = out.get_or_insert_with(|| Vec::with_capacity(buf.len()));
+ out.extend_from_slice(&buf[copied_to..span_start]);
+ out.extend_from_slice(replacement.as_bytes());
+ copied_to = span_end;
+ search_from = span_end;
+ }
+ match out {
+ Some(mut out) => {
+ out.extend_from_slice(&buf[copied_to..]);
+ out
+ }
+ None => buf,
+ }
+ }
+}
+
+fn parse_hex_id(bytes: &[u8]) -> Option<u32> {
+ let s = std::str::from_utf8(bytes).ok()?;
+ u32::from_str_radix(s, 16).ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testkit::png_data_uri;
+
+ #[test]
+ fn submit_dedups_by_uri_and_patch_replaces_every_occurrence() {
+ let q = ImageQueue::default();
+ let uri = png_data_uri(64, 32, [10, 20, 30, 255]);
+ let t1 = q
+ .submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+ let t2 = q
+ .submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+ assert_eq!(t1, t2);
+ assert_eq!(q.next_id.get(), 1);
+
+ let raw = q
+ .submit(&uri, ImageFallback::Blank, false, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+ assert!(t1.ends_with(&raw));
+
+ let buf = format!("{{\"a\":\"{t1}\",\"b\":\"{t2}\",\"c\":\"{raw}\"}}").into_bytes();
+ let patched = String::from_utf8(q.patch(buf)).unwrap();
+ let expected = blur_image_data_uri(&uri).unwrap();
+ let expected_b64 = expected.strip_prefix("data:image/png;base64,").unwrap();
+ assert_eq!(
+ patched,
+ format!("{{\"a\":\"{expected}\",\"b\":\"{expected}\",\"c\":\"{expected_b64}\"}}")
+ );
+ assert_eq!(q.blur_count.get(), 1);
+ assert!(q.blur_ns.get() > 0);
+ }
+
+ #[test]
+ fn failed_blur_patches_to_the_occurrence_fallback() {
+ let q = ImageQueue::default();
+ let bad = "data:image/png;base64,bm90IGFuIGltYWdl";
+ let wrapped = q
+ .submit(bad, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+ let placeholder = q
+ .submit(bad, ImageFallback::Placeholder, true, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+ let raw = q
+ .submit(bad, ImageFallback::Blank, false, MAX_QUEUED_URI_BYTES)
+ .unwrap();
+
+ let buf = format!("[\"{wrapped}\",\"{placeholder}\",\"{raw}\"]").into_bytes();
+ let patched = String::from_utf8(q.patch(buf)).unwrap();
+ assert_eq!(
+ patched,
+ format!("[\"data:image/png;base64,{BLANK_PNG_BASE64}\",\"{PLACEHOLDER_SRC}\",\"{BLANK_PNG_BASE64}\"]")
+ );
+ assert_eq!(q.blur_count.get(), 1);
+ }
+
+ #[test]
+ fn submissions_over_the_count_cap_decline() {
+ let q = ImageQueue::default();
+ q.next_id.set(MAX_QUEUED_IMAGES_PER_MESSAGE);
+ let uri = png_data_uri(8, 8, [7, 7, 7, 255]);
+ assert_eq!(
+ q.submit(&uri, ImageFallback::Blank, true, MAX_QUEUED_URI_BYTES),
+ None
+ );
+ }
+
+ #[test]
+ fn over_budget_submissions_decline_but_known_uris_still_dedup() {
+ let q = ImageQueue::default();
+ let a = png_data_uri(16, 16, [1, 2, 3, 255]);
+ let b = png_data_uri(16, 16, [4, 5, 6, 255]);
+ let budget = a.len() + 1;
+ let t1 = q.submit(&a, ImageFallback::Blank, true, budget).unwrap();
+ // A new URI over the budget declines; the caller scrubs it inline.
+ assert_eq!(q.submit(&b, ImageFallback::Blank, true, budget), None);
+ // An already-queued URI still resolves to its token, budget notwithstanding.
+ assert_eq!(q.submit(&a, ImageFallback::Blank, true, budget), Some(t1));
+ }
+
+ #[test]
+ fn replacements_never_need_json_escaping() {
+ // patch() splices replacements into already-serialized JSON without escaping, which is
+ // only sound while every possible replacement is escape-free.
+ let needs_escape = |s: &str| s.bytes().any(|b| b == b'"' || b == b'\\' || b < 0x20);
+ assert!(!needs_escape(PLACEHOLDER_SRC));
+ assert!(!needs_escape(BLANK_PNG_BASE64));
+ let blurred = blur_image_data_uri(&png_data_uri(32, 32, [9, 9, 9, 255])).unwrap();
+ assert!(!needs_escape(&blurred));
+ }
+
+ #[test]
+ fn patch_is_a_no_op_without_queued_jobs() {
+ let q = ImageQueue::default();
+ let buf = b"{\"text\":\"no tokens here\"}".to_vec();
+ assert_eq!(q.patch(buf.clone()), buf);
+ }
+}
diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rs
index 3e5771eebe8a..ec913f562bfe 100644
--- a/rust/replay-anonymizer/src/lib.rs
+++ b/rust/replay-anonymizer/src/lib.rs
@@ -43,6 +43,7 @@ pub mod cv;
#[doc(hidden)]
pub mod dom;
pub mod event;
+pub mod images;
#[doc(hidden)]
pub mod json;
#[doc(hidden)]
@@ -65,6 +66,7 @@ pub use event::{
anonymize_event, anonymize_event_str, anonymize_line, anonymize_line_with_ctx,
anonymize_message,
};
+pub use images::ImagePolicy;
pub use snapshot::{
anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_kafka_payload_timed,
AnonymizeOpts, AnonymizedMessage, FailKind, Failure, Route,
diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rs
index 00e39aebecef..2c7ae9454d12 100644
--- a/rust/replay-anonymizer/src/snapshot.rs
+++ b/rust/replay-anonymizer/src/snapshot.rs
@@ -33,6 +33,7 @@ use crate::event::{
SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,
TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META, TYPE_PLUGIN,
};
+use crate::images::ImagePolicy;
use crate::json::{
as_f64, as_object, as_small_uint, as_str, parse_untrusted, parse_untrusted_with_buffers,
reject_if_too_deep,
@@ -170,11 +171,17 @@ pub struct AnonymizeOpts {
/// ([`crate::bytewalk`]) instead of a simd-json tree; anything the walk can't prove safe falls
/// back to the parse per event. The differential tests pin both engines by toggling this.
pub byte_walk: bool,
+ /// How images are scrubbed: inline on the walk thread, or deferred onto the shared worker
+ /// pool with a token-patch pass over the serialized output. The differential tests pin both.
+ pub image_policy: ImagePolicy,
}
impl Default for AnonymizeOpts {
fn default() -> Self {
- Self { byte_walk: true }
+ Self {
+ byte_walk: true,
+ image_policy: ImagePolicy::Inline,
+ }
}
}
@@ -401,7 +408,7 @@ fn anonymize_snapshot_data_inner(
// No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines
// past its limit, and every recursive parse below is preceded by a span-local
// reject_if_too_deep — so the common all-walked path never pays a depth scan at all.
- let ctx = Ctx::with_timings(allow, timings);
+ let ctx = Ctx::with_options(allow, timings, opts.image_policy);
match stream_message(&ctx, distinct_id, inner, opts)? {
Some(msg) => Ok(msg),
// Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was
@@ -704,7 +711,7 @@ fn stream_message(
if let Some(e) = deferred {
return Err(e);
}
- finish(distinct_id, env, sink, Route::Stream).map(Some)
+ finish(ctx, distinct_id, env, sink, Route::Stream).map(Some)
}
/// Locate a props value span and advance the cursor past it.
@@ -757,6 +764,7 @@ impl Sink {
}
fn finish(
+ ctx: &Ctx<'_>,
distinct_id: &str,
env: ScannedEnvelope,
sink: Sink,
@@ -796,6 +804,8 @@ fn finish(
lines.extend_from_slice(&sink.lines[sink.line_starts[i]..body_end]);
lines.extend_from_slice(b"]\n");
}
+ // Deferred image jobs resolve here: the block lines are the last surface tokens can be on.
+ let lines = ctx.patch_pending_images(lines);
Ok(AnonymizedMessage {
lines,
route,
@@ -1379,6 +1389,7 @@ fn anonymize_via_tree_mut(
}
finish(
+ ctx,
distinct_id,
ScannedEnvelope {
session_id,
diff --git a/rust/replay-anonymizer/src/timings.rs b/rust/replay-anonymizer/src/timings.rs
index d02b6809c49f..6c5eb441bd8d 100644
--- a/rust/replay-anonymizer/src/timings.rs
+++ b/rust/replay-anonymizer/src/timings.rs
@@ -91,6 +91,14 @@ impl PhaseTimings {
self.last_op.set(op);
}
+ /// Fold in blur work measured elsewhere (the parallel image workers time their own jobs).
+ pub fn add_blur(&self, elapsed_ns: u64, count: u32) {
+ self.blur_total_ns
+ .set(self.blur_total_ns.get().saturating_add(elapsed_ns));
+ self.blur_count
+ .set(self.blur_count.get().saturating_add(count));
+ }
+
/// Times one in-scrub op into the `cv` or `blur` totals. Restores the `"scrub"` marker only on
/// clean exit, so after a panic `last_op` names the op that died.
pub(crate) fn time_op<T>(&self, op: &'static str, f: impl FnOnce() -> T) -> T {
diff --git a/rust/replay-anonymizer/tests/bench_images.rs b/rust/replay-anonymizer/tests/bench_images.rs
new file mode 100644
index 000000000000..d3c100b2ebdf
--- /dev/null
+++ b/rust/replay-anonymizer/tests/bench_images.rs
@@ -0,0 +1,136 @@
+//! Manual benchmark for inline vs deferred-parallel image scrubbing. Ignored in CI (timing is
+//! machine-dependent); run with:
+//!
+//! ```sh
+//! cargo test --release -p posthog-replay-anonymizer --test bench_images -- --ignored --nocapture
+//! ```
+
+use std::time::Instant;
+
+use base64::Engine;
+use posthog_replay_anonymizer::snapshot::{anonymize_kafka_payload_opts, AnonymizeOpts};
+use posthog_replay_anonymizer::{AllowLists, ImagePolicy};
+use serde_json::json;
+
+fn image_data_uri(side: u32, seed: u8, format: image::ImageFormat) -> String {
+ let mut img = image::RgbaImage::new(side, side);
+ for (x, y, px) in img.enumerate_pixels_mut() {
+ *px = image::Rgba([
+ (x as u8).wrapping_mul(seed),
+ (y as u8).wrapping_add(seed),
+ seed,
+ 255,
+ ]);
+ }
+ let img = if format == image::ImageFormat::Jpeg {
+ // JPEG has no alpha channel.
+ image::DynamicImage::ImageRgb8(image::DynamicImage::ImageRgba8(img).to_rgb8())
+ } else {
+ image::DynamicImage::ImageRgba8(img)
+ };
+ let mut buf = Vec::new();
+ img.write_to(&mut std::io::Cursor::new(&mut buf), format)
+ .unwrap();
+ let mime = if format == image::ImageFormat::Jpeg {
+ "jpeg"
+ } else {
+ "png"
+ };
+ format!(
+ "data:image/{mime};base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(buf)
+ )
+}
+
+fn payload(images: usize, side: u32, duplicates: usize, format: image::ImageFormat) -> Vec<u8> {
+ let mut children = Vec::new();
+ for i in 0..images {
+ let uri = image_data_uri(side, (i + 1) as u8, format);
+ for d in 0..=duplicates {
+ children.push(json!({
+ "type": 2,
+ "id": 10 + children.len(),
+ "tagName": "img",
+ "attributes": { "src": uri, "alt": format!("img-{i}-{d}") },
+ "childNodes": [],
+ }));
+ }
+ }
+ let inner = json!({
+ "event": "$snapshot_items",
+ "properties": {
+ "$session_id": "bench-session",
+ "$window_id": "w",
+ "$snapshot_items": [{
+ "type": 2,
+ "timestamp": 1_700_000_000_000u64,
+ "data": {
+ "node": { "type": 0, "id": 1, "childNodes": children },
+ "initialOffset": { "top": 0, "left": 0 },
+ },
+ }],
+ },
+ });
+ serde_json::to_string(&json!({
+ "distinct_id": "d",
+ "data": inner.to_string(),
+ }))
+ .unwrap()
+ .into_bytes()
+}
+
+fn run(allow: &AllowLists, payload: &[u8], policy: ImagePolicy, iters: usize) -> Vec<u128> {
+ let mut samples = Vec::with_capacity(iters);
+ for _ in 0..iters {
+ let mut bytes = payload.to_vec();
+ let start = Instant::now();
+ let out = anonymize_kafka_payload_opts(
+ allow,
+ &mut bytes,
+ AnonymizeOpts {
+ image_policy: policy,
+ ..Default::default()
+ },
+ )
+ .expect("bench payload must anonymize");
+ samples.push(start.elapsed().as_micros());
+ assert!(!out.lines.is_empty());
+ }
+ samples.sort_unstable();
+ samples
+}
+
+#[test]
+#[ignore = "manual benchmark; run in release with --nocapture"]
+fn bench_inline_vs_parallel_images() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ println!(
+ "image workers: REPLAY_ANONYMIZER_IMAGE_THREADS={}",
+ std::env::var("REPLAY_ANONYMIZER_IMAGE_THREADS").unwrap_or_else(|_| "(default)".into())
+ );
+ for (images, side, duplicates, format) in [
+ (4usize, 256u32, 0usize, image::ImageFormat::Png),
+ (16, 256, 0, image::ImageFormat::Png),
+ (16, 512, 0, image::ImageFormat::Png),
+ (16, 256, 3, image::ImageFormat::Png),
+ (4, 512, 0, image::ImageFormat::Jpeg),
+ (16, 1024, 0, image::ImageFormat::Jpeg),
+ (4, 2048, 0, image::ImageFormat::Jpeg),
+ ] {
+ let payload = payload(images, side, duplicates, format);
+ // Warm both paths (decoder init, worker pool spawn) before sampling.
+ run(&allow, &payload, ImagePolicy::Inline, 1);
+ run(&allow, &payload, ImagePolicy::Parallel, 1);
+ let inline = run(&allow, &payload, ImagePolicy::Inline, 7);
+ let parallel = run(&allow, &payload, ImagePolicy::Parallel, 7);
+ let median = |s: &Vec<u128>| s[s.len() / 2];
+ println!(
+ "{images:2} distinct {side}x{side} {format:?} x{} occurrences ({:6} KB payload): inline {:7}us parallel {:7}us ({:.2}x)",
+ duplicates + 1,
+ payload.len() / 1024,
+ median(&inline),
+ median(&parallel),
+ median(&inline) as f64 / median(&parallel) as f64,
+ );
+ }
+}
diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rs
index 996fdef99276..15540986dc61 100644
--- a/rust/replay-anonymizer/tests/snapshot.rs
+++ b/rust/replay-anonymizer/tests/snapshot.rs
@@ -11,7 +11,7 @@ use posthog_replay_anonymizer::snapshot::{
AnonymizedMessage, FailKind, Failure, FLAG_ACTIVE, FLAG_CLICK, FLAG_KEYPRESS,
FLAG_MOUSE_ACTIVITY,
};
-use posthog_replay_anonymizer::Ctx;
+use posthog_replay_anonymizer::{Ctx, ImagePolicy};
use serde_json::{json, Value};
use std::path::Path;
@@ -368,32 +368,44 @@ fn assert_stream_matches_tree(allow: &AllowLists, inner_json: &str, label: &str)
let ctx = Ctx::new(allow);
let tree = anonymize_via_tree(&ctx, "d", inner_json.as_bytes());
- // Both scrub engines are pinned: the parse-free byte walk (with its per-event fallbacks)
- // and the simd path.
+ // Every engine combination is pinned against the tree reference: the parse-free byte walk
+ // (with its per-event fallbacks) vs the simd path, and inline vs deferred-parallel images.
for byte_walk in [true, false] {
- let mut bytes = payload.as_bytes().to_vec();
- let stream = anonymize_kafka_payload_opts(allow, &mut bytes, AnonymizeOpts { byte_walk });
- match (&stream, &tree) {
- (Ok(s), Ok(t)) => {
- let s_lines = parse_lines(&s.lines);
- let t_lines = parse_lines(&t.lines);
- assert_eq!(
- s_lines, t_lines,
- "lines diverged (walk={byte_walk}): {label}"
- );
- assert_eq!(s.meta, t.meta, "meta diverged (walk={byte_walk}): {label}");
- }
- (Err(s), Err(t)) => {
- assert_eq!(
- s.kind, t.kind,
- "failure kind diverged (walk={byte_walk}): {label}"
- );
+ for image_policy in [ImagePolicy::Inline, ImagePolicy::Parallel] {
+ let mut bytes = payload.as_bytes().to_vec();
+ let stream = anonymize_kafka_payload_opts(
+ allow,
+ &mut bytes,
+ AnonymizeOpts {
+ byte_walk,
+ image_policy,
+ },
+ );
+ match (&stream, &tree) {
+ (Ok(s), Ok(t)) => {
+ let s_lines = parse_lines(&s.lines);
+ let t_lines = parse_lines(&t.lines);
+ assert_eq!(
+ s_lines, t_lines,
+ "lines diverged (walk={byte_walk}, images={image_policy:?}): {label}"
+ );
+ assert_eq!(
+ s.meta, t.meta,
+ "meta diverged (walk={byte_walk}, images={image_policy:?}): {label}"
+ );
+ }
+ (Err(s), Err(t)) => {
+ assert_eq!(
+ s.kind, t.kind,
+ "failure kind diverged (walk={byte_walk}, images={image_policy:?}): {label}"
+ );
+ }
+ (s, t) => panic!(
+ "outcome diverged (walk={byte_walk}, images={image_policy:?}) for {label}: stream={:?} tree={:?}",
+ s.as_ref().map(|m| parse_lines(&m.lines)),
+ t.as_ref().map(|m| parse_lines(&m.lines)),
+ ),
}
- (s, t) => panic!(
- "outcome diverged (walk={byte_walk}) for {label}: stream={:?} tree={:?}",
- s.as_ref().map(|m| parse_lines(&m.lines)),
- t.as_ref().map(|m| parse_lines(&m.lines)),
- ),
}
}
}