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(ai-research): quarantine rejected image fetch records (#89761)

Robbie5bc049437059
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
index c8c53f2c12f9..784fa64b48cc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/IMPLEMENTATION_NOTES.md
@@ -84,6 +84,8 @@ The Grafana dashboard uses these runtime metrics. Its frontier health panels exc
The Helm deployment defines fetch, scrub, and three retry consumers. Fetch and retry synchronization remains manual until their dependencies exist.
+The optional fetch dead-letter topic stores each rejected frontier record with its original key and value. It adds bounded headers for the reason, schema version class, source topic, partition, and offset. The value can contain an original URL, so this topic has the same sensitivity as the frontier. The consumer waits for every dead-letter acknowledgement before it can commit the source offset. It publishes with bounded concurrency and a 50-second batch budget after other batch work succeeds. A failed publish fails the source batch. A retry can duplicate records that reached the dead-letter topic before another dead-letter publish failed. Operators can identify those duplicates by source topic, partition, and offset. The lane has no automatic dead-letter replay.
+
## Failure-mode observability
The lane uses bounded labels for all signals. The dashboards group failures by a fixed operation, reason, outcome, stage, or destination.
@@ -101,7 +103,8 @@ The lane uses bounded labels for all signals. The dashboards group failures by a
| A registrable domain repeatedly fails, or an origin refuses access. | Request outcomes, bounded retry causes, registrable-domain block state, origin-policy decisions, and terminal refusal reasons change. | Fetch dashboard: request outcomes, retry causes, policy and budget decisions, and refused URLs. | Check the origin policy and response status. Do not override an opt-out signal. |
| Retry release cannot return work to the frontier. | `ml_image_fetch_retry_released_total{outcome="failed"}` and a durable consumer-loop error log. | Fetch dashboard: delivery failures. Loki alert: `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the frontier producer and Kafka connectivity. |
| Retry input is invalid. | `ml_image_fetch_retry_released_total` increases with a `malformed` or `invalid_timestamp` outcome. Missing content is committed and dropped. An invalid timestamp leaves the offset uncommitted and writes a durable consumer-loop error log. | Fetch dashboard: delivery failures. Alerts: `IngestionSessionReplayImageFetchRetryInputRejected` for missing content and `IngestionSessionReplayImageFetchConsumerLoopFailed` for an invalid timestamp. | Check the retry producer and the delay topic's `LogAppendTime` configuration. |
-| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dropped_total` increases by a bounded reason. The consumer commits and drops those jobs. | Fetch dashboard: **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected`. | Check the mirror and fetch versions and the frontier record schema. |
+| The fetch consumer rejects frontier input. | `ml_image_fetch_consumer_dead_lettered_total` increases after Kafka acknowledges the original record. `ml_image_fetch_consumer_dropped_total` counts the rejected jobs. | Fetch dashboard: quarantine activity and **URLs refused**. Alert: `IngestionSessionReplayImageFetchInputRejected` for a sustained rate. | Check the mirror and fetch versions and the frontier record schema. Inspect the restricted dead-letter topic only when necessary. |
+| The fetch consumer cannot quarantine rejected input. | `ml_image_fetch_consumer_dead_letter_failed_total` increases and `ml_image_fetch_dead_letter_publish_failed` logs before the consumer fails the batch. The source offsets remain uncommitted. | Fetch dashboard: quarantine activity. Alerts: `IngestionSessionReplayImageFetchDeadLetterPublishFailed` and the durable-log `IngestionSessionReplayImageFetchConsumerLoopFailed`. | Check the dead-letter topic, producer connectivity, and message-size configuration. |
| A retry worker shuts down during a deliberate wait. | `ml_image_fetch_retry_released_total{outcome="abandoned"}` increases. The consumer does not commit that offset. | Fetch dashboard only. This expected shutdown outcome does not alert. | Check pod lifecycle only if the rate does not match a rollout or scale-down. |
| The scrub sidecar is saturated or unreachable. | Scrub waits increase by `busy`, `timeout`, or `transport`. | Scrub dashboard: scrub waits and sidecar pressure. Alert: `IngestionSessionReplayImageScrubSidecarUnreachable`. | Scale for `busy`. Check CPU for `timeout`. Check pod health for `transport`. |
| The scrub consumer rejects input. | `ml_mirror_image_scrub_consumer_invalid_key_total` increases. The consumer commits and drops the record. | Scrub dashboard: invalid-key events. Alert: `IngestionSessionReplayImageScrubInputRejected`. | Check the fetch and scrub versions, the content-ref format, and the scrub topic. |
@@ -160,7 +163,7 @@ The implementation also has these rollout and repository-state deltas. They do n
The Node.js image with grouped, bounded republish delivery must be active before the chart raises the poll batch to 50 records and the request budget to 40 seconds. The older per-URL publisher can spend too much of Kafka's poll interval finalizing the larger batch.
-1. Apply the Kafka topic sizes and broker timestamp settings from `posthog-cloud-infra`.
+1. Apply the Kafka topic sizes and broker timestamp settings from `posthog-cloud-infra`, including the image-fetch dead-letter topic.
2. Apply the DynamoDB table, workload permissions, Smokescreen, and required secrets.
3. Deploy the scrubber changes and the ML data-preparation resolver.
4. Deploy the fetch and retry workloads with automatic synchronization disabled. Keep fetch dry-run enabled and the version 2 mirror producer disabled.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.test.ts
new file mode 100644
index 000000000000..08e2fe83add5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.test.ts
@@ -0,0 +1,94 @@
+import { Message } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+
+import { MAX_RECORD_BYTES } from './collected-urls-record'
+import { KafkaFrontierDeadLetterSink } from './frontier-dead-letter-sink'
+
+describe('KafkaFrontierDeadLetterSink', () => {
+ it('preserves the source key and value with bounded diagnostic headers', async () => {
+ const produce = jest.fn(() => Promise.resolve())
+ const sink = new KafkaFrontierDeadLetterSink({ produce } as unknown as KafkaProducerWrapper, 'frontier-dlq', [
+ 'frontier',
+ ])
+ const source = {
+ topic: 'frontier',
+ partition: 7,
+ offset: 42,
+ key: Buffer.from('example.com'),
+ value: Buffer.from('{"v":2,"jobs":[]}'),
+ } as Message
+
+ await sink.park(source, 'bad_url')
+
+ expect(produce).toHaveBeenCalledWith({
+ topic: 'frontier-dlq',
+ key: source.key,
+ value: source.value,
+ headers: {
+ 'dlq-reason': 'bad_url',
+ 'frontier-record-version': '2',
+ 'source-topic': 'frontier',
+ 'source-partition': '7',
+ 'source-offset': '42',
+ },
+ })
+ })
+
+ it('does not copy an unsupported version into a header', async () => {
+ const produce = jest.fn(() => Promise.resolve())
+ const sink = new KafkaFrontierDeadLetterSink({ produce } as unknown as KafkaProducerWrapper, 'frontier-dlq', [
+ 'frontier',
+ ])
+
+ await sink.park(
+ {
+ topic: 'frontier',
+ partition: 0,
+ offset: 1,
+ key: null,
+ value: Buffer.from('{"v":"private input"}'),
+ } as Message,
+ 'unsupported_version'
+ )
+
+ expect(produce).toHaveBeenCalledWith(
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'frontier-record-version': 'unsupported' }),
+ })
+ )
+ })
+
+ it('does not parse an oversized rejected value to classify its version', async () => {
+ const produce = jest.fn(() => Promise.resolve())
+ const sink = new KafkaFrontierDeadLetterSink({ produce } as unknown as KafkaProducerWrapper, 'frontier-dlq', [
+ 'frontier',
+ ])
+
+ await sink.park(
+ {
+ topic: 'frontier',
+ partition: 0,
+ offset: 1,
+ key: null,
+ value: Buffer.alloc(MAX_RECORD_BYTES + 1, '{'),
+ } as Message,
+ 'oversized_record'
+ )
+
+ expect(produce).toHaveBeenCalledWith(
+ expect.objectContaining({
+ headers: expect.objectContaining({ 'frontier-record-version': 'unknown' }),
+ })
+ )
+ })
+
+ it('refuses a destination used by the image-fetch pipeline', () => {
+ expect(
+ () =>
+ new KafkaFrontierDeadLetterSink({ produce: jest.fn() } as unknown as KafkaProducerWrapper, 'frontier', [
+ 'frontier',
+ ])
+ ).toThrow('SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts
new file mode 100644
index 000000000000..fabe1655cdc0
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink.ts
@@ -0,0 +1,61 @@
+import { Message } from 'node-rdkafka'
+
+import { KafkaProducerWrapper } from '~/common/kafka/producer'
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { MAX_RECORD_BYTES, UrlDropReason } from './collected-urls-record'
+
+export type FrontierDeadLetterReason = UrlDropReason | 'multiple'
+type FrontierRecordVersion = '1' | '2' | 'unsupported' | 'unknown'
+
+export interface FrontierDeadLetterSink {
+ park(message: Message, reason: FrontierDeadLetterReason): Promise<void>
+}
+
+export class KafkaFrontierDeadLetterSink implements FrontierDeadLetterSink {
+ constructor(
+ private readonly producer: KafkaProducerWrapper,
+ private readonly topic: string,
+ blockedDestinations: readonly string[]
+ ) {
+ if (blockedDestinations.includes(topic)) {
+ throw new Error(`SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC cannot use image-fetch topic ${topic}`)
+ }
+ }
+
+ public async park(message: Message, reason: FrontierDeadLetterReason): Promise<void> {
+ await this.producer.produce({
+ topic: this.topic,
+ key: message.key ?? null,
+ value: message.value,
+ headers: {
+ 'dlq-reason': reason,
+ 'frontier-record-version': classifyFrontierRecordVersion(message.value),
+ 'source-topic': message.topic,
+ 'source-partition': String(message.partition),
+ 'source-offset': String(message.offset),
+ },
+ })
+ }
+}
+
+function classifyFrontierRecordVersion(value: Buffer | null): FrontierRecordVersion {
+ if (!value || value.length > MAX_RECORD_BYTES) {
+ return 'unknown'
+ }
+ try {
+ const parsed: unknown = parseJSON(value.toString())
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed) || !('v' in parsed)) {
+ return 'unknown'
+ }
+ if (parsed.v === 1) {
+ return '1'
+ }
+ if (parsed.v === 2) {
+ return '2'
+ }
+ return 'unsupported'
+ } catch {
+ return 'unknown'
+ }
+}
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 a88e99a2dfec..d1abd6f6083e 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
@@ -2,6 +2,7 @@ import { Counter, Gauge, Histogram } from 'prom-client'
import type { RepublishReason, UrlDropReason } from './collected-urls-record'
import type { AttemptOutcome } from './fetch-runner'
+import type { FrontierDeadLetterReason } from './frontier-dead-letter-sink'
import type { FetchRefusalReason, RequestScheduleBlockReason, TransientFetchOutcome } from './image-fetcher'
/** What the in-flight gauge reads. Narrower than `ConcurrencyController`, so the metrics do not depend on the whole of it. */
@@ -45,7 +46,17 @@ export class ImageFetchConsumerMetrics {
*/
private static readonly dropped = new Counter({
name: 'ml_image_fetch_consumer_dropped_total',
- help: 'URLs refused before dedup because the versioned record, URL, ref, or registrable-domain key was invalid',
+ help: 'URLs refused before dedup because the versioned record, URL, ref, or registrable-domain key was invalid. When a dead-letter topic is configured, its Kafka acknowledgement precedes this increment and the source commit',
+ labelNames: ['reason'],
+ })
+ private static readonly deadLettered = new Counter({
+ name: 'ml_image_fetch_consumer_dead_lettered_total',
+ help: 'Rejected frontier records acknowledged by the dead-letter topic before the source offset can advance',
+ labelNames: ['reason'],
+ })
+ private static readonly deadLetterFailed = new Counter({
+ name: 'ml_image_fetch_consumer_dead_letter_failed_total',
+ help: 'Rejected frontier records that could not reach the dead-letter topic. The source batch fails so its offsets remain uncommitted',
labelNames: ['reason'],
})
/**
@@ -130,6 +141,12 @@ export class ImageFetchConsumerMetrics {
public static incDropped(reason: UrlDropReason, count: number): void {
this.dropped.labels(reason).inc(count)
}
+ public static incDeadLettered(reason: FrontierDeadLetterReason): void {
+ this.deadLettered.labels(reason).inc()
+ }
+ public static incDeadLetterFailed(reason: FrontierDeadLetterReason): void {
+ this.deadLetterFailed.labels(reason).inc()
+ }
public static incStoreError(operation: 'read' | 'write', count: number): void {
this.storeErrors.labels(operation).inc(count)
}
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 8a0db2984734..47b802bf42fc 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
@@ -3,6 +3,7 @@ import { Message } from 'node-rdkafka'
import { FetchCandidate, MAX_HOPS, serializeFrontierRecord } from './collected-urls-record'
import { CrawlHistoryItem, CrawlHistoryStore, configurationCacheKey } from './crawl-history'
import { AttemptOutcome, DELAY_TOO_LONG, FetchAttempt, FetchPass, HOPS_EXHAUSTED } from './fetch-runner'
+import { FrontierDeadLetterSink } from './frontier-dead-letter-sink'
import { FrontierPublisher, RepublishFlushResult, RepublishResult } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
import { UrlFetchConsumer } from './url-fetch-consumer'
@@ -91,22 +92,25 @@ interface Harness {
run: jest.Mock<Promise<FetchAttempt[]>, [FetchCandidate[], Map<string, CrawlHistoryItem>]>
republish: jest.Mock<Promise<RepublishResult>, any[]>
flush: jest.Mock<Promise<RepublishFlushResult>, []>
+ park: jest.Mock<Promise<void>, any[]>
}
-function build(dryRun = false): Harness {
+function build(dryRun = false, deadLettersEnabled = true): Harness {
const history = new FakeCrawlHistory()
const run = jest.fn((candidates: FetchCandidate[], _stored: Map<string, CrawlHistoryItem>) =>
Promise.resolve(candidates.map((item) => terminal(item)))
)
const republish = jest.fn(() => Promise.resolve('queued' as const))
const flush = jest.fn(() => Promise.resolve({ failedUrls: 0 }))
+ const park = jest.fn(() => Promise.resolve())
const consumer = new UrlFetchConsumer(
history,
{ createRepublishBatch: () => ({ republish, flush }) } as unknown as FrontierPublisher,
{ seenTtlSeconds: 30 * 24 * 60 * 60, dryRun },
- dryRun ? undefined : ({ run } as FetchPass)
+ dryRun ? undefined : ({ run } as FetchPass),
+ deadLettersEnabled ? ({ park } as FrontierDeadLetterSink) : null
)
- return { consumer, history, run, republish, flush }
+ return { consumer, history, run, republish, flush, park }
}
describe('UrlFetchConsumer', () => {
@@ -346,12 +350,95 @@ describe('UrlFetchConsumer', () => {
expect(retryCause).not.toHaveBeenCalled()
})
- it('drops a malformed record without running the fetch pass', async () => {
+ it('quarantines a malformed record before completing the source batch', async () => {
const harness = build()
const invalid = message([candidate('a')])
invalid.value = Buffer.from('{')
+ let releasePark: () => void = () => undefined
+ harness.park.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ releasePark = resolve
+ })
+ )
+ const completed = jest.fn()
+
+ const sourceBatch = harness.consumer.handleBatch([invalid], NOW_MS)
+ void sourceBatch.then(completed)
+ await new Promise((resolve) => setImmediate(resolve))
+
+ expect(harness.park).toHaveBeenCalledWith(invalid, 'malformed')
+ expect(completed).not.toHaveBeenCalled()
+ expect(harness.run).not.toHaveBeenCalled()
+
+ releasePark()
+ await expect(sourceBatch).resolves.toBeUndefined()
+ expect(completed).toHaveBeenCalledTimes(1)
+ })
+
+ it('quarantines rejected records concurrently', async () => {
+ const harness = build()
+ const first = message([candidate('a')])
+ first.value = Buffer.from('{')
+ const second = message([candidate('b')])
+ second.value = Buffer.from('{')
+ second.offset = 1
+ const releases: Array<() => void> = []
+ harness.park.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ releases.push(resolve)
+ })
+ )
+
+ const sourceBatch = harness.consumer.handleBatch([first, second], NOW_MS)
+ await new Promise((resolve) => setImmediate(resolve))
+
+ expect(harness.park).toHaveBeenCalledTimes(2)
+
+ for (const release of releases) {
+ release()
+ }
+ await expect(sourceBatch).resolves.toBeUndefined()
+ })
+
+ it('does not quarantine rejected records before other batch work succeeds', async () => {
+ const harness = build()
+ const invalid = message([candidate('a')])
+ invalid.value = Buffer.from('{')
+ harness.history.readError = new Error('read failed')
+
+ await expect(harness.consumer.handleBatch([invalid, message([candidate('b')])], NOW_MS)).rejects.toThrow(
+ 'read failed'
+ )
+
+ expect(harness.park).not.toHaveBeenCalled()
+ })
+
+ it('keeps the source batch uncommitted when quarantine publication fails', async () => {
+ const harness = build()
+ const invalid = message([candidate('a')])
+ invalid.value = Buffer.from('{')
+ harness.park.mockRejectedValue(new Error('DLQ unavailable'))
+ const deadLetterFailed = jest.spyOn(ImageFetchConsumerMetrics, 'incDeadLetterFailed')
+ const dropped = jest.spyOn(ImageFetchConsumerMetrics, 'incDropped')
+
+ await expect(harness.consumer.handleBatch([invalid], NOW_MS)).rejects.toThrow('DLQ unavailable')
+
+ expect(deadLetterFailed).toHaveBeenCalledWith('malformed')
+ expect(dropped).not.toHaveBeenCalled()
+ expect(harness.run).not.toHaveBeenCalled()
+ expect(harness.history.readKeys).toEqual([])
+ })
+
+ it('commits and drops rejected input when quarantine is disabled', async () => {
+ const harness = build(false, false)
+ const invalid = message([candidate('a')])
+ invalid.value = Buffer.from('{')
await expect(harness.consumer.handleBatch([invalid], NOW_MS)).resolves.toBeUndefined()
+
+ expect(harness.park).not.toHaveBeenCalled()
expect(harness.run).not.toHaveBeenCalled()
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
index a73b22a62555..849bfe4ccead 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/url-fetch-consumer.ts
@@ -1,4 +1,5 @@
import { Message } from 'node-rdkafka'
+import pLimit from 'p-limit'
import { logger } from '~/common/utils/logger'
@@ -13,11 +14,19 @@ import {
HOPS_EXHAUSTED,
isTransientOutcome,
} from './fetch-runner'
+import { FrontierDeadLetterReason, FrontierDeadLetterSink } from './frontier-dead-letter-sink'
import { FrontierPublisher, RepublishBatch } from './frontier-publisher'
import { ImageFetchConsumerMetrics, ImageFetchRequestMetrics } from './metrics'
const ONE_HOUR_MS = 60 * 60 * 1000
const REPUBLISH_DEADLINE_FROM_BATCH_START_MS = 200_000
+const DEAD_LETTER_BATCH_BUDGET_MS = 50_000
+const DEAD_LETTER_PUBLISH_CONCURRENCY = 8
+
+type RejectedFrontierRecord = {
+ message: Message
+ reasons: UrlDropReason[]
+}
export interface UrlFetchConsumerOptions {
seenTtlSeconds: number
@@ -29,7 +38,8 @@ export class UrlFetchConsumer {
private readonly crawlHistory: CrawlHistoryStore,
private readonly publisher: FrontierPublisher,
private readonly options: UrlFetchConsumerOptions,
- private readonly runner?: FetchPass
+ private readonly runner?: FetchPass,
+ private readonly deadLetters: FrontierDeadLetterSink | null = null
) {
if (!Number.isInteger(options.seenTtlSeconds) || options.seenTtlSeconds < 60 * 60) {
throw new Error('AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS must be at least 3600')
@@ -44,6 +54,7 @@ export class UrlFetchConsumer {
const startedAt = process.hrtime.bigint()
const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MS
const drops = new Map<UrlDropReason, number>()
+ const rejectedRecords: RejectedFrontierRecord[] = []
const candidatesByRef = new Map<string, FetchCandidate>()
let dedupedInBatch = 0
let originCount = 0
@@ -56,12 +67,15 @@ export class UrlFetchConsumer {
for (const message of messages) {
const parsed = this.parse(message)
if (!parsed.ok) {
- drops.set(parsed.reason, (drops.get(parsed.reason) ?? 0) + 1)
+ rejectedRecords.push({ message, reasons: [parsed.reason] })
continue
}
ImageFetchConsumerMetrics.observeRecord(parsed.urlCount)
- for (const rejected of parsed.rejected) {
- drops.set(rejected.reason, (drops.get(rejected.reason) ?? 0) + 1)
+ if (parsed.rejected.length > 0) {
+ rejectedRecords.push({
+ message,
+ reasons: parsed.rejected.map((rejected) => rejected.reason),
+ })
}
for (const candidate of parsed.candidates) {
const existing = candidatesByRef.get(candidate.originalRef)
@@ -91,6 +105,7 @@ export class UrlFetchConsumer {
registrableDomainCandidateCounts = [...registrableDomains.values()]
if (this.options.dryRun || candidates.length === 0) {
+ await this.parkRejectedRecords(rejectedRecords, drops)
return
}
@@ -146,6 +161,7 @@ export class UrlFetchConsumer {
ImageFetchRequestMetrics.incRetryCause(attempt.outcome)
}
}
+ await this.parkRejectedRecords(rejectedRecords, drops)
} finally {
ImageFetchConsumerMetrics.finishBatch()
this.recordMetrics(
@@ -171,6 +187,87 @@ export class UrlFetchConsumer {
}
}
+ private async parkRejectedRecords(
+ records: RejectedFrontierRecord[],
+ drops: Map<UrlDropReason, number>
+ ): Promise<void> {
+ const deadlineAtMonotonicMs = performance.now() + DEAD_LETTER_BATCH_BUDGET_MS
+ const limit = pLimit(DEAD_LETTER_PUBLISH_CONCURRENCY)
+ let firstFailure: unknown
+ const outcomes = await Promise.allSettled(
+ records.map(({ message, reasons }) =>
+ limit(async () => {
+ if (firstFailure) {
+ throw firstFailure
+ }
+ try {
+ await this.parkRejectedRecord(message, reasons, deadlineAtMonotonicMs)
+ } catch (error) {
+ firstFailure = error
+ throw error
+ }
+ })
+ )
+ )
+ for (const outcome of outcomes) {
+ if (outcome.status === 'rejected') {
+ throw outcome.reason
+ }
+ }
+ for (const { reasons } of records) {
+ for (const reason of reasons) {
+ drops.set(reason, (drops.get(reason) ?? 0) + 1)
+ }
+ }
+ }
+
+ private async parkRejectedRecord(
+ message: Message,
+ reasons: UrlDropReason[],
+ deadlineAtMonotonicMs: number
+ ): Promise<void> {
+ if (!this.deadLetters) {
+ return
+ }
+ const reason = this.deadLetterReason(reasons)
+ const remainingMs = deadlineAtMonotonicMs - performance.now()
+ if (remainingMs <= 0) {
+ const error = new Error('image-fetch dead-letter batch exceeded its publish budget')
+ ImageFetchConsumerMetrics.incDeadLetterFailed(reason)
+ logger.error('🌐', 'ml_image_fetch_dead_letter_publish_failed', { reason, error: error.name })
+ throw error
+ }
+ let timeout: NodeJS.Timeout | undefined
+ try {
+ await Promise.race([
+ this.deadLetters.park(message, reason),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error('image-fetch dead-letter batch exceeded its publish budget')),
+ remainingMs
+ )
+ }),
+ ])
+ } catch (error) {
+ ImageFetchConsumerMetrics.incDeadLetterFailed(reason)
+ logger.error('🌐', 'ml_image_fetch_dead_letter_publish_failed', {
+ reason,
+ error: error instanceof Error ? error.name : 'unknown',
+ })
+ throw error
+ } finally {
+ if (timeout) {
+ clearTimeout(timeout)
+ }
+ }
+ ImageFetchConsumerMetrics.incDeadLettered(reason)
+ }
+
+ private deadLetterReason(reasons: UrlDropReason[]): FrontierDeadLetterReason {
+ const distinctReasons = new Set(reasons)
+ return distinctReasons.size === 1 ? reasons[0] : 'multiple'
+ }
+
private async runCrawlHistoryOperation<T>(
operation: 'read' | 'write',
affectedKeys: number,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index eea6bae910f9..f9f0ca134a4c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -81,6 +81,8 @@ export type MlMirrorConfig = {
/** While true, the fetch lane parses input but sends no request and writes no crawl history. */
SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: boolean
+ /** Optional topic for rejected frontier records. Empty commits and drops rejected input without quarantine. */
+ SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC: string
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: string
SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: number
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: string
@@ -229,6 +231,7 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_URL_CRAWL_HISTORY_PRECHECK_TIMEOUT_MS: 500,
WEB_BOT_AUTH_PRIVATE_KEYS: '',
SESSION_RECORDING_ML_IMAGE_FETCH_DRY_RUN: true,
+ SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC: '',
SESSION_RECORDING_ML_IMAGE_FETCH_GROUP_ID: 'session-replay-ml-image-fetch',
SESSION_RECORDING_ML_IMAGE_FETCH_BATCH_SIZE: 500,
AI_RESEARCH_IMAGE_FETCH_DYNAMODB_TABLE: '',
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
index bd20e6b1f80a..5af7568fd420 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-server.ts
@@ -20,6 +20,7 @@ import {
} from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/configuration-policy'
import { DynamoDBCrawlHistory } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/dynamodb-crawl-history'
import { FetchRunner } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/fetch-runner'
+import { KafkaFrontierDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-dead-letter-sink'
import { FrontierPublisher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/frontier-publisher'
import { HostBudget } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/host-budget'
import { HttpImageFetcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/image-fetcher'
@@ -48,6 +49,14 @@ const STORE_BATCH_BUDGET_MS = 50_000
/** Matches MAX_URL_LEN in the crate, which is what the collector applied to the first candidate. */
const MAX_REDIRECT_URL_LENGTH = 2048
+const BLOCKED_IMAGE_FETCH_DEAD_LETTER_TOPICS = [
+ KAFKA_SESSION_REPLAY_IMAGE_FETCH,
+ KAFKA_SESSION_REPLAY_IMAGE_SCRUB,
+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1M,
+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_10M,
+ KAFKA_SESSION_REPLAY_IMAGE_FETCH_RETRY_1H,
+]
+
/** The addon holds a 15 MB native library and `index.ts` imports every server, so it loads on first use. */
let anonymizer: typeof import('@posthog/replay-anonymizer') | undefined
function getAnonymizer(): typeof import('@posthog/replay-anonymizer') {
@@ -208,10 +217,15 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
// Built even in dry run, so the wiring is exercised by every start rather than only by the
// one that clears the flag.
this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
+ const producer = this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER)
const publisher = buildFrontierPublisher(
- this.producerRegistry.getProducer(INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER),
+ producer,
this.config.SESSION_RECORDING_ML_IMAGE_FETCH_MAX_PENDING_PUBLISHES
)
+ const deadLetterTopic = this.config.SESSION_RECORDING_ML_IMAGE_FETCH_DLQ_TOPIC
+ const deadLetters = deadLetterTopic
+ ? new KafkaFrontierDeadLetterSink(producer, deadLetterTopic, BLOCKED_IMAGE_FETCH_DEAD_LETTER_TOPICS)
+ : null
const fetchConsumer = new UrlFetchConsumer(
crawlHistory,
@@ -220,7 +234,8 @@ export class IngestionSessionReplayMlImageFetchServer implements NodeServer {
seenTtlSeconds: this.config.AI_RESEARCH_IMAGE_FETCH_CRAWL_HISTORY_TTL_SECONDS,
dryRun,
},
- buildFetchRunner(this.config, publisher)
+ buildFetchRunner(this.config, publisher),
+ deadLetters
)
logger.info('🌐', 'ml_image_fetch_started', { dryRun })