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.

feat(workflows): Add distinct_id, person_id and action_id columns to cyclotron (#57720)

Daniel Marchuk61399b068896
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index d71d348d0b1c..e767e5561af3 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -240,7 +240,7 @@ jobs:
- name: Install sqlx-cli
working-directory: rust
- run: cargo install [email protected] --locked --no-default-features --features native-tls,postgres
+ run: cargo install [email protected] --locked --no-default-features --features native-tls,postgres
- name: Install SAML (python3-saml) dependencies
if: steps.setup-uv.outputs.cache-hit != 'true'
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index fe23ad7b018f..c38c53b0b8b6 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -59,6 +59,9 @@ interface RawJobRow {
last_transition: string | Date
parent_run_id: string | null
state: Buffer | null
+ distinct_id: string | null
+ person_id: string | null
+ action_id: string | null
}
async function queryJob(id: string): Promise<RawJobRow> {
@@ -191,6 +194,65 @@ describe('Cyclotron V2', () => {
expect(await totalJobCount()).toBe(0)
})
+ // [columnName, initKey, sampleValueFactory]
+ const lookupColumns: Array<[keyof RawJobRow, keyof CyclotronV2JobInit, () => string]> = [
+ ['distinct_id', 'distinctId', () => 'user-42'],
+ ['person_id', 'personId', () => uuidv7()],
+ ['action_id', 'actionId', () => 'action-7'],
+ ]
+
+ it.each(lookupColumns)('createJob persists %s when provided', async (column, initKey, factory) => {
+ const value = factory()
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE, [initKey]: value })
+ const row = await queryJob(id)
+ expect(row[column]).toBe(value)
+ })
+
+ it.each(lookupColumns)('createJob defaults %s to null when omitted', async (column) => {
+ const id = await manager.createJob({ teamId: 1, queueName: QUEUE })
+ const row = await queryJob(id)
+ expect(row[column]).toBeNull()
+ })
+
+ it.each(lookupColumns)('bulkCreateJobs persists %s per row', async (column, initKey, factory) => {
+ const a = factory()
+ const b = factory()
+ const ids = await manager.bulkCreateJobs([
+ { teamId: 1, queueName: QUEUE, [initKey]: a },
+ { teamId: 1, queueName: QUEUE, [initKey]: b },
+ { teamId: 1, queueName: QUEUE },
+ ])
+ expect(ids).toHaveLength(3)
+ const rows = await assertPool.query<RawJobRow>(
+ `SELECT id, ${column} FROM cyclotron_jobs WHERE id = ANY($1::uuid[]) ORDER BY id`,
+ [ids]
+ )
+ const byId = new Map(rows.rows.map((r) => [r.id, r[column]]))
+ expect(byId.get(ids[0])).toBe(a)
+ expect(byId.get(ids[1])).toBe(b)
+ expect(byId.get(ids[2])).toBeNull()
+ })
+
+ // Only distinct_id and person_id are indexed; action_id intentionally is not.
+ const indexedLookupColumns = lookupColumns.filter(([col]) => col !== 'action_id')
+
+ it.each(indexedLookupColumns)(
+ 'partial index supports lookup by (team_id, %s)',
+ async (column, initKey, factory) => {
+ const shared = factory()
+ await manager.createJob({ teamId: 1, queueName: QUEUE, [initKey]: shared })
+ await manager.createJob({ teamId: 1, queueName: QUEUE, [initKey]: shared })
+ await manager.createJob({ teamId: 2, queueName: QUEUE, [initKey]: shared })
+ await manager.createJob({ teamId: 1, queueName: QUEUE })
+
+ const res = await assertPool.query<{ count: string }>(
+ `SELECT COUNT(*) AS count FROM cyclotron_jobs WHERE team_id = $1 AND ${column} = $2`,
+ [1, shared]
+ )
+ expect(Number(res.rows[0].count)).toBe(2)
+ }
+ )
+
it('backpressure throws when queue depth exceeds limit', async () => {
const smallManager = createManager({ depthLimit: 2, depthCheckIntervalMs: 0 })
await smallManager.connect()
@@ -202,6 +264,23 @@ describe('Cyclotron V2', () => {
await smallManager.disconnect()
}
})
+
+ it('createJob rejects non-UUID personId before reaching the database', async () => {
+ await expect(manager.createJob({ teamId: 1, queueName: QUEUE, personId: 'not-a-uuid' })).rejects.toThrow(
+ /uuid/i
+ )
+ })
+
+ it('bulkCreateJobs rejects non-UUID values without writing any rows', async () => {
+ const before = await totalJobCount()
+ await expect(
+ manager.bulkCreateJobs([
+ { teamId: 1, queueName: QUEUE, personId: uuidv7() },
+ { teamId: 1, queueName: QUEUE, personId: 'bad-uuid' as any },
+ ])
+ ).rejects.toThrow(/uuid/i)
+ expect(await totalJobCount()).toBe(before)
+ })
})
// ── Worker ───────────────────────────────────────────────────────
@@ -307,6 +386,91 @@ describe('Cyclotron V2', () => {
expect(row.state).toBeNull()
})
+ it('reschedule({ actionId }) updates action_id column', async () => {
+ const { id, job } = await seedAndDequeue({ actionId: 'step-a' })
+ await job.reschedule({ actionId: 'step-b' })
+
+ const row = await queryJob(id)
+ expect(row.action_id).toBe('step-b')
+ })
+
+ it('reschedule({ actionId: null }) clears action_id', async () => {
+ const { id, job } = await seedAndDequeue({ actionId: 'step-a' })
+ await job.reschedule({ actionId: null })
+
+ const row = await queryJob(id)
+ expect(row.action_id).toBeNull()
+ })
+
+ it('reschedule() without actionId leaves action_id unchanged', async () => {
+ const { id, job } = await seedAndDequeue({ actionId: 'step-a' })
+ await job.reschedule({ state: Buffer.from('new-state') })
+
+ const row = await queryJob(id)
+ expect(row.action_id).toBe('step-a')
+ })
+
+ it('dequeued job exposes distinctId, personId, and actionId', async () => {
+ const personId = uuidv7()
+ const { job } = await seedAndDequeue({
+ distinctId: 'd-on-job',
+ personId,
+ actionId: 'a-on-job',
+ })
+ expect(job.distinctId).toBe('d-on-job')
+ expect(job.personId).toBe(personId)
+ expect(job.actionId).toBe('a-on-job')
+ })
+
+ it('reschedule rejects non-UUID personId before reaching the database', async () => {
+ const { job } = await seedAndDequeue()
+ await expect(job.reschedule({ personId: 'bad-uuid' as any })).rejects.toThrow(/uuid/i)
+ })
+
+ it('reschedule({ distinctId }) updates distinct_id column', async () => {
+ const { id, job } = await seedAndDequeue({ distinctId: 'd-old' })
+ await job.reschedule({ distinctId: 'd-new' })
+
+ const row = await queryJob(id)
+ expect(row.distinct_id).toBe('d-new')
+ })
+
+ it('reschedule({ distinctId: null }) clears distinct_id', async () => {
+ const { id, job } = await seedAndDequeue({ distinctId: 'd-old' })
+ await job.reschedule({ distinctId: null })
+
+ const row = await queryJob(id)
+ expect(row.distinct_id).toBeNull()
+ })
+
+ it('reschedule({ personId }) updates person_id column', async () => {
+ const original = uuidv7()
+ const next = uuidv7()
+ const { id, job } = await seedAndDequeue({ personId: original })
+ await job.reschedule({ personId: next })
+
+ const row = await queryJob(id)
+ expect(row.person_id).toBe(next)
+ })
+
+ it('reschedule({ personId: null }) clears person_id', async () => {
+ const { id, job } = await seedAndDequeue({ personId: uuidv7() })
+ await job.reschedule({ personId: null })
+
+ const row = await queryJob(id)
+ expect(row.person_id).toBeNull()
+ })
+
+ it('reschedule() without identifiers leaves them unchanged', async () => {
+ const original = uuidv7()
+ const { id, job } = await seedAndDequeue({ distinctId: 'd-keep', personId: original })
+ await job.reschedule({ state: Buffer.from('new-state') })
+
+ const row = await queryJob(id)
+ expect(row.distinct_id).toBe('d-keep')
+ expect(row.person_id).toBe(original)
+ })
+
it('heartbeat() extends last_heartbeat', async () => {
const { id, job } = await seedAndDequeue()
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index aa011477d202..035d5fbee723 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -2,7 +2,7 @@ import { Pool } from 'pg'
import { v7 as uuidv7 } from 'uuid'
import { logger } from '../../../utils/logger'
-import { CyclotronV2JobInit, CyclotronV2ManagerConfig } from './types'
+import { CyclotronV2JobInit, CyclotronV2JobInitSchema, CyclotronV2ManagerConfig } from './types'
export class CyclotronV2Manager {
private pool: Pool
@@ -26,7 +26,8 @@ export class CyclotronV2Manager {
client.release()
}
- async createJob(job: CyclotronV2JobInit): Promise<string> {
+ async createJob(input: CyclotronV2JobInit): Promise<string> {
+ const job = CyclotronV2JobInitSchema.parse(input)
await this.insertGuard()
const id = job.id ?? uuidv7()
@@ -35,10 +36,10 @@ export class CyclotronV2Manager {
`INSERT INTO cyclotron_jobs
(id, team_id, function_id, queue_name, status, priority, scheduled, created,
lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,
- parent_run_id, state)
+ parent_run_id, state, distinct_id, person_id, action_id)
VALUES ($1, $2, $3, $4, 'available', $5, $6, $7,
NULL, NULL, 0, 0, $7,
- $8, $9)`,
+ $8, $9, $10, $11, $12)`,
[
id,
job.teamId,
@@ -49,16 +50,21 @@ export class CyclotronV2Manager {
now,
job.parentRunId ?? null,
job.state ?? null,
+ job.distinctId ?? null,
+ job.personId ?? null,
+ job.actionId ?? null,
]
)
return id
}
- async bulkCreateJobs(jobs: CyclotronV2JobInit[]): Promise<string[]> {
- if (jobs.length === 0) {
+ async bulkCreateJobs(inputs: CyclotronV2JobInit[]): Promise<string[]> {
+ if (inputs.length === 0) {
return []
}
+ const jobs = inputs.map((input) => CyclotronV2JobInitSchema.parse(input))
+
await this.insertGuard()
const ids: string[] = []
@@ -69,6 +75,9 @@ export class CyclotronV2Manager {
const scheduleds: Date[] = []
const parentRunIds: (string | null)[] = []
const states: (Buffer | null)[] = []
+ const distinctIds: (string | null)[] = []
+ const personIds: (string | null)[] = []
+ const actionIds: (string | null)[] = []
const now = new Date()
@@ -82,13 +91,16 @@ export class CyclotronV2Manager {
scheduleds.push(job.scheduled ?? now)
parentRunIds.push(job.parentRunId ?? null)
states.push(job.state ?? null)
+ distinctIds.push(job.distinctId ?? null)
+ personIds.push(job.personId ?? null)
+ actionIds.push(job.actionId ?? null)
}
await this.pool.query(
`INSERT INTO cyclotron_jobs
(id, team_id, function_id, queue_name, status, priority, scheduled, created,
lock_id, last_heartbeat, janitor_touch_count, transition_count, last_transition,
- parent_run_id, state)
+ parent_run_id, state, distinct_id, person_id, action_id)
SELECT
unnest($1::uuid[]),
unnest($2::int[]),
@@ -97,15 +109,31 @@ export class CyclotronV2Manager {
'available'::CyclotronJobStatus,
unnest($5::smallint[]),
unnest($6::timestamptz[]),
- $9::timestamptz,
+ $12::timestamptz,
NULL::uuid,
NULL::timestamptz,
0::smallint,
0::smallint,
- $9::timestamptz,
+ $12::timestamptz,
unnest($7::text[]),
- unnest($8::bytea[])`,
- [ids, teamIds, functionIds, queueNames, priorities, scheduleds, parentRunIds, states, now]
+ unnest($8::bytea[]),
+ unnest($9::text[]),
+ unnest($10::uuid[]),
+ unnest($11::text[])`,
+ [
+ ids,
+ teamIds,
+ functionIds,
+ queueNames,
+ priorities,
+ scheduleds,
+ parentRunIds,
+ states,
+ distinctIds,
+ personIds,
+ actionIds,
+ now,
+ ]
)
return ids
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index dbe3e5c27f08..ad648c0b7612 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -1,4 +1,5 @@
import { DateTime } from 'luxon'
+import { z } from 'zod'
export type CyclotronV2JobStatus = 'available' | 'running' | 'completed' | 'failed' | 'canceled'
@@ -8,16 +9,35 @@ export type CyclotronV2PoolConfig = {
idleTimeoutMs?: number
}
-export type CyclotronV2JobInit = {
- id?: string
- teamId: number
- functionId?: string | null
- queueName: string
- priority?: number
- scheduled?: Date
- parentRunId?: string | null
- state?: Buffer | null
-}
+// `id` and `functionId` use PostHog's UUIDT-style identifiers which don't set
+// valid UUID version bits, so we only validate them as non-empty strings here.
+// `personId` comes from posthog_person.uuid (a real UUID v4/v7) and ingestion's
+// resolution, so we validate it strictly to catch any bad data at the boundary.
+export const CyclotronV2JobInitSchema = z.object({
+ id: z.string().min(1).optional(),
+ teamId: z.number().int(),
+ functionId: z.string().min(1).nullish(),
+ queueName: z.string().min(1),
+ priority: z.number().int().optional(),
+ scheduled: z.date().optional(),
+ parentRunId: z.string().nullish(),
+ state: z.instanceof(Buffer).nullish(),
+ distinctId: z.string().nullish(),
+ personId: z.uuid().nullish(),
+ actionId: z.string().nullish(),
+})
+
+export type CyclotronV2JobInit = z.infer<typeof CyclotronV2JobInitSchema>
+
+export const CyclotronV2RescheduleOptionsSchema = z.object({
+ scheduledAt: z.date().optional(),
+ state: z.instanceof(Buffer).nullish(),
+ distinctId: z.string().nullish(),
+ personId: z.uuid().nullish(),
+ actionId: z.string().nullish(),
+})
+
+export type CyclotronV2RescheduleOptions = z.infer<typeof CyclotronV2RescheduleOptionsSchema>
export interface CyclotronV2DequeuedJob {
readonly id: string
@@ -30,10 +50,13 @@ export interface CyclotronV2DequeuedJob {
readonly parentRunId: string | null
readonly transitionCount: number
readonly state: Buffer | null
+ readonly distinctId: string | null
+ readonly personId: string | null
+ readonly actionId: string | null
ack(): Promise<void>
fail(): Promise<void>
- reschedule(options?: { scheduledAt?: Date; state?: Buffer | null }): Promise<void>
+ reschedule(options?: CyclotronV2RescheduleOptions): Promise<void>
cancel(): Promise<void>
heartbeat(): Promise<void>
}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/worker.ts b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
index 9909270c0690..285bdb2b98cd 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/worker.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/worker.ts
@@ -3,7 +3,12 @@ import { Pool } from 'pg'
import { v7 as uuidv7 } from 'uuid'
import { logger } from '../../../utils/logger'
-import { CyclotronV2DequeuedJob, CyclotronV2WorkerConfig } from './types'
+import {
+ CyclotronV2DequeuedJob,
+ CyclotronV2RescheduleOptions,
+ CyclotronV2RescheduleOptionsSchema,
+ CyclotronV2WorkerConfig,
+} from './types'
interface RawJobRow {
id: string
@@ -16,6 +21,9 @@ interface RawJobRow {
parent_run_id: string | null
transition_count: number
state: Buffer | null
+ distinct_id: string | null
+ person_id: string | null
+ action_id: string | null
lock_id: string
}
@@ -109,6 +117,9 @@ export class CyclotronV2Worker {
cyclotron_jobs.parent_run_id,
cyclotron_jobs.transition_count,
cyclotron_jobs.state,
+ cyclotron_jobs.distinct_id,
+ cyclotron_jobs.person_id,
+ cyclotron_jobs.action_id,
cyclotron_jobs.lock_id`,
[this.config.queueName, this.batchMaxSize, lockId]
)
@@ -143,6 +154,9 @@ export class CyclotronV2Worker {
parentRunId: row.parent_run_id,
transitionCount: row.transition_count,
state: row.state,
+ distinctId: row.distinct_id,
+ personId: row.person_id,
+ actionId: row.action_id,
async ack(): Promise<void> {
releaseGuard('ack')
@@ -166,31 +180,43 @@ export class CyclotronV2Worker {
)
},
- async reschedule(options?: { scheduledAt?: Date; state?: Buffer | null }): Promise<void> {
+ async reschedule(input?: CyclotronV2RescheduleOptions): Promise<void> {
releaseGuard('reschedule')
+ const options = input ? CyclotronV2RescheduleOptionsSchema.parse(input) : undefined
const scheduled = options?.scheduledAt ?? new Date()
- const hasStateUpdate = options?.state !== undefined
-
- if (hasStateUpdate) {
- await pool.query(
- `UPDATE cyclotron_jobs
- SET status = 'available', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1,
- scheduled = $3,
- state = $4
- WHERE id = $1 AND lock_id = $2`,
- [row.id, lockId, scheduled, options!.state ?? null]
- )
- } else {
- await pool.query(
- `UPDATE cyclotron_jobs
- SET status = 'available', lock_id = NULL, last_heartbeat = NULL,
- last_transition = NOW(), transition_count = transition_count + 1,
- scheduled = $3
- WHERE id = $1 AND lock_id = $2`,
- [row.id, lockId, scheduled]
- )
+
+ const setClauses = [
+ `status = 'available'`,
+ `lock_id = NULL`,
+ `last_heartbeat = NULL`,
+ `last_transition = NOW()`,
+ `transition_count = transition_count + 1`,
+ `scheduled = $3`,
+ ]
+ const params: any[] = [row.id, lockId, scheduled]
+
+ if (options?.state !== undefined) {
+ params.push(options.state ?? null)
+ setClauses.push(`state = $${params.length}`)
+ }
+ if (options?.distinctId !== undefined) {
+ params.push(options.distinctId ?? null)
+ setClauses.push(`distinct_id = $${params.length}`)
+ }
+ if (options?.personId !== undefined) {
+ params.push(options.personId ?? null)
+ setClauses.push(`person_id = $${params.length}`)
+ }
+ if (options?.actionId !== undefined) {
+ params.push(options.actionId ?? null)
+ setClauses.push(`action_id = $${params.length}`)
}
+
+ await pool.query(
+ `UPDATE cyclotron_jobs SET ${setClauses.join(', ')}
+ WHERE id = $1 AND lock_id = $2`,
+ params
+ )
},
async cancel(): Promise<void> {
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
index 08d7d632333f..a214adb4afe2 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.test.ts
@@ -3,8 +3,13 @@ import { v4 as uuidv4 } from 'uuid'
import { parseJSON } from '~/utils/json-parse'
-import { CyclotronJobInvocationResult } from '../../types'
-import { CyclotronJobQueuePostgresV2 } from './job-queue-postgres-v2'
+import { CyclotronJobInvocation, CyclotronJobInvocationResult } from '../../types'
+import {
+ CyclotronJobQueuePostgresV2,
+ extractActionId,
+ extractDistinctId,
+ extractPersonId,
+} from './job-queue-postgres-v2'
jest.mock('../cyclotron-v2', () => ({
CyclotronV2Manager: jest.fn(),
@@ -72,6 +77,70 @@ describe('CyclotronJobQueuePostgresV2', () => {
}
}
+ describe('extractDistinctId', () => {
+ const cases: Array<[string, any, string | null]> = [
+ [
+ 'returns event.distinct_id when present',
+ { state: { event: { distinct_id: 'user-from-event' } } },
+ 'user-from-event',
+ ],
+ ['returns null when state has no event', { state: { personId: 'p' } }, null],
+ ['returns null when state is null', { state: null }, null],
+ ['returns null when state is undefined', { state: undefined }, null],
+ ['returns null for empty event.distinct_id', { state: { event: { distinct_id: '' } } }, null],
+ ]
+ it.each(cases)('%s', (_desc, overrides, expected) => {
+ const invocation = { ...baseInvocation, id: uuidv4(), ...overrides } as CyclotronJobInvocation
+ expect(extractDistinctId(invocation)).toBe(expected)
+ })
+ })
+
+ describe('extractPersonId', () => {
+ const cases: Array<[string, any, string | null]> = [
+ [
+ 'returns invocation.person.id when present (event-triggered)',
+ { person: { id: 'person-from-event' }, state: {} },
+ 'person-from-event',
+ ],
+ [
+ 'falls back to state.personId (batch-triggered)',
+ { state: { personId: 'person-from-batch' } },
+ 'person-from-batch',
+ ],
+ [
+ 'prefers invocation.person.id over state.personId',
+ { person: { id: 'person-from-event' }, state: { personId: 'person-from-batch' } },
+ 'person-from-event',
+ ],
+ ['returns null when neither is present', { state: { globals: {} } }, null],
+ ['returns null when state is null', { state: null }, null],
+ ['returns null when state is undefined', { state: undefined }, null],
+ ['falls through empty person.id to state.personId', { person: { id: '' }, state: { personId: 'p' } }, 'p'],
+ ]
+ it.each(cases)('%s', (_desc, overrides, expected) => {
+ const invocation = { ...baseInvocation, id: uuidv4(), ...overrides } as CyclotronJobInvocation
+ expect(extractPersonId(invocation)).toBe(expected)
+ })
+ })
+
+ describe('extractActionId', () => {
+ const cases: Array<[string, Partial<CyclotronJobInvocation>, string | null]> = [
+ [
+ 'returns currentAction.id when present',
+ { state: { currentAction: { id: 'action-uuid' } } as any },
+ 'action-uuid',
+ ],
+ ['returns null when currentAction is absent', { state: { event: {} } as any }, null],
+ ['returns null when state is null', { state: null as any }, null],
+ ['returns null when state is undefined', { state: undefined as any }, null],
+ ['returns null when currentAction.id is empty', { state: { currentAction: { id: '' } } as any }, null],
+ ]
+ it.each(cases)('%s', (_desc, overrides, expected) => {
+ const invocation = { ...baseInvocation, id: uuidv4(), ...overrides } as CyclotronJobInvocation
+ expect(extractActionId(invocation)).toBe(expected)
+ })
+ })
+
describe('queueInvocations', () => {
it('should serialize state into a Buffer', async () => {
const { queue, bulkCreateJobs } = createQueue()
@@ -107,6 +176,24 @@ describe('CyclotronJobQueuePostgresV2', () => {
expect(stateBlob.queueMetadata).toEqual({ retryCount: 2 })
})
+ it('forwards extracted distinctId, personId and actionId to bulkCreateJobs', async () => {
+ const { queue, bulkCreateJobs } = createQueue()
+ await queue.queueInvocations([
+ {
+ ...baseInvocation,
+ id: uuidv4(),
+ person: { id: 'event-person' },
+ state: { event: { distinct_id: 'd-1' }, currentAction: { id: 'a-1' } } as any,
+ } as any,
+ { ...baseInvocation, id: uuidv4(), state: { personId: 'batch-person' } as any },
+ { ...baseInvocation, id: uuidv4() },
+ ])
+ const jobs = bulkCreateJobs.mock.calls[0][0]
+ expect(jobs.map((j: any) => j.distinctId)).toEqual(['d-1', null, null])
+ expect(jobs.map((j: any) => j.personId)).toEqual(['event-person', 'batch-person', null])
+ expect(jobs.map((j: any) => j.actionId)).toEqual(['a-1', null, null])
+ })
+
it('should not call bulkCreateJobs for empty invocations', async () => {
const { queue, bulkCreateJobs } = createQueue()
diff --git a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
index c4a43040e9ff..3bd694f28aec 100644
--- a/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
+++ b/nodejs/src/cdp/services/job-queue/job-queue-postgres-v2.ts
@@ -176,6 +176,9 @@ export class CyclotronJobQueuePostgresV2 {
await job.reschedule({
state: stateBuffer,
scheduledAt: result.invocation.queueScheduledAt?.toJSDate(),
+ distinctId: extractDistinctId(result.invocation),
+ personId: extractPersonId(result.invocation),
+ actionId: extractActionId(result.invocation),
})
}
})
@@ -232,6 +235,7 @@ function invocationToV2JobInit(invocation: CyclotronJobInvocation): CyclotronV2J
const state = serializeState(invocation)
cdpJobSizeKb.labels('postgres-v2').observe(state.length / 1024)
cdpJobSizeCompressedKb.labels('postgres-v2').observe(state.length / 1024)
+
return {
id: invocation.id,
teamId: invocation.teamId,
@@ -241,9 +245,34 @@ function invocationToV2JobInit(invocation: CyclotronJobInvocation): CyclotronV2J
scheduled: invocation.queueScheduledAt?.toJSDate() ?? new Date(),
parentRunId: invocation.parentRunId ?? null,
state,
+ distinctId: extractDistinctId(invocation),
+ personId: extractPersonId(invocation),
+ actionId: extractActionId(invocation),
}
}
+type LookupColumnSource = {
+ person?: { id?: string }
+ state?: {
+ event?: { distinct_id?: string }
+ personId?: string
+ currentAction?: { id?: string }
+ } | null
+}
+
+export function extractDistinctId(invocation: CyclotronJobInvocation): string | null {
+ return (invocation as LookupColumnSource).state?.event?.distinct_id || null
+}
+
+export function extractPersonId(invocation: CyclotronJobInvocation): string | null {
+ const inv = invocation as LookupColumnSource
+ return inv.person?.id || inv.state?.personId || null
+}
+
+export function extractActionId(invocation: CyclotronJobInvocation): string | null {
+ return (invocation as LookupColumnSource).state?.currentAction?.id || null
+}
+
function v2JobToInvocation(job: CyclotronV2DequeuedJob): CyclotronJobInvocation {
let parsed: SerializedJobState = { state: null }
diff --git a/rust/cyclotron-node-migrations/20260417000001_add_lookup_columns.sql b/rust/cyclotron-node-migrations/20260417000001_add_lookup_columns.sql
new file mode 100644
index 000000000000..a350c18fbb28
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260417000001_add_lookup_columns.sql
@@ -0,0 +1,4 @@
+ALTER TABLE cyclotron_jobs
+ ADD COLUMN IF NOT EXISTS distinct_id TEXT,
+ ADD COLUMN IF NOT EXISTS person_id UUID,
+ ADD COLUMN IF NOT EXISTS action_id TEXT;
diff --git a/rust/cyclotron-node-migrations/20260417000002_add_distinct_id_index.sql b/rust/cyclotron-node-migrations/20260417000002_add_distinct_id_index.sql
new file mode 100644
index 000000000000..bfa20a4b93f6
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260417000002_add_distinct_id_index.sql
@@ -0,0 +1,4 @@
+-- no-transaction
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_cyclotron_jobs_distinct_id
+ ON cyclotron_jobs (team_id, distinct_id)
+ WHERE distinct_id IS NOT NULL;
diff --git a/rust/cyclotron-node-migrations/20260417000003_add_person_id_index.sql b/rust/cyclotron-node-migrations/20260417000003_add_person_id_index.sql
new file mode 100644
index 000000000000..ca7a7db5c025
--- /dev/null
+++ b/rust/cyclotron-node-migrations/20260417000003_add_person_id_index.sql
@@ -0,0 +1,4 @@
+-- no-transaction
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_cyclotron_jobs_person_id
+ ON cyclotron_jobs (team_id, person_id)
+ WHERE person_id IS NOT NULL;