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(session-replay): expose image scrub outcomes and latency (#89042)

Robbie52df08eb42ff
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
index 2293835b0a53..d5deac1d7afe 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/README.md
@@ -453,7 +453,7 @@ A fetch batch can publish more frontier records than it consumed. This can occur
**11.5** The provider domain is the effective top-level domain plus one when only the ICANN section is active. For example, it is `posthog.com` for `app.posthog.com` and `vercel.app` for `myapp.vercel.app`. This document does not use the ambiguous term `root domain`.
-**11.6** Every metric label defined by this lane uses a fixed set of values. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.
+**11.6** Every metric label defined by this lane uses a fixed set of values. HTTP responses use `2xx`, `3xx`, `4xx`, `5xx`, or `other`. Republish destination classes use `frontier` or `delay`. Republish topic classes use `frontier`, `retry_1m`, `retry_10m`, or `retry_1h`. Image scrub sources use `inline` or `url`. Unexpected scrub source formats use `other`. No label defined by this lane contains a configured Kafka topic name, registrable domain, provider domain, origin, host, URL, image ref, team, project, exception message, or other external value.
**11.7** The lane counts republished URLs by reason and bounded destination class. For each used topic class in a fetch batch, it observes the number of Kafka record delivery attempts, the number of attempted registrable-domain keys, and the wall time from topic-class scheduling until all started delivery attempts settle. It also observes total republish flush wall time and counts batches that reached the republish finalization deadline.
@@ -606,10 +606,11 @@ ai_research_session_replay_image_fetch_retry_1h
**17.4** The record has these Kafka headers:
-| Header | Value |
-| ------------------ | --------------------------------------------------------------------------------------------------- |
-| `content-type` | The normalized media type accepted under requirement 14.10, in lowercase and without parameters |
-| `content-encoding` | The response content codings in the order in which the server applied them, normalized to lowercase |
+| Header | Value |
+| ---------------------- | --------------------------------------------------------------------------------------------------- |
+| `content-type` | The normalized media type accepted under requirement 14.10, in lowercase and without parameters |
+| `content-encoding` | The response content codings in the order in which the server applied them, normalized to lowercase |
+| `capture-timestamp-ms` | The Unix timestamp from the replay Kafka record where the collector first saw the URL |
**17.5** The fetcher omits `content-encoding` when the response has no content coding or specifies `identity`. The scrubber treats a missing header as `identity`.
@@ -617,9 +618,9 @@ ai_research_session_replay_image_fetch_retry_1h
**17.7** After content decoding, the scrubber checks that the bytes match `content-type` before it sends them to the image scrubber.
-**17.8** Existing inline image records keep their current format: the key is an `image:<pseudo-team>:<hash>` ref, the value is the raw image bytes, and no transport headers are required.
+**17.8** Inline image records use an `image:<pseudo-team>:<hash>` key and raw image bytes. They carry `capture-timestamp-ms` from the source replay Kafka record.
-**17.9** This design does not add a dead-letter topic. The existing image-scrubber dead-letter path and its replay preserve the original key, value, `content-type`, and `content-encoding`. The dead-letter path can add diagnostic headers and update its replay counter.
+**17.9** This design does not add a dead-letter topic. The existing image-scrubber dead-letter path and its replay preserve the original key, value, `content-type`, `content-encoding`, and `capture-timestamp-ms`. The dead-letter path can add diagnostic headers and update its replay counter.
**17.10** The maximum record size is the response byte limit in requirement 5.10 plus the maximum key, header, and Kafka protocol overhead. The fetcher producer, image-scrub topic, existing image-scrub dead-letter topic, and their consumers must accept that size.
@@ -631,6 +632,8 @@ ai_research_session_replay_image_fetch_retry_1h
**17.14** Inline images keep their existing sharded S3 storage and Parquet index.
+**17.15** After a successful S3 write, the scrubber observes capture-to-S3 duration in a fixed-bucket histogram. The `source` label is `inline` or `url`. The scrubber does not observe a URL candidate when the conditional write finds an existing object.
+
## External specifications
| Specification | What it governs here |
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
index c51aa2db7650..55d7dc909da5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.test.ts
@@ -435,7 +435,11 @@ describe('FrontierPublisher', () => {
topic: SCRUB,
key: `imageurl:${'a'.repeat(22)}`,
value: Buffer.from('image'),
- headers: { 'content-type': 'image/png', 'content-encoding': 'gzip' },
+ headers: {
+ 'content-type': 'image/png',
+ 'content-encoding': 'gzip',
+ 'capture-timestamp-ms': '1700000000000',
+ },
})
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
index fbdb072ea17b..ab652da18a00 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher.ts
@@ -1,6 +1,7 @@
import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { ConcurrencyController } from '~/common/utils/concurrencyController'
import { logger } from '~/common/utils/logger'
+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
import {
FetchCandidate,
@@ -109,7 +110,10 @@ export class FrontierPublisher {
throw new Error('an image publish needs response bytes and a content type')
}
const bytes = result.bytes
- const headers: Record<string, string> = { 'content-type': result.contentType }
+ const headers: Record<string, string> = {
+ 'content-type': result.contentType,
+ [CAPTURE_TIMESTAMP_HEADER]: String(candidate.firstSeenAtMs),
+ }
if (result.contentEncoding) {
headers['content-encoding'] = result.contentEncoding
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
index 04726ec71636..92caa2b98716 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
@@ -1,5 +1,10 @@
// These params must stay in sync with rust/replay-anonymizer/src/blur.rs, or the mirror diverges from the inline anonymizer.
-import { PermanentImageError, UndecodableImageError, inspectImage, sharpForImage } from './image-input.ts'
+import {
+ PermanentImageError,
+ inspectImage,
+ sharpForImage,
+ undecodableImageErrorFromDecodeFailure,
+} from './image-input.ts'
export { LIMIT_INPUT_PIXELS, UndecodableImageError } from './image-input.ts'
@@ -25,6 +30,6 @@ export async function blurOnly(input: Buffer): Promise<Buffer> {
const [tw, th] = targetDims(description.width, description.height)
return await sharpForImage(input).resize(tw, th, { fit: 'fill' }).blur(BLUR_SIGMA).png().toBuffer()
} catch (e) {
- throw e instanceof PermanentImageError ? e : new UndecodableImageError(String(e))
+ throw e instanceof PermanentImageError ? e : undecodableImageErrorFromDecodeFailure(e)
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs
index 66f696e6894c..2f40ae4f9dc8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/fake-scrub-worker.mjs
@@ -30,7 +30,10 @@ parentPort.on('message', async (job) => {
return
}
if (kind === 'undecodable') {
- parentPort.postMessage({ id: job.id, failure: { message: 'bad bytes', kind: 'undecodable' } })
+ parentPort.postMessage({
+ id: job.id,
+ failure: { message: 'bad bytes', kind: 'undecodable', reason: 'decode_failed' },
+ })
return
}
if (kind === 'opt-out') {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts
index d9924c16adcc..32eeb285533e 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/image-input.ts
@@ -12,9 +12,34 @@ sharp.block({ operation: ['VipsForeignLoadTiff', 'VipsForeignLoadVips'] })
export const LIMIT_INPUT_PIXELS = 50_000_000
export class PermanentImageError extends Error {}
-export class UndecodableImageError extends PermanentImageError {}
+export type UndecodableImageReason =
+ | 'decode_failed'
+ | 'invalid_body'
+ | 'invalid_dimensions'
+ | 'pixel_limit'
+ | 'unsupported_format'
+
+export class UndecodableImageError extends PermanentImageError {
+ public constructor(
+ public readonly reason: UndecodableImageReason,
+ message: string
+ ) {
+ super(message)
+ }
+}
export class ImageOptOutError extends PermanentImageError {}
+export function undecodableImageErrorFromDecodeFailure(error: unknown): UndecodableImageError {
+ const message = error instanceof Error ? error.message : String(error)
+ const normalizedMessage = message.toLowerCase()
+ const reason = normalizedMessage.includes('pixel limit')
+ ? 'pixel_limit'
+ : normalizedMessage.includes('unsupported image format')
+ ? 'unsupported_format'
+ : 'decode_failed'
+ return new UndecodableImageError(reason, message)
+}
+
export interface ImageDescription {
width: number
height: number
@@ -24,10 +49,10 @@ export interface ImageDescription {
export async function inspectImage(input: Buffer): Promise<ImageDescription> {
const metadata = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()
if (!metadata.width || !metadata.height) {
- throw new UndecodableImageError('image has invalid dimensions')
+ throw new UndecodableImageError('invalid_dimensions', 'image has invalid dimensions')
}
if (metadata.width * metadata.height > LIMIT_INPUT_PIXELS) {
- throw new UndecodableImageError('image exceeds the pixel limit')
+ throw new UndecodableImageError('pixel_limit', 'image exceeds the pixel limit')
}
if (imageMetadataProhibitsAiTraining(input, metadata.xmp)) {
throw new ImageOptOutError('image metadata prohibits AI training')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts
index e06a9dad48f8..501f6cfdf464 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.test.ts
@@ -40,6 +40,13 @@ async function sourceFormatLabels(): Promise<string[]> {
return (metric as { values: { labels: Record<string, string> }[] }).values.map((value) => value.labels.format)
}
+async function undecodableReasonLabels(): Promise<string[]> {
+ const metric = (await register.getMetricsAsJSON()).find(
+ (candidate) => candidate.name === 'ml_mirror_image_scrub_undecodable_total'
+ )
+ return (metric as { values: { labels: Record<string, string> }[] }).values.map((value) => value.labels.reason)
+}
+
describe('observeScrubOutcome', () => {
beforeEach(() => register.resetMetrics())
@@ -72,4 +79,11 @@ describe('observeScrubOutcome', () => {
expect(await sourceFormatLabels()).toEqual(['other'])
}
)
+
+ it('records bounded undecodable reasons', async () => {
+ ScrubMetrics.incUndecodable('decode_failed')
+ ScrubMetrics.incUndecodable('unsupported_format')
+
+ expect(await undecodableReasonLabels()).toEqual(['decode_failed', 'unsupported_format'])
+ })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
index d5de0c91fab4..80cc493a9284 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
@@ -1,5 +1,6 @@
import { Counter, Gauge, Histogram, Registry } from 'prom-client'
+import { type UndecodableImageReason } from './image-input.ts'
import { type StageTimings } from './scrub.ts'
export const register = new Registry()
@@ -36,7 +37,8 @@ const failed = new Counter({
})
const undecodable = new Counter({
name: 'ml_mirror_image_scrub_undecodable_total',
- help: 'Inputs sharp could not decode (422) — permanently skipped, never retried',
+ help: 'Inputs permanently rejected as undecodable, by bounded reason',
+ labelNames: ['reason'],
registers: [register],
})
const optedOut = new Counter({
@@ -206,7 +208,7 @@ export const ScrubMetrics = {
incWorkerRestartFailure: () => workerRestartFailures.inc(),
incScrubbed: () => scrubbed.inc(),
incFailed: () => failed.inc(),
- incUndecodable: () => undecodable.inc(),
+ incUndecodable: (reason: UndecodableImageReason) => undecodable.labels(reason).inc(),
incOptedOut: () => optedOut.inc(),
incRejected: () => rejected.inc(),
incTooLarge: () => tooLarge.inc(),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts
index 7317777e889b..7b46aba69570 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.test.ts
@@ -3,7 +3,6 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
-import { UndecodableImageError } from './blur.ts'
import { ImageOptOutError } from './image-input.ts'
import { ScrubAbandonedError, type ScrubPool, type ScrubResult, startPool } from './pool.ts'
@@ -106,7 +105,9 @@ describe('startPool', () => {
// consumer then attempts four times.
pool = await startPool(1, FAKE_WORKER)
- await expect(pool.scrub(Buffer.from('undecodable'))).rejects.toBeInstanceOf(UndecodableImageError)
+ await expect(pool.scrub(Buffer.from('undecodable'))).rejects.toMatchObject({
+ reason: 'decode_failed',
+ })
})
it('rebuilds an ImageOptOutError from the wire', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts
index bfec2abc9eb4..3d648ea4186f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/pool.ts
@@ -197,7 +197,7 @@ export async function startPool(
if ('failure' in msg) {
const error =
msg.failure.kind === 'undecodable'
- ? new UndecodableImageError(msg.failure.message)
+ ? new UndecodableImageError(msg.failure.reason, msg.failure.message)
: msg.failure.kind === 'opt-out'
? new ImageOptOutError(msg.failure.message)
: new Error(msg.failure.message)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts
index 03f32a4924db..73aefd896982 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub-worker.ts
@@ -10,7 +10,7 @@ import { parentPort } from 'node:worker_threads'
import { UndecodableImageError } from './blur.ts'
import { ImageOptOutError } from './image-input.ts'
import { advancedScrub, loadModels } from './scrub.ts'
-import { type ScrubJob, type ScrubReply } from './worker-protocol.ts'
+import { type ScrubFailure, type ScrubJob, type ScrubReply } from './worker-protocol.ts'
if (!parentPort) {
throw new Error('scrub-worker must be started as a worker thread')
@@ -38,17 +38,13 @@ port.on('message', (job: ScrubJob) => {
.catch((error: unknown) => {
// Structured clone drops the prototype, so the one distinction the HTTP layer acts on
// (422 permanent versus 500 retriable) has to travel as data rather than as a class.
- port.postMessage({
- id: job.id,
- failure: {
- message: error instanceof Error ? error.message : String(error),
- kind:
- error instanceof ImageOptOutError
- ? 'opt-out'
- : error instanceof UndecodableImageError
- ? 'undecodable'
- : 'failed',
- },
- } satisfies ScrubReply)
+ const message = error instanceof Error ? error.message : String(error)
+ const failure: ScrubFailure =
+ error instanceof ImageOptOutError
+ ? { message, kind: 'opt-out' as const }
+ : error instanceof UndecodableImageError
+ ? { message, kind: 'undecodable' as const, reason: error.reason }
+ : { message, kind: 'failed' as const }
+ port.postMessage({ id: job.id, failure } satisfies ScrubReply)
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts
index c41821e722a5..82cfe7361024 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts
@@ -12,11 +12,11 @@
*/
import sharp, { type Sharp } from 'sharp'
-import { BLANK_PNG, LIMIT_INPUT_PIXELS, UndecodableImageError, blurOnly } from './blur.ts'
+import { BLANK_PNG, LIMIT_INPUT_PIXELS, blurOnly } from './blur.ts'
import { type DbnetModel, detectTextDbnet, loadDbnet } from './dbnet.ts'
import { numFromEnv } from './env.ts'
import { type Box } from './geometry.ts'
-import { PermanentImageError } from './image-input.ts'
+import { PermanentImageError, undecodableImageErrorFromDecodeFailure } from './image-input.ts'
import { detectCodes } from './qr.ts'
import { type SafetyModel, classifySafety, loadSafety } from './safety.ts'
import { type Dims, type ScalePlan, limitsFromEnv, planScales } from './scale-plan.ts'
@@ -147,7 +147,7 @@ export async function advancedScrub(
plan = planScales(meta, limitsFromEnv())
src = await decodeSrc(input, plan.frame)
} catch (e) {
- throw e instanceof PermanentImageError ? e : new UndecodableImageError(String(e))
+ throw e instanceof PermanentImageError ? e : undecodableImageErrorFromDecodeFailure(e)
}
const { W, H } = src
timings.decodeMs = performance.now() - tDec
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
index c8c860f00597..c1eadc5ea8f0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
@@ -3,6 +3,7 @@ import type { AddressInfo } from 'node:net'
import sharp from 'sharp'
import { blurOnly } from './blur.ts'
+import { register } from './metrics.ts'
import { startServer } from './server.ts'
const PNG = Buffer.from(
@@ -23,6 +24,7 @@ describe('image-scrub sidecar server', () => {
base = `http://127.0.0.1:${(servers.scrub.address() as AddressInfo).port}`
metricsBase = `http://127.0.0.1:${(servers.metrics.address() as AddressInfo).port}`
})
+ beforeEach(() => register.resetMetrics())
afterAll((done) => {
let remaining = 2
for (const server of [servers.scrub, servers.metrics]) {
@@ -42,6 +44,9 @@ describe('image-scrub sidecar server', () => {
it('422s on undecodable bytes so the consumer skips them instead of retrying forever', async () => {
const res = await fetch(`${base}/scrub`, { method: 'POST', body: Buffer.from('not-an-image') })
expect(res.status).toBe(422)
+ expect(await (await fetch(`${metricsBase}/metrics`)).text()).toContain(
+ 'ml_mirror_image_scrub_undecodable_total{reason="unsupported_format"} 1'
+ )
})
it('413s on a body over the size cap so the consumer skips it', async () => {
@@ -52,11 +57,17 @@ describe('image-scrub sidecar server', () => {
it('422s a request with no body', async () => {
const res = await fetch(`${base}/scrub`, { method: 'POST' })
expect(res.status).toBe(422)
+ expect(await (await fetch(`${metricsBase}/metrics`)).text()).toContain(
+ 'ml_mirror_image_scrub_undecodable_total{reason="invalid_body"} 1'
+ )
})
it('422s a truncated image (fails mid-decode, not just at the header)', async () => {
const res = await fetch(`${base}/scrub`, { method: 'POST', body: PNG.subarray(0, 40) })
expect(res.status).toBe(422)
+ expect(await (await fetch(`${metricsBase}/metrics`)).text()).toContain(
+ 'ml_mirror_image_scrub_undecodable_total{reason="decode_failed"} 1'
+ )
})
it('422s an image whose PLUS metadata prohibits AI training', async () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
index 3e6127f87ee3..f6e7ea10a848 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
@@ -75,8 +75,8 @@ export function startServer(
app.post('/scrub', shedIfBusy, express.raw({ type: () => true, limit: maxBodyBytes }), (req, res, next) => {
const body = req.body
- if (!Buffer.isBuffer(body)) {
- next(new UndecodableImageError('request body is not image bytes'))
+ if (!Buffer.isBuffer(body) || body.length === 0) {
+ next(new UndecodableImageError('invalid_body', 'request body is not image bytes'))
return
}
res.locals.scrubStarted = true
@@ -123,7 +123,7 @@ export function startServer(
return
}
if (err instanceof UndecodableImageError) {
- ScrubMetrics.incUndecodable()
+ ScrubMetrics.incUndecodable(err.reason)
res.status(422).send('undecodable image')
return
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts
index 6b7ed16e55a1..b115bd3b5816 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/worker-protocol.ts
@@ -1,3 +1,4 @@
+import { type UndecodableImageReason } from './image-input.ts'
import { type StageTimings } from './scrub.ts'
export interface ScrubJob {
@@ -5,8 +6,12 @@ export interface ScrubJob {
input: Uint8Array
}
+export type ScrubFailure =
+ | { message: string; kind: 'undecodable'; reason: UndecodableImageReason }
+ | { message: string; kind: 'opt-out' | 'failed' }
+
/** A worker sends `ready` once, then exactly one reply per job. */
export type ScrubReply =
| { ready: true }
| { id: number; out: Uint8Array; timings: StageTimings }
- | { id: number; failure: { message: string; kind: 'undecodable' | 'opt-out' | 'failed' } }
+ | { id: number; failure: ScrubFailure }
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts
index f596896b8e9d..a19a22a0a125 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.test.ts
@@ -4,6 +4,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { MAX_REPLAYS, replayBatch } from './dlq-replay'
import { REPLAY_COUNT_HEADER } from './image-batcher'
+import { CAPTURE_TIMESTAMP_HEADER } from './image-transport'
function parked(
ref: string,
@@ -87,6 +88,7 @@ describe('replayBatch', () => {
parked('ref-1', 'compressed-image', undefined, {
'content-type': 'image/png',
'content-encoding': 'gzip',
+ [CAPTURE_TIMESTAMP_HEADER]: '1700000000000',
}),
],
producer,
@@ -96,6 +98,7 @@ describe('replayBatch', () => {
expect(produced[0].headers).toEqual({
'content-type': 'image/png',
'content-encoding': 'gzip',
+ [CAPTURE_TIMESTAMP_HEADER]: '1700000000000',
[REPLAY_COUNT_HEADER]: '1',
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
index bcaca7827f87..71174fa66d2c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dlq-replay.ts
@@ -5,7 +5,7 @@ import { KafkaProducerWrapper } from '~/common/kafka/producer'
import { logger } from '~/common/utils/logger'
import { REPLAY_COUNT_HEADER } from './image-batcher'
-import { CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'
+import { CAPTURE_TIMESTAMP_HEADER, CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'
import { ImageScrubConsumerMetrics } from './metrics'
/**
@@ -64,6 +64,9 @@ export async function replayBatch(
...(headers[CONTENT_ENCODING_HEADER]
? { [CONTENT_ENCODING_HEADER]: headers[CONTENT_ENCODING_HEADER] }
: {}),
+ ...(headers[CAPTURE_TIMESTAMP_HEADER]
+ ? { [CAPTURE_TIMESTAMP_HEADER]: headers[CAPTURE_TIMESTAMP_HEADER] }
+ : {}),
[REPLAY_COUNT_HEADER]: String(replayCount + 1),
},
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
index ee331ddcbf73..015f4568f1db 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.test.ts
@@ -3,12 +3,14 @@ import { gzipSync } from 'node:zlib'
import { hashImageBytes, imageRef, urlRef } from './content-ref'
import { ImageBatcher, OffsetStore } from './image-batcher'
-import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage } from './image-shard-store'
+import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage, UrlImageWriteOutcome } from './image-shard-store'
+import { CAPTURE_TIMESTAMP_HEADER } from './image-transport'
import { ImageScrubConsumerMetrics } from './metrics'
import { ScrubClient, ScrubPoisoned } from './scrub-client'
const pt = (n: number): string => String(n).padStart(32, '0')
const CONTENT_KEY = 'fedcba9876543210fedcba9876543210'
+const CAPTURED_AT = 1_700_000_000_000
function msg(
partition: number,
@@ -34,6 +36,7 @@ class FakeStore {
public urlWrites: ScrubbedUrlImage[] = []
public failNext = false
public failNextUrl = false
+ public urlWriteOutcome: UrlImageWriteOutcome = 'created'
// eslint-disable-next-line @typescript-eslint/require-await
async writeShard(images: ScrubbedImage[]): Promise<{ shard: string; bytes: number }> {
if (this.failNext) {
@@ -44,11 +47,12 @@ class FakeStore {
}
// eslint-disable-next-line @typescript-eslint/require-await
- async writeUrlImage(image: ScrubbedUrlImage): Promise<void> {
+ async writeUrlImage(image: ScrubbedUrlImage): Promise<UrlImageWriteOutcome> {
if (this.failNextUrl) {
throw new Error('url s3 down')
}
this.urlWrites.push(image)
+ return this.urlWriteOutcome
}
}
@@ -79,13 +83,24 @@ describe('ImageBatcher', () => {
it('scrubs a multi-team batch into one shard for the flush, storing offsets after', async () => {
const store = new FakeStore()
const offsets = new FakeOffsets()
+ const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()
const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)
- await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a')), msg(0, 1, pt(2), Buffer.from('b'))], 1)
+ const captureHeader = [{ [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) }]
+ await batcher.handleBatch(
+ [
+ msg(0, 0, pt(1), Buffer.from('a'), undefined, captureHeader),
+ msg(0, 1, pt(2), Buffer.from('b'), undefined, captureHeader),
+ ],
+ 1
+ )
expect(store.writes).toHaveLength(1)
expect(store.writes[0].map((i) => i.pseudoTeam).sort()).toEqual([pt(1), pt(2)])
expect(offsets.stored).toBe(1)
+ expect(observeCaptureToS3).toHaveBeenCalledTimes(2)
+ expect(observeCaptureToS3).toHaveBeenNthCalledWith(1, 'inline', CAPTURED_AT, expect.any(Number))
+ expect(observeCaptureToS3).toHaveBeenNthCalledWith(2, 'inline', CAPTURED_AT, expect.any(Number))
})
it('trusts the producer ref: the bytes are indexed under the key hash without recomputing it', async () => {
@@ -117,6 +132,7 @@ describe('ImageBatcher', () => {
},
} as unknown as ScrubClient
const store = new FakeStore()
+ const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()
const batcher = new ImageBatcher(
store as unknown as ImageShardStore,
new FakeOffsets(),
@@ -131,6 +147,7 @@ describe('ImageBatcher', () => {
msg(0, 0, pt(1), gzipSync(png), ref, [
{ 'content-type': Buffer.from('image/png') },
{ 'content-encoding': Buffer.from('gzip') },
+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },
]),
],
1
@@ -146,6 +163,35 @@ describe('ImageBatcher', () => {
},
])
expect(store.writes).toHaveLength(0)
+ expect(observeCaptureToS3).toHaveBeenCalledWith('url', CAPTURED_AT, expect.any(Number))
+ })
+
+ it('does not observe URL latency when the object already exists', async () => {
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
+ const store = new FakeStore()
+ store.urlWriteOutcome = 'already_exists'
+ const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()
+ const batcher = new ImageBatcher(
+ store as unknown as ImageShardStore,
+ new FakeOffsets(),
+ { scrub: (bytes: Buffer) => Promise.resolve(bytes) } as unknown as ScrubClient,
+ options,
+ 0
+ )
+ const ref = urlRef(hashImageBytes(CONTENT_KEY, Buffer.from('https://example.com/image.png')))
+
+ await batcher.handleBatch(
+ [
+ msg(0, 0, pt(1), png, ref, [
+ { 'content-type': Buffer.from('image/png') },
+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },
+ ]),
+ ],
+ 1
+ )
+
+ expect(store.urlWrites).toHaveLength(1)
+ expect(observeCaptureToS3).not.toHaveBeenCalled()
})
it('submits every valid URL image for the conditional store to select the first completed write', async () => {
@@ -271,6 +317,7 @@ describe('ImageBatcher', () => {
it('drops a URL image whose bytes do not match its Kafka content-type', async () => {
let scrubCalls = 0
+ const incSkipped = jest.spyOn(ImageScrubConsumerMetrics, 'incSkipped')
const batcher = new ImageBatcher(
new FakeStore() as unknown as ImageShardStore,
new FakeOffsets(),
@@ -291,16 +338,28 @@ describe('ImageBatcher', () => {
)
expect(scrubCalls).toBe(0)
+ expect(incSkipped).toHaveBeenCalledWith('content_type_mismatch')
})
it('does not store offsets when the shard write fails (at-least-once replay)', async () => {
const store = new FakeStore()
store.failNext = true
const offsets = new FakeOffsets()
+ const observeCaptureToS3 = jest.spyOn(ImageScrubConsumerMetrics, 'observeCaptureToS3').mockImplementation()
const batcher = new ImageBatcher(store as unknown as ImageShardStore, offsets, scrubClient, options, 0)
- await expect(batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)).rejects.toThrow('s3 down')
+ await expect(
+ batcher.handleBatch(
+ [
+ msg(0, 0, pt(1), Buffer.from('a'), undefined, [
+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },
+ ]),
+ ],
+ 1
+ )
+ ).rejects.toThrow('s3 down')
expect(offsets.stored).toBe(0)
+ expect(observeCaptureToS3).not.toHaveBeenCalled()
})
it('does not create a random inline shard before deterministic URL writes succeed', async () => {
@@ -670,11 +729,13 @@ describe('ImageBatcher', () => {
0
)
const broken = Buffer.from('broken')
+ const incSkipped = jest.spyOn(ImageScrubConsumerMetrics, 'incSkipped')
await batcher.handleBatch([msg(0, 0, pt(1), broken)], 1)
await batcher.handleBatch([msg(0, 1, pt(1), broken)], 2)
expect(calls).toBe(1)
+ expect(incSkipped).toHaveBeenCalledWith('sidecar_rejected')
})
it('dedupMaxRefs 0 disables the cross-batch cache but never intra-batch dedup', async () => {
@@ -805,6 +866,7 @@ describe('ImageBatcher', () => {
msg(0, 0, pt(1), compressed, ref, [
{ 'content-type': Buffer.from('image/png') },
{ 'content-encoding': Buffer.from('gzip') },
+ { [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(CAPTURED_AT)) },
]),
],
1
@@ -813,7 +875,11 @@ describe('ImageBatcher', () => {
expect(parked).toEqual([
{
bytes: compressed,
- headers: { 'content-type': 'image/png', 'content-encoding': 'gzip' },
+ headers: {
+ 'content-type': 'image/png',
+ 'content-encoding': 'gzip',
+ [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT),
+ },
},
])
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
index cef11ad3b650..b35d14f09ed7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher.ts
@@ -8,6 +8,7 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de
import { parseImageRef } from './content-ref'
import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage } from './image-shard-store'
import {
+ CAPTURE_TIMESTAMP_HEADER,
CONTENT_ENCODING_HEADER,
CONTENT_TYPE_HEADER,
InvalidImageTransportError,
@@ -70,6 +71,7 @@ interface PlannedScrub {
source: 'bytes' | 'url'
value: Buffer
transportHeaders: Record<string, string>
+ capturedAtMs?: number
/** Where this image came from, carried only so a parked one can be traced back to its source. */
sourceTopic: string
sourcePartition: number
@@ -88,6 +90,7 @@ interface ScrubbedRef {
ref: string
source: 'bytes' | 'url'
image: ScrubbedImage | ScrubbedUrlImage
+ capturedAtMs?: number
}
/** Carries the window slot so a completion can be matched back to its position, which is what
@@ -361,14 +364,16 @@ export class ImageBatcher {
continue
}
const headers = parseKafkaHeaders(m.headers)
- const transportHeaders =
+ const allowedTransportHeaders =
parsed.source === 'url'
- ? Object.fromEntries(
- [CONTENT_TYPE_HEADER, CONTENT_ENCODING_HEADER]
- .filter((header) => headers[header] !== undefined)
- .map((header) => [header, headers[header]])
- )
- : {}
+ ? [CONTENT_TYPE_HEADER, CONTENT_ENCODING_HEADER, CAPTURE_TIMESTAMP_HEADER]
+ : [CAPTURE_TIMESTAMP_HEADER]
+ const transportHeaders = Object.fromEntries(
+ allowedTransportHeaders
+ .filter((header) => headers[header] !== undefined)
+ .map((header) => [header, headers[header]])
+ )
+ const capturedAtMs = Number(transportHeaders[CAPTURE_TIMESTAMP_HEADER])
const candidate: PlannedScrub = {
index,
ref,
@@ -377,6 +382,7 @@ export class ImageBatcher {
source: parsed.source,
value: m.value,
transportHeaders,
+ capturedAtMs: Number.isSafeInteger(capturedAtMs) && capturedAtMs > 0 ? capturedAtMs : undefined,
sourceTopic: m.topic,
sourcePartition: m.partition,
sourceOffset: m.offset,
@@ -435,7 +441,7 @@ export class ImageBatcher {
.then(
(image): SettledScrub => ({
slot,
- scrubbed: image ? { ref: p.ref, source: p.source, image } : null,
+ scrubbed: image ? { ref: p.ref, source: p.source, image, capturedAtMs: p.capturedAtMs } : null,
}),
(error): SettledScrub => ({ slot, scrubbed: null, error: error ?? new Error('scrub failed') })
)
@@ -467,7 +473,7 @@ export class ImageBatcher {
throw error
}
this.rememberContentAddressedRef(planned)
- ImageScrubConsumerMetrics.incSkipped()
+ ImageScrubConsumerMetrics.incSkipped(error.reason)
return null
}
}
@@ -492,7 +498,7 @@ export class ImageBatcher {
// Null is a verdict on these bytes. Inline refs are content-addressed, so their later
// copies cannot succeed. URL refs stay eligible because a recrawl can carry new bytes.
this.rememberContentAddressedRef(planned)
- ImageScrubConsumerMetrics.incSkipped()
+ ImageScrubConsumerMetrics.incSkipped('sidecar_rejected')
return null
}
ImageScrubConsumerMetrics.incScrubbed()
@@ -582,23 +588,32 @@ export class ImageBatcher {
public async flush(nowMs: number): Promise<void> {
this.lastFlushMs = nowMs
if (this.buffer.length > 0) {
- const inlineImages = this.buffer
- .filter((item): item is ScrubbedRef & { image: ScrubbedImage } => item.source === 'bytes')
- .map((item) => item.image)
- const urlImages = this.buffer
- .filter((item): item is ScrubbedRef & { image: ScrubbedUrlImage } => item.source === 'url')
- .map((item) => item.image)
+ const inlineItems = this.buffer.filter(
+ (item): item is ScrubbedRef & { image: ScrubbedImage } => item.source === 'bytes'
+ )
+ const urlItems = this.buffer.filter(
+ (item): item is ScrubbedRef & { image: ScrubbedUrlImage } => item.source === 'url'
+ )
await Promise.all(
- urlImages.map((image) =>
- this.scrubConcurrency.run({
- debugTag: image.hash,
- fn: () => this.store.writeUrlImage(image),
+ urlItems.map(async (item) => {
+ const outcome = await this.scrubConcurrency.run({
+ debugTag: item.image.hash,
+ fn: () => this.store.writeUrlImage(item.image),
})
- )
+ if (outcome === 'created' && item.capturedAtMs !== undefined) {
+ ImageScrubConsumerMetrics.observeCaptureToS3('url', item.capturedAtMs, Date.now())
+ }
+ })
)
- if (inlineImages.length > 0) {
- const { bytes } = await this.store.writeShard(inlineImages)
- ImageScrubConsumerMetrics.observeShard(inlineImages.length, bytes)
+ if (inlineItems.length > 0) {
+ const { bytes } = await this.store.writeShard(inlineItems.map((item) => item.image))
+ const storedAtMs = Date.now()
+ for (const item of inlineItems) {
+ if (item.capturedAtMs !== undefined) {
+ ImageScrubConsumerMetrics.observeCaptureToS3('inline', item.capturedAtMs, storedAtMs)
+ }
+ }
+ ImageScrubConsumerMetrics.observeShard(inlineItems.length, bytes)
}
this.buffer = []
this.bufferBytes = 0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
index b3679a0b2b8b..b81f194d7a87 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.test.ts
@@ -47,7 +47,7 @@ describe('ImageShardStore', () => {
const send = jest.fn().mockResolvedValueOnce({})
const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')
- await store.writeUrlImage(urlImage)
+ await expect(store.writeUrlImage(urlImage)).resolves.toBe('created')
const put = send.mock.calls[0][0] as PutObjectCommand
expect(put.input).toMatchObject({
@@ -65,7 +65,7 @@ describe('ImageShardStore', () => {
const send = jest.fn().mockRejectedValueOnce(exists)
const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')
- await store.writeUrlImage(urlImage)
+ await expect(store.writeUrlImage(urlImage)).resolves.toBe('already_exists')
expect(send).toHaveBeenCalledTimes(1)
expect((send.mock.calls[0][0] as PutObjectCommand).input.IfNoneMatch).toBe('*')
@@ -79,7 +79,7 @@ describe('ImageShardStore', () => {
const send = jest.fn().mockRejectedValueOnce(conflict).mockResolvedValueOnce({})
const store = new ImageShardStore({ send } as unknown as S3Client, 'bucket', 'images', 1_000, 'node')
- await store.writeUrlImage(urlImage)
+ await expect(store.writeUrlImage(urlImage)).resolves.toBe('created')
expect(send).toHaveBeenCalledTimes(2)
expect(send.mock.calls.map(([command]) => (command as PutObjectCommand).input.IfNoneMatch)).toEqual(['*', '*'])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
index bfce2ddeb528..80fe323c7e39 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store.ts
@@ -17,6 +17,8 @@ export interface ScrubbedUrlImage {
sourceOffset: number
}
+export type UrlImageWriteOutcome = 'created' | 'already_exists'
+
interface IndexRow {
pseudoTeam: string
hash: string
@@ -120,7 +122,7 @@ export class ImageShardStore {
return { shard: shardKey, bytes: offset }
}
- public async writeUrlImage(image: ScrubbedUrlImage): Promise<void> {
+ public async writeUrlImage(image: ScrubbedUrlImage): Promise<UrlImageWriteOutcome> {
if (
!Number.isSafeInteger(image.sourcePartition) ||
image.sourcePartition < 0 ||
@@ -145,10 +147,10 @@ export class ImageShardStore {
IfNoneMatch: '*',
})
)
- return
+ return 'created'
} catch (error) {
if (isPreconditionFailed(error)) {
- return
+ return 'already_exists'
}
if (isConditionalRequestConflict(error)) {
continue
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
index ac390b6cb74e..711065a7ec5b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.test.ts
@@ -1,7 +1,6 @@
import { brotliCompressSync, deflateSync, gzipSync, zstdCompressSync } from 'node:zlib'
import {
- InvalidImageTransportError,
MAX_UNCOMPRESSED_IMAGE_BYTES,
SUPPORTED_IMAGE_MEDIA_TYPES,
imageBytesMatchMediaType,
@@ -51,36 +50,40 @@ describe('image transport', () => {
'image/png',
'identity, identity, identity, identity, identity'
)
- ).rejects.toThrow('content-encoding exceeds 4 codings')
+ ).rejects.toMatchObject({
+ reason: 'content_encoding_too_deep',
+ message: 'content-encoding exceeds 4 codings',
+ })
})
it('stops decompression when the decoded bytes cross the 20 MiB cap', async () => {
const compressed = gzipSync(Buffer.alloc(MAX_UNCOMPRESSED_IMAGE_BYTES + 1))
- await expect(prepareFetchedImage(compressed, 'image/png', 'gzip')).rejects.toThrow(
- `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`
- )
+ await expect(prepareFetchedImage(compressed, 'image/png', 'gzip')).rejects.toMatchObject({
+ reason: 'decoded_too_large',
+ message: `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`,
+ })
})
it.each([
- ['an unsupported content coding', imageHeaders['image/png'], 'compress'],
- ['a malformed content coding list', imageHeaders['image/png'], 'gzip,'],
- ['compressed bytes that are malformed', Buffer.from('not gzip'), 'gzip'],
- ])('rejects %s', async (_case, bytes, contentEncoding) => {
- await expect(prepareFetchedImage(bytes, 'image/png', contentEncoding)).rejects.toBeInstanceOf(
- InvalidImageTransportError
- )
+ ['an unsupported content coding', imageHeaders['image/png'], 'compress', 'unsupported_content_encoding'],
+ ['a malformed content coding list', imageHeaders['image/png'], 'gzip,', 'malformed_content_encoding'],
+ ['compressed bytes that are malformed', Buffer.from('not gzip'), 'gzip', 'decompression_failed'],
+ ] as const)('labels %s', async (_case, bytes, contentEncoding, reason) => {
+ await expect(prepareFetchedImage(bytes, 'image/png', contentEncoding)).rejects.toMatchObject({ reason })
})
it('rejects bytes that do not match the declared media type', async () => {
- await expect(prepareFetchedImage(imageHeaders['image/jpeg'], 'image/png', undefined)).rejects.toThrow(
- 'image bytes do not match content-type image/png'
- )
+ await expect(prepareFetchedImage(imageHeaders['image/jpeg'], 'image/png', undefined)).rejects.toMatchObject({
+ reason: 'content_type_mismatch',
+ message: 'image bytes do not match content-type image/png',
+ })
})
- it('rejects BMP images', async () => {
- await expect(prepareFetchedImage(Buffer.from('BM', 'ascii'), 'image/bmp', undefined)).rejects.toThrow(
- 'unsupported content-type: image/bmp'
- )
+ it.each([
+ ['a missing content-type', imageHeaders['image/png'], undefined, 'missing_content_type'],
+ ['a BMP content-type', Buffer.from('BM', 'ascii'), 'image/bmp', 'unsupported_content_type'],
+ ] as const)('labels %s', async (_case, bytes, contentType, reason) => {
+ await expect(prepareFetchedImage(bytes, contentType, undefined)).rejects.toMatchObject({ reason })
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
index e2eadf580ce9..8811e99aea80 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport.ts
@@ -4,6 +4,7 @@ import { createBrotliDecompress, createGunzip, createInflate, createZstdDecompre
export const MAX_UNCOMPRESSED_IMAGE_BYTES = 20 * 1024 * 1024
export const CONTENT_TYPE_HEADER = 'content-type'
export const CONTENT_ENCODING_HEADER = 'content-encoding'
+export const CAPTURE_TIMESTAMP_HEADER = 'capture-timestamp-ms'
const MAX_CONTENT_ENCODING_LAYERS = 4
@@ -11,7 +12,24 @@ export const SUPPORTED_IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/gi
export type SupportedImageMediaType = (typeof SUPPORTED_IMAGE_MEDIA_TYPES)[number]
-export class InvalidImageTransportError extends Error {}
+export type ImageTransportRejectionReason =
+ | 'content_encoding_too_deep'
+ | 'malformed_content_encoding'
+ | 'unsupported_content_encoding'
+ | 'decompression_failed'
+ | 'decoded_too_large'
+ | 'missing_content_type'
+ | 'unsupported_content_type'
+ | 'content_type_mismatch'
+
+export class InvalidImageTransportError extends Error {
+ public constructor(
+ public readonly reason: ImageTransportRejectionReason,
+ message: string
+ ) {
+ super(message)
+ }
+}
const decoderFactories: Record<string, () => Transform> = {
gzip: createGunzip,
@@ -26,10 +44,13 @@ function parseContentEncodings(contentEncoding: string | undefined): string[] {
}
const encodings = contentEncoding.split(',').map((encoding) => encoding.trim().toLowerCase())
if (encodings.length > MAX_CONTENT_ENCODING_LAYERS) {
- throw new InvalidImageTransportError(`content-encoding exceeds ${MAX_CONTENT_ENCODING_LAYERS} codings`)
+ throw new InvalidImageTransportError(
+ 'content_encoding_too_deep',
+ `content-encoding exceeds ${MAX_CONTENT_ENCODING_LAYERS} codings`
+ )
}
if (encodings.some((encoding) => encoding.length === 0)) {
- throw new InvalidImageTransportError('content-encoding contains an empty coding')
+ throw new InvalidImageTransportError('malformed_content_encoding', 'content-encoding contains an empty coding')
}
return encodings.filter((encoding) => encoding !== 'identity')
}
@@ -37,7 +58,10 @@ function parseContentEncodings(contentEncoding: string | undefined): string[] {
async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer> {
const decoderFactory = decoderFactories[encoding]
if (!decoderFactory) {
- throw new InvalidImageTransportError(`unsupported content-encoding: ${encoding}`)
+ throw new InvalidImageTransportError(
+ 'unsupported_content_encoding',
+ `unsupported content-encoding: ${encoding}`
+ )
}
const input = Readable.from([bytes])
@@ -50,7 +74,10 @@ async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer>
for await (const chunk of decoder) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
if (outputBytes + buffer.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {
- throw new InvalidImageTransportError(`decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`)
+ throw new InvalidImageTransportError(
+ 'decoded_too_large',
+ `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`
+ )
}
chunks.push(buffer)
outputBytes += buffer.length
@@ -59,7 +86,7 @@ async function decodeWithLimit(bytes: Buffer, encoding: string): Promise<Buffer>
if (error instanceof InvalidImageTransportError) {
throw error
}
- throw new InvalidImageTransportError(`invalid ${encoding} content: ${String(error)}`)
+ throw new InvalidImageTransportError('decompression_failed', `invalid ${encoding} content: ${String(error)}`)
} finally {
input.destroy()
decoder.destroy()
@@ -111,11 +138,17 @@ export async function prepareFetchedImage(
contentType: string | undefined,
contentEncoding: string | undefined
): Promise<Buffer> {
- if (!contentType || !isSupportedImageMediaType(contentType)) {
- throw new InvalidImageTransportError(`unsupported content-type: ${contentType ?? 'missing'}`)
+ if (!contentType) {
+ throw new InvalidImageTransportError('missing_content_type', 'unsupported content-type: missing')
+ }
+ if (!isSupportedImageMediaType(contentType)) {
+ throw new InvalidImageTransportError('unsupported_content_type', `unsupported content-type: ${contentType}`)
}
if (bytes.length > MAX_UNCOMPRESSED_IMAGE_BYTES) {
- throw new InvalidImageTransportError(`decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`)
+ throw new InvalidImageTransportError(
+ 'decoded_too_large',
+ `decoded image exceeds ${MAX_UNCOMPRESSED_IMAGE_BYTES} bytes`
+ )
}
let decoded = bytes
@@ -124,7 +157,10 @@ export async function prepareFetchedImage(
decoded = await decodeWithLimit(decoded, encoding)
}
if (!imageBytesMatchMediaType(decoded, contentType)) {
- throw new InvalidImageTransportError(`image bytes do not match content-type ${contentType}`)
+ throw new InvalidImageTransportError(
+ 'content_type_mismatch',
+ `image bytes do not match content-type ${contentType}`
+ )
}
return decoded
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
index 4bbfef90ba26..9b96d8552263 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts
@@ -1,7 +1,11 @@
import { Counter, Gauge, Histogram } from 'prom-client'
+import { type ImageTransportRejectionReason } from './image-transport'
import { ScrubWaitReason } from './scrub-client'
+export type ImageScrubSkipReason = ImageTransportRejectionReason | 'sidecar_rejected'
+export type ImageScrubSource = 'inline' | 'url'
+
export class ImageScrubConsumerMetrics {
private static readonly scrubbed = new Counter({
name: 'ml_mirror_image_scrub_consumer_scrubbed_total',
@@ -9,7 +13,8 @@ export class ImageScrubConsumerMetrics {
})
private static readonly skipped = new Counter({
name: 'ml_mirror_image_scrub_consumer_skipped_total',
- help: 'Images skipped because the sidecar rejected them as undecodable (resolve to nothing)',
+ help: 'Images permanently skipped by bounded reason. sidecar_rejected is split by the sidecar outcome metrics',
+ labelNames: ['reason'],
})
private static readonly deduped = new Counter({
name: 'ml_mirror_image_scrub_consumer_deduped_total',
@@ -46,6 +51,12 @@ export class ImageScrubConsumerMetrics {
name: 'ml_mirror_image_scrub_consumer_shard_bytes_total',
help: 'Scrubbed image bytes written into shards',
})
+ private static readonly captureToS3 = new Histogram({
+ name: 'ml_mirror_image_scrub_consumer_capture_to_s3_seconds',
+ help: 'Wall time from the source replay Kafka timestamp to a successful S3 write, by image source',
+ labelNames: ['source'],
+ buckets: [0.5, 1, 2, 5, 10, 30, 60, 120, 300, 600, 1800, 3600, 10800, 21600, 43200, 86400, 259200, 604800],
+ })
/**
* The saturation signal, and the one to alert on.
*
@@ -156,8 +167,8 @@ export class ImageScrubConsumerMetrics {
public static incScrubbed(): void {
this.scrubbed.inc()
}
- public static incSkipped(): void {
- this.skipped.inc()
+ public static incSkipped(reason: ImageScrubSkipReason): void {
+ this.skipped.labels(reason).inc()
}
public static incScrubWait(reason: ScrubWaitReason): void {
this.scrubWaits.labels(reason).inc()
@@ -206,4 +217,10 @@ export class ImageScrubConsumerMetrics {
this.shardImages.inc(images)
this.shardBytes.inc(bytes)
}
+ public static observeCaptureToS3(source: ImageScrubSource, capturedAtMs: number, storedAtMs: number): void {
+ if (!Number.isSafeInteger(capturedAtMs) || capturedAtMs <= 0 || !Number.isFinite(storedAtMs)) {
+ return
+ }
+ this.captureToS3.labels(source).observe(Math.max(0, storedAtMs - capturedAtMs) / 1000)
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
index b656886fd08d..2bda2c9b7293 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.test.ts
@@ -1,21 +1,25 @@
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { PipelineResultType } from '~/ingestion/framework/results'
+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { createProduceCollectedImagesStep } from './produce-collected-images-step'
describe('produceCollectedImagesStep', () => {
- let queued: { key: string; value: Buffer }[][]
+ const CAPTURED_AT = 1_700_000_000_000
+ let queued: { key: string; value: Buffer; headers?: Record<string, string> }[][]
let outputs: IngestionOutputs<MlImageScrubOutput>
let queueMessages: jest.Mock
beforeEach(() => {
queued = []
- queueMessages = jest.fn((_output: string, messages: { key: string; value: Buffer }[]) => {
- queued.push(messages)
- return Promise.resolve()
- })
+ queueMessages = jest.fn(
+ (_output: string, messages: { key: string; value: Buffer; headers?: Record<string, string> }[]) => {
+ queued.push(messages)
+ return Promise.resolve()
+ }
+ )
outputs = { queueMessages } as unknown as IngestionOutputs<MlImageScrubOutput>
})
@@ -23,7 +27,7 @@ describe('produceCollectedImagesStep', () => {
return { ref, bytes: Buffer.from([byte]) }
}
- async function run<T extends { collectedImages?: CollectedImage[] }>(
+ async function run<T extends { collectedImages?: CollectedImage[]; message: { timestamp?: number } }>(
step: ReturnType<typeof createProduceCollectedImagesStep<T>>,
input: T
) {
@@ -38,41 +42,70 @@ describe('produceCollectedImagesStep', () => {
it('produces each image keyed by its ref as a side effect and strips them from the element', async () => {
const step = createProduceCollectedImagesStep(outputs)
const images = [image('image:aa:h1', 1), image('image:aa:h2', 2)]
- const result = await run(step, { collectedImages: images })
+ const result = await run(step, { collectedImages: images, message: { timestamp: CAPTURED_AT } })
expect(result.value.collectedImages).toBeUndefined()
expect(queued).toEqual([
[
- { key: 'image:aa:h1', value: Buffer.from([1]) },
- { key: 'image:aa:h2', value: Buffer.from([2]) },
+ {
+ key: 'image:aa:h1',
+ value: Buffer.from([1]),
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ },
+ {
+ key: 'image:aa:h2',
+ value: Buffer.from([2]),
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ },
],
])
})
it('passes through elements with no collected images without producing', async () => {
const step = createProduceCollectedImagesStep(outputs)
- await run(step, { collectedImages: undefined })
- await run(step, { collectedImages: [] })
+ await run(step, { collectedImages: undefined, message: { timestamp: CAPTURED_AT } })
+ await run(step, { collectedImages: [], message: { timestamp: CAPTURED_AT } })
expect(queueMessages).not.toHaveBeenCalled()
})
it('dedups refs it already produced across messages', async () => {
const step = createProduceCollectedImagesStep(outputs)
- await run(step, { collectedImages: [image('image:aa:h1')] })
- await run(step, { collectedImages: [image('image:aa:h1'), image('image:aa:h2')] })
+ await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
+ await run(step, {
+ collectedImages: [image('image:aa:h1'), image('image:aa:h2')],
+ message: { timestamp: CAPTURED_AT },
+ })
expect(queued).toEqual([
- [{ key: 'image:aa:h1', value: Buffer.from([1]) }],
- [{ key: 'image:aa:h2', value: Buffer.from([1]) }],
+ [
+ {
+ key: 'image:aa:h1',
+ value: Buffer.from([1]),
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ },
+ ],
+ [
+ {
+ key: 'image:aa:h2',
+ value: Buffer.from([1]),
+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(CAPTURED_AT) },
+ },
+ ],
])
})
it('evicts oldest refs at capacity instead of forgetting the whole working set', async () => {
const step = createProduceCollectedImagesStep(outputs, 2)
- await run(step, { collectedImages: [image('image:aa:h1'), image('image:aa:h2')] })
- await run(step, { collectedImages: [image('image:aa:h3')] })
+ await run(step, {
+ collectedImages: [image('image:aa:h1'), image('image:aa:h2')],
+ message: { timestamp: CAPTURED_AT },
+ })
+ await run(step, { collectedImages: [image('image:aa:h3')], message: { timestamp: CAPTURED_AT } })
// Only h1 (the oldest) made room for h3; h2 must still dedup — a wholesale clear-on-full
// would re-produce the entire hot working set every time the cap is hit.
- await run(step, { collectedImages: [image('image:aa:h2'), image('image:aa:h1')] })
+ await run(step, {
+ collectedImages: [image('image:aa:h2'), image('image:aa:h1')],
+ message: { timestamp: CAPTURED_AT },
+ })
expect(queued.map((batch) => batch.map((m) => m.key))).toEqual([
['image:aa:h1', 'image:aa:h2'],
['image:aa:h3'],
@@ -83,18 +116,21 @@ describe('produceCollectedImagesStep', () => {
it('swallows produce failures (a dangling ref reads as a placeholder downstream)', async () => {
queueMessages.mockRejectedValueOnce(new Error('broker down'))
const step = createProduceCollectedImagesStep(outputs)
- const result = await run(step, { collectedImages: [image('image:aa:h1')] })
+ const result = await run(step, {
+ collectedImages: [image('image:aa:h1')],
+ message: { timestamp: CAPTURED_AT },
+ })
expect(result.type).toBe(PipelineResultType.OK)
})
it('un-marks refs whose produce failed so a recurring image re-produces naturally', async () => {
queueMessages.mockRejectedValueOnce(new Error('broker down'))
const step = createProduceCollectedImagesStep(outputs)
- await run(step, { collectedImages: [image('image:aa:h1')] })
- await run(step, { collectedImages: [image('image:aa:h1')] })
+ await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
+ await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
expect(queueMessages).toHaveBeenCalledTimes(2)
// Once a produce succeeds, the ref dedups again.
- await run(step, { collectedImages: [image('image:aa:h1')] })
+ await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })
expect(queueMessages).toHaveBeenCalledTimes(2)
})
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
index e8ae939cd52f..f76db2d8c5d3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-images-step.ts
@@ -3,6 +3,7 @@ import { logger } from '~/common/utils/logger'
import { ok } from '~/ingestion/framework/results'
import { ProcessingStep } from '~/ingestion/framework/steps'
import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'
import { CollectedImage } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'
@@ -24,7 +25,9 @@ const PRODUCED_REF_CACHE_MAX = 500_000
* fails the message: the mirrored lines already carry the refs, and a ref whose image never lands
* is defined as equivalent to a placeholder for training joins.
*/
-export function createProduceCollectedImagesStep<T extends { collectedImages?: CollectedImage[] }>(
+export function createProduceCollectedImagesStep<
+ T extends { collectedImages?: CollectedImage[]; message: { timestamp?: number } },
+>(
outputs: IngestionOutputs<MlImageScrubOutput>,
producedRefCacheMax: number = PRODUCED_REF_CACHE_MAX
): ProcessingStep<T, T> {
@@ -48,6 +51,11 @@ export function createProduceCollectedImagesStep<T extends { collectedImages?: C
bytes += image.bytes.length
}
SessionRecordingIngesterMetrics.incrementMlImagesCollected('queued', fresh.length)
+ const captureTimestampMs = input.message.timestamp
+ const headers =
+ captureTimestampMs !== undefined && Number.isSafeInteger(captureTimestampMs) && captureTimestampMs > 0
+ ? { [CAPTURE_TIMESTAMP_HEADER]: String(captureTimestampMs) }
+ : undefined
// The ack handlers must capture only the refs: `image.bytes` are subarray views into the
// whole packed FFI buffer (up to 32 MB per source message), and queueMessages copies the
@@ -57,7 +65,7 @@ export function createProduceCollectedImagesStep<T extends { collectedImages?: C
const produce = outputs
.queueMessages(
ML_IMAGE_SCRUB_OUTPUT,
- fresh.map((image) => ({ key: image.ref, value: image.bytes }))
+ fresh.map((image) => ({ key: image.ref, value: image.bytes, headers }))
)
.then(() => {
// queueMessages resolves on delivery acks, so `produced` counts what actually landed.