: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(workflows): wake parked waits when their distinct_id first gets a person (#76044)
Daniel Marchuk43b0780d791e
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex b47c0b73dd3f..972ad461646d 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -71,9 +71,10 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {const isAccountAudience =hogFlowInvocationState.accountAudience === true ||(hogFlow.trigger?.type === 'batch' && hogFlow.trigger.filters?.audience_type === 'accounts')- // A person merge repointed this job's distinct_id and re-keyed personId onto the survivor.- // Resolve by that personId so the step reads the merged person — resolving by the repointed- // distinct_id would hit its stale ~1min cache entry (the pre-merge person) and e.g. drop an email.+ // The matcher wrote this job's personId anchor: a merge repointed the distinct_id onto a+ // survivor, or the distinct_id acquired its first person. Resolve by that personId so the step+ // reads the right person — resolving by the distinct_id would hit its stale ~1min cache entry+ // (the pre-merge person, or none at all) and e.g. drop an email.const resolveByRepointedPerson =hogFlowInvocationState.personIdRepointed === true && !!hogFlowInvocationState.personId// One-shot: consume the flag on this wake-resolution only. Later steps fall back to normaldiff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.tsindex a304ab851814..99b5b56e2296 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts@@ -1351,11 +1351,16 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {expect(result).toEqual([{ teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 }])})- it('drops version-0 inserts, deletions, missing-id and malformed messages', () => {+ it('admits a version-0 first mapping, which a wait parked with no person needs', () => {+ const result = (matcher as any)._parsePersonDistinctIdBatch([rawMove({ version: 0 })])+ expect(result).toEqual([{ teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 0 }])+ })++ it('drops deletions, missing-id, versionless and malformed messages', () => {const result = (matcher as any)._parsePersonDistinctIdBatch([- rawMove({ version: 0 }), // brand-new distinct_id (person creation), not a repointrawMove({ is_deleted: 1 }), // distinct_id being deleted- rawMove({ person_id: '' }), // no survivor to point at+ rawMove({ person_id: '' }), // no person to point at+ rawMove({ version: null }), // no version to order against{ value: Buffer.from('not json') }, // malformedrawMove(),])@@ -1458,6 +1463,81 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {)!expect(select.params[3]).toEqual(['wait_node'])})++ it('anchors a wait that parked before its distinct_id had a person', async () => {+ // The gap this closes: person wakes are keyed on person_id alone, so a wait parked with a null+ // anchor is unwakeable by any person-property change and only the polling re-check advances it.+ // The distinct_id's first mapping (version 0) is the one chance to give it an anchor.+ // currentAction is populated so the rekeyWake assertion below exercises the gate rather than+ // passing because there was no action to flag.+ matcher.moveRows = [+ parkedWaitRow({+ person_id: null,+ state: Buffer.from(JSON.stringify({ state: { currentAction: { id: 'wait_node' } } })),+ }),+ ]++ await matcher.processMoveBatch([+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'first-person-uuid', version: 0 },+ ])++ const update = lastUpdate()+ expect(update).toBeDefined()+ expect(update!.params[1]).toEqual(['first-person-uuid'])+ const newState = parseJSON((update!.params[2][0] as Buffer).toString('utf-8')) as any+ expect(newState.state.personId).toBe('first-person-uuid')+ // Waking it here is the point: it re-checks against the now-resolvable person immediately, and+ // re-parks with an anchor that later person updates can address.+ expect(update!.sql).toContain('scheduled = NOW()')+ // Not attributed as a merge re-key: counterHogflowRekeyWake measures whether waking on a merge+ // is wasted churn, so a first-mapping fill must stay out of that ratio.+ expect(newState.state.currentAction?.rekeyWake).toBeUndefined()+ })++ it('scopes a first mapping to jobs with no anchor, leaving anchored waits alone', async () => {+ // A first mapping says "this distinct_id now has a person". That tells us nothing about a job+ // already anchored elsewhere, so it must not rewrite one — and the null-anchor scope is also+ // what keeps this off the insert firehose.+ matcher.moveRows = [parkedWaitRow({ person_id: null, state: Buffer.from(JSON.stringify({ state: {} })) })]++ await matcher.processMoveBatch([+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'first-person-uuid', version: 0 },+ ])++ const select = matcher.calls.find(+ (c) =>+ c.sql.includes('SELECT id, team_id, distinct_id, function_id, action_id, state') &&+ c.sql.includes('person_id IS NULL')+ )+ expect(select).toBeDefined()+ })++ it('keeps a repoint able to rewrite an existing anchor', async () => {+ // The complement of the scoping above: a merge must still move an anchored wait, so the+ // null-anchor restriction has to apply to first mappings only.+ matcher.moveRows = [+ parkedWaitRow({+ state: Buffer.from(+ JSON.stringify({ state: { personId: 'old-uuid', currentAction: { id: 'wait_node' } } })+ ),+ }),+ ]++ await matcher.processMoveBatch([+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 },+ ])++ const select = matcher.calls.find((c) =>+ c.sql.includes('SELECT id, team_id, distinct_id, function_id, action_id, state')+ )!+ expect(select.sql).not.toContain('person_id IS NULL')+ const update = lastUpdate()!+ expect(update.params[1]).toEqual(['survivor-uuid'])+ // And a merge still is attributed as a re-key wake, so the gate above didn't cost the+ // merge-churn signal the counter exists to provide.+ const newState = parseJSON((update.params[2][0] as Buffer).toString('utf-8')) as any+ expect(newState.state.currentAction.rekeyWake).toBe(true)+ })})// The full combination matrix lives here (mocked pg, ~ms each) rather than in the E2E suite:diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 885a6fe4ca68..fd39cb4f341c 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -72,6 +72,17 @@ const counterHogflowMatcherJobsRekeyedOnMove = new Counter({help: 'Parked wait_until_condition jobs re-keyed to the surviving person after a distinct_id was repointed by a merge.',})+// A wait parked before its distinct_id had a person keeps a null person_id, and person wakes are keyed on+// person_id alone, so nothing can ever wake it — only the polling re-check advances it. The distinct_id's+// first mapping (version 0) is where that anchor becomes available. 'seen' is every first mapping admitted+// for a team with a wait flow, which is the load this path adds; 'filled' is the jobs it actually anchored.+// A 'seen' rate far above 'filled' is expected — watch the gap for query cost, not correctness.+const counterHogflowMatcherFirstMapping = new Counter({+ name: 'cdp_hogflow_matcher_first_mapping_total',+ help: 'distinct_id first mappings processed for parked waits with no person anchor, by outcome.',+ labelNames: ['outcome'],+})+// Latency of the cyclotron lookup for parked jobs. Watch this for cyclotron-node// read pressure as the wait-until-event feature ramps.const histogramHogflowMatcherFindParkedJobs = new Histogram({@@ -684,9 +695,12 @@ export class CdpHogflowSubscriptionMatcherConsumer<for (const message of messages) {try {const data = parseJSON(message.value!.toString()) as ClickHousePersonDistinctId2- // Only repoints matter. version 0 is a brand-new distinct_id (person creation) that no- // parked wait can be keyed on yet — skipping it also keeps this off the insert firehose.- if (!data.version || data.version <= 0) {+ // version > 0 is a repoint (identify/merge). version 0 is the distinct_id's first mapping+ // to a person, which a wait parked before the person resolved needs to acquire its anchor:+ // person wakes are keyed on person_id alone, so a job left with a null anchor is+ // unwakeable by any person-property change. processMoveBatch scopes version 0 to exactly+ // those jobs, which is what keeps this off the insert firehose.+ if (data.version === undefined || data.version === null || data.version < 0) {continue}// A distinct_id being deleted can't wake anything, and must never re-point a wait at a@@ -712,18 +726,32 @@ export class CdpHogflowSubscriptionMatcherConsumer<return moves}- // Re-key parked wait_until_condition jobs whose distinct_id was repointed by a merge onto the- // surviving person. We only rewrite the person_id anchor (column + state.personId) and leave the- // schedule alone: the survivor's clickhouse_person / event updates then wake the wait through the- // existing person/event streams (matched by the new person_id), and the worker takes the matched- // branch via the eventMatched flag without re-resolving the person. Waking here instead would make- // the worker re-resolve the distinct_id against PersonsManager's ~1-minute cache, which can return- // the stale pre-merge person and, on re-park, write the old person_id back — undoing this re-key.+ // Point parked wait_until_condition jobs at the person their distinct_id now belongs to, for the two+ // ways that can change: a merge repointing it onto a survivor, or the distinct_id acquiring a person+ // for the first time. Either way the job's existing anchor can no longer be woken — person and event+ // wakes are keyed on person_id — so we rewrite the anchor (column + state.personId) and wake it.public async processMoveBatch(moves: PersonDistinctIdMove[]): Promise<void> {if (moves.length === 0) {return}+ // A repoint (version > 0) may rewrite any parked wait's anchor. A first mapping (version 0) may+ // only fill an anchor that is missing: it says "this distinct_id now has a person", which tells us+ // nothing about a job already anchored elsewhere, and the null-anchor scope is what keeps the+ // insert firehose off the whole flow set.+ const repoints = moves.filter((m) => m.version > 0)+ const firstMappings = moves.filter((m) => m.version === 0)++ if (repoints.length > 0) {+ await this.applyMoves(repoints, false)+ }+ if (firstMappings.length > 0) {+ counterHogflowMatcherFirstMapping.labels({ outcome: 'seen' }).inc(firstMappings.length)+ await this.applyMoves(firstMappings, true)+ }+ }++ private async applyMoves(moves: PersonDistinctIdMove[], onlyNullAnchor: boolean): Promise<void> {// Only flows with a wait_until_condition step can have a parked wait to re-key. Scope the// function_id filter to them so the cyclotron query stays index-friendly and skips repoints for// teams with no such flow.@@ -763,6 +791,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<flow.actions.filter((a: HogFlowAction) => a.type === 'wait_until_condition').map((a) => a.id))+ let updatedCount = 0const client = await this.cyclotronPool.connect()try {await client.query('BEGIN')@@ -774,6 +803,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<WHERE status = 'available'AND function_id = ANY($3::uuid[])AND action_id = ANY($4::text[])+ ${onlyNullAnchor ? 'AND person_id IS NULL' : ''}AND (team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))ORDER BY idFOR UPDATE`,@@ -795,7 +825,13 @@ export class CdpHogflowSubscriptionMatcherConsumer<if (!newPerson || !row.state) {continue}- const newState = rewriteStatePersonId(row.state, newPerson.personId, newPerson.version, row.id)+ const newState = rewriteStatePersonId(+ row.state,+ newPerson.personId,+ newPerson.version,+ row.id,+ onlyNullAnchor+ )if (!newState) {continue}@@ -816,9 +852,18 @@ export class CdpHogflowSubscriptionMatcherConsumer<WHERE cj.id = u.id AND cj.status = 'available'`,[updates.map((u) => u.id), updates.map((u) => u.personId), updates.map((u) => u.state)])- counterHogflowMatcherJobsRekeyedOnMove.inc(result.rowCount ?? 0)+ updatedCount = result.rowCount ?? 0}await client.query('COMMIT')+ // Counted after COMMIT: an UPDATE that succeeds and then fails to commit is rolled back, so+ // counting before this would report anchors that no job actually carries.+ if (updatedCount > 0) {+ if (onlyNullAnchor) {+ counterHogflowMatcherFirstMapping.labels({ outcome: 'filled' }).inc(updatedCount)+ } else {+ counterHogflowMatcherJobsRekeyedOnMove.inc(updatedCount)+ }+ }} catch (err) {await client.query('ROLLBACK').catch(() => {})throw err@@ -1040,7 +1085,8 @@ function rewriteStatePersonId(stateBuffer: Buffer,newPersonId: string,newVersion: number,- jobId: string+ jobId: string,+ fillingNullAnchor = false): Buffer | null {try {const parsed = parseJSON(stateBuffer.toString('utf-8'))@@ -1048,8 +1094,10 @@ function rewriteStatePersonId(// delayed lower-version move (anon → A, v2) can arrive in a later batch than a higher one already// applied (anon → B, v3); without this watermark it would rewind the wait onto the obsolete// person A, and B's person-stream updates would no longer address the parked job.+ // A first mapping is exempt: it carries version 0, which no watermark can beat, and there is no+ // anchor to rewind — the caller has already scoped it to jobs with none.const appliedVersion = parsed.state?.personIdRepointVersion ?? 0- if (newVersion <= appliedVersion) {+ if (!fillingNullAnchor && newVersion <= appliedVersion) {return null}// Flag the re-key so the worker resolves the person by this survivor personId, not the repointed@@ -1062,7 +1110,9 @@ function rewriteStatePersonId(}// Mark this as a re-key wake so the wait handler can attribute its re-check outcome to the// re-key (see rekeyWake). currentAction is always a wait_until_condition here (re-key scope).- if (parsed.state.currentAction) {+ // Only for merges: counterHogflowRekeyWake exists to judge whether waking on a merge is wasted+ // churn, so folding first-mapping fills into it would blend two causes into one ratio.+ if (parsed.state.currentAction && !fillingNullAnchor) {parsed.state.currentAction = { ...parsed.state.currentAction, rekeyWake: true }}return Buffer.from(JSON.stringify(parsed))diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 1d38be08d29a..df79279873d3 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -348,10 +348,11 @@ export type HogFlowInvocationContext = {// group key, not a person distinct_id. The worker must trust this over the live trigger config,// which can be edited to a person audience while these children are still queued.accountAudience?: boolean- // Set by the subscription matcher when a person merge repointed this job's distinct_id and re-keyed- // personId onto the survivor. Tells the worker to resolve the person by personId, not the distinct_id- // (whose ~1min PersonsManager cache entry still points at the pre-merge person) — otherwise a- // merge-woken step reads stale person props (e.g. an email step gets no recipient and drops the send).+ // Set by the subscription matcher when it wrote this job's personId anchor: either a merge repointed+ // the distinct_id onto a survivor, or the distinct_id acquired its first person. Tells the worker to+ // resolve the person by personId, not the distinct_id (whose ~1min PersonsManager cache entry still+ // points at the pre-merge person, or at no person at all) — otherwise the woken step reads stale+ // person props (e.g. an email step gets no recipient and drops the send).personIdRepointed?: boolean// High-water mark of the repoint version last applied to this job's personId. Repoints aren't// Kafka-keyed, so a delayed lower-version move can arrive in a later batch than a higher one alreadydiff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 90efd493bdf6..194d4bbd1f8c 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -1453,7 +1453,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)last_seen_at: null,distinct_id: 'distinct_id',})- const distinctIdMoveMessage = (): any => ({+ const distinctIdMoveMessage = (overrides: Record<string, any> = {}): any => ({value: Buffer.from(JSON.stringify({team_id: team.id,@@ -1461,6 +1461,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)person_id: 'new-uuid',version: 2,is_deleted: 0,+ ...overrides,})),})@@ -1503,6 +1504,101 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())})+ it('anchors and wakes a wait that parked before its distinct_id had a person', async () => {+ // Production shape: an event arrives for a distinct_id with no person yet, so the wait parks+ // with person_id NULL. Person wakes are keyed on person_id alone, so nothing can address that+ // job — before this was fixed, only the 10-minute polling re-check ever advanced it.+ await createWaitUntilWorkflow({+ condition: { filters: personPropertyConditionFilters('plan', 'enterprise') },+ max_wait_duration: '5m',+ })+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([])+ await triggerWorkflow(createGlobals())+ await expectParked()++ // The premise of the test: no anchor to wake.+ const parked = await cyclotronPool.query(+ `SELECT person_id FROM cyclotron_jobs WHERE ${statusColumn} = 'available'`+ )+ expect(parked.rows).toHaveLength(1)+ expect(parked.rows[0].person_id).toBeNull()++ // The distinct_id acquires a person for the first time (version 0), and that person already+ // satisfies the condition. The matcher fills the missing anchor and wakes the wait, which then+ // resolves by personId and advances down the matched branch.+ mockPersonRepo.fetchPersonsByPersonIds.mockResolvedValue([survivorPersonRow()])+ await matcher.processMoveBatch(+ matcher._parsePersonDistinctIdBatch([distinctIdMoveMessage({ version: 0 }) as any])+ )++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())+ })++ it('anchors a wait whose condition is still false, so a later person update can wake it', async () => {+ // The shape the affected production runs actually take, and the one the test above does not+ // cover: the person exists by the time the anchor is filled, but does not satisfy the condition+ // yet. So the fill wakes the wait, the re-check fails, and it re-parks — this time WITH an+ // anchor. The property is then set, and that person update has to be able to find the job.+ // Without the anchor there is no key for the person stream to match on and only the polling+ // re-check would ever advance it.+ await createWaitUntilWorkflow({+ condition: { filters: personPropertyConditionFilters('plan', 'enterprise') },+ max_wait_duration: '5m',+ })+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([])+ await triggerWorkflow(createGlobals())+ await expectParked()++ const beforeFill = await cyclotronPool.query(+ `SELECT person_id FROM cyclotron_jobs WHERE ${statusColumn} = 'available'`+ )+ expect(beforeFill.rows[0].person_id).toBeNull()++ // First mapping arrives. The person exists now but has no `plan`, so the condition is false.+ const personWithoutPlan = { ...survivorPersonRow(), properties: { email: '[email protected]' } }+ mockPersonRepo.fetchPersonsByPersonIds.mockResolvedValue([personWithoutPlan])+ await matcher.processMoveBatch(+ matcher._parsePersonDistinctIdBatch([distinctIdMoveMessage({ version: 0 }) as any])+ )++ // It re-parked rather than advancing, and it now carries the anchor.+ await waitForExpect(async () => {+ const afterFill = await cyclotronPool.query(+ `SELECT person_id FROM cyclotron_jobs WHERE ${statusColumn} = 'available'`+ )+ expect(afterFill.rows).toHaveLength(1)+ expect(afterFill.rows[0].person_id).toBe('new-uuid')+ }, 10000)+ expect(mockFetch).not.toHaveBeenCalled()++ // Now the property is set. This is a person mutation with no analytics event, so it can only be+ // matched on person_id — the anchor written above is what makes it findable.+ const personMessage = {+ value: Buffer.from(+ JSON.stringify({+ id: 'new-uuid',+ team_id: team.id,+ properties: JSON.stringify({ email: '[email protected]', plan: 'enterprise' }),+ is_deleted: 0,+ is_identified: 1,+ created_at: '2024-09-03 09:00:00.000',+ timestamp: '2024-09-03 09:00:00.000',+ version: 3,+ })+ ),+ }+ mockPersonRepo.fetchPersonsByPersonIds.mockResolvedValue([survivorPersonRow()])+ await matcher.processBatch(await matcher._parsePersonBatch([personMessage as any]))++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())+ })+it('wakes a parked wait from a cdp_internal_events signal with no analytics event', async () => {// CDP-generated signals (e.g. $insight_alert_firing) arrive on cdp_internal_events and never// hit the analytics events topic. The matcher parses them via _parseInternalEventsBatch and