:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): report capture watermarks for the ML replay lanes (#109772)
Robbief63b56797811
diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts b/nodejs/src/common/kafka/consumer/consumer-v2.test.tsindex 1ea91bedbffe..c589e7d7cc89 100644--- a/nodejs/src/common/kafka/consumer/consumer-v2.test.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v2.test.ts@@ -135,9 +135,10 @@ describe('KafkaConsumerV2', () => {const startConsuming = async (eachBatch: jest.Mock,partitions = [{ topic: 'test-topic', partition: 0 }],- onPartitionsRevoked?: (assignments: { topic: string; partition: number }[]) => Promise<void>+ onPartitionsRevoked?: (assignments: { topic: string; partition: number }[]) => Promise<void>,+ onOffsetsStored?: jest.Mock) => {- await consumer.connect(eachBatch, onPartitionsRevoked)+ await consumer.connect(eachBatch, onPartitionsRevoked, onOffsetsStored)registeredRebalanceCb!({ code: CODES.ERRORS.ERR__ASSIGN_PARTITIONS } as any, partitions)// The loop is currently inside the IDLE keepalive consume(1, cb). Release it with// an empty batch so the loop processes ASSIGN and arms a fresh consume() in CONSUMING.@@ -222,7 +223,8 @@ describe('KafkaConsumerV2', () => {? Promise.resolve({ backgroundTask: processBatch(messages) }): joiner.handleBatch(messages))- await startConsuming(eachBatch)+ const onOffsetsStored = jest.fn()+ await startConsuming(eachBatch, undefined, undefined, onOffsetsStored)consumeCallback!(null, [createMessage({ offset: 1, partition: 0 })])await delay(5)@@ -237,6 +239,7 @@ describe('KafkaConsumerV2', () => {await delay(5)expect(mockRdKafka.consume).toHaveBeenCalledTimes(pollsAfterFirstBatch)expect(mockRdKafka.offsetsStore).not.toHaveBeenCalled()+ expect(onOffsetsStored).not.toHaveBeenCalled()p1.resolve()await delay(5)@@ -245,9 +248,26 @@ describe('KafkaConsumerV2', () => {[[{ topic: 'test-topic', partition: 0, offset: 2 }]],[[{ topic: 'test-topic', partition: 0, offset: 3 }]],])+ expect(onOffsetsStored.mock.calls).toEqual(mockRdKafka.offsetsStore.mock.calls)})+ it('reports only the offsets that librdkafka accepted to store', async () => {+ const eachBatch = jest.fn(() => Promise.resolve({}))+ const onOffsetsStored = jest.fn()+ await startConsuming(eachBatch, undefined, undefined, onOffsetsStored)+ mockRdKafka.offsetsStore.mockImplementationOnce(() => {+ throw new Error('Local: Erroneous state')+ })++ await dispatchBatch(eachBatch, [createMessage({ offset: 1, partition: 0 })], Promise.resolve())+ await dispatchBatch(eachBatch, [createMessage({ offset: 2, partition: 0 })], Promise.resolve())+ await delay(10)++ expect(mockRdKafka.offsetsStore).toHaveBeenCalledTimes(2)+ expect(onOffsetsStored.mock.calls).toEqual([[[{ topic: 'test-topic', partition: 0, offset: 3 }]]])+ })+it('REVOKE drain: incrementalUnassign called only after every settled completes', async () => {;(consumer as any).maxBackgroundTasks = 5const eachBatch = jest.fn(() => Promise.resolve({}))@@ -802,7 +822,8 @@ describe('KafkaConsumerV2', () => {// committing past the lost events.;(consumer as any).maxBackgroundTasks = 4const eachBatch = jest.fn(() => Promise.resolve({}))- await startConsuming(eachBatch)+ const onOffsetsStored = jest.fn()+ await startConsuming(eachBatch, undefined, undefined, onOffsetsStored);((consumer as any).loopDone as Promise<void>).catch(() => {})const failure = new Error('column "X" does not exist')@@ -824,6 +845,7 @@ describe('KafkaConsumerV2', () => {offsets.some((o: any) => o.partition === 0))expect(partition0Stores).toEqual([])+ expect(onOffsetsStored).not.toHaveBeenCalled()})it('fails unfinished background work at the configured timeout without advancing offsets', async () => {diff --git a/nodejs/src/common/kafka/consumer/consumer-v2.ts b/nodejs/src/common/kafka/consumer/consumer-v2.tsindex d1fc272a6a4a..64fe699e827e 100644--- a/nodejs/src/common/kafka/consumer/consumer-v2.ts+++ b/nodejs/src/common/kafka/consumer/consumer-v2.ts@@ -115,6 +115,11 @@ export class KafkaConsumerV2 {// revoke during disconnect — callers flush explicitly before disconnecting.private onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>+ // Optional hook invoked with the offsets that the auto offset store passed to librdkafka and+ // librdkafka accepted. It runs in batch order and never for a failed batch or a fenced+ // partition, so a caller can track how far each partition is durably done.+ private onOffsetsStored?: (offsets: TopicPartitionOffset[]) => void+// Tunables (resolved at construction)private fetchBatchSize: numberprivate batchTimeoutMs: number@@ -261,9 +266,11 @@ export class KafkaConsumerV2 {public async connect(eachBatch: EachBatch,- onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>+ onPartitionsRevoked?: (assignments: Assignment[]) => Promise<void>,+ onOffsetsStored?: (offsets: TopicPartitionOffset[]) => void): Promise<void> {this.onPartitionsRevoked = onPartitionsRevoked+ this.onOffsetsStored = onOffsetsStoredtry {await promisifyCallback<Metadata>((cb) => this.rdKafkaConsumer.connect({}, cb))logger.info('📝', 'kafka_consumer_v2_connected', { groupId: this.config.groupId, topic: this.config.topic })@@ -664,7 +671,9 @@ export class KafkaConsumerV2 {error: String(error),offsets,})+ return}+ this.onOffsetsStored?.(offsets)}// === Rebalance callback — pure event source, mutates nothing except the queue ===diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.tsindex a80cc36d5d75..92d42d22b65d 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts@@ -18,6 +18,7 @@ import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { IngestionConsumerConfig } from '~/ingestion/config'import { TopHog } from '~/ingestion/framework/tophog/tophog'import { SessionReplayPipelineConfig, createSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'+import { CaptureWatermark } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { getBlockEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto'import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'import { getKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore'@@ -86,6 +87,8 @@ export interface SessionRecordingIngesterCollaborators {* (which would let it mark a session seen without the main key and cause a cleartext recording).*/redisKeyNamespace?: string+ /** The ML mirror reports how far back its events are complete; the main lane leaves this unset. */+ captureWatermark?: CaptureWatermark}export class SessionRecordingIngester {@@ -135,6 +138,7 @@ export class SessionRecordingIngester {private readonly runner: StagedBatchRunnerprivate readonly batchStages: BatchStagesprivate readonly usageBatch: UsageRecordBatch+ private readonly captureWatermark?: CaptureWatermarkconstructor(private config: SessionRecordingIngesterConfig,@@ -273,6 +277,7 @@ export class SessionRecordingIngester {})this.lagReporter = new SessionReplayLagReporter(this.topic)+ this.captureWatermark = collaborators.captureWatermarkthis.currentBatch = this.sessionBatchManager.createBatch()this.lastFlushTime = Date.now()@@ -299,6 +304,16 @@ export class SessionRecordingIngester {SessionRecordingIngesterMetrics.incrementMessageReceived(message.partition)})+ this.captureWatermark?.hold(+ messages.map((message) => ({+ topic: message.topic,+ partition: message.partition,+ offset: message.offset,+ data: 'events',+ capturedAtMs: message.timestamp,+ }))+ )+const batchSize = messages.lengthconst batchSizeKb = messages.reduce((acc, m) => (m.value?.length ?? 0) + acc, 0) / 1024SessionRecordingIngesterMetrics.observeKafkaBatchSize(batchSize)@@ -463,6 +478,8 @@ export class SessionRecordingIngester {return Promise.resolve()}+ // Forgotten before the flush, because a failed revoke flush is swallowed and the partitions still go to the next owner.+ this.captureWatermark?.forget(topicPartitions)SessionRecordingIngesterMetrics.resetSessionsHandled()return this.flushCurrentBatch()}@@ -470,6 +487,7 @@ export class SessionRecordingIngester {private async commitOffsets(offsets: TopicPartitionOffset[]): Promise<void> {await instrumentFn(`recordingingesterv2.handleEachBatch.flush.commitOffsets`, () => {this.kafkaConsumer.offsetsStore(offsets)+ this.captureWatermark?.release(offsets)return Promise.resolve()})}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.mdindex 65939165642b..5dec0a29d88f 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@@ -420,6 +420,8 @@ A terminal refusal has no destination Kafka record, so it starts at step 2. A de`v` is the integer `2`. The parser also accepts the two version `1` shapes that preceded this schema, so records already in a topic drain across an upgrade. `jobs` contains 1 to 1,000 entries, and the decoded JSON record cannot exceed 512 KiB. `originalRef` is the ref calculated for the URL first seen in the replay. `currentUrl` is the next URL to request after any redirects. `remainingHops`, `notBeforeMs`, `firstSeenAtMs`, `fetchCount`, and `republishCount` are non-negative safe integers. `firstSeenAtMs` is the Unix time when the producer first collected the URL. `fetchCount` counts image HTTP requests, and `republishCount` counts frontier and delay-topic republishes. `lastRepublishReason` is `null`, `redirect`, `retry`, `not_ready`, `pass_deadline`, `origin_map_full`, or `registrable_domain_map_full`. The parser accepts and removes the legacy optional `lowOriginDiversityDeferred` field.+Each frontier or delay record also carries a `capture-timestamp-ms` header. Its value is the smallest `firstSeenAtMs` of the record's jobs. The lane reads the header to report its capture watermark (requirement 11.13) without parsing the record.+The parser ignores unknown fields so that a producer can add optional data without breaking an older consumer. It rejects a missing field, an invalid field type or value, an unsupported version, or a record whose jobs do not all match the Kafka key. It derives the current origin and registrable domain from `currentUrl` with the shared URL-policy implementation. It uses `originalRef` as the crawl-history key so that a redirect result completes the URL that the recording referenced.**10.5** The fetcher drops an unparseable input message. The fetcher has no dead-letter topic.@@ -483,6 +485,8 @@ The frontier retains an exact block reason across delay topics. Records createdEach metric returns the top 20 domain-factor keys per flush and tracks at most 2,000 keys in pod memory.+**11.13** The lane reports `ml_replay_capture_watermark_timestamp_seconds{data="image_urls"}` for each frontier partition. The value is the earliest `capture-timestamp-ms` among the records that the lane holds on the partition, or that it finished in the last 10 minutes. A record stays held until the consumer stores an offset past it. The mirror, the scrub lane, the Parquet sink, and the retry lane report the same gauge. The minimum over the lanes on a data path is how far back that data is complete in the training bucket. A record that waits in Kafka behind the consumer position does not count until the lane reads it. A URL in a delay topic that no retry consumer reads never counts again.+### 12. Conditional requests**12.1** The lane stores the request time, response time, `ETag`, `Last-Modified`, `Date`, `Age`, `Cache-Control`, and `Expires` metadata in the crawl history for that URL.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.tsindex 4e210fc7b4c6..1ddae5daebc7 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@@ -1,5 +1,6 @@import { KafkaProducerWrapper } from '~/common/kafka/producer'import { parseJSON } from '~/common/utils/json-parse'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import {FetchCandidate,@@ -85,14 +86,22 @@ describe('FrontierPublisher', () => {expect(await batch.republish(candidate(), target, 'redirect')).toBe('queued')expect(- await batch.republish(candidate({ originalRef: `imageurl:${'b'.repeat(22)}` }), target, 'redirect')+ await batch.republish(+ candidate({ originalRef: `imageurl:${'b'.repeat(22)}`, firstSeenAtMs: 1_699_999_000_000 }),+ target,+ 'redirect'+ )).toBe('queued')expect(sent).toEqual([])await expect(batch.flush()).resolves.toEqual({ failedUrls: 0 })expect(republished).toHaveBeenCalledTimes(2)expect(sent).toHaveLength(1)- expect(sent[0]).toMatchObject({ topic: FRONTIER, key: 'other.net' })+ expect(sent[0]).toMatchObject({+ topic: FRONTIER,+ key: 'other.net',+ headers: { [CAPTURE_TIMESTAMP_HEADER]: '1699999000000' },+ })expect(parseCollectedUrlsRecord(sent[0].value, 'other.net')).toMatchObject({ok: true,candidates: [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.tsindex a10d9fad994c..409dd34716a4 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,8 +1,8 @@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 { mlKafkaRecord } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import {FetchCandidate,@@ -301,13 +301,18 @@ class BufferedRepublishBatch implements RepublishBatch {return 'skipped'}try {+ const record = mlKafkaRecord(+ plan.candidates[0].sessionId ? '2' : '1',+ serializeFrontierRecord(plan.candidates)+ )await this.producer.produce({topic: plan.topic,key: Buffer.from(plan.registrableDomain),- ...mlKafkaRecord(- plan.candidates[0].sessionId ? '2' : '1',- serializeFrontierRecord(plan.candidates)- ),+ value: record.value,+ headers: {+ [CAPTURE_TIMESTAMP_HEADER]: String(earliestFirstSeenAtMs(plan.candidates)),+ ...record.headers,+ },})return 'published'} catch {@@ -359,3 +364,11 @@ class BufferedRepublishBatch implements RepublishBatch {}}}++function earliestFirstSeenAtMs(candidates: FetchCandidate[]): number {+ let earliest = candidates[0].firstSeenAtMs+ for (const candidate of candidates) {+ earliest = Math.min(earliest, candidate.firstSeenAtMs)+ }+ return earliest+}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.tsindex a19a22a0a125..1a4f53a9f9fc 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@@ -1,10 +1,10 @@import { Message } from 'node-rdkafka'import { KafkaProducerWrapper } from '~/common/kafka/producer'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'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,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.tsindex 220dde4a6b32..7a15d9d476a5 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@@ -4,9 +4,10 @@ import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'import { KafkaProducerWrapper } from '~/common/kafka/producer'import { logger } from '~/common/utils/logger'import { INGESTION_VERSION_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { REPLAY_COUNT_HEADER } from './image-batcher'-import { CAPTURE_TIMESTAMP_HEADER, CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'+import { CONTENT_ENCODING_HEADER, CONTENT_TYPE_HEADER } from './image-transport'import { ImageScrubConsumerMetrics } from './metrics'/**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.tsindex e1adac7fc8cc..d78a236e92fa 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@@ -9,11 +9,11 @@ import {tableKeyString,} from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'import { MlKafkaTransport } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { hashImageBytes, imageRef, urlRef } from './content-ref'import { ImageBatcher, OffsetStore, WRITE_CONCURRENCY } from './image-batcher'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'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.tsindex 4f211e0e0546..3efe00916e18 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@@ -12,12 +12,12 @@ import {tableKeyString,} from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/schema'import { MlDecodedMessage, ingestionVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/transport'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'import { parseImageRef } from './content-ref'import { ImageShardStore, ScrubbedImage, ScrubbedUrlImage } from './image-shard-store'import {- CAPTURE_TIMESTAMP_HEADER,CONTENT_ENCODING_HEADER,CONTENT_TYPE_HEADER,InvalidImageTransportError,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.tsindex 10b20c8fe30b..9a7c2bbec70b 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,7 +4,6 @@ import { createBrotliDecompress, createGunzip, createInflate, createZstdDecompreexport const MAX_UNCOMPRESSED_IMAGE_BYTES = 20 * 1024 * 1024export 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 = 4diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.tsindex 764c980aff61..eacdd64be2b9 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts@@ -1,6 +1,7 @@import { DateTime } from 'luxon'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import {SessionBlockMetadata,createNoopBlockMetadata,@@ -48,6 +49,18 @@ describe('MlBlockMetadataSink', () => {expect(messages).toHaveLength(1)})+ it('stamps a record with the capture time of the earliest message in its block', async () => {+ await sink.storeSessionBlocks([+ block('legacy-session', 1, { earliestCapturedAtMs: 1_700_000_000_000 }),+ block('legacy-other', 1),+ ])+ const [, messages] = outputs.queueMessages.mock.calls[0]+ expect(messages.map((message) => message.headers?.[CAPTURE_TIMESTAMP_HEADER])).toEqual([+ '1700000000000',+ undefined,+ ])+ })+it('still calls queueMessages for an all-skipped batch', async () => {await sink.storeSessionBlocks([block('01a0a4f0-3200-7000-8000-000000000001', 1, { isDeleted: true })])expect(outputs.queueMessages).toHaveBeenCalledWith(ML_BLOCK_METADATA_OUTPUT, [])diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.tsindex e62654c7d81a..a523b65f4176 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts@@ -1,4 +1,5 @@import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink'import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'@@ -36,7 +37,12 @@ export class MlBlockMetadataSink implements SessionMetadataSink {}const version = mlWireVersion(key)producedByVersion.set(version, (producedByVersion.get(version) ?? 0) + 1)- return [{ key: row.session_id, ...mlKafkaRecord(version, Buffer.from(JSON.stringify(row))) }]+ const record = mlKafkaRecord(version, Buffer.from(JSON.stringify(row)))+ const headers =+ block.earliestCapturedAtMs === undefined+ ? record.headers+ : { [CAPTURE_TIMESTAMP_HEADER]: String(block.earliestCapturedAtMs), ...record.headers }+ return [{ key: row.session_id, value: record.value, headers }]})await this.outputs.queueMessages(ML_BLOCK_METADATA_OUTPUT, messages)for (const [version, count] of producedByVersion) {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.tsindex bafb3f1dd115..afadf7fd2710 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,6 +1,6 @@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 { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { MlMirrorMetrics } from './metrics'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.tsindex d8460b2de489..6f56b2ad12d8 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@@ -2,7 +2,7 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { logger } from '~/common/utils/logger'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { ML_IMAGE_SCRUB_OUTPUT, MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'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.tsindex 4b3a57367328..4d0413df3b3c 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@@ -3,6 +3,7 @@ import { parseJSON } from '~/common/utils/json-parse'import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'import { PipelineResultType } from '~/ingestion/framework/results'import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { RecordedTopHogMetric, createRecordingTopHog } from '~/tests/helpers/tophog'@@ -12,7 +13,7 @@ import { CollectedUrlsMessage, createProduceCollectedUrlsStep } from './produce-describe('produceCollectedUrlsStep', () => {const TEAM_ID = '42'const CAPTURED_AT = 1_700_000_000_000- let queued: { key: string; value: Buffer }[][]+ let queued: { key: string; value: Buffer; headers?: Record<string, string> }[][]let outputs: IngestionOutputs<MlImageFetchOutput>let queueMessages: jest.Mocklet topHog: TopHogRegistry@@ -127,6 +128,10 @@ describe('produceCollectedUrlsStep', () => {},},])+ expect(queued[0].map((message) => message.headers?.[CAPTURE_TIMESTAMP_HEADER])).toEqual([+ String(CAPTURED_AT),+ String(CAPTURED_AT),+ ])expect(topHogRecords.get('ml_image_fetch_produced_urls_by_registrable_domain')).toEqual([{ key: { registrable_domain: 'cdn.example.com' }, value: 2 },{ key: { registrable_domain: 'img.other.com' }, value: 1 },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.tsindex 10521fc3929d..fac1817c66ab 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@@ -7,6 +7,7 @@ import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import type { CrawlHistoryStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/crawl-history'import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'+import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { ML_IMAGE_FETCH_OUTPUT, MlImageFetchOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-dedup-cache'@@ -272,7 +273,12 @@ export function createProduceCollectedUrlsStep<} satisfies CollectedUrlsMessage))MlMirrorMetrics.observeMlUrlRecord(slice.length, value.length)- return { key: domain, ...mlKafkaRecord(mlWireVersion(key), value) }+ const record = mlKafkaRecord(mlWireVersion(key), value)+ return {+ key: domain,+ value: record.value,+ headers: { [CAPTURE_TIMESTAMP_HEADER]: String(firstSeenAtMs), ...record.headers },+ }}))diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.tsindex 6da25906fd29..bde0b3ce083c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts@@ -48,6 +48,7 @@ export class SessionBlockRecorderMock {private size: number = 0private startDateTime: DateTime | null = nullprivate endDateTime: DateTime | null = null+ private earliestCapturedAtMs: number | undefinedprivate _distinctId: string | null = nullconstructor(@@ -70,6 +71,9 @@ export class SessionBlockRecorderMock {if (!this.endDateTime || message.eventsRange.end > this.endDateTime) {this.endDateTime = message.eventsRange.end}+ if (message.metadata.timestamp > 0) {+ this.earliestCapturedAtMs = Math.min(this.earliestCapturedAtMs ?? Infinity, message.metadata.timestamp)+ }Object.entries(message.eventsByWindowId).forEach(([windowId, events]) => {events.forEach((event) => {@@ -109,6 +113,7 @@ export class SessionBlockRecorderMock {snapshotLibrary: null,snapshotMode: null,batchId: this.batchId,+ ...(this.earliestCapturedAtMs === undefined ? {} : { earliestCapturedAtMs: this.earliestCapturedAtMs }),}}}@@ -459,6 +464,24 @@ describe('SessionBatchRecorder', () => {])})+ it('passes the earliest capture time of each block to the metadata store', async () => {+ await record(+ createMessage('session1', [{ type: EventType.Meta, timestamp: 1000, data: {} }], {+ timestamp: 1_700_000_002_000,+ })+ )+ await record(+ createMessage('session1', [{ type: EventType.Meta, timestamp: 2000, data: {} }], {+ timestamp: 1_700_000_001_000,+ })+ )+ await recorder.flush()++ expect(mockMetadataStore.storeSessionBlocks).toHaveBeenCalledWith([+ expect.objectContaining({ sessionId: 'session1', earliestCapturedAtMs: 1_700_000_001_000 }),+ ])+ })+it('should handle empty events array', async () => {const message = createMessage('session1', [])const bytesWritten = await record(message)diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.tsindex 33f55ab51b30..e2794cf2cce5 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts@@ -301,6 +301,7 @@ export class SessionBatchRecorder {replayIndexEntries,replayIndexTruncated,batchId,+ earliestCapturedAtMs,} = built[index]const features = featureRecorder.end()@@ -358,6 +359,7 @@ export class SessionBatchRecorder {eventCount,retentionPeriodDays,isDeleted: false,+ ...(earliestCapturedAtMs === undefined ? {} : { earliestCapturedAtMs }),})totalEvents += eventCountdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.tsindex 1f760dce3841..e44e02fb6bcc 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.test.ts@@ -22,7 +22,7 @@ describe('SessionBlockRecorder', () => {recorder = new SessionBlockRecorder('test_session_id', 1, 'test_batch_id')})- const createMessage = (windowId: string, events: any[]): ParsedMessageData => ({+ const createMessage = (windowId: string, events: any[], capturedAtMs = 0): ParsedMessageData => ({distinct_id: 'distinct_id',session_id: 'session_id',token: null,@@ -39,7 +39,7 @@ describe('SessionBlockRecorder', () => {partition: 1,topic: 'test',offset: 0,- timestamp: 0,+ timestamp: capturedAtMs,rawSize: 0,},})@@ -309,14 +309,25 @@ describe('SessionBlockRecorder', () => {it('should track min/max timestamps across multiple messages', async () => {const messages = [- createMessage('window1', [- { type: RRWebEventType.Meta, timestamp: new Date('2025-01-01T01:00:00Z').getTime() },- { type: RRWebEventType.FullSnapshot, timestamp: new Date('2025-01-01T01:00:01Z').getTime() },- ]),- createMessage('window2', [- { type: RRWebEventType.FullSnapshot, timestamp: new Date('2025-01-01T01:00:02Z').getTime() },- { type: RRWebEventType.IncrementalSnapshot, timestamp: new Date('2025-01-01T01:00:03Z').getTime() },- ]),+ createMessage(+ 'window1',+ [+ { type: RRWebEventType.Meta, timestamp: new Date('2025-01-01T01:00:00Z').getTime() },+ { type: RRWebEventType.FullSnapshot, timestamp: new Date('2025-01-01T01:00:01Z').getTime() },+ ],+ 1_700_000_002_000+ ),+ createMessage(+ 'window2',+ [+ { type: RRWebEventType.FullSnapshot, timestamp: new Date('2025-01-01T01:00:02Z').getTime() },+ {+ type: RRWebEventType.IncrementalSnapshot,+ timestamp: new Date('2025-01-01T01:00:03Z').getTime(),+ },+ ],+ 1_700_000_001_000+ ),]messages.forEach((message) => recorder.recordMessage(message))@@ -324,6 +335,7 @@ describe('SessionBlockRecorder', () => {expect(result.startDateTime).toEqual(DateTime.fromMillis(new Date('2025-01-01T01:00:00Z').getTime())) // Min from all messagesexpect(result.endDateTime).toEqual(DateTime.fromMillis(new Date('2025-01-01T01:00:03Z').getTime())) // Max from all messages+ expect(result.earliestCapturedAtMs).toBe(1_700_000_001_000)})it('should handle empty events array', async () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.tsindex c63a899585b6..756dd9a8cb2b 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-block-recorder.ts@@ -65,6 +65,8 @@ export interface EndResult {snapshotMode: SnapshotMode | null/** ID of the batch this session belongs to */batchId: string+ /** Kafka timestamp of the earliest message in the block, which is the capture clock that the ML lanes compare */+ earliestCapturedAtMs?: numberreplayIndexEntries?: ReplayIndexEntry[]replayIndexTruncated?: boolean}@@ -100,6 +102,7 @@ export class SessionBlockRecorder {private building?: Promise<EndResult>private startDateTime: DateTime | null = nullprivate endDateTime: DateTime | null = null+ private earliestCapturedAtMs: number | undefinedprivate _distinctId: string | null = nullprivate urls: Set<string> = new Set()private firstUrl: string | null = null@@ -161,6 +164,10 @@ export class SessionBlockRecorder {if (!this.endDateTime || message.eventsRange.end > this.endDateTime) {this.endDateTime = message.eventsRange.end}+ const capturedAtMs = message.metadata.timestamp+ if (capturedAtMs > 0 && (this.earliestCapturedAtMs === undefined || capturedAtMs < this.earliestCapturedAtMs)) {+ this.earliestCapturedAtMs = capturedAtMs+ }if (message.preSerialized) {return this.recordPreSerialized(message)@@ -356,6 +363,7 @@ export class SessionBlockRecorder {snapshotLibrary: this.snapshotLibrary,snapshotMode: this.snapshotMode,batchId: this.batchId,+ ...(this.earliestCapturedAtMs === undefined ? {} : { earliestCapturedAtMs: this.earliestCapturedAtMs }),...(this.replayIndexEntries.length ? { replayIndexEntries: this.replayIndexEntries } : {}),...(this.replayIndexTruncated ? { replayIndexTruncated: true } : {}),}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.test.tsnew file mode 100644index 000000000000..7ca6b74d07ca--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.test.ts@@ -0,0 +1,98 @@+import { Message, TopicPartitionOffset } from 'node-rdkafka'+import { register } from 'prom-client'++import {+ CAPTURE_TIMESTAMP_HEADER,+ CaptureWatermark,+ CapturedRecord,+ capturedRecords,+ releasingOffsetStore,+} from './capture-watermark'++const TOPIC = 'session_replay_image_scrub'+const MINUTE_MS = 60_000++function record(offset: number, capturedAtMs: number | undefined, overrides: Partial<CapturedRecord> = {}) {+ return { topic: TOPIC, partition: 0, offset, data: 'inline_images' as const, capturedAtMs, ...overrides }+}++function stored(offset: number, partition = 0): TopicPartitionOffset[] {+ return [{ topic: TOPIC, partition, offset }]+}++function message(offset: number, capturedAtMs: number, partition = 0): Message {+ return {+ topic: TOPIC,+ partition,+ offset,+ value: null,+ size: 0,+ headers: [{ [CAPTURE_TIMESTAMP_HEADER]: Buffer.from(String(capturedAtMs)) }],+ }+}++describe('CaptureWatermark', () => {+ it('holds a batch until a stored offset passes its last record, then keeps it for the finished window', () => {+ const watermark = new CaptureWatermark('held', 10 * MINUTE_MS)+ watermark.hold([record(0, 2_000), record(1, 1_000)])+ // librdkafka reports a record without a timestamp as -1, and a record without the header has none.+ watermark.hold([record(2, 3_000), record(3, 4_000), record(4, -1), record(5, undefined)])++ watermark.release(stored(3), 0)+ expect(watermark.snapshot(20 * MINUTE_MS)).toEqual([+ { topic: TOPIC, partition: 0, data: 'inline_images', capturedAtMs: 3_000 },+ ])++ watermark.release(stored(4), 20 * MINUTE_MS)+ expect(watermark.snapshot(25 * MINUTE_MS)[0].capturedAtMs).toBe(3_000)+ // A partition that delivers nothing more keeps its last value, so a stalled consumer still shows its lag.+ expect(watermark.snapshot(60 * MINUTE_MS)[0].capturedAtMs).toBe(3_000)+ })++ it('reports each kind of data on a partition apart, and releases them together', () => {+ const watermark = new CaptureWatermark('kinds', 0)+ watermark.hold([record(0, 9_000), record(1, 1_000, { data: 'url_images' }), record(2, 5_000, { partition: 1 })])++ expect(watermark.snapshot(0)).toEqual([+ { topic: TOPIC, partition: 0, data: 'inline_images', capturedAtMs: 9_000 },+ { topic: TOPIC, partition: 0, data: 'url_images', capturedAtMs: 1_000 },+ { topic: TOPIC, partition: 1, data: 'inline_images', capturedAtMs: 5_000 },+ ])++ watermark.hold([record(3, 10_000), record(4, 11_000, { data: 'url_images' })])+ watermark.release(stored(3), 0)+ watermark.forget([{ topic: TOPIC, partition: 1 }])+ expect(watermark.snapshot(1)).toEqual([+ { topic: TOPIC, partition: 0, data: 'inline_images', capturedAtMs: 10_000 },+ { topic: TOPIC, partition: 0, data: 'url_images', capturedAtMs: 11_000 },+ ])+ })++ it('does not release offsets that Kafka refused to store', () => {+ const watermark = new CaptureWatermark('refused', 0)+ const store = releasingOffsetStore(+ {+ offsetsStore: () => {+ throw new Error('Local: Erroneous state')+ },+ },+ watermark+ )+ watermark.hold(capturedRecords([message(0, 1_000), message(1, 2_000)], () => 'event_metadata'))+ watermark.hold(capturedRecords([message(2, 3_000)], () => 'event_metadata'))++ expect(() => store.offsetsStore(stored(2))).toThrow('Erroneous state')+ expect(watermark.snapshot(Date.now() + 1)[0].capturedAtMs).toBe(1_000)+ })++ it('exports the watermark in seconds for each partition and kind of data', async () => {+ new CaptureWatermark('exported', 0).hold([record(7, 1_790_000_000_500, { partition: 17, data: 'url_images' })])++ const metric = await register.getSingleMetric('ml_replay_capture_watermark_timestamp_seconds')!.get()++ expect(metric.values).toContainEqual({+ labels: { partition: '17', data: 'url_images' },+ value: 1_790_000_000.5,+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.tsnew file mode 100644index 000000000000..8f67d903e865--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/capture-watermark.ts@@ -0,0 +1,261 @@+import { Message, TopicPartition, TopicPartitionOffset } from 'node-rdkafka'+import { Gauge } from 'prom-client'++import { parseKafkaHeaders } from '~/common/kafka/consumer/consumer-v1'++/**+ * Every record on an ML replay topic carries the Kafka timestamp of the replay record that its data+ * came from. Each lane compares its watermark on this one clock, so the minimum over the lanes on a+ * data path is how far back that data is complete in the training bucket.+ */+export const CAPTURE_TIMESTAMP_HEADER = 'capture-timestamp-ms'++/**+ * Events go through the mirror and the Parquet sink. Inline images go through the mirror and the+ * scrub lane. URL images go through the mirror, the fetch lane and the scrub lane.+ */+export type CapturedData = 'events' | 'event_metadata' | 'image_urls' | 'inline_images' | 'url_images'++export interface CapturedRecord {+ topic: string+ partition: number+ offset: number+ data: CapturedData+ capturedAtMs: number | undefined+}++export interface CaptureWatermarkRow {+ topic: string+ partition: number+ data: CapturedData+ capturedAtMs: number+}++export interface OffsetStore {+ offsetsStore(offsets: TopicPartitionOffset[]): void+}++/**+ * The fetch lane sends a URL that a pass cannot finish to the end of its frontier partition, and the+ * scrub lane receives URL images in fetch order, not capture order. So a finished record does not+ * prove that the next records on the partition are newer. Finished records stay in the watermark for+ * this long, which lets a URL that comes back within the window keep the watermark down.+ */+const FINISHED_WINDOW_MS = 10 * 60 * 1000+/** Finished batches merge into one bucket per this span, so that a busy partition keeps a bounded number of buckets. */+const FINISHED_BUCKET_MS = 60 * 1000++interface HeldBatch {+ lastOffset: number+ earliestCapturedAtMs: number+}++interface FinishedBucket {+ startedAtMs: number+ lastFinishedAtMs: number+ earliestCapturedAtMs: number+}++interface DataWatermark {+ held: HeldBatch[]+ finished: FinishedBucket[]+ lastExpiredCapturedAtMs?: number+}++interface PartitionWatermarks {+ topic: string+ partition: number+ byData: Map<CapturedData, DataWatermark>+}++/** Read at scrape time by the gauge, which keeps the batch path free of gauge writes. */+const liveWatermarks = new Map<string, CaptureWatermark>()++// Never referenced again: constructing it registers it, and it pulls its own values at scrape time.+new Gauge({+ name: 'ml_replay_capture_watermark_timestamp_seconds',+ help: 'Unix time of the earliest capture among the records that this lane holds on the partition or finished in the last 10 minutes. The lane finished every record that it read with an earlier capture time. A record that the lane has not read yet can be older, for example a URL that the fetch lane sent back to the end of the frontier. The minimum over the lanes on a data path is how far back that data is complete',+ // No topic label, because the lanes' metric labels never carry a configured topic name. Each lane reads one topic.+ labelNames: ['partition', 'data'],+ collect() {+ const earliestByLabels = new Map<string, { partition: string; data: CapturedData; capturedAtMs: number }>()+ const nowMs = Date.now()+ for (const watermark of liveWatermarks.values()) {+ for (const row of watermark.snapshot(nowMs)) {+ const key = `${row.partition}\0${row.data}`+ const earliest = earliestByLabels.get(key)+ if (!earliest || row.capturedAtMs < earliest.capturedAtMs) {+ earliestByLabels.set(key, {+ partition: String(row.partition),+ data: row.data,+ capturedAtMs: row.capturedAtMs,+ })+ }+ }+ }+ // Reset before setting, so that a partition that this pod gave up stops being reported from here.+ this.reset()+ for (const { partition, data, capturedAtMs } of earliestByLabels.values()) {+ this.labels({ partition, data }).set(capturedAtMs / 1000)+ }+ },+})++export class CaptureWatermark {+ private readonly partitions = new Map<string, PartitionWatermarks>()++ constructor(+ lane: string,+ private readonly finishedWindowMs = FINISHED_WINDOW_MS+ ) {+ liveWatermarks.set(lane, this)+ }++ /** Holds the capture time of each record until a stored offset passes it. */+ public hold(records: Iterable<CapturedRecord>): void {+ const batches = new Map<DataWatermark, HeldBatch>()+ for (const { topic, partition, offset, data, capturedAtMs } of records) {+ if (!isCaptureTimestamp(capturedAtMs)) {+ continue+ }+ const watermark = this.dataWatermark(topic, partition, data)+ const batch = batches.get(watermark)+ if (batch) {+ batch.lastOffset = Math.max(batch.lastOffset, offset)+ batch.earliestCapturedAtMs = Math.min(batch.earliestCapturedAtMs, capturedAtMs)+ } else {+ const held = { lastOffset: offset, earliestCapturedAtMs: capturedAtMs }+ batches.set(watermark, held)+ watermark.held.push(held)+ }+ }+ }++ /** `offsets` are what Kafka stores: the next offset to read on each partition. */+ public release(offsets: TopicPartitionOffset[], nowMs = Date.now()): void {+ for (const { topic, partition, offset } of offsets) {+ const watermarks = this.partitions.get(partitionKey(topic, partition))+ for (const watermark of watermarks?.byData.values() ?? []) {+ const stillHeld: HeldBatch[] = []+ for (const batch of watermark.held) {+ if (batch.lastOffset < offset) {+ this.finish(watermark, batch.earliestCapturedAtMs, nowMs)+ } else {+ stillHeld.push(batch)+ }+ }+ watermark.held = stillHeld+ }+ }+ }++ /** Called on revoke, so that only the next owner of the partition reports it. */+ public forget(partitions: TopicPartition[]): void {+ for (const { topic, partition } of partitions) {+ this.partitions.delete(partitionKey(topic, partition))+ }+ }++ public snapshot(nowMs = Date.now()): CaptureWatermarkRow[] {+ const rows: CaptureWatermarkRow[] = []+ for (const { topic, partition, byData } of this.partitions.values()) {+ for (const [data, watermark] of byData) {+ this.expireFinished(watermark, nowMs)+ let earliestCapturedAtMs = Infinity+ for (const batch of watermark.held) {+ earliestCapturedAtMs = Math.min(earliestCapturedAtMs, batch.earliestCapturedAtMs)+ }+ for (const bucket of watermark.finished) {+ earliestCapturedAtMs = Math.min(earliestCapturedAtMs, bucket.earliestCapturedAtMs)+ }+ // A partition that stops delivering records keeps its last value instead of disappearing,+ // so that the minimum across partitions still includes a stalled consumer.+ const capturedAtMs = Number.isFinite(earliestCapturedAtMs)+ ? earliestCapturedAtMs+ : watermark.lastExpiredCapturedAtMs+ if (capturedAtMs !== undefined) {+ rows.push({ topic, partition, data, capturedAtMs })+ }+ }+ }+ return rows+ }++ private finish(watermark: DataWatermark, earliestCapturedAtMs: number, nowMs: number): void {+ this.expireFinished(watermark, nowMs)+ const last = watermark.finished.at(-1)+ if (last && nowMs - last.startedAtMs < FINISHED_BUCKET_MS) {+ last.lastFinishedAtMs = nowMs+ last.earliestCapturedAtMs = Math.min(last.earliestCapturedAtMs, earliestCapturedAtMs)+ } else {+ watermark.finished.push({ startedAtMs: nowMs, lastFinishedAtMs: nowMs, earliestCapturedAtMs })+ }+ }++ private expireFinished(watermark: DataWatermark, nowMs: number): void {+ while (+ watermark.finished.length > 0 &&+ nowMs - watermark.finished[0].lastFinishedAtMs > this.finishedWindowMs+ ) {+ watermark.lastExpiredCapturedAtMs = watermark.finished.shift()!.earliestCapturedAtMs+ }+ }++ private dataWatermark(topic: string, partition: number, data: CapturedData): DataWatermark {+ const key = partitionKey(topic, partition)+ let watermarks = this.partitions.get(key)+ if (!watermarks) {+ watermarks = { topic, partition, byData: new Map() }+ this.partitions.set(key, watermarks)+ }+ let watermark = watermarks.byData.get(data)+ if (!watermark) {+ watermark = { held: [], finished: [] }+ watermarks.byData.set(data, watermark)+ }+ return watermark+ }+}++export function captureTimestampMs(message: Pick<Message, 'headers'>): number | undefined {+ const capturedAtMs = Number(parseKafkaHeaders(message.headers)[CAPTURE_TIMESTAMP_HEADER])+ return isCaptureTimestamp(capturedAtMs) ? capturedAtMs : undefined+}++export function capturedRecords(+ messages: Message[],+ dataOf: (message: Message) => CapturedData | undefined+): CapturedRecord[] {+ const records: CapturedRecord[] = []+ for (const message of messages) {+ const data = dataOf(message)+ if (data !== undefined) {+ records.push({+ topic: message.topic,+ partition: message.partition,+ offset: message.offset,+ data,+ capturedAtMs: captureTimestampMs(message),+ })+ }+ }+ return records+}++/** A refused store leaves the records to be read again, so the watermark moves only after Kafka accepts the offsets. */+export function releasingOffsetStore(store: OffsetStore, watermark: CaptureWatermark): OffsetStore {+ return {+ offsetsStore(offsets) {+ store.offsetsStore(offsets)+ watermark.release(offsets)+ },+ }+}++function isCaptureTimestamp(capturedAtMs: number | undefined): capturedAtMs is number {+ return capturedAtMs !== undefined && Number.isSafeInteger(capturedAtMs) && capturedAtMs > 0+}++function partitionKey(topic: string, partition: number): string {+ return `${topic}\0${partition}`+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.tsindex 3f465534386a..23adddff8e82 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata.ts@@ -97,4 +97,6 @@ export interface SessionBlockMetadata {retentionPeriodDays: number | null/** Whether this recording has been deleted */isDeleted: boolean+ /** Kafka timestamp of the earliest message in the block, which is the capture clock that the ML lanes compare */+ earliestCapturedAtMs?: number}diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.tsindex c7aa1c5c9c2f..afb488129d6e 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-fetch-retry-server.ts@@ -12,6 +12,7 @@ import { logger } from '~/common/utils/logger'import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'import { RetryDelayConsumer } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-fetch/retry-delay-consumer'import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'+import { CaptureWatermark, capturedRecords } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'import { CleanupResources } from './base-server'@@ -86,11 +87,14 @@ export class IngestionSessionReplayMlImageFetchRetryServer extends MlMirrorConsu// The shutdown handler sets this before it disconnects the consumer, so a stopping pod// abandons the wait it holds rather than making the rolling deploy wait out a tier period.let stopping = false+ const watermark = new CaptureWatermark(`image_fetch_retry_${delayMs}`)const delayConsumer = new RetryDelayConsumer(producer, {isStopping: () => stopping,storeOffsets: (messages) => {try {- consumer.offsetsStore(findOffsetsToCommit(messages))+ const offsets = findOffsetsToCommit(messages)+ consumer.offsetsStore(offsets)+ watermark.release(offsets)} catch (error) {const code = (error as LibrdKafkaError | undefined)?.codeif (!stopping && !REVOKED_PARTITION_CODES.has(code ?? 0)) {@@ -109,7 +113,16 @@ export class IngestionSessionReplayMlImageFetchRetryServer extends MlMirrorConsu})logger.info('🌐', 'ml_image_fetch_retry_started', { topic, delayMs, pollIntervalMs })- await consumer.connect((messages) => delayConsumer.handleBatch(messages))+ await consumer.connect(+ (messages) => {+ watermark.hold(capturedRecords(messages, () => 'image_urls'))+ return delayConsumer.handleBatch(messages)+ },+ (partitions) => {+ watermark.forget(partitions)+ return Promise.resolve()+ }+ )this.lifecycle.services.push({id: 'session-replay-ml-image-fetch-retry',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.tsindex 6d71ce9a7954..1b2aeffad224 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@@ -44,6 +44,7 @@ import { createWebBotAuthRequestSigner } from '~/ingestion/pipelines/sessionreplimport { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'+import { CaptureWatermark, capturedRecords } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { INGESTION_SESSIONREPLAY_ML_IMAGE_FETCH_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'import { HealthCheckResultOk } from '~/types'@@ -392,7 +393,22 @@ export class IngestionSessionReplayMlImageFetchServer extends MlMirrorConsumerSereturn new HealthCheckResultOk()},})- await Promise.all(consumers.map((consumer, index) => consumer.connect(batchHandlers.handlers[index])))+ const watermark = new CaptureWatermark('image_fetch')+ await Promise.all(+ consumers.map((consumer, index) =>+ consumer.connect(+ (messages) => {+ watermark.hold(capturedRecords(messages, () => 'image_urls'))+ return batchHandlers.handlers[index](messages)+ },+ (partitions) => {+ watermark.forget(partitions)+ return Promise.resolve()+ },+ (offsets) => watermark.release(offsets)+ )+ )+ )}protected getCleanupResources(): CleanupResources {diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.tsindex db992f88e7b0..ce58b7e708ac 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.test.ts@@ -1,6 +1,7 @@import {IngestionSessionReplayMlImageScrubServer,buildImageScrubConsumerConfig,+ scrubbedImageData,} from './ingestion-session-replay-ml-image-scrub-server'import { buildMlMirrorServerConfig } from './ml-mirror-server-config'@@ -43,6 +44,15 @@ describe('image scrub server startup', () => {})+ it.each([+ ['image:v3:42:2026-09:aaaaaaaaaaaaaaaaaaaaaa', 'inline_images'],+ ['imageurl:v3:42:2026-09:aaaaaaaaaaaaaaaaaaaaaa', 'url_images'],+ ['imageurl:aaaaaaaaaaaaaaaaaaaaaa', 'url_images'],+ ['not-a-ref', undefined],+ ])('reports the watermark of %s as %s', (ref, data) => {+ expect(scrubbedImageData({ key: Buffer.from(ref) })).toBe(data)+ })+it('allows a disabled DLQ without a key manager and continues to the S3 configuration check', async () => {const server = new TestImageScrubServer({AI_RESEARCH_REPLAY_KEY_TABLE: '',diff --git a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.tsindex 1be06a3cd669..3bb9a427ca02 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-image-scrub-server.ts@@ -1,15 +1,23 @@import { S3Client } from '@aws-sdk/client-s3'+import { Message } from 'node-rdkafka'import { KAFKA_SESSION_REPLAY_IMAGE_SCRUB } from '~/common/config/kafka-topics'import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { SessionReplayProducerName } from '~/ingestion/pipelines/sessionreplay/config'+import { parseImageRef } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/content-ref'import { KafkaDeadLetterSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/dead-letter-sink'import { ImageBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-batcher'import { ImageShardStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-shard-store'import { ScrubClient } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/scrub-client'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'+import {+ CaptureWatermark,+ CapturedData,+ capturedRecords,+ releasingOffsetStore,+} from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { INGESTION_SESSIONREPLAY_ML_IMAGE_SCRUB_PRODUCER } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'@@ -67,6 +75,12 @@ export function buildImageScrubConsumerConfig(config: IngestionSessionReplayMlMi}}+/** URL images reach the scrub topic in fetch order, not capture order, so they keep a watermark apart from inline images. */+export function scrubbedImageData(message: Pick<Message, 'key'>): CapturedData | undefined {+ const source = parseImageRef(message.key?.toString('utf8') ?? '')?.source+ return source === undefined ? undefined : source === 'url' ? 'url_images' : 'inline_images'+}+export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerServer {private keyManager?: MlKeyManagerprivate producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>@@ -123,9 +137,10 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSe'fetch.message.max.bytes': maximumRecordBytes,'max.partition.fetch.bytes': maximumRecordBytes,})+ const watermark = new CaptureWatermark('image_scrub')const batcher = new ImageBatcher(store,- consumer,+ releasingOffsetStore(consumer, watermark),scrubClient,{flushIntervalMs: this.config.SESSION_RECORDING_ML_IMAGE_SCRUB_FLUSH_INTERVAL_MS,@@ -138,10 +153,17 @@ export class IngestionSessionReplayMlImageScrubServer extends MlMirrorConsumerSethis.keyManager)await scrubClient.waitUntilReachable()- await consumer.connect((messages) => {- const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)- return batcher.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))- })+ await consumer.connect(+ (messages) => {+ watermark.hold(capturedRecords(messages, scrubbedImageData))+ const heartbeat = setInterval(() => consumer.heartbeat(), BATCH_HEARTBEAT_INTERVAL_MS)+ return batcher.handleBatch(messages, Date.now()).finally(() => clearInterval(heartbeat))+ },+ (partitions) => {+ watermark.forget(partitions)+ return Promise.resolve()+ }+ )this.lifecycle.services.push({id: 'session-replay-ml-image-scrub',diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.tsindex e54f7ca0ac6c..73e86931770c 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts@@ -28,6 +28,7 @@ import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outpuimport { BlackholeSessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer'import { S3SessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer'import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'+import { CaptureWatermark } from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'import { RedisPool } from '~/types'@@ -179,6 +180,7 @@ export class IngestionSessionReplayMlMirrorServer extends MlMirrorConsumerServer// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane// would then fetch a missing key and record cleartext.redisKeyNamespace: 'ml-mirror',+ captureWatermark: new CaptureWatermark('ml_mirror'),}const ingester = new SessionRecordingIngester(diff --git a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.tsindex 4726d5114a2e..de90ab5ac064 100644--- a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts+++ b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts@@ -5,6 +5,11 @@ import { logger } from '~/common/utils/logger'import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'import { MlKeyManager } from '~/ingestion/pipelines/sessionreplay/ml-mirror/keys/runtime'+import {+ CaptureWatermark,+ capturedRecords,+ releasingOffsetStore,+} from '~/ingestion/pipelines/sessionreplay/shared/capture-watermark'import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'import { CleanupResources } from './base-server'@@ -55,9 +60,10 @@ export class IngestionSessionReplayMlParquetSinkServer extends MlMirrorConsumerS)const consumer = new KafkaConsumer(buildSinkConsumerConfig(this.config))+ const watermark = new CaptureWatermark('parquet_sink')const batcher = new BlockMetadataBatcher(store,- consumer,+ releasingOffsetStore(consumer, watermark),{flushIntervalMs: this.config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS,maxRows: this.config.SESSION_RECORDING_ML_PARQUET_MAX_ROWS,@@ -65,10 +71,17 @@ export class IngestionSessionReplayMlParquetSinkServer extends MlMirrorConsumerSDate.now(),this.keyManager?.kafka)- await consumer.connect((messages) => {- consumer.heartbeat()- return batcher.handleBatch(messages, Date.now())- })+ await consumer.connect(+ (messages) => {+ consumer.heartbeat()+ watermark.hold(capturedRecords(messages, () => 'event_metadata'))+ return batcher.handleBatch(messages, Date.now())+ },+ (partitions) => {+ watermark.forget(partitions)+ return Promise.resolve()+ }+ )this.lifecycle.services.push({id: 'session-replay-ml-parquet-sink',