: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): count ml records by wire format version (#100998)
Robbieaa15924458f1
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.tsindex a26c944d5bff..5d68bea11f38 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@@ -1,5 +1,7 @@import { Counter, Gauge, Histogram } from 'prom-client'+import type { MlWireVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'+import type { RepublishReason, UrlDropReason, UrlSkipReason } from './collected-urls-record'import type { AttemptOutcome } from './fetch-runner'import type { FrontierDeadLetterReason } from './frontier-dead-letter-sink'@@ -31,6 +33,11 @@ type PolicyAndBudgetReason = FetchRefusalReason | RequestScheduleBlockReason | 'const BATCH_DIVERSITY_TOP_COUNTS = [1, 5, 10] as constexport class ImageFetchConsumerMetrics {+ private static readonly wireVersion = new Counter({+ name: 'ml_image_fetch_consumer_version_total',+ help: 'Frontier records accepted by wire format version, counted before parsing. Version 2 arrived as an encrypted envelope this consumer decrypted, version 1 as cleartext. The mirror stamps the version, so this is the consumer-side view of its switchover and the two rates should track each other across a deploy',+ labelNames: ['version'],+ })private static readonly fetchable = new Counter({name: 'ml_image_fetch_consumer_fetchable_total',help: 'URLs that passed every check and would have been fetched. In dry run no request is sent, so this is the offered rate rather than the sent rate',@@ -165,6 +172,12 @@ export class ImageFetchConsumerMetrics {help: '1 while the lane sends no outbound request, 0 once fetching is enabled. Every other metric of this lane means something different either side of this value',})+ public static incrementVersion(version: MlWireVersion, count: number): void {+ if (count > 0) {+ this.wireVersion.labels(version).inc(count)+ }+ }+public static setDryRun(enabled: boolean): void {this.dryRun.set(enabled ? 1 : 0)}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.tsindex 4fcba989d554..8603f0e87ee4 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@@ -85,6 +85,10 @@ export class UrlFetchConsumer {}return { message, original: message, key: undefined, invalid: undefined }})+ const decodedValid = decoded.filter((entry) => !entry.invalid)+ const encrypted = decodedValid.filter((entry) => entry.key).length+ ImageFetchConsumerMetrics.incrementVersion('2', encrypted)+ ImageFetchConsumerMetrics.incrementVersion('1', decodedValid.length - encrypted)const startedAt = process.hrtime.bigint()const republishDeadlineAtMonotonicMs = performance.now() + REPUBLISH_DEADLINE_FROM_BATCH_START_MSconst drops = new Map<UrlDropReason, number>()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 f5be849ae434..70937eabdd2c 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@@ -98,6 +98,7 @@ describe('ImageBatcher', () => {read: jest.fn().mockResolvedValue(new Map()),} as unknown as MlKeyReader),} as MlPrivacyRuntime+ const incrementVersion = jest.spyOn(ImageScrubConsumerMetrics, 'incrementVersion')const batcher = new ImageBatcher(store as unknown as ImageShardStore,offsets,@@ -114,6 +115,11 @@ describe('ImageBatcher', () => {await jest.advanceTimersByTimeAsync(0)expect(park).toHaveBeenCalledTimes(1)expect(offsets.received).toEqual([])+ // Neither bucket moves: a decryption outage must not read as a rollback to version 1.+ expect(incrementVersion.mock.calls).toEqual([+ ['2', 0],+ ['1', 0],+ ])if (stop) {batcher.stop()} else {@@ -193,6 +199,24 @@ describe('ImageBatcher', () => {expect(store.writes[0][0].hash).toBe(ref.split(':')[2])})+ it('counts a cleartext image as version 1', async () => {+ const incrementVersion = jest.spyOn(ImageScrubConsumerMetrics, 'incrementVersion')+ const batcher = new ImageBatcher(+ new FakeStore() as unknown as ImageShardStore,+ new FakeOffsets(),+ scrubClient,+ options,+ 0+ )++ await batcher.handleBatch([msg(0, 0, pt(1), Buffer.from('a'))], 1)++ expect(incrementVersion.mock.calls).toEqual([+ ['2', 0],+ ['1', 1],+ ])+ })+it('decodes and validates a URL image from its Kafka transport headers before scrubbing it', async () => {const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])const received: Buffer[] = []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 5176a921799a..29a7dfb2aa08 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@@ -227,8 +227,12 @@ export class ImageBatcher {if (ingestionVersion(message) === 2) {throw new Error('ML v2 images require privacy configuration')}- return { message, original: message, invalid: undefined }+ return { message, original: message, key: undefined, invalid: undefined }})+ const decodedValid = decoded.filter((entry) => !entry.invalid)+ const encrypted = decodedValid.filter((entry) => entry.key).length+ ImageScrubConsumerMetrics.incrementVersion('2', encrypted)+ ImageScrubConsumerMetrics.incrementVersion('1', decodedValid.length - encrypted)for (const entry of decoded.filter((entry) => entry.invalid)) {if (!this.deadLetters) {throw new Error('Invalid encrypted ML image requires a dead-letter destination')diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.tsindex 46755b6e4b45..f4774042c86c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/metrics.ts@@ -1,5 +1,7 @@import { Counter, Gauge, Histogram } from 'prom-client'+import type { MlWireVersion } from '~/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema'+import { type ImageTransportRejectionReason } from './image-transport'import { ScrubWaitReason } from './scrub-client'@@ -7,6 +9,11 @@ export type ImageScrubSkipReason = ImageTransportRejectionReason | 'sidecar_rejeexport type ImageScrubSource = 'inline' | 'url'export class ImageScrubConsumerMetrics {+ private static readonly wireVersion = new Counter({+ name: 'ml_mirror_image_scrub_consumer_version_total',+ help: 'Images accepted by wire format version, counted before scrubbing. Version 2 arrived as an encrypted envelope this consumer decrypted, version 1 as cleartext. The mirror stamps the version, so this is the consumer-side view of its switchover and the two rates should track each other across a deploy',+ labelNames: ['version'],+ })private static readonly scrubbed = new Counter({name: 'ml_mirror_image_scrub_consumer_scrubbed_total',help: 'Images scrubbed by the sidecar and buffered for a shard write',@@ -209,6 +216,12 @@ export class ImageScrubConsumerMetrics {public static incInvalidKey(): void {this.invalidKey.inc()}+ public static incrementVersion(version: MlWireVersion, count: number): void {+ if (count > 0) {+ this.wireVersion.labels(version).inc(count)+ }+ }+public static observeBatchMessages(count: number): void {this.batchMessages.observe(count)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex f60b2d7210d7..ac1d5be04225 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -1,5 +1,9 @@import { Counter, Histogram } from 'prom-client'+import { MlWireVersion } from './privacy/schema'++export type MlProducedLane = 'image' | 'url' | 'metadata'+/** Which anonymizer produced the output; the label makes the flag rollout a direct A/B. */export type MlAnonymizeImpl = 'rust' | 'ts'/** Rust engine that produced the output (tree = the parse fallback fired). `''` when not applicable. */@@ -50,6 +54,12 @@ export class MlMirrorMetrics {labelNames: ['outcome'],})+ private static readonly mlProducedVersion = new Counter({+ name: 'recording_blob_ingestion_v2_ml_produced_version_total',+ help: 'Kafka records the mirror delivered, by lane and wire format version, counted on the delivery ack. Version 2 is encrypted per session and version 1 is cleartext, so the split across a deploy is how far the encryption switchover has reached. The consumer counters count records too, so the two rates compare directly. A lane stuck on version 1 means the session key never resolved, which no other mirror metric distinguishes from ordinary traffic',+ labelNames: ['lane', 'version'],+ })+private static readonly mlImageReferencesByProperty = new Counter({name: 'recording_blob_ingestion_v2_ml_image_references_by_property',help: 'Collected CSS and HTML image ref occurrences by bounded source, property, and lane. Counts references before per-message content or URL deduplication',@@ -136,6 +146,12 @@ export class MlMirrorMetrics {this.mlImagesCollected.labels(outcome).inc(count)}+ public static incrementMlProducedVersion(lane: MlProducedLane, version: MlWireVersion, count: number): void {+ if (count > 0) {+ this.mlProducedVersion.labels(lane, version).inc(count)+ }+ }+public static incrementMlImageReferencesByProperty(source: MlImageSource,property: string,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 d5dac7ec28d8..a59c3814f66a 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@@ -4,9 +4,10 @@ import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/sharedimport { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'import { toBlockMetadataRow } from './block-metadata-row'+import { MlMirrorMetrics } from './metrics'import { MlKeyReader } from './privacy/reader'-import { sessionKeyId, tableKeyString } from './privacy/schema'-import { encryptedKafkaValue } from './privacy/transport'+import { MlWireVersion, sessionKeyId, tableKeyString } from './privacy/schema'+import { encryptedKafkaValue, mlWireVersion } from './privacy/transport'import { usesRawSessionIdentifiers } from './session-identifier-format'export class MlBlockMetadataSink implements SessionMetadataSink {@@ -26,14 +27,20 @@ export class MlBlockMetadataSink implements SessionMetadataSink {const keys =(await this.privacy?.read(currentBlocks.map((block) => sessionKeyId(block.teamId, block.sessionId)))) ??new Map()+ const producedByVersion = new Map<MlWireVersion, number>()const messages = blocks.flatMap((block) => {const row = toBlockMetadataRow(block, this.pseudonymSecret)const key = keys.get(tableKeyString(sessionKeyId(block.teamId, block.sessionId)))if (!row || (usesRawSessionIdentifiers(block.sessionId) && !key)) {return []}+ const version = mlWireVersion(key)+ producedByVersion.set(version, (producedByVersion.get(version) ?? 0) + 1)return [{ key: row.session_id, ...encryptedKafkaValue(key, 'metadata', Buffer.from(JSON.stringify(row))) }]})await this.outputs.queueMessages(ML_BLOCK_METADATA_OUTPUT, messages)+ for (const [version, count] of producedByVersion) {+ MlMirrorMetrics.incrementMlProducedVersion('metadata', version, count)+ }}}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.tsindex a51d2459816f..a7c0e20f11bb 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/schema.ts@@ -5,6 +5,9 @@ import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirrorexport const ML_KEY_SHARDS = 32export const INGESTION_VERSION_HEADER = 'ai_research_ingestion_version'+/** Value of {@link INGESTION_VERSION_HEADER}: '2' carries an encrypted envelope, '1' carries cleartext. */+export type MlWireVersion = '1' | '2'+export interface MlSessionIdentity {teamId: numberorganizationId: stringdiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.tsindex 106eec810174..f088603b6270 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/privacy/transport.ts@@ -7,7 +7,7 @@ import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirrorimport { MlDataKey, MlEncryptedEnvelope, MlKeyReadExpiredError, decryptEnvelope, encryptEnvelope } from './crypto'import { MlKeyReader } from './reader'-import { INGESTION_VERSION_HEADER, sessionKeyId, tableKeyString } from './schema'+import { INGESTION_VERSION_HEADER, MlWireVersion, sessionKeyId, tableKeyString } from './schema'export interface MlDecodedMessage {message: Message@@ -27,6 +27,11 @@ export function ingestionVersion(message: Pick<Message, 'headers'>): 1 | 2 {throw new Error('Unsupported ML ingestion version')}+/** Only an encrypted record carries a key, so the key decides the version every producer stamps. */+export function mlWireVersion(key: MlDataKey | undefined): MlWireVersion {+ return key ? '2' : '1'+}+export function encryptedKafkaValue(key: MlDataKey | undefined,kind: string,@@ -37,10 +42,10 @@ export function encryptedKafkaValue(? {value: encryptEnvelope(key, kind, value, ref),headers: {- [INGESTION_VERSION_HEADER]: '2',+ [INGESTION_VERSION_HEADER]: mlWireVersion(key),},}- : { value, headers: { [INGESTION_VERSION_HEADER]: '1' } }+ : { value, headers: { [INGESTION_VERSION_HEADER]: mlWireVersion(key) } }}export function validateImageOwner(ref: string, key: MlDataKey | undefined): void {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 c3fb992b3696..1e8284c6a872 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@@ -3,6 +3,7 @@ import { PipelineResultType } from '~/ingestion/framework/results'import { CAPTURE_TIMESTAMP_HEADER } from '~/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub/image-transport'import { MlImageScrubOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'+import { MlMirrorMetrics } from './metrics'import { CollectedImage } from './parse-and-anonymize-step'import { createProduceCollectedImagesStep } from './produce-collected-images-step'@@ -123,6 +124,23 @@ describe('produceCollectedImagesStep', () => {expect(result.type).toBe(PipelineResultType.OK)})+ it.each([+ ['delivered', false, 1],+ ['failed', true, 0],+ ])('counts the wire version of a %s produce', async (_outcome, rejects, expected) => {+ if (rejects) {+ queueMessages.mockRejectedValueOnce(new Error('broker down'))+ }+ const incrementVersion = jest.spyOn(MlMirrorMetrics, 'incrementMlProducedVersion')+ try {+ const step = createProduceCollectedImagesStep(outputs)+ await run(step, { collectedImages: [image('image:aa:h1')], message: { timestamp: CAPTURED_AT } })+ expect(incrementVersion).toHaveBeenCalledTimes(expected)+ } finally {+ incrementVersion.mockRestore()+ }+ })+it('un-marks refs whose produce failed so a recurring image re-produces naturally', async () => {queueMessages.mockRejectedValueOnce(new Error('broker down'))const step = createProduceCollectedImagesStep(outputs)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 d6b0c2d54500..5ef6091af2eb 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@@ -9,7 +9,7 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-deimport { MlMirrorMetrics } from './metrics'import { CollectedImage } from './parse-and-anonymize-step'import { MlPrivacyBatchController } from './privacy/batch-controller'-import { encryptedKafkaValue, validateImageOwner } from './privacy/transport'+import { encryptedKafkaValue, mlWireVersion, validateImageOwner } from './privacy/transport'import { usesRawSessionIdentifiers } from './session-identifier-format'/**@@ -90,6 +90,7 @@ export function createProduceCollectedImagesStep<.then(() => {// queueMessages resolves on delivery acks, so `produced` counts what actually landed.MlMirrorMetrics.incrementMlImagesCollected('produced', refs.length)+ MlMirrorMetrics.incrementMlProducedVersion('image', mlWireVersion(key), refs.length)MlMirrorMetrics.incrementMlImageBytesProduced(bytes)}).catch((error) => {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 1cdca6773b7c..ba0153b55e45 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@@ -13,7 +13,7 @@ import { RefDedupCache } from '~/ingestion/pipelines/sessionreplay/shared/ref-deimport { MlMirrorMetrics } from './metrics'import { CollectedUrl } from './parse-and-anonymize-step'import { MlPrivacyBatchController } from './privacy/batch-controller'-import { encryptedKafkaValue, validateImageOwner } from './privacy/transport'+import { encryptedKafkaValue, mlWireVersion, validateImageOwner } from './privacy/transport'import { usesRawSessionIdentifiers } from './session-identifier-format'/**@@ -283,6 +283,8 @@ export function createProduceCollectedUrlsStep<}))+ // The fetch consumer counts records, so the producer counts records too and the two rates compare.+ const recordCount = messages.length// The failure handler captures only the cache keys, so that a produce which is not yet// delivered does not hold the URL strings alive longer than the messages themselves.const producedCacheKeys = publishable.map(({ cacheKey }) => cacheKey)@@ -291,6 +293,7 @@ export function createProduceCollectedUrlsStep<.then(() => {// queueMessages resolves on the delivery acks, so `produced` counts what landed.MlMirrorMetrics.incrementMlUrlsCollected('produced', producedCacheKeys.length)+ MlMirrorMetrics.incrementMlProducedVersion('url', mlWireVersion(key), recordCount)for (const [registrableDomain, jobs] of byDomain) {producedUrlsByRegistrableDomain.record({ registrable_domain: registrableDomain }, jobs.length)}