Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(ai-research): keep recording under the organization a stored ML key names instead of crashing the lane (#101660)

Robbiea606ba5ddfac
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
index cd3b22222209..ed24ccff0d38 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.test.ts
@@ -4,7 +4,7 @@ import {
DynamoDBClient,
PutItemCommand,
} from '@aws-sdk/client-dynamodb'
-import { GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
+import { DecryptCommand, GenerateDataKeyCommand, KMSClient } from '@aws-sdk/client-kms'
import { S3Client } from '@aws-sdk/client-s3'
import { Message } from 'node-rdkafka'
import { register } from 'prom-client'
@@ -77,20 +77,20 @@ describe('ML session key batches', () => {
let store: MlSessionKeyStore
let reader: MlKeyReader
let generated: number
+ let kmsSend: jest.Mock
beforeEach(() => {
boundary = new DynamoBoundary()
generated = 0
+ kmsSend = jest.fn((command) => {
+ if (command instanceof GenerateDataKeyCommand) {
+ const bytes = Buffer.alloc(32, ++generated)
+ return Promise.resolve({ Plaintext: bytes, CiphertextBlob: bytes })
+ }
+ return Promise.resolve({ Plaintext: command.input.CiphertextBlob })
+ })
encryption = new MlKeyEncryption(
- {
- send: jest.fn((command) => {
- if (command instanceof GenerateDataKeyCommand) {
- const bytes = Buffer.alloc(32, ++generated)
- return Promise.resolve({ Plaintext: bytes, CiphertextBlob: bytes })
- }
- return Promise.resolve({ Plaintext: command.input.CiphertextBlob })
- }),
- } as unknown as KMSClient,
+ { send: kmsSend } as unknown as KMSClient,
'test-key',
1000,
60000,
@@ -290,6 +290,37 @@ describe('ML session key batches', () => {
expect((await reader.read(locations)).size).toBe(0)
})
+ it('keeps using a key whose row names the organization the team used to belong to', async () => {
+ const first = await store.prepare([session])
+ await first.commit()
+ const location = tableKeyString(sessionKeyId(session.teamId, session.sessionId))
+ const stored = boundary.items.get(location)!
+ const moved = { ...session, organizationId: 'organization-new' }
+ encryption.clear()
+ const next = await store.prepare([moved])
+ const keys = next.get(moved.teamId, moved.sessionId)!
+ expect(keys.session.wrapped).toEqual(Buffer.from(stored.wrapped_key!.B!))
+ expect(keys.session.identity.organizationId).toBe(session.organizationId)
+ const unwrap = kmsSend.mock.calls
+ .map(([command]) => command)
+ .find((command) => command instanceof DecryptCommand)
+ expect(unwrap?.input.EncryptionContext?.organization_id).toBe(session.organizationId)
+ await next.commit()
+ expect(boundary.items.get(location)).toEqual(stored)
+ })
+
+ it('drops the sessions behind a stored key that has no wrapped key and no tombstone', async () => {
+ const first = await store.prepare([session])
+ await first.commit()
+ const location = tableKeyString(sessionKeyId(session.teamId, session.sessionId))
+ const { wrapped_key: _wrapped, ...stored } = boundary.items.get(location)!
+ boundary.items.set(location, stored)
+ const next = await store.prepare([session])
+ expect(next.get(session.teamId, session.sessionId)).toBeUndefined()
+ await next.commit()
+ expect(boundary.items.get(location)).toEqual(stored)
+ })
+
it('adopts a competing writer key', async () => {
const first = await store.prepare([session])
const second = await store.prepare([session])
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
index fbc4e21332de..f9335f5b14d3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/key-store.ts
@@ -1,4 +1,5 @@
import { logger } from '~/common/utils/logger'
+import { MlMirrorMetrics } from '~/ingestion/pipelines/sessionreplay/ml-mirror/metrics'
import { sessionStartMonth } from '~/ingestion/pipelines/sessionreplay/ml-mirror/session-identifier-format'
import { MlDataKey, MlKeyEncryption } from './crypto'
@@ -56,6 +57,13 @@ export interface MlSessionKeys {
image: MlDataKey
}
+interface MlStoredKeyMismatch {
+ id: string
+ teamId: number
+ expectedOrganizationId: string
+ storedOrganizationId?: string
+}
+
function storedKeyId(identity: MlKeyIdentity): TableKey {
return identity.sessionId
? sessionKeyId(identity.teamId, identity.sessionId)
@@ -124,6 +132,8 @@ export class MlKeyBatch {
for (const [id, item] of await this.db.read(remaining, deadline)) {
this.state.set(id, item)
}
+ const unusable: MlStoredKeyMismatch[] = []
+ const rehomed: MlStoredKeyMismatch[] = []
await Promise.all(
[...keyIdentities].map(async ([id, identity]) => {
const item = this.state.get(id)
@@ -131,10 +141,27 @@ export class MlKeyBatch {
return
}
if (item) {
- if (!item.wrapped_key?.B || item.organization_id?.S !== identity.organizationId) {
- throw new Error('Invalid stored ML key identity')
+ const storedOrganizationId = item.organization_id?.S
+ if (!item.wrapped_key?.B || !storedOrganizationId) {
+ unusable.push({
+ id,
+ teamId: identity.teamId,
+ expectedOrganizationId: identity.organizationId,
+ storedOrganizationId,
+ })
+ return
}
- this.keys.set(id, await this.encryption.decrypt(identity, Buffer.from(item.wrapped_key.B)))
+ // The key was wrapped under the organization the row names, and KMS only unwraps it under that same context, so a team that moved organizations keeps its key under the old one.
+ if (storedOrganizationId !== identity.organizationId) {
+ rehomed.push({
+ id,
+ teamId: identity.teamId,
+ expectedOrganizationId: identity.organizationId,
+ storedOrganizationId,
+ })
+ }
+ const storedIdentity = { ...identity, organizationId: storedOrganizationId }
+ this.keys.set(id, await this.encryption.decrypt(storedIdentity, Buffer.from(item.wrapped_key.B)))
} else {
let candidate = this.candidates.get(id)
if (!candidate) {
@@ -145,6 +172,23 @@ export class MlKeyBatch {
}
})
)
+ if (rehomed.length) {
+ MlMirrorMetrics.incrementMlKeyIdentityMismatch('organization_changed', rehomed.length)
+ logger.warn('🔑', 'ml_key_organization_changed', {
+ count: rehomed.length,
+ teamIds: [...new Set(rehomed.map((entry) => entry.teamId))].slice(0, 20),
+ sample: rehomed.slice(0, 5),
+ })
+ }
+ // A row with no wrapped key and no tombstone cannot serve this batch; its sessions are dropped like blocked ones so one bad row cannot stop the lane, and the log names it so the data can be repaired.
+ if (unusable.length) {
+ MlMirrorMetrics.incrementMlKeyIdentityMismatch('wrapped_key_missing', unusable.length)
+ logger.error('🔑', 'ml_key_stored_key_unusable', {
+ count: unusable.length,
+ teamIds: [...new Set(unusable.map((entry) => entry.teamId))].slice(0, 20),
+ sample: unusable.slice(0, 5),
+ })
+ }
}
public get(teamId: number, sessionId: string): MlSessionKeys | undefined {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
index 74b1d6f6df4a..31647d8ce8b9 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts
@@ -19,6 +19,7 @@ export type MlUrlCrawlHistoryOutcome = 'fresh' | 'miss' | 'error'
export type MlImageSource = 'css' | 'html'
/** Phases of the ML key work around one Kafka batch: the key bulk read before processing, the key writes and re-read after it, and the deferred publications. */
export type MlKeyPhase = 'prepare' | 'commit' | 'publish'
+export type MlKeyIdentityMismatchReason = 'organization_changed' | 'wrapped_key_missing'
export type MlKeyRequest =
| 'kms_generate'
| 'kms_decrypt'
@@ -67,6 +68,11 @@ export class MlMirrorMetrics {
name: 'recording_blob_ingestion_v2_ml_legacy_envelopes_dropped_total',
help: 'Kafka records still in the sealed envelope shape the ML lanes wrote before they switched to cleartext records. The consumers drop them without dead-lettering, so this counter is the only trace of the backlog draining; once it stays at zero after a rollout, nothing else reads that shape',
})
+ private static readonly mlKeyIdentityMismatch = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_key_identity_mismatch_total',
+ help: 'Stored ML keys whose row disagrees with the team. organization_changed: the row names another organization than the team has now, and the key is unwrapped under the one the row names (ml_key_organization_changed log). wrapped_key_missing: the row has no wrapped key and no tombstone, and its sessions are dropped (ml_key_stored_key_unusable log)',
+ labelNames: ['reason'],
+ })
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',
@@ -179,6 +185,10 @@ export class MlMirrorMetrics {
this.mlImagesCollected.labels(outcome).inc(count)
}
+ public static incrementMlKeyIdentityMismatch(reason: MlKeyIdentityMismatchReason, count: number): void {
+ this.mlKeyIdentityMismatch.labels(reason).inc(count)
+ }
+
public static incrementMlLegacyEnvelopesDropped(count: number): void {
if (count > 0) {
this.mlLegacyEnvelopesDropped.inc(count)