: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(replay): report ml-mirror anonymizer rust phase timings as APM spans (#72872)
Robbie0bbf0270ab34
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.tsnew file mode 100644index 000000000000..3453bb52b65d--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-timing-spans.ts@@ -0,0 +1,89 @@+import { Span, SpanStatusCode, context, trace } from '@opentelemetry/api'++import type { AnonymizeTimings } from '@posthog/replay-anonymizer'++import { defaultConfig } from '~/common/config/config'++const tracer = trace.getTracer('replay-anonymizer')++const NS_PER_MS = 1e6++export interface AnonymizeOutcome {+ route: string | null+ /** The dlq/drop reason when the addon failed, else null. */+ failureReason: string | null+}++/**+ * Materialize the addon's phase timings as retroactive child spans of the current step span. The+ * addon runs on the libuv threadpool where no OTel context exists, so it reports monotonic offsets+ * instead and this converts them to spans after the fact. All offsets are anchored on the caller's+ * clock at the moment of the addon call, so no cross-clock (JS vs Rust wall time) skew is possible.+ *+ * A phase that started but never ended (contained panic) still gets a span, ended at "now"; on+ * failure the deepest emitted span carries the reason and the `lastOp` that was in flight.+ */+export function recordAnonymizeTimingSpans(+ callStartEpochMs: number,+ timings: AnonymizeTimings | null | undefined,+ outcome: AnonymizeOutcome+): void {+ if (!timings || defaultConfig.DISABLE_OPENTELEMETRY_TRACING) {+ return+ }+ const parent = context.active()+ const at = (offsetNs: number): number => callStartEpochMs + offsetNs / NS_PER_MS+ const nowMs = (): number => performance.timeOrigin + performance.now()++ const decorateFailure = (span: Span): void => {+ span.setAttribute('anonymize.last_op', timings.lastOp)+ if (outcome.failureReason) {+ span.setStatus({ code: SpanStatusCode.ERROR, message: outcome.failureReason })+ span.setAttribute('anonymize.failure_reason', outcome.failureReason)+ }+ }++ interface PhaseSpan {+ name: string+ startMs: number+ endMs: number+ decorate?: (span: Span) => void+ }+ const phases: PhaseSpan[] = []++ if (timings.taskStartNs !== null) {+ phases.push({ name: 'anonymize.queueWait', startMs: callStartEpochMs, endMs: at(timings.taskStartNs) })+ }+ if (timings.decompressStartNs !== null) {+ phases.push({+ name: 'anonymize.decompress',+ startMs: at(timings.decompressStartNs),+ endMs: timings.decompressEndNs !== null ? at(timings.decompressEndNs) : nowMs(),+ })+ }+ if (timings.scrubStartNs !== null) {+ phases.push({+ name: 'anonymize.scrub',+ startMs: at(timings.scrubStartNs),+ endMs: timings.scrubEndNs !== null ? at(timings.scrubEndNs) : nowMs(),+ decorate: (span) => {+ span.setAttributes({+ 'anonymize.route': outcome.route ?? '',+ 'anonymize.cv_total_ms': timings.cvTotalNs / NS_PER_MS,+ 'anonymize.cv_count': timings.cvCount,+ 'anonymize.blur_total_ms': timings.blurTotalNs / NS_PER_MS,+ 'anonymize.blur_count': timings.blurCount,+ })+ },+ })+ }++ phases.forEach((phase, i) => {+ const span = tracer.startSpan(phase.name, { startTime: phase.startMs }, parent)+ phase.decorate?.(span)+ if (i === phases.length - 1) {+ decorateFailure(span)+ }+ span.end(Math.max(phase.endMs, phase.startMs))+ })+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.tsindex ed04b95ac25a..49a9a5927244 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts@@ -183,5 +183,31 @@ describeAddon('native rust addon matches the shared fixtures', () => {const decoded = unzstdLatin1(line[1].data.texts) as { value: string }[]expect(decoded[0].value).toBe('keep ******')})++ it('reports ordered phase timings with cv op totals on success', async () => {+ rustAddon!.initAnonymizer({ text: ['keep'], url: [] })+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [fullSnapshot]))+ expect(result.failed).toBe(false)+ const t = result.timings!+ expect(t.taskStartNs).not.toBeNull()+ expect(t.decompressStartNs).toBeGreaterThanOrEqual(t.taskStartNs!)+ expect(t.decompressEndNs).toBeGreaterThanOrEqual(t.decompressStartNs!)+ expect(t.scrubStartNs).toBeGreaterThanOrEqual(t.decompressEndNs!)+ expect(t.scrubEndNs).toBeGreaterThanOrEqual(t.scrubStartNs!)+ // The cv full snapshot forces at least one timed de/recompression op.+ expect(t.cvCount).toBeGreaterThanOrEqual(1)+ expect(t.lastOp).toBe('done')+ })++ it('still reports timings when the payload fails, naming the phase that died', async () => {+ rustAddon!.initAnonymizer({ text: [], url: [] })+ // Gzip magic bytes followed by garbage: decompression starts, then fails.+ const result = await rustAddon!.anonymizeKafkaPayload(Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0xde, 0xad]))+ expect(result.failed).toBe(true)+ const t = result.timings!+ expect(t.decompressStartNs).not.toBeNull()+ expect(t.scrubStartNs).toBeNull()+ expect(t.lastOp).toBe('decompress')+ })})})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.tsindex fee021fe1414..5793f9bba97b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts@@ -7,6 +7,7 @@ import { logger } from '~/common/utils/logger'import { normalizeSessionId } from '~/common/utils/utils'import { dlq, drop, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'+import { recordAnonymizeTimingSpans } from '~/ingestion/pipelines/sessionreplay/anonymize-timing-spans'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'@@ -62,6 +63,7 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInp)const t0 = performance.now()+ const callStartEpochMs = performance.timeOrigin + t0let resulttry {result = await getRustAnonymizer().anonymizeKafkaPayload(message.value, contentEncoding)@@ -72,6 +74,10 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpreturn drop('anonymize_failed')}SessionRecordingIngesterMetrics.observeMlAnonymizeDuration('rust', performance.now() - t0, result.route ?? '')+ recordAnonymizeTimingSpans(callStartEpochMs, result.timings, {+ route: result.route,+ failureReason: result.failed ? (result.reason ?? 'anonymize_failed') : null,+ })if (result.failed) {if (result.reason && DLQ_REASONS.has(result.reason)) {diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 4897ca6dc9ed..7f1278ef9ed5 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -38,6 +38,31 @@ export interface AnonymizeMeta {events: AnonymizeEventMeta[]}+/**+ * Phase timings for one {@link anonymizeKafkaPayload} call, reported on success and failure alike+ * (including contained panics). All offsets are monotonic nanoseconds from the moment the addon+ * was invoked on the JS thread; a `null` boundary means the phase was never reached.+ */+export interface AnonymizeTimings {+ /** Threadpool pickup — this offset IS the libuv queue wait. */+ taskStartNs: number | null+ decompressStartNs: number | null+ decompressEndNs: number | null+ scrubStartNs: number | null+ scrubEndNs: number | null+ /** Accumulated cv de/recompression time across all events in the message. */+ cvTotalNs: number+ cvCount: number+ /** Accumulated image blur/pixelate time (cache misses only). */+ blurTotalNs: number+ blurCount: number+ /**+ * The op in flight when processing stopped: `done` on success, else the phase or op+ * (`queued` | `decompress` | `scrub` | `cv` | `blur` | `serialize_meta`) that was running.+ */+ lastOp: string+}+export interface AnonymizeKafkaPayloadResult {/** True if the message could not be anonymized — the caller must drop or DLQ it (fail-closed). */failed: boolean@@ -58,6 +83,8 @@ export interface AnonymizeKafkaPayloadResult {* whole-message parse fallback fired; the label is an A/B / fallback-rate signal.*/route: 'stream' | 'tree' | null+ /** Phase timings; present on success and failure alike. `null` only if serialization failed. */+ timings: AnonymizeTimings | null}/** Initialize the process-wide allow lists. Call once at startup before {@link anonymizeKafkaPayload}. */@@ -73,9 +100,19 @@ export function initAnonymizer(allow: AllowListsInput): void {** `cv` payloads re-emit as zstd; the reader dispatches on magic bytes.*/-export function anonymizeKafkaPayload(+export async function anonymizeKafkaPayload(payload: Buffer,contentEncoding?: string | null): Promise<AnonymizeKafkaPayloadResult> {- return native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)+ const result = await native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)+ // Timings are best-effort telemetry: a malformed timings blob must never fail the message.+ let timings: AnonymizeTimings | null = null+ if (typeof result.timings === 'string') {+ try {+ timings = JSON.parse(result.timings)+ } catch {+ timings = null+ }+ }+ return { ...result, timings }}diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rsindex 6540634486c1..2626a44d325e 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};+use posthog_replay_anonymizer::{snapshot, AllowLists, FailKind, PhaseTimings};use serde::Deserialize;// The fail-closed contract depends on `catch_unwind` containing panics on untrusted input. Under@@ -46,6 +46,9 @@ fn init_anonymizer(mut cx: FunctionContext) -> JsResult<JsNull> {/// unclassified error (panic, missing init) that the caller must treat as `anonymize_failed`.type TaskOutcome = Result<Result<(Vec<u8>, String, &'static str), (&'static str, String)>, String>;+/// The outcome plus the JSON phase timings, reported on every arm including panics.+type TaskResult = (TaskOutcome, Option<String>);+fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {// One copy on the event loop: the buffer's bytes move into the task (they can't be borrowed// across threads, and simd-json needs a mutable scratch anyway). Decompression happens inside@@ -56,39 +59,63 @@ fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {.argument_opt(1).and_then(|v| v.downcast::<JsString, _>(&mut cx).ok()).map(|s| s.value(&mut cx));+ // Created on the JS thread so every offset shares one monotonic origin: the task-start mark+ // becomes the threadpool queue wait, and no wall clock is involved.+ let timings = PhaseTimings::new();let promise = cx- .task(move || -> TaskOutcome {+ .task(move || -> TaskResult {+ timings.task_started();+ // The sink stays outside the catch_unwind so partial timings survive a panic.// Contain any panic on untrusted input so it fails closed (the caller drops the message)// rather than risking process abort.- std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {let guard = ALLOW.read().map_err(|_| "allow lists lock poisoned".to_string())?;let allow = guard.as_ref().ok_or_else(|| {"anonymizer not initialized (call initAnonymizer first)".to_string()})?;+ timings.decompress_started();let mut payload =match snapshot::decompress_payload(raw, content_encoding.as_deref()) {Ok(p) => p,Err(f) => return Ok(Err((f.kind.reason(), f.detail))),};- match snapshot::anonymize_kafka_payload_opts(+ timings.decompress_finished();+ timings.scrub_started();+ let scrubbed = snapshot::anonymize_kafka_payload_timed(allow,&mut payload,snapshot::AnonymizeOpts::default(),- ) {+ Some(&timings),+ );+ timings.scrub_finished();+ match scrubbed {Ok(out) => {+ timings.mark("serialize_meta");let meta = serde_json::to_string(&out.meta).map_err(|e| format!("serialize meta: {e}"))?;+ timings.mark("done");Ok(Ok((out.lines, meta, out.route.as_str())))}Err(f) => Ok(Err((f.kind.reason(), f.detail))),}}))- .unwrap_or_else(|_| Err("panic while anonymizing".to_string()))+ .unwrap_or_else(|_| Err("panic while anonymizing".to_string()));+ (outcome, serde_json::to_string(&timings.snapshot()).ok())})- .promise(|mut cx, result: TaskOutcome| {+ .promise(|mut cx, (result, timings_json): TaskResult| {let obj = cx.empty_object();+ match timings_json {+ Some(json) => {+ let timings = cx.string(json);+ obj.set(&mut cx, "timings", timings)?;+ }+ None => {+ let null = cx.null();+ obj.set(&mut cx, "timings", null)?;+ }+ }let set_failure = |cx: &mut TaskContext<'_>,obj: &Handle<'_, JsObject>,reason: &str,diff --git a/rust/replay-anonymizer/src/context.rs b/rust/replay-anonymizer/src/context.rsindex c7221cdfa16e..21a9c016ec9d 100644--- a/rust/replay-anonymizer/src/context.rs+++ b/rust/replay-anonymizer/src/context.rs@@ -12,6 +12,7 @@ use anyhow::{bail, Result};use crate::allow_lists::AllowLists;use crate::blur::{blur_image_data_uri, pixelate_raw_rgba};+use crate::timings::PhaseTimings;/// Cumulative decompressed-bytes budget across all cv payloads in one message: the per-payload/// `compression::MAX_DECOMPRESSED_BYTES` cap bounds each field, this bounds their sum so many high-ratio@@ -25,14 +26,27 @@ pub struct Ctx<'a> {// key: the original data URI (data-image blur), or `raw:{w}x{h}:{base64}` (raw RGBA pixelate).// 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>,}impl<'a> Ctx<'a> {pub fn new(allow: &'a AllowLists) -> Self {+ Self::with_timings(allow, None)+ }++ pub fn with_timings(allow: &'a AllowLists, timings: Option<&'a PhaseTimings>) -> Self {Self {allow,cv_budget: Cell::new(CV_MESSAGE_DECOMPRESSION_BUDGET),blur_cache: RefCell::new(HashMap::new()),+ timings,+ }+ }++ fn timed<T>(&self, op: &'static str, f: impl FnOnce() -> T) -> T {+ match self.timings {+ Some(t) => t.time_op(op, f),+ None => f(),}}@@ -47,7 +61,7 @@ impl<'a> Ctx<'a> {/// codecs directly. Magic-byte dispatch (gzip or zstd, unknown fails closed) lives in/// [`crate::compression::decompress_by_magic`]; this layers the cumulative budget on top.pub fn decompress_cv(&self, raw: &[u8]) -> Result<Vec<u8>> {- let out = crate::compression::decompress_by_magic(raw)?;+ let out = self.timed("cv", || crate::compression::decompress_by_magic(raw))?;match self.cv_budget.get().checked_sub(out.len()) {Some(rest) => self.cv_budget.set(rest),None => bail!("message exceeds the cumulative cv decompression budget"),@@ -63,7 +77,7 @@ impl<'a> Ctx<'a> {if let Some(hit) = self.blur_cache.borrow().get(original) {return hit.clone();}- let result = blur_image_data_uri(original);+ let result = self.timed("blur", || blur_image_data_uri(original));self.blur_cache.borrow_mut().insert(original.to_string(), result.clone());@@ -76,7 +90,7 @@ impl<'a> Ctx<'a> {if let Some(hit) = self.blur_cache.borrow().get(&key) {return hit.clone();}- let result = pixelate_raw_rgba(rgba_base64, width, height);+ let result = self.timed("blur", || pixelate_raw_rgba(rgba_base64, width, height));self.blur_cache.borrow_mut().insert(key, result.clone());result}diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 4dea2d7d95ca..3e5771eebe8a 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -50,6 +50,7 @@ pub mod scan;pub mod snapshot;#[doc(hidden)]pub mod text;+pub mod timings;#[cfg(feature = "typed-parse")]pub mod typed;mod unwind;@@ -65,9 +66,10 @@ pub use event::{anonymize_message,};pub use snapshot::{- anonymize_kafka_payload, anonymize_kafka_payload_opts, AnonymizeOpts, AnonymizedMessage,- FailKind, Failure, Route,+ anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_kafka_payload_timed,+ AnonymizeOpts, AnonymizedMessage, FailKind, Failure, Route,};+pub use timings::{PhaseTimings, PhaseTimingsSnapshot};#[cfg(feature = "typed-parse")]pub use typed::{parse_scrubbed_event, parse_scrubbed_event_with_ctx};diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 09ef3109bc0f..00e39aebecef 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -38,6 +38,7 @@ use crate::json::{reject_if_too_deep,};use crate::scan::{self, Span};+use crate::timings::PhaseTimings;/// Why a payload could not be anonymized; maps onto the TS pipeline's dlq/drop reasons so the fused/// step classifies failures exactly like the TS parse step does.@@ -223,18 +224,30 @@ pub fn anonymize_kafka_payload_opts(payload: &mut [u8],opts: AnonymizeOpts,) -> SResult<AnonymizedMessage> {- contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts))+ anonymize_kafka_payload_timed(allow, payload, opts, None)+}++/// [`anonymize_kafka_payload_opts`] with a phase-timing sink, which the caller should own outside+/// any `catch_unwind` boundary so partial timings survive a contained panic.+pub fn anonymize_kafka_payload_timed(+ allow: &AllowLists,+ payload: &mut [u8],+ opts: AnonymizeOpts,+ timings: Option<&PhaseTimings>,+) -> SResult<AnonymizedMessage> {+ contain_panics(|| anonymize_kafka_payload_opts_impl(allow, payload, opts, timings))}fn anonymize_kafka_payload_opts_impl(allow: &AllowLists,payload: &mut [u8],opts: AnonymizeOpts,+ timings: Option<&PhaseTimings>,) -> SResult<AnonymizedMessage> {if let Some((distinct_id_span, data_span)) = scan_outer_envelope(payload) {// Resolve distinct_id to an owned string first — the unescape below rewrites the buffer.let Ok(distinct_id) = scan::unescape(payload, distinct_id_span) else {- return anonymize_kafka_payload_via_parse(allow, payload, opts);+ return anonymize_kafka_payload_via_parse(allow, payload, opts, timings);};let distinct_id = distinct_id.into_owned();// Point of no return: the in-place unescape consumes the buffer, so failures past here are@@ -252,9 +265,9 @@ fn anonymize_kafka_payload_opts_impl("invalid utf-8 in data string",));}- return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts);+ return anonymize_snapshot_data_inner(allow, &distinct_id, inner, opts, timings);}- anonymize_kafka_payload_via_parse(allow, payload, opts)+ anonymize_kafka_payload_via_parse(allow, payload, opts, timings)}/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let@@ -329,6 +342,7 @@ fn anonymize_kafka_payload_via_parse(allow: &AllowLists,payload: &mut [u8],opts: AnonymizeOpts,+ timings: Option<&PhaseTimings>,) -> SResult<AnonymizedMessage> {reject_if_too_deep(payload, "kafka payload").map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;@@ -354,7 +368,7 @@ fn anonymize_kafka_payload_via_parse(};// Rare path (the scanner bailed): one owned copy buys the in-place processing a mutable buffer.let mut data_bytes = data.as_bytes().to_vec();- anonymize_snapshot_data_opts(allow, distinct_id, &mut data_bytes, opts)+ anonymize_snapshot_data_inner(allow, distinct_id, &mut data_bytes, opts, timings)}/// Anonymize the inner `$snapshot_items` event JSON (the payload's `data` string). The buffer is@@ -374,18 +388,26 @@ pub fn anonymize_snapshot_data_opts(inner: &mut [u8],opts: AnonymizeOpts,) -> SResult<AnonymizedMessage> {- contain_panics(|| {- // 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::new(allow);- 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- // consumed before the signal, so the tree path re-reads the intact buffer.- None => anonymize_via_tree_mut(&ctx, distinct_id, inner),- }- })+ contain_panics(|| anonymize_snapshot_data_inner(allow, distinct_id, inner, opts, None))+}++fn anonymize_snapshot_data_inner(+ allow: &AllowLists,+ distinct_id: &str,+ inner: &mut [u8],+ opts: AnonymizeOpts,+ timings: Option<&PhaseTimings>,+) -> SResult<AnonymizedMessage> {+ // 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);+ 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+ // consumed before the signal, so the tree path re-reads the intact buffer.+ None => anonymize_via_tree_mut(&ctx, distinct_id, inner),+ }}const MAX_FAIL_DETAIL: usize = 200;diff --git a/rust/replay-anonymizer/src/timings.rs b/rust/replay-anonymizer/src/timings.rsnew file mode 100644index 000000000000..d02b6809c49f--- /dev/null+++ b/rust/replay-anonymizer/src/timings.rs@@ -0,0 +1,178 @@+//! Phase-timing sink for the snapshot pipeline: contiguous phase boundaries plus accumulated+//! in-scrub op totals (cv de/recompression, image blur), all as nanosecond offsets from one+//! monotonic origin captured when the sink is created.+//!+//! `Cell`-based so the caller can own it outside a `catch_unwind` boundary: whatever completed+//! before a panic is still readable, and `last_op` names the op that was in flight.++use std::cell::Cell;+use std::time::Instant;++use serde::Serialize;++const UNSET: u64 = u64::MAX;++pub struct PhaseTimings {+ origin: Instant,+ task_start_ns: Cell<u64>,+ decompress_start_ns: Cell<u64>,+ decompress_end_ns: Cell<u64>,+ scrub_start_ns: Cell<u64>,+ scrub_end_ns: Cell<u64>,+ cv_total_ns: Cell<u64>,+ cv_count: Cell<u32>,+ blur_total_ns: Cell<u64>,+ blur_count: Cell<u32>,+ last_op: Cell<&'static str>,+}++/// Serializable view of a [`PhaseTimings`]; field names match the TS `AnonymizeTimings`.+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PhaseTimingsSnapshot {+ pub task_start_ns: Option<u64>,+ pub decompress_start_ns: Option<u64>,+ pub decompress_end_ns: Option<u64>,+ pub scrub_start_ns: Option<u64>,+ pub scrub_end_ns: Option<u64>,+ pub cv_total_ns: u64,+ pub cv_count: u32,+ pub blur_total_ns: u64,+ pub blur_count: u32,+ pub last_op: &'static str,+}++impl PhaseTimings {+ #[allow(clippy::new_without_default)]+ pub fn new() -> Self {+ Self {+ origin: Instant::now(),+ task_start_ns: Cell::new(UNSET),+ decompress_start_ns: Cell::new(UNSET),+ decompress_end_ns: Cell::new(UNSET),+ scrub_start_ns: Cell::new(UNSET),+ scrub_end_ns: Cell::new(UNSET),+ cv_total_ns: Cell::new(0),+ cv_count: Cell::new(0),+ blur_total_ns: Cell::new(0),+ blur_count: Cell::new(0),+ last_op: Cell::new("queued"),+ }+ }++ fn now_ns(&self) -> u64 {+ u64::try_from(self.origin.elapsed().as_nanos()).unwrap_or(u64::MAX - 1)+ }++ /// Marks the threadpool pickup; the offset from the sink's creation is the queue wait.+ pub fn task_started(&self) {+ self.task_start_ns.set(self.now_ns());+ }++ pub fn decompress_started(&self) {+ self.last_op.set("decompress");+ self.decompress_start_ns.set(self.now_ns());+ }++ pub fn decompress_finished(&self) {+ self.decompress_end_ns.set(self.now_ns());+ }++ pub fn scrub_started(&self) {+ self.last_op.set("scrub");+ self.scrub_start_ns.set(self.now_ns());+ }++ pub fn scrub_finished(&self) {+ self.scrub_end_ns.set(self.now_ns());+ }++ pub fn mark(&self, op: &'static str) {+ self.last_op.set(op);+ }++ /// 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 {+ let (total, count) = match op {+ "cv" => (&self.cv_total_ns, &self.cv_count),+ _ => (&self.blur_total_ns, &self.blur_count),+ };+ self.last_op.set(op);+ let start = Instant::now();+ let out = f();+ let elapsed = u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX - 1);+ total.set(total.get().saturating_add(elapsed));+ count.set(count.get().saturating_add(1));+ self.last_op.set("scrub");+ out+ }++ pub fn snapshot(&self) -> PhaseTimingsSnapshot {+ let opt = |c: &Cell<u64>| Some(c.get()).filter(|&v| v != UNSET);+ PhaseTimingsSnapshot {+ task_start_ns: opt(&self.task_start_ns),+ decompress_start_ns: opt(&self.decompress_start_ns),+ decompress_end_ns: opt(&self.decompress_end_ns),+ scrub_start_ns: opt(&self.scrub_start_ns),+ scrub_end_ns: opt(&self.scrub_end_ns),+ cv_total_ns: self.cv_total_ns.get(),+ cv_count: self.cv_count.get(),+ blur_total_ns: self.blur_total_ns.get(),+ blur_count: self.blur_count.get(),+ last_op: self.last_op.get(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::unwind::contain_unwind;++ #[test]+ fn accumulates_ops_and_phase_boundaries() {+ let t = PhaseTimings::new();+ t.task_started();+ t.decompress_started();+ t.decompress_finished();+ t.scrub_started();+ t.time_op("cv", || {});+ t.time_op("blur", || {});+ t.time_op("blur", || {});+ t.scrub_finished();++ let snap = t.snapshot();+ assert!(snap.task_start_ns.unwrap() <= snap.decompress_start_ns.unwrap());+ assert!(snap.decompress_start_ns.unwrap() <= snap.decompress_end_ns.unwrap());+ assert!(snap.scrub_start_ns.unwrap() <= snap.scrub_end_ns.unwrap());+ assert_eq!(snap.cv_count, 1);+ assert_eq!(snap.blur_count, 2);+ assert_eq!(snap.last_op, "scrub");+ }++ #[test]+ fn survives_a_panic_and_names_the_op_in_flight() {+ let t = PhaseTimings::new();+ t.task_started();+ t.decompress_started();+ t.decompress_finished();+ t.scrub_started();+ t.time_op("cv", || {});+ let result = contain_unwind(+ || -> Result<(), String> {+ t.time_op("blur", || panic!("image decode exploded"));+ Ok(())+ },+ |m| m,+ );+ assert!(result.is_err());++ let snap = t.snapshot();+ assert!(snap.decompress_end_ns.is_some());+ assert!(snap.scrub_start_ns.is_some());+ assert_eq!(snap.scrub_end_ns, None);+ assert_eq!(snap.cv_count, 1);+ assert_eq!(snap.last_op, "blur");+ }+}