: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): add v4 team month keys to node (#117980)
Nicholas Waltz604203120396
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/canonical-json.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/canonical-json.tsnew file mode 100644index 000000000000..5379d208ba6f--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/canonical-json.ts@@ -0,0 +1,15 @@+/** Both readers rebuild this byte for byte, so key order is sorted and there is no whitespace. */+export function canonicalJson(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map(canonicalJson).join(',')}]`+ }+ if (value && typeof value === 'object') {+ // An absent field is left out, as in the Rust context, so `{ ref: undefined }` matches `{}`.+ return `{${Object.keys(value)+ .filter((k) => (value as Record<string, unknown>)[k] !== undefined)+ .sort()+ .map((k) => `${JSON.stringify(k)}:${canonicalJson((value as Record<string, unknown>)[k])}`)+ .join(',')}}`+ }+ return JSON.stringify(value)+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/frame.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/frame.tsnew file mode 100644index 000000000000..64b89031407c--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/frame.ts@@ -0,0 +1,38 @@+import { createCipheriv, randomBytes } from 'node:crypto'++import { canonicalJson } from './canonical-json'++/** The owner and kind of a v4 object. Field names are the ones the v3 frame uses, plus `keyMonth`. */+export interface V4FrameContext {+ teamId: number+ keyMonth: string+ sessionId?: string+ kind: string+ codec: 'none' | 'brotli' | 'zstd'+ ref?: string+}++const MAGIC = Buffer.from('AISR03')+const NONCE_BYTES = 12++/**+ * The v3 AISR03 frame with `"v": 4` in the authenticated data, so a v3 reader never opens a v4 object. The format is+ * in `products/ai_training/docs/replay-data.md`, section "v4 dataset".+ */+export function sealV4Frame(+ key: Buffer,+ context: V4FrameContext,+ body: Buffer,+ nonce = randomBytes(NONCE_BYTES)+): Buffer {+ const aad = Buffer.from(canonicalJson({ v: 4, context }))+ if (aad.length > 0xffff) {+ throw new Error('v4 frame context is too long to frame')+ }+ const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 })+ cipher.setAAD(aad)+ const sealed = Buffer.concat([cipher.update(body), cipher.final(), cipher.getAuthTag()])+ const length = Buffer.alloc(2)+ length.writeUInt16BE(aad.length)+ return Buffer.concat([MAGIC, length, aad, nonce, sealed])+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys.tsnew file mode 100644index 000000000000..ddfd29d57b60--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/team-month-keys.ts@@ -0,0 +1,183 @@+import { AttributeValue, DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'+import { DecryptCommand, KMSClient } from '@aws-sdk/client-kms'+import { LRUCache } from 'lru-cache'+import { setTimeout as sleep } from 'node:timers/promises'+import pLimit from 'p-limit'++const KMS_TIMEOUT_MS = 5000+const DYNAMODB_TIMEOUT_MS = 5000+/** Bounds one lookup with its retries, well inside Kafka's max.poll.interval.ms of 300s, as the v3 read budget does. */+const READ_BUDGET_MS = 30_000+const KMS_CONCURRENCY = 8+/** A tombstone written after this is seen within this time, as the v3 row cache bounds it. */+const CACHE_LIFETIME_MS = 300_000++type Item = Record<string, AttributeValue>++type PendingRead = { result: Promise<TeamMonthKey>; controller: AbortController; waiters: number }++/**+ * The key rows of a month expire at the start of the month this many months later. A session writes up to about 15+ * days after its key month and its objects live up to 98 days, so this leaves a margin to raise the raw window.+ */+const KEY_LIFETIME_MONTHS = 5++/**+ * A team's key for one UTC month. `missing` means no row: the recorder stores the row before it sends a URL, so the row+ * expired or was removed. `deleted` is a tombstone. In both cases the caller stores nothing.+ */+export type TeamMonthKey = { status: 'ok'; key: Buffer } | { status: 'missing' } | { status: 'deleted' }++/** The KMS encryption context of a team month key. The Rust recorder and the key policy use the same one. */+export function teamMonthWrappingContext(teamId: number, keyMonth: string): Record<string, string> {+ return { key_month: keyMonth, purpose: 'ai-research-v4', team_id: String(teamId) }+}++export function teamMonthRowKey(teamId: number, keyMonth: string): Item {+ return { pk: { S: `team:${teamId}` }, sk: { S: `month:${keyMonth}` } }+}++/** The `expires_at` of the key rows of `keyMonth` (`YYYY-MM`), in milliseconds. The Rust recorder writes the same value. */+export function teamMonthKeyExpiresAtMs(keyMonth: string): number {+ const [year, month] = keyMonth.split('-').map(Number)+ return Date.UTC(year, month - 1 + KEY_LIFETIME_MONTHS, 1)+}++/**+ * Reads the v4 team month keys in `ai-research-replay-v4-keys`. Only the recorder writes this table, so this class+ * never stores a key, and the caller drops an image whose team and month have no key.+ */+export class TeamMonthKeys {+ private readonly cache = new LRUCache<string, TeamMonthKey>({ max: 10_000, ttl: CACHE_LIFETIME_MS })+ private readonly pending = new Map<string, PendingRead>()+ private readonly kmsConcurrency = pLimit(KMS_CONCURRENCY)+ private nextKmsRequestAt = 0++ constructor(+ private readonly dynamo: Pick<DynamoDBClient, 'send'>,+ private readonly kms: Pick<KMSClient, 'send'>,+ private readonly tableName: string,+ private readonly kmsKeyArn: string,+ private readonly kmsRequestsPerSecond = 150,+ private readonly readBudgetMs = READ_BUDGET_MS+ ) {+ if (!(kmsRequestsPerSecond > 0)) {+ throw new Error('the v4 KMS request rate must be positive')+ }+ }++ /** `signal` stops this caller's wait. A shared read stops only once every caller that waits on it has stopped. */+ public async get(teamId: number, keyMonth: string, signal?: AbortSignal): Promise<TeamMonthKey> {+ signal?.throwIfAborted()+ const id = `${teamId}:${keyMonth}`+ const cached = this.cache.get(id)+ if (cached) {+ return cached+ }+ // Concurrent requests for one team and month share a read, so a burst of images makes one KMS call.+ let read = this.pending.get(id)+ if (!read) {+ const controller = new AbortController()+ const result = this.resolve(teamId, keyMonth, controller.signal).then((key) => {+ // Only a key row and a tombstone are held, as in the v3 row cache.+ if (key.status !== 'missing') {+ this.cache.set(id, key)+ }+ return key+ })+ const started: PendingRead = { result, controller, waiters: 0 }+ const forget = (): void => {+ if (this.pending.get(id) === started) {+ this.pending.delete(id)+ }+ }+ result.then(forget, forget)+ this.pending.set(id, started)+ read = started+ }+ read.waiters += 1+ try {+ return await (signal ? untilAborted(read.result, signal) : read.result)+ } finally {+ read.waiters -= 1+ if (read.waiters === 0 && signal?.aborted) {+ // A later caller must start a new read, not join one that is about to fail.+ if (this.pending.get(id) === read) {+ this.pending.delete(id)+ }+ read.controller.abort(signal.reason)+ }+ }+ }++ private async resolve(teamId: number, keyMonth: string, abandoned: AbortSignal): Promise<TeamMonthKey> {+ const deadline = AbortSignal.any([AbortSignal.timeout(this.readBudgetMs), abandoned])+ const stored = await this.dynamo.send(+ new GetItemCommand({+ TableName: this.tableName,+ Key: teamMonthRowKey(teamId, keyMonth),+ ConsistentRead: true,+ }),+ { abortSignal: AbortSignal.any([deadline, AbortSignal.timeout(DYNAMODB_TIMEOUT_MS)]) }+ )+ if (!stored.Item) {+ return { status: 'missing' }+ }+ if (stored.Item.deleted?.BOOL === true) {+ return { status: 'deleted' }+ }+ const wrapped = stored.Item.wrapped_key?.B+ if (!wrapped?.length) {+ throw new Error('a v4 team month row has no wrapped key')+ }+ const decrypted = await this.kmsRequest(deadline, (abortSignal) =>+ this.kms.send(+ new DecryptCommand({+ KeyId: this.kmsKeyArn,+ CiphertextBlob: wrapped,+ EncryptionContext: teamMonthWrappingContext(teamId, keyMonth),+ }),+ { abortSignal }+ )+ )+ if (decrypted.Plaintext?.length !== 32) {+ throw new Error('KMS returned an invalid v4 plaintext key')+ }+ return { status: 'ok', key: Buffer.from(decrypted.Plaintext) }+ }++ private async kmsRequest<T>(deadline: AbortSignal, send: (abortSignal: AbortSignal) => Promise<T>): Promise<T> {+ deadline.throwIfAborted()+ const admitted = this.kmsConcurrency(async () => {+ // A waiter whose deadline passed in the queue has already left, so its turn makes no KMS call.+ deadline.throwIfAborted()+ const now = Date.now()+ const scheduledAt = Math.max(now, this.nextKmsRequestAt)+ this.nextKmsRequestAt = scheduledAt + 1000 / this.kmsRequestsPerSecond+ if (scheduledAt > now) {+ await sleep(scheduledAt - now, undefined, { signal: deadline })+ }+ return await send(AbortSignal.any([deadline, AbortSignal.timeout(KMS_TIMEOUT_MS)]))+ })+ // The read budget also bounds the wait for a KMS turn and for the rate limit.+ return await untilAborted(admitted, deadline)+ }+}++/** Rejects with the signal's reason once it aborts, and leaves `work` to settle on its own. */+export async function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {+ let onAbort!: () => void+ const aborted = new Promise<never>((_resolve, reject) => {+ onAbort = () => reject(signal.reason)+ if (signal.aborted) {+ onAbort()+ } else {+ signal.addEventListener('abort', onAbort, { once: true })+ }+ })+ try {+ return await Promise.race([work, aborted])+ } finally {+ signal.removeEventListener('abort', onAbort)+ }+}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/v4-keys.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/v4-keys.test.tsnew file mode 100644index 000000000000..02929c0cb3f5--- /dev/null+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-research/v4-keys/v4-keys.test.ts@@ -0,0 +1,137 @@+import { GetItemCommand } from '@aws-sdk/client-dynamodb'+import { DecryptCommand } from '@aws-sdk/client-kms'++import vector from '~/ingestion/pipelines/sessionreplay/ai-research/v4-keys/encryption-vector-v4.json'++import { V4FrameContext, sealV4Frame } from './frame'+import { TeamMonthKeys, teamMonthKeyExpiresAtMs, teamMonthWrappingContext } from './team-month-keys'++const base64 = (value: string): Buffer => Buffer.from(value, 'base64')++describe('v4 keys', () => {+ it.each([+ [+ 'an inline image under the team month key',+ vector.teamMonthKey,+ vector.image.context,+ vector.image.bytes,+ vector.image.nonce,+ vector.image.frame,+ ],+ [+ 'a fetched image under the team month key',+ vector.teamMonthKey,+ vector.imageUrl.context,+ vector.imageUrl.bytes,+ vector.imageUrl.nonce,+ vector.imageUrl.frame,+ ],+ [+ 'a fetched image whose context sets its absent fields to undefined',+ vector.teamMonthKey,+ { ...vector.imageUrl.context, sessionId: undefined },+ vector.imageUrl.bytes,+ vector.imageUrl.nonce,+ vector.imageUrl.frame,+ ],+ [+ 'a block under the session key',+ vector.sessionKey,+ vector.block.context,+ vector.block.body,+ vector.block.nonce,+ vector.block.frame,+ ],+ ])('seals %s exactly as the Rust recorder does', (_name, key, context, body, nonce, frame) => {+ // The Rust crate pins the same file, so the two writers cannot drift apart.+ expect(sealV4Frame(base64(key), context as V4FrameContext, base64(body), base64(nonce))).toEqual(base64(frame))+ })++ const TEAM = 7+ const MONTH = '2026-10'+ const wrapped = Buffer.from('wrapped')+ const stored = { pk: { S: 'team:7' }, sk: { S: `month:${MONTH}` }, wrapped_key: { B: wrapped } }++ function fakes(row: Record<string, any> | undefined, kmsRequestsPerSecond?: number, readBudgetMs?: number) {+ const dynamo = {+ send: jest.fn((command: unknown) => {+ if (command instanceof GetItemCommand) {+ return Promise.resolve({ Item: row })+ }+ throw new Error('the fetcher never writes a key row')+ }),+ }+ const kms = {+ send: jest.fn((command: unknown) => {+ if (command instanceof DecryptCommand) {+ expect(command.input.EncryptionContext).toEqual(teamMonthWrappingContext(TEAM, MONTH))+ return Promise.resolve({ Plaintext: Buffer.alloc(32, 2) })+ }+ throw new Error('the fetcher never generates a key')+ }),+ }+ return { keys: new TeamMonthKeys(dynamo, kms, 'table', 'arn', kmsRequestsPerSecond, readBudgetMs), dynamo, kms }+ }++ it.each([+ ['unwraps a stored key', stored, { status: 'ok', key: Buffer.alloc(32, 2) }, 1],+ // The recorder stores the row before it sends a URL, so no row means it expired: nothing is minted.+ ['finds no key for a month without a row, and reads again next time', undefined, { status: 'missing' }, 2],+ ['holds a tombstone', { ...stored, wrapped_key: undefined, deleted: { BOOL: true } }, { status: 'deleted' }, 1],+ ])('%s', async (_name, row, expected, reads) => {+ const { keys, dynamo } = fakes(row)+ expect(await keys.get(TEAM, MONTH)).toEqual(expected)+ expect(await keys.get(TEAM, MONTH)).toEqual(expected)+ expect(dynamo.send).toHaveBeenCalledTimes(reads)+ })++ it.each([+ ['2026-10', '2027-03-01'],+ ['2026-12', '2027-05-01'],+ ])('expires the key rows of %s at 00:00 UTC on %s, as the recorder writes them', (keyMonth, expiresOn) => {+ expect(teamMonthKeyExpiresAtMs(keyMonth)).toBe(Date.parse(`${expiresOn}T00:00:00Z`))+ })++ it('gives up within its budget while it waits for a KMS turn, and makes no KMS call after that', async () => {+ // One request a minute: the first lookup takes the only slot, the next ones wait on the rate limit or the queue.+ const { keys, kms } = fakes(stored, 1 / 60, 50)+ const months = [+ MONTH,+ ...Array.from({ length: 11 }, (_, month) => `2025-${String(month + 1).padStart(2, '0')}`),+ ]+ const lookups = months.map((month) => keys.get(TEAM, month))++ const settled = await Promise.allSettled(lookups)+ await new Promise((resolve) => setImmediate(resolve))++ expect(settled.map((lookup) => lookup.status)).toEqual(['fulfilled', ...Array(11).fill('rejected')])+ expect(kms.send).toHaveBeenCalledTimes(1)+ })++ it('stops a shared read only once every caller waiting on it has stopped', async () => {+ const { keys, dynamo } = fakes(stored)+ let release!: () => void+ dynamo.send.mockImplementation(+ (_command: unknown, options?: { abortSignal?: AbortSignal }) =>+ new Promise((resolve, reject) => {+ release = () => resolve({ Item: stored })+ options?.abortSignal?.addEventListener('abort', () => reject(options.abortSignal!.reason))+ }) as any+ )+ const batch = new AbortController()+ const admission = keys.get(TEAM, MONTH, batch.signal)+ const store = keys.get(TEAM, MONTH)+ batch.abort(new Error('budget'))++ await expect(admission).rejects.toThrow('budget')+ release()+ expect(await store).toEqual({ status: 'ok', key: Buffer.alloc(32, 2) })++ const alone = new AbortController()+ const abandoned = keys.get(TEAM, '2026-09', alone.signal)+ alone.abort(new Error('budget'))+ await expect(abandoned).rejects.toThrow('budget')+ const [, readOptions] = dynamo.send.mock.calls[1] as unknown as [unknown, { abortSignal: AbortSignal }]+ expect(readOptions.abortSignal.aborted).toBe(true)+ })+})