: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
fix(ml-mirror): store keys only for sessions a message is written under (#116917)
Nicholas Waltz876064d5c025
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.tsindex dc9379fe4b1f..445594234a30 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/batch-handle.ts@@ -10,6 +10,7 @@ import { PartitionOwnership } from '~/ingestion/pipelines/sessionreplay/staged-bimport { MlKeyBatchController } from './keys/batch-controller'import { MlKeyBatch, MlSessionKeys } from './keys/key-store'+import { MlSessionIdentity } from './keys/schema'import { MlMirrorMetrics } from './metrics'export interface MlDeferrableInput {@@ -37,6 +38,7 @@ type DeferredAction = (export class MlBatchHandle {public keys?: MlKeyBatchprivate deferred: DeferredAction[] = []+ private deferredSessions: MlSessionIdentity[] = []private readonly publish = pLimit(8)constructor(private readonly keyManager?: MlKeyBatchController) {}@@ -46,6 +48,7 @@ export class MlBatchHandle {action: (input: T & SessionBatchContext) => Promise<PipelineResult<unknown>>,recordsMessage = false): Promise<PipelineResult<T>> {+ this.deferredSessions.push({ teamId: input.team.teamId, sessionId: input.headers.session_id })this.deferred.push(async (recorder, sideEffects, isAssigned) => {if (!isAssigned(input.message.partition)) {return null@@ -75,7 +78,8 @@ export class MlBatchHandle {isAssigned: PartitionOwnership = () => true): Promise<Message[]> {if (this.keys && this.keyManager) {- await this.keyManager.commit(this.keys)+ // Only messages that survived the batch deferred anything, so a session every message of was dropped stores no key.+ await this.keyManager.commit(this.keys, this.deferredSessions)}const startedAt = performance.now()const sideEffects: SideEffectSink = async (promises) => {@@ -92,6 +96,7 @@ export class MlBatchHandle {}const actions = this.deferredthis.deferred = []+ this.deferredSessions = []if (!actions.length) {return []}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.tsindex 36bab5d7654c..0cfdec656d20 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/keys/batch-controller.ts@@ -56,9 +56,9 @@ export class MlKeyBatchController implements KeyStore, RecordingEncryptor {return batch}- public async commit(batch: MlKeyBatch): Promise<void> {+ public async commit(batch: MlKeyBatch, used?: Iterable<MlSessionIdentity>): Promise<void> {const startedAt = performance.now()- await batch.commit()+ await batch.commit(used)MlMirrorMetrics.observeMlKeyPhase('commit', performance.now() - startedAt)}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.tsindex ddecaf730085..25c4c451c8d8 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@@ -191,6 +191,23 @@ describe('ML session key batches', () => {}})+ it.each([+ ['the used session and both month keys', true, 6],+ ['both month keys only', false, 4],+ ])('stores only keys of used sessions: %s', async (_case, sessionUsed, stored) => {+ const unused = { ...session, sessionId: '01a0a4f0-3200-7000-8000-0000000000ff' }+ const batch = await store.prepare([session, unused])+ await batch.commit(sessionUsed ? [session] : [])+ expect(boundary.items.size).toBe(stored)+ const readBack = await reader.read([+ sessionKeyId(session.teamId, session.sessionId),+ sessionKeyId(unused.teamId, unused.sessionId),+ ])+ expect(readBack.size).toBe(sessionUsed ? 1 : 0)+ expect(batch.get(unused.teamId, unused.sessionId)).toBeUndefined()+ expect(batch.get(session.teamId, session.sessionId) !== undefined).toBe(sessionUsed)+ })+it('writes one request per key instead of two by batching the month index entries', async () => {const identities = Array.from({ length: 60 }, (_, index) => ({...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.tsindex 05038869e02f..62a7cfd235b1 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@@ -70,6 +70,9 @@ export class MlKeyBatch {private readonly candidates = new Map<string, MlDataKey>()private readonly keys = new Map<string, MlDataKey>()private committed = false+ // Undefined stores every new session key. Otherwise only new keys for these sessions are stored. Month keys are always+ // stored: one is a single row per team month, and leaving it out would have the next batch generate it again through KMS.+ private used?: Set<string>// persist re-reads the batch after its writes and on every retry, so a row is reported the first time this batch meets it and not on each pass.private readonly reportedUnusable = new Set<string>()@@ -208,7 +211,9 @@ export class MlKeyBatch {// The index entry goes first and is idempotent, so every stored key has an index entry even when the key put fails or a retried put reports the batch's own write as a competitor's. An index entry without a key is harmless: the month sweep leaves a tombstone that a later key put respects.private async persist(deadline: AbortSignal): Promise<void> {- const unstored = [...this.keys].filter(([id]) => !this.state.has(id))+ const unstored = [...this.keys].filter(+ ([id, key]) => !this.state.has(id) && (!key.identity.sessionId || !this.used || this.used.has(id))+ )// The month key commits first. A put that loses leaves session keys sealed under bytes that nobody stored.const monthKeys = unstored.filter(([, key]) => !key.identity.sessionId)if (monthKeys.length) {@@ -318,16 +323,36 @@ export class MlKeyBatch {return { sealed_key: { B: sealed.sealed }, key_nonce: { B: sealed.nonce }, ...shared }}- public async commit(): Promise<void> {+ /** `used` names the sessions a published message will be written under; a key no message uses is not stored. */+ /** A candidate that was never stored must not reach a caller, so nothing can be sealed under it. */+ private forgetUnusedSessionKeys(): void {+ const used = this.used+ if (!used) {+ return+ }+ for (const [id, key] of this.keys) {+ if (key.identity.sessionId && !used.has(id)) {+ this.keys.delete(id)+ }+ }+ }++ public async commit(used?: Iterable<MlSessionIdentity>): Promise<void> {if (this.committed) {throw new Error('ML batch already committed')}+ if (used) {+ this.used = new Set(+ [...used].map((identity) => tableKeyString(sessionKeyId(identity.teamId, identity.sessionId)))+ )+ }const startedAt = Date.now()const deadline = AbortSignal.timeout(COMMIT_BUDGET_MS)for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt++) {try {await this.persist(deadline)this.committed = true+ this.forgetUnusedSessionKeys()return} catch (error) {const delayMs = commitRetryDelayMs(attempt)