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.

fix(ai-research): raise the per-message url cap to 512 (#81804)

Robbie947b199b1c47
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index a010750627ff..56693e84110b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -16,6 +16,8 @@ export type MlImageLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' |
* ships. */
export type MlUrlLaneStage = 'collected' | 'deduped' | 'queued' | 'produced' | 'produce_failed' | 'ref_unusable'
+const URL_BYTES_SAMPLE_RATE = 16
+
export class SessionRecordingIngesterMetrics {
private static readonly sessionsHandled = new Gauge({
name: 'recording_blob_ingestion_v2_session_manager_count',
@@ -109,7 +111,7 @@ export class SessionRecordingIngesterMetrics {
private static readonly mlUrlsPerMessage = new Histogram({
name: 'recording_blob_ingestion_v2_ml_urls_per_message',
help: 'URLs collected from one message that carried at least one. The counter alone gives a mean; sizing the fetch lane needs the tail',
- buckets: [1, 2, 5, 10, 25, 50, 100, 256],
+ buckets: [1, 2, 5, 10, 25, 50, 100, 256, 512],
})
private static readonly mlImageBytesProduced = new Counter({
@@ -171,6 +173,36 @@ export class SessionRecordingIngesterMetrics {
this.mlImagesCollected.labels(outcome).inc(count)
}
+ private static readonly mlUrlBytes = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_bytes',
+ help: 'Bytes in one collected remote image URL, sampled. The tail sizes the per-record packing budget, because a record is filled by bytes rather than by a fixed number of URLs. Read the shape, not the count: one URL in URL_BYTES_SAMPLE_RATE is observed',
+ buckets: [64, 128, 256, 512, 1024, 2048],
+ })
+ /**
+ * A message can carry hundreds of URLs, and an observation costs several allocations, so
+ * observing each one puts the size of the payload on the mirror's hot path.
+ */
+ private static urlBytesSeen = 0
+ private static readonly mlUrlsPerRecord = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_urls_per_record',
+ help: 'URLs packed into one record on the fetch topic. Bounded in practice by the collector cap per message, since a record holds one domain from one message',
+ buckets: [1, 8, 32, 64, 128, 256, 512],
+ })
+ private static readonly mlUrlRecordBytes = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_url_record_bytes',
+ help: 'Serialized bytes of one record on the fetch topic. Read against librdkafka message.max.bytes, which this producer leaves at its 1,000,000 byte default: the packing budget is what keeps a record under it',
+ buckets: [1024, 8192, 65536, 262144, 524288, 1_000_000],
+ })
+
+ public static observeMlUrlBytes(bytes: number): void {
+ if (this.urlBytesSeen++ % URL_BYTES_SAMPLE_RATE === 0) {
+ this.mlUrlBytes.observe(bytes)
+ }
+ }
+ public static observeMlUrlRecord(urls: number, bytes: number): void {
+ this.mlUrlsPerRecord.observe(urls)
+ this.mlUrlRecordBytes.observe(bytes)
+ }
public static incrementMlUrlsCollected(outcome: MlUrlLaneStage, count: number): void {
this.mlUrlsCollected.labels(outcome).inc(count)
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
index 87a5760b7c2a..63819897f11b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/collected-urls-record.ts
@@ -9,11 +9,11 @@ const MAX_URL_LENGTH = 2048
const FETCHABLE_SCHEMES = new Set(['http:', 'https:'])
/**
- * The producer splits a record at 64 URLs. A record above this came from a producer that does not
- * agree with this one, and its size drives a Redis pipeline and a batch's memory, so it is refused
- * rather than trusted.
+ * A record holds one domain from one message, and the collector caps a message at 512, so a
+ * well-formed record stays under this. Headroom is deliberately small: the Redis round trips of a
+ * batch scale with this value and run one after another inside one batch budget.
*/
-const MAX_URLS_PER_RECORD = 128
+const MAX_URLS_PER_RECORD = 640
export interface FetchCandidate {
ref: string
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
index cd3adbb73d46..0b9f706b85b6 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/metrics.ts
@@ -63,8 +63,8 @@ export class ImageFetchConsumerMetrics {
})
private static readonly urlsPerRecord = new Histogram({
name: 'ml_image_fetch_consumer_urls_per_record',
- help: 'URLs carried by one Kafka record. The producer caps this, so a distribution pinned at the cap means records are being split and the cap is the binding constraint',
- buckets: [1, 2, 4, 8, 16, 32, 64],
+ help: 'URLs carried by one Kafka record. The producer packs a record to a byte budget, so a distribution pinned at the top means the count bound rather than the byte budget is what split it',
+ buckets: [1, 8, 32, 64, 128, 256, 512],
})
private static readonly storeErrors = new Counter({
name: 'ml_image_fetch_consumer_store_errors_total',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
index 15536ac842b3..bbe34ff6ae54 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.test.ts
@@ -201,7 +201,7 @@ describe('UrlFetchConsumer', () => {
})
it('drops a record carrying more URLs than any producer sends', async () => {
- const many = Array.from({ length: 300 }, (_value, index) => url(`u${index}`))
+ const many = Array.from({ length: 1100 }, (_value, index) => url(`u${index}`))
await consumer.handleBatch([record(many)], NOW)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
index a1467a991971..86f7b021fa92 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.test.ts
@@ -182,6 +182,53 @@ describe('produceCollectedUrlsStep', () => {
])
})
+ it('packs many short urls into one record', async () => {
+ // A fixed count would have cut this into several records and used a fraction of each. The
+ // budget is bytes, so ordinary URLs pack until the bytes run out.
+ const step = createProduceCollectedUrlsStep(outputs, 100_000)
+ const many = Array.from({ length: 400 }, (_v, i) =>
+ collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${i}.png`)
+ )
+
+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: many })
+
+ expect(decode(queued[0])).toHaveLength(1)
+ })
+
+ it('splits on the count bound even when the bytes would fit', async () => {
+ // The fetcher refuses a record above its own count cap, whole. Byte packing alone would let
+ // the collector's per-message cap in another crate decide how many entries a record holds.
+ const step = createProduceCollectedUrlsStep(outputs, 100_000)
+ const many = Array.from({ length: 600 }, (_v, i) =>
+ collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${i}.png`)
+ )
+
+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: many })
+
+ const sent = decode(queued[0])
+ expect(sent.length).toBeGreaterThan(1)
+ for (const record of sent) {
+ expect(record.value.urls.length).toBeLessThanOrEqual(512)
+ }
+ })
+
+ it('splits when the urls are long enough to fill a record', async () => {
+ const step = createProduceCollectedUrlsStep(outputs, 100_000)
+ const long = 'x'.repeat(2000)
+ const many = Array.from({ length: 400 }, (_v, i) =>
+ collected(`h${i}`.padEnd(22, 'x'), 'img.example.com', `https://img.example.com/${long}${i}.png`)
+ )
+
+ await run(step, { message: { timestamp: CAPTURED_AT }, collectedUrls: many })
+
+ expect(queued[0].length).toBeGreaterThan(1)
+ const [first] = queued[0]
+ expect(first.value.length).toBeGreaterThan(400 * 1024)
+ for (const record of queued[0]) {
+ expect(record.value.length).toBeLessThan(1_000_000)
+ }
+ })
+
it('drops an entry whose ref names another team', async () => {
const step = createProduceCollectedUrlsStep(outputs, 100)
const otherTeam = 'b'.repeat(32)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
index 4e1e7450e25d..d05a46b86bca 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/produce-collected-urls-step.ts
@@ -17,14 +17,26 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-de
const PRODUCED_REF_CACHE_MAX = 500_000
/**
- * Records for one host per Kafka message.
+ * Bytes of URL payload one record may carry, against the 1,000,000 byte `message.max.bytes` default
+ * that this producer does not override. The rest absorbs the envelope.
*
- * The Rust collector caps one replay message at 256 URLs of up to 2048 bytes each, which is about
- * 540 KB if they all share one host. That is under librdkafka's 1 MB default, but only just, and
- * the bound lives in another crate. This cap keeps the record size inside this file, where the
- * produce happens.
+ * A URL may be anything up to `MAX_URL_LEN`, so a fixed count is either unsafe for the longest URLs
+ * or wasteful for ordinary ones.
*/
-const MAX_URLS_PER_RECORD = 64
+const MAX_RECORD_URL_BYTES = 512 * 1024
+
+/**
+ * URLs one record may carry, whatever their size. Without this the collector's cap, which lives in
+ * another crate, would decide it, and raising it there would produce records the fetcher refuses
+ * whole. Must stay below MAX_URLS_PER_RECORD in `ml-mirror-image-fetch/collected-urls-record.ts`.
+ */
+const MAX_RECORD_URLS = 512
+
+export interface RecordUrl {
+ ref: string
+ url: string
+ host: string
+}
/** One record on the fetch topic. The Kafka key is the registrable domain, so every URL here
* belongs to one operator. Hosts can differ within it: a CDN sharding over img1..img8 keeps one
@@ -44,7 +56,7 @@ export interface CollectedUrlsMessage {
* age check exists for.
*/
capturedAtMs: number
- urls: { ref: string; url: string; host: string }[]
+ urls: RecordUrl[]
}
/**
@@ -122,11 +134,12 @@ export function createProduceCollectedUrlsStep<
return Promise.resolve(ok({ ...input, collectedUrls: undefined }))
}
- const byDomain = new Map<string, { ref: string; url: string; host: string }[]>()
+ const byDomain = new Map<string, RecordUrl[]>()
for (const entry of usable) {
producedRefs.add(entry.ref)
const group = byDomain.get(entry.domain)
- const record = { ref: entry.ref, url: entry.url, host: entry.host }
+ const record: RecordUrl = { ref: entry.ref, url: entry.url, host: entry.host }
+ SessionRecordingIngesterMetrics.observeMlUrlBytes(Buffer.byteLength(entry.url))
if (group) {
group.push(record)
} else {
@@ -141,17 +154,18 @@ export function createProduceCollectedUrlsStep<
const messageTimestamp = input.message.timestamp
const capturedAtMs = messageTimestamp !== undefined && messageTimestamp > 0 ? messageTimestamp : Date.now()
const messages = [...byDomain].flatMap(([domain, urls]) =>
- chunk(urls, MAX_URLS_PER_RECORD).map((slice) => ({
- key: domain,
- value: Buffer.from(
+ packByBytes(urls, MAX_RECORD_URL_BYTES).map((slice) => {
+ const value = Buffer.from(
JSON.stringify({
v: 1,
pseudoTeam,
capturedAtMs,
urls: slice,
} satisfies CollectedUrlsMessage)
- ),
- }))
+ )
+ SessionRecordingIngesterMetrics.observeMlUrlRecord(slice.length, value.length)
+ return { key: domain, value }
+ })
)
// The failure handler captures only the refs, so that a produce which is not yet delivered
@@ -182,13 +196,45 @@ export function createProduceCollectedUrlsStep<
}
}
-function chunk<T>(items: T[], size: number): T[][] {
- if (items.length <= size) {
- return [items]
+/**
+ * An entry always goes somewhere, even alone in a record over the budget, because dropping it here
+ * would lose an image every earlier check accepted. `MAX_URL_LEN` bounds that case under the broker
+ * limit.
+ */
+function packByBytes(entries: RecordUrl[], maxBytes: number): RecordUrl[][] {
+ const out: RecordUrl[][] = []
+ let current: RecordUrl[] = []
+ let bytes = 0
+ for (const entry of entries) {
+ const size = entryBytes(entry)
+ if (current.length > 0 && (bytes + size > maxBytes || current.length >= MAX_RECORD_URLS)) {
+ out.push(current)
+ current = []
+ bytes = 0
+ }
+ current.push(entry)
+ bytes += size
}
- const out: T[][] = []
- for (let i = 0; i < items.length; i += size) {
- out.push(items.slice(i, i + size))
+ if (current.length > 0) {
+ out.push(current)
}
return out
}
+
+/**
+ * The JSON punctuation around the three fields, so packing measures what the record will hold.
+ *
+ * `JSON.stringify` widens a quote or a backslash, so this is a lower bound. Canonicalization
+ * percent-encodes those upstream and the budget is half the broker limit, so the gap has room.
+ * `ml_url_record_bytes` is what would show it closing.
+ */
+const ENTRY_OVERHEAD_BYTES = '{"ref":"","url":"","host":""},'.length
+
+function entryBytes(entry: RecordUrl): number {
+ return (
+ Buffer.byteLength(entry.ref) +
+ Buffer.byteLength(entry.url) +
+ Buffer.byteLength(entry.host) +
+ ENTRY_OVERHEAD_BYTES
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
index 81736a4fd8c9..ab033dc31d44 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/producer-config.ts
@@ -158,7 +158,8 @@ export function getDefaultKafkaMlImageFetchProducerEnvConfig(): KafkaMlImageFetc
// JSON URLs compress well, unlike the image bytes on the scrub lane.
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_COMPRESSION_CODEC: 'snappy',
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_LINGER_MS: '',
- // Records here are small, so the queue is sized by count rather than by bytes.
+ // A record is packed to a byte budget, so bytes rather than count are what bind here:
+ // this holds roughly 60 full records in flight against 50,000 small ones.
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_MESSAGES: '50000',
KAFKA_INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER_QUEUE_BUFFERING_MAX_KBYTES: '32768',
// The same short local timeout as the scrub lane, and for the same reason: these ack
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 6e46da7e740e..01591d29793f 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -8971,7 +8971,7 @@ dependencies = [
[[package]]
name = "posthog-replay-anonymizer"
-version = "0.4.2"
+version = "0.4.3"
dependencies = [
"ahash 0.8.12",
"anyhow",
diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.toml
index 6d1fabd64ff0..49a7923436b6 100644
--- a/rust/replay-anonymizer/Cargo.toml
+++ b/rust/replay-anonymizer/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "posthog-replay-anonymizer"
-version = "0.4.2"
+version = "0.4.3"
edition = "2021"
description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"
license = "MIT"
diff --git a/rust/replay-anonymizer/src/url_collect.rs b/rust/replay-anonymizer/src/url_collect.rs
index 1ae16e4c9379..79b4dd6ea5d9 100644
--- a/rust/replay-anonymizer/src/url_collect.rs
+++ b/rust/replay-anonymizer/src/url_collect.rs
@@ -38,11 +38,18 @@ use crate::url_policy::{try_canonicalize, MAX_URL_LEN};
/// collector declined, and a decline is exactly what a repeat should not pay for twice. Past this
/// the memo stops growing and repeats fall back to the full check, which is slower and bounded
/// rather than unbounded.
-const MAX_MEMO_ENTRIES: usize = 1024;
+const MAX_MEMO_ENTRIES: usize = 2048;
-/// Distinct URLs collected from one message. A page with more media than this is already past the
-/// point where the extra images teach a model anything, and the cap bounds the Kafka fan-out.
-pub const MAX_URLS_PER_MESSAGE: usize = 256;
+/// Distinct URLs collected from one message.
+///
+/// One message holds a batch of rrweb events for one session, so this budget covers a full snapshot
+/// and every mutation after it, including those describing a different page after a navigation. A
+/// message at the cap loses its later images rather than its least useful ones.
+///
+/// What bounds it is the payload: the whole set crosses the FFI boundary in one call, and each URL
+/// can be [`MAX_URL_LEN`] bytes. Read ml_urls_declined{reason="over_cap"} against ml_urls_collected
+/// before changing it, and keep [`MAX_MEMO_ENTRIES`] above it.
+pub const MAX_URLS_PER_MESSAGE: usize = 512;
/// Enables URL collection for one anonymize call.
#[derive(Debug, Clone)]