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): wake parked waits on person merge via distinct_id repoints (#72433)

Daniel Marchuk365148bf50d2
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts
index d6e6ca316617..cee442202855 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow-personhog.test.ts
@@ -162,6 +162,81 @@ describe('CdpCyclotronWorkerHogFlow with PersonHog', () => {
expect(mockRepo.fetchPersonsByPersonIds).toHaveBeenCalled()
})
+ it('resolves person by personId (not the repointed distinct_id) when a merge re-keyed the job', async () => {
+ // A person merge repointed this parked wait's distinct_id and re-keyed personId onto the survivor
+ // (state.personIdRepointed). The survivor must be resolved by personId: resolving by the repointed
+ // distinct_id hits its stale ~1min cache entry — the pre-merge person — so a downstream step (e.g.
+ // an email) reads the wrong/empty properties and drops the send. Guards that regression.
+ const survivorUuid = 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1'
+ const survivor = makePerson(team.id, survivorUuid, 'survivor_did', {
+ name: 'Survivor',
+ email: '[email protected]',
+ })
+
+ const mockRepo = createMockPersonReadRepository({
+ // The distinct_id path would return the stale pre-merge person; personId returns the survivor.
+ fetchPersonsByDistinctIds: jest
+ .fn()
+ .mockResolvedValue([makePerson(team.id, 'old-uuid', 'anon_did', { name: 'Pre-merge anon' })]),
+ fetchPersonsByPersonIds: jest.fn().mockResolvedValue([survivor]),
+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({ [survivor.id]: ['survivor_did'] }),
+ })
+
+ const processor = new CdpCyclotronWorkerHogFlow(
+ hub,
+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },
+ createMockJobQueue()
+ )
+
+ const invocations = [
+ createSerializedHogFlowInvocation(hogFlow, {
+ // The event still carries the anon distinct_id, but the re-key set personId + the flag.
+ event: { distinct_id: 'anon_did', properties: {} } as any,
+ personId: survivorUuid,
+ personIdRepointed: true,
+ }),
+ ]
+
+ const results = (await processor.processInvocations(
+ invocations
+ )) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]
+
+ expect(results).toHaveLength(1)
+ // Resolved the survivor (via personId), not the stale pre-merge person (via distinct_id).
+ expect(results[0].invocation.person?.properties).toEqual({ name: 'Survivor', email: '[email protected]' })
+ expect(mockRepo.fetchPersonsByPersonIds).toHaveBeenCalled()
+ expect(mockRepo.fetchPersonsByDistinctIds).not.toHaveBeenCalled()
+ })
+
+ it('clears personIdRepointed after the wake-resolution so later steps resolve by distinct_id again', async () => {
+ // The flag is a one-shot override for the merge-wake resolution only. If it stuck around, a second
+ // merge onto a non-wait step (out of the matcher's re-key scope) would leave the flow pinned to the
+ // now-stale first survivor forever instead of self-healing via distinct_id. Guards that regression.
+ const survivorUuid = 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1'
+ const mockRepo = createMockPersonReadRepository({
+ fetchPersonsByPersonIds: jest
+ .fn()
+ .mockResolvedValue([makePerson(team.id, survivorUuid, 'survivor_did', { name: 'Survivor' })]),
+ fetchDistinctIdsForPersons: jest.fn().mockResolvedValue({ [survivorUuid]: ['survivor_did'] }),
+ })
+
+ const processor = new CdpCyclotronWorkerHogFlow(
+ hub,
+ { ...createCdpConsumerDeps(hub), personRepository: mockRepo },
+ createMockJobQueue()
+ )
+
+ const results = (await processor.processInvocations([
+ createSerializedHogFlowInvocation(hogFlow, {
+ event: { distinct_id: 'anon_did', properties: {} } as any,
+ personId: survivorUuid,
+ personIdRepointed: true,
+ }),
+ ])) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]
+
+ expect(results[0].invocation.state.personIdRepointed).toBeUndefined()
+ })
+
it('propagates error when personhog is unavailable', async () => {
const mockRepo = createMockPersonReadRepository({
fetchPersonsByDistinctIds: jest.fn().mockRejectedValue(new Error('gRPC unavailable')),
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
index f4fdecfdc9c0..304fd5d1338c 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts
@@ -62,10 +62,24 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {
// rather than relying on event.distinct_id being empty so future changes to the
// synthetic event shape don't accidentally re-enable the lookup.
const isWarehouseRow = hogFlow.trigger?.type === 'data-warehouse-table'
+ // 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.
+ const resolveByRepointedPerson =
+ hogFlowInvocationState.personIdRepointed === true && !!hogFlowInvocationState.personId
+ // One-shot: consume the flag on this wake-resolution only. Later steps fall back to normal
+ // distinct_id-first resolution, which self-heals to the latest survivor if the distinct_id is
+ // repointed again (a second merge onto a non-wait step is out of processMoveBatch's scope).
+ if (resolveByRepointedPerson) {
+ delete hogFlowInvocationState.personIdRepointed
+ }
const personIdOrDistinctId = isWarehouseRow
? undefined
- : hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personId
- const kind = hogFlowInvocationState.event.distinct_id ? 'distinct_id' : 'person_id'
+ : resolveByRepointedPerson
+ ? hogFlowInvocationState.personId
+ : hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personId
+ const kind =
+ resolveByRepointedPerson || !hogFlowInvocationState.event.distinct_id ? 'person_id' : 'distinct_id'
const [person, groups] = await Promise.all([
personIdOrDistinctId
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.test.ts
index 7ac850ae882f..a304ab851814 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
@@ -109,6 +109,7 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {
public calls: QueryCall[] = []
public findRows: MockRow[] = []
public wakeRows: MockRow[] = []
+ public moveRows: MockRow[] = []
public updateRowCount = 0
constructor() {
@@ -127,6 +128,9 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {
if (sql.includes('SELECT id, state FROM cyclotron_jobs')) {
return Promise.resolve({ rows: this.wakeRows, rowCount: this.wakeRows.length })
}
+ if (sql.includes('SELECT id, team_id, distinct_id, function_id, action_id, state')) {
+ return Promise.resolve({ rows: this.moveRows, rowCount: this.moveRows.length })
+ }
if (sql.startsWith('UPDATE cyclotron_jobs')) {
return Promise.resolve({ rows: [], rowCount: this.updateRowCount })
}
@@ -1328,6 +1332,134 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {
})
})
+ describe('_parsePersonDistinctIdBatch', () => {
+ const rawMove = (overrides: Record<string, any> = {}): any => ({
+ value: Buffer.from(
+ JSON.stringify({
+ team_id: 1,
+ distinct_id: 'anon-did',
+ person_id: 'survivor-uuid',
+ version: 2,
+ is_deleted: 0,
+ ...overrides,
+ })
+ ),
+ })
+
+ it('maps a version>0 repoint to its distinct_id + survivor person', () => {
+ const result = (matcher as any)._parsePersonDistinctIdBatch([rawMove()])
+ expect(result).toEqual([{ teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 }])
+ })
+
+ it('drops version-0 inserts, deletions, missing-id and malformed messages', () => {
+ const result = (matcher as any)._parsePersonDistinctIdBatch([
+ rawMove({ version: 0 }), // brand-new distinct_id (person creation), not a repoint
+ rawMove({ is_deleted: 1 }), // distinct_id being deleted
+ rawMove({ person_id: '' }), // no survivor to point at
+ { value: Buffer.from('not json') }, // malformed
+ rawMove(),
+ ])
+ expect(result).toEqual([{ teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 }])
+ })
+ })
+
+ describe('processMoveBatch', () => {
+ beforeEach(() => {
+ matcher.setHogFlows({ 'flow-1': makeHogFlow({ id: 'flow-1', team_id: 1 }) })
+ })
+
+ const parkedWaitRow = (overrides: Record<string, any> = {}): any => ({
+ id: 'job-1',
+ team_id: 1,
+ distinct_id: 'anon-did',
+ function_id: 'flow-1',
+ action_id: 'wait_node',
+ state: Buffer.from(JSON.stringify({ state: { personId: 'old-uuid' } })),
+ ...overrides,
+ })
+
+ const lastUpdate = (): QueryCall | undefined =>
+ matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))
+
+ it('re-keys a parked wait onto the survivor (person_id column + state.personId)', async () => {
+ matcher.moveRows = [parkedWaitRow()]
+ await matcher.processMoveBatch([
+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 },
+ ])
+
+ const update = lastUpdate()
+ expect(update).toBeDefined()
+ // params: [ids, person_ids, states]. The person_id column moves to the survivor...
+ expect(update!.params[1]).toEqual(['survivor-uuid'])
+ const newState = parseJSON((update!.params[2][0] as Buffer).toString('utf-8')) as any
+ // ...and so does the persisted state.personId, so a distinct_id-less re-resolution follows it.
+ expect(newState.state.personId).toBe('survivor-uuid')
+ // The repoint also wakes the parked wait (scheduled = NOW()) so it re-checks against the
+ // merged person immediately, rather than depending on the poll tick — closes the race where
+ // the person-property update lands before this re-key. Dropping this hangs the wait.
+ expect(update!.sql).toContain('scheduled = NOW()')
+ })
+
+ it('re-keys onto the highest-version survivor when a batch chains merges out of order', async () => {
+ // anon-did → A (v2) then → B (v3) in the same batch, but the array carries them B-then-A.
+ // Repoints aren't Kafka-keyed, so this ordering is real; the highest version must win or the
+ // wait re-keys onto intermediate A, whose person-stream updates can't wake it once the poll is gone.
+ matcher.moveRows = [parkedWaitRow()]
+ await matcher.processMoveBatch([
+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-B', version: 3 },
+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'intermediate-A', version: 2 },
+ ])
+
+ expect(lastUpdate()!.params[1]).toEqual(['survivor-B'])
+ })
+
+ it('rejects an older repoint that arrives in a later batch than a newer one already applied', async () => {
+ // Cross-batch ordering: anon-did → B (v3) was applied in an earlier batch (persisted as
+ // personIdRepointVersion), then a delayed anon-did → A (v2) lands. The version watermark must
+ // reject it — otherwise the wait rewinds onto obsolete A and B's updates no longer wake it.
+ matcher.moveRows = [
+ parkedWaitRow({
+ state: Buffer.from(
+ JSON.stringify({ state: { personId: 'survivor-B', personIdRepointVersion: 3 } })
+ ),
+ }),
+ ]
+ await matcher.processMoveBatch([
+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'obsolete-A', version: 2 },
+ ])
+
+ expect(lastUpdate()).toBeUndefined()
+ })
+
+ it('skips a job parked on a delay step and scopes the lock to wait actions only', async () => {
+ // A job of the same wait-containing flow can sit on a delay step; rewriting its person_id off
+ // a repoint would be wrong. Two layers keep it safe: the SELECT is scoped to wait action_ids
+ // ($4), and the JS guard skips any row whose action isn't a wait_until_condition. Assert both.
+ const flow = makeHogFlow({ id: 'flow-1', team_id: 1 })
+ flow.actions.push({
+ id: 'delay_node',
+ name: 'Delay',
+ type: 'delay',
+ config: { delay_duration: '1h' },
+ } as any)
+ matcher.setHogFlows({ 'flow-1': flow })
+
+ matcher.moveRows = [parkedWaitRow({ action_id: 'delay_node' })]
+ await matcher.processMoveBatch([
+ { teamId: 1, distinctId: 'anon-did', newPersonId: 'survivor-uuid', version: 2 },
+ ])
+
+ // JS guard: the delay-parked job is left untouched.
+ expect(lastUpdate()).toBeUndefined()
+ // SQL scoping: the lock/state fetch targets the wait step only — the delay/trigger/exit
+ // actions are excluded from the $4 action_id list.
+ const select = matcher.calls.find((c) =>
+ c.sql.includes('SELECT id, team_id, distinct_id, function_id, action_id, state')
+ )!
+ expect(select.params[3]).toEqual(['wait_node'])
+ })
+ })
+
// The full combination matrix lives here (mocked pg, ~ms each) rather than in the E2E suite:
// it exercises the same wake decision the matcher makes for every events/property/action shape.
describe('wake matrix: events / property / action combinations', () => {
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
index e8a07fdc0e67..885a6fe4ca68 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -3,7 +3,12 @@ import { Pool } from 'pg'
import { Counter, Histogram } from 'prom-client'
import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'
-import { KAFKA_CDP_INTERNAL_EVENTS, KAFKA_EVENTS_JSON, KAFKA_PERSON } from '~/common/config/kafka-topics'
+import {
+ KAFKA_CDP_INTERNAL_EVENTS,
+ KAFKA_EVENTS_JSON,
+ KAFKA_PERSON,
+ KAFKA_PERSON_DISTINCT_ID,
+} from '~/common/config/kafka-topics'
import { KafkaConsumerInterface, RdKafkaConsumerConfig, createKafkaConsumer } from '~/common/kafka/consumer'
import { InternalCaptureEvent } from '~/common/services/internal-capture'
import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'
@@ -12,7 +17,14 @@ import { logger } from '~/common/utils/logger'
import { captureException } from '~/common/utils/posthog'
import { UUIDT } from '~/common/utils/utils'
-import { ClickHousePerson, HealthCheckResult, PluginsServerConfig, RawClickHouseEvent, Team } from '../../types'
+import {
+ ClickHousePerson,
+ ClickHousePersonDistinctId2,
+ HealthCheckResult,
+ PluginsServerConfig,
+ RawClickHouseEvent,
+ Team,
+} from '../../types'
import { CdpInternalEventSchema } from '../schema'
import {
hasEventOrActionTarget,
@@ -51,6 +63,15 @@ const counterHogflowMatcherConversionsCounted = new Counter({
help: 'Event-based conversions counted by the matcher (deduped to once per run via conversionCounted).',
})
+// A person merge repoints the merged-away person's distinct_ids at the survivor. A wait parked while
+// that distinct_id belonged to the old person still references the old person_id, so the survivor's
+// person/event updates (keyed on the new id) can't wake it. We re-key such waits onto the survivor;
+// this counts the re-keyed jobs.
+const counterHogflowMatcherJobsRekeyedOnMove = new Counter({
+ name: 'cdp_hogflow_matcher_jobs_rekeyed_on_distinct_id_move',
+ help: 'Parked wait_until_condition jobs re-keyed to the surviving person after a distinct_id was repointed by a merge.',
+})
+
// 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({
@@ -80,6 +101,15 @@ type ParkedCandidate = {
personId: string | null
}
+// A distinct_id repointed by a merge: the distinct_id and the survivor person it now resolves to.
+// version orders repoints for the same distinct_id — the highest wins when a batch carries several.
+type PersonDistinctIdMove = {
+ teamId: number
+ distinctId: string
+ newPersonId: string
+ version: number
+}
+
// A parked job the matcher needs to act on this batch: either resume it (stepMatched, or a
// conversion match on an exit-on-conversion flow) and/or count its conversion once. Carries the
// fields needed to emit the `conversion` metric without re-reading the hogflow.
@@ -122,6 +152,10 @@ export class CdpHogflowSubscriptionMatcherConsumer<
// analytics events topic. (Email engagement events, by contrast, flow through capture to
// clickhouse_events_json and are already covered by the events stream.)
private internalEventsKafkaConsumer: KafkaConsumerInterface
+ // clickhouse_person_distinct_id carries distinct_id → person repoints (version > 0). A merge moves the
+ // merged-away person's distinct_ids onto the survivor here; we consume it to re-key parked waits onto
+ // the survivor's id so the survivor's person/event updates can wake them.
+ private personDistinctIdKafkaConsumer: KafkaConsumerInterface
private cyclotronPool: Pool
constructor(config: TConfig, deps: CdpConsumerBaseDeps) {
@@ -147,6 +181,13 @@ export class CdpHogflowSubscriptionMatcherConsumer<
},
startAtLatest
)
+ this.personDistinctIdKafkaConsumer = createKafkaConsumer(
+ {
+ groupId: 'cdp-hogflow-subscription-matcher-person-distinct-id-consumer',
+ topic: KAFKA_PERSON_DISTINCT_ID,
+ },
+ startAtLatest
+ )
// The matcher does nothing but read/write cyclotron_jobs, so a missing connection
// string means it would silently consume the event stream and wake nothing. Fail
@@ -636,6 +677,156 @@ export class CdpHogflowSubscriptionMatcherConsumer<
return events
}
+ // Synchronous (no getTeam/globals conversion — a repoint only carries ids), so unlike the other
+ // parsers this isn't async or @instrumented.
+ public _parsePersonDistinctIdBatch(messages: Message[]): PersonDistinctIdMove[] {
+ const moves: PersonDistinctIdMove[] = []
+ 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) {
+ continue
+ }
+ // A distinct_id being deleted can't wake anything, and must never re-point a wait at a
+ // person that is going away.
+ if (data.is_deleted) {
+ continue
+ }
+ if (!data.distinct_id || !data.person_id) {
+ counterHogflowMatcherEventSkipped.labels({ reason: 'no_identifiers' }).inc()
+ continue
+ }
+ moves.push({
+ teamId: data.team_id,
+ distinctId: data.distinct_id,
+ newPersonId: data.person_id,
+ version: data.version,
+ })
+ } catch (e) {
+ logger.error('Error parsing person distinct id message', e)
+ counterParseError.labels({ error: e.message }).inc()
+ }
+ }
+ 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.
+ public async processMoveBatch(moves: PersonDistinctIdMove[]): Promise<void> {
+ if (moves.length === 0) {
+ return
+ }
+
+ // 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.
+ const teamIds = [...new Set(moves.map((m) => m.teamId))]
+ const hogFlowsByTeam = await this.hogFlowManager.getHogFlowsForTeams(teamIds)
+ const hogflows: Record<string, HogFlow> = {}
+ for (const flows of Object.values(hogFlowsByTeam)) {
+ for (const flow of flows) {
+ if (flow.actions.some((a: HogFlowAction) => a.type === 'wait_until_condition')) {
+ hogflows[flow.id] = flow
+ }
+ }
+ }
+ const functionIds = Object.keys(hogflows)
+ if (functionIds.length === 0) {
+ return
+ }
+
+ // A batch can carry several repoints for the same distinct_id (chained merges anon → A → B).
+ // Repoints aren't Kafka-keyed, so they may arrive out of order within the batch — keep the
+ // highest-version survivor per key rather than the last array entry, or we could re-key onto an
+ // intermediate person the survivor's person-stream updates would never wake.
+ const newPersonByKey = new Map<string, { personId: string; version: number }>()
+ for (const move of moves) {
+ const key = `${move.teamId}:${move.distinctId}`
+ const existing = newPersonByKey.get(key)
+ if (!existing || move.version > existing.version) {
+ newPersonByKey.set(key, { personId: move.newPersonId, version: move.version })
+ }
+ }
+ const moveTeamIds = moves.map((m) => m.teamId)
+ const moveDistinctIds = moves.map((m) => m.distinctId)
+
+ // Scope the lock + state fetch to the wait_until_condition steps we can actually re-key, so jobs
+ // of the same flow parked on unrelated steps (e.g. a delay) aren't locked or shipped over the wire.
+ const waitActionIds = Object.values(hogflows).flatMap((flow) =>
+ flow.actions.filter((a: HogFlowAction) => a.type === 'wait_until_condition').map((a) => a.id)
+ )
+
+ const client = await this.cyclotronPool.connect()
+ try {
+ await client.query('BEGIN')
+ // Lock the parked jobs for the repointed distinct_ids. ORDER BY id keeps lock order consistent
+ // with processMatchedJobs so concurrent move/match batches can't deadlock.
+ const rows = await client.query(
+ `SELECT id, team_id, distinct_id, function_id, action_id, state
+ FROM cyclotron_jobs
+ WHERE status = 'available'
+ AND function_id = ANY($3::uuid[])
+ AND action_id = ANY($4::text[])
+ AND (team_id, distinct_id) IN (SELECT * FROM unnest($1::int[], $2::text[]))
+ ORDER BY id
+ FOR UPDATE`,
+ [moveTeamIds, moveDistinctIds, functionIds, waitActionIds]
+ )
+
+ const updates: { id: string; personId: string; state: Buffer }[] = []
+ for (const row of rows.rows) {
+ // Only re-key jobs currently parked ON a wait_until_condition step. A job of the same flow
+ // could be parked in a delay; rewriting its person_id off a repoint would be wrong, and it
+ // must never be pulled forward.
+ const action = row.action_id
+ ? hogflows[row.function_id]?.actions.find((a: HogFlowAction) => a.id === row.action_id)
+ : undefined
+ if (action?.type !== 'wait_until_condition') {
+ continue
+ }
+ const newPerson = newPersonByKey.get(`${row.team_id}:${row.distinct_id}`)
+ if (!newPerson || !row.state) {
+ continue
+ }
+ const newState = rewriteStatePersonId(row.state, newPerson.personId, newPerson.version, row.id)
+ if (!newState) {
+ continue
+ }
+ updates.push({ id: row.id, personId: newPerson.personId, state: newState })
+ }
+
+ if (updates.length > 0) {
+ // scheduled = NOW() wakes the parked wait on the repoint itself, closing the ordering
+ // race where the person-property update lands before this re-key (the matcher would
+ // otherwise miss the still-anon-keyed job and the wait would hang until its poll tick).
+ // Safe now that the worker resolves a re-keyed job by survivor personId (personIdRepointed).
+ const result = await client.query(
+ `UPDATE cyclotron_jobs cj
+ SET person_id = u.person_id, state = u.state, scheduled = NOW()
+ FROM (
+ SELECT unnest($1::uuid[]) AS id, unnest($2::text[]) AS person_id, unnest($3::bytea[]) AS state
+ ) u
+ 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)
+ }
+ await client.query('COMMIT')
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw err
+ } finally {
+ client.release()
+ }
+ }
+
public override async start(): Promise<void> {
await super.start()
// Surface failures to each kafka consumer so the offset doesn't advance past a batch we
@@ -663,6 +854,15 @@ export class CdpHogflowSubscriptionMatcherConsumer<
}
})
}),
+ this.personDistinctIdKafkaConsumer.connect(async (messages) => {
+ // Parsing repoints is synchronous, so wrap in a resolved promise to satisfy instrumentFn's
+ // promise-returning callback without a no-op async body.
+ return await instrumentFn('cdpHogflowSubscriptionMatcher.handlePersonDistinctIdBatch', () =>
+ Promise.resolve({
+ backgroundTask: this.processMoveBatch(this._parsePersonDistinctIdBatch(messages)),
+ })
+ )
+ }),
])
}
@@ -672,6 +872,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<
this.kafkaConsumer.disconnect(),
this.personKafkaConsumer.disconnect(),
this.internalEventsKafkaConsumer.disconnect(),
+ this.personDistinctIdKafkaConsumer.disconnect(),
])
await this.cyclotronPool.end()
await super.stop()
@@ -684,6 +885,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<
this.kafkaConsumer.isHealthy(),
this.personKafkaConsumer.isHealthy(),
this.internalEventsKafkaConsumer.isHealthy(),
+ this.personDistinctIdKafkaConsumer.isHealthy(),
]
return results.find((r) => r.status !== 'ok') ?? results[0]
}
@@ -831,6 +1033,45 @@ function collectCandidateGlobals(
return [...seen]
}
+// Point the persisted personId at the merge survivor so the worker's re-resolution — which falls back
+// to state.personId when the job has no distinct_id — lands on the survivor. Returns the new state
+// buffer, or null if the state can't be parsed (leave the row untouched).
+function rewriteStatePersonId(
+ stateBuffer: Buffer,
+ newPersonId: string,
+ newVersion: number,
+ jobId: string
+): Buffer | null {
+ try {
+ const parsed = parseJSON(stateBuffer.toString('utf-8'))
+ // Reject a repoint no newer than the one already applied. Repoints aren't Kafka-keyed, so a
+ // 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.
+ const appliedVersion = parsed.state?.personIdRepointVersion ?? 0
+ if (newVersion <= appliedVersion) {
+ return null
+ }
+ // Flag the re-key so the worker resolves the person by this survivor personId, not the repointed
+ // distinct_id whose ~1min cache still points at the pre-merge person (see personIdRepointed).
+ parsed.state = {
+ ...parsed.state,
+ personId: newPersonId,
+ personIdRepointed: true,
+ personIdRepointVersion: newVersion,
+ }
+ // 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) {
+ parsed.state.currentAction = { ...parsed.state.currentAction, rekeyWake: true }
+ }
+ return Buffer.from(JSON.stringify(parsed))
+ } catch (err) {
+ logger.warn('Failed to parse state during distinct_id-move re-key', { jobId, err })
+ return null
+ }
+}
+
type MatchOutcome = { state: Buffer; wake: boolean; countConversion: boolean }
// Applies a batch match to a parked job's state. Returns the new state plus whether the job should
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
index 32f15ab457e0..7df7d65b49e6 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts
@@ -8,11 +8,19 @@ import { CyclotronJobInvocationHogFlow } from '~/cdp/types'
import { createInvocationResult } from '~/cdp/utils/invocation-utils'
import { findActionById, findActionByType } from '../hogflow-utils'
-import { ConditionalBranchHandler, checkConditions, counterHogflowWaitPollOnlyAdvance } from './conditional_branch'
+import {
+ ConditionalBranchHandler,
+ checkConditions,
+ counterHogflowRekeyWake,
+ counterHogflowWaitPollOnlyAdvance,
+} from './conditional_branch'
const pollOnlyAdvanceCount = async (): Promise<number> =>
(await counterHogflowWaitPollOnlyAdvance.get()).values[0]?.value ?? 0
+const rekeyWakeCount = async (outcome: 'advanced' | 'reparked'): Promise<number> =>
+ (await counterHogflowRekeyWake.get()).values.find((v) => v.labels.outcome === outcome)?.value ?? 0
+
describe('action.conditional_branch', () => {
let invocation: CyclotronJobInvocationHogFlow
let action: Extract<HogFlowAction, { type: 'conditional_branch' }>
@@ -205,6 +213,7 @@ describe('action.conditional_branch', () => {
}
handler = new ConditionalBranchHandler()
counterHogflowWaitPollOnlyAdvance.reset()
+ counterHogflowRekeyWake.reset()
})
it('advances to the matched branch and clears eventMatched', async () => {
@@ -336,5 +345,45 @@ describe('action.conditional_branch', () => {
expect(await pollOnlyAdvanceCount()).toBe(0)
})
+
+ it('records a rekey wake as advanced and consumes the one-shot flag when the merge makes the condition match', async () => {
+ // A merge re-keyed this parked wait onto the survivor and woke it (rekeyWake). The re-check
+ // now finds the condition true. Consuming the flag is what keeps the next re-check from
+ // re-emitting the outcome — without it a re-parked wake would inflate the churn metric.
+ waitAction.config.condition = {
+ filters: {
+ bytecode: ['_H', 1, 32, 'test', 32, 'event', 1, 1, 11],
+ events: [{ id: 'test', name: 'test', type: 'events', order: 0 }],
+ },
+ }
+ waitInvocation.state.currentAction!.rekeyWake = true
+
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.nextAction).toEqual(findActionById(waitInvocation.hogFlow, 'matched_target'))
+ expect(await rekeyWakeCount('advanced')).toBe(1)
+ expect(await rekeyWakeCount('reparked')).toBe(0)
+ expect(waitInvocation.state.currentAction!.rekeyWake).toBe(false)
+ })
+
+ it('records a rekey wake as reparked and consumes the one-shot flag when the merge does not satisfy the wait', async () => {
+ // The default condition still does not match after the re-key, so waking was wasted churn.
+ waitInvocation.state.currentAction!.rekeyWake = true
+
+ const result = await handler.execute({
+ invocation: waitInvocation,
+ action: waitAction,
+ result: createInvocationResult(waitInvocation),
+ })
+
+ expect(result.scheduledAt).toBeDefined()
+ expect(await rekeyWakeCount('reparked')).toBe(1)
+ expect(await rekeyWakeCount('advanced')).toBe(0)
+ expect(waitInvocation.state.currentAction!.rekeyWake).toBe(false)
+ })
})
})
diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
index 094cf8751d32..1016a2e89a66 100644
--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts
@@ -20,6 +20,16 @@ export const counterHogflowWaitPollOnlyAdvance = new Counter({
help: 'wait_until_condition advanced via the polling re-check, not the subscription matcher — a wake the streams missed.',
})
+// Outcome of a wait_until_condition re-check that ran because a person merge re-keyed the parked job
+// onto the survivor and woke it (scheduled=now). 'advanced' = the merge made the condition match;
+// 'reparked' = it didn't, so waking was wasted churn. A high reparked:advanced ratio means the wake
+// is firing on merges that don't satisfy the wait — signal to narrow when the matcher wakes.
+export const counterHogflowRekeyWake = new Counter({
+ name: 'cdp_hogflow_matcher_rekey_wake_total',
+ help: 'wait_until_condition re-checks triggered by a merge re-key wake, by outcome.',
+ labelNames: ['outcome'],
+})
+
export class ConditionalBranchHandler implements ActionHandler {
async execute({
invocation,
@@ -27,6 +37,14 @@ export class ConditionalBranchHandler implements ActionHandler {
}: ActionHandlerOptions<
Extract<HogFlowAction, { type: 'conditional_branch' | 'wait_until_condition' }>
>): Promise<ActionHandlerResult> {
+ // The subscription matcher sets rekeyWake when it re-keyed this parked wait onto a merge
+ // survivor and woke it (scheduled=now). Consume it here (one-shot) and attribute this
+ // re-check's outcome to the re-key below, so the wasted-re-park churn from waking is observable.
+ const rekeyWoken = action.type === 'wait_until_condition' && invocation.state?.currentAction?.rekeyWake === true
+ if (rekeyWoken && invocation.state.currentAction) {
+ invocation.state.currentAction.rekeyWake = false
+ }
+
// The subscription matcher sets eventMatched when an incoming event matched this
// step's wait condition. Honor it as a forced match and advance immediately,
// rather than re-evaluating the stored condition against the original event.
@@ -65,6 +83,9 @@ export class ConditionalBranchHandler implements ActionHandler {
if (isWait && invocation.state.currentAction) {
invocation.state.currentAction.pollReparked = true
}
+ if (rekeyWoken) {
+ counterHogflowRekeyWake.labels('reparked').inc()
+ }
return { scheduledAt: conditionResult.scheduledAt, result: { conditionResult } }
} else if (conditionResult.nextAction) {
// Poll-only advance: a wait whose condition matched on a re-check (not via the matcher's
@@ -72,6 +93,9 @@ export class ConditionalBranchHandler implements ActionHandler {
if (isWait && invocation.state.currentAction?.pollReparked === true) {
counterHogflowWaitPollOnlyAdvance.inc()
}
+ if (rekeyWoken) {
+ counterHogflowRekeyWake.labels('advanced').inc()
+ }
return { nextAction: conditionResult.nextAction, result: { conditionResult } }
}
diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.ts
index 926836cca585..6c4bea0f0c49 100644
--- a/nodejs/src/cdp/types.ts
+++ b/nodejs/src/cdp/types.ts
@@ -342,6 +342,16 @@ export type CyclotronJobInvocationHogFlow = CyclotronJobInvocation & {
export type HogFlowInvocationContext = {
event: HogFunctionInvocationGlobals['event']
personId?: string // Persisted person UUID, used when distinct_id is not available (e.g. batch workflows, manual person triggers)
+ // 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).
+ 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 already
+ // applied; the matcher rejects any repoint whose version isn't strictly greater, so an out-of-order
+ // older move can't rewind the wait onto an obsolete person.
+ personIdRepointVersion?: number
actionStepCount: number
currentAction?: {
id: string
@@ -358,6 +368,10 @@ export type HogFlowInvocationContext = {
eventMatchedEventUuid?: string
// Paired with the UUID to build the event link in the logs view; never displayed.
eventMatchedEventTimestamp?: string
+ // Set by the subscription matcher when it re-keys a parked wait onto a merge survivor and wakes
+ // it (scheduled=now). The wait handler consumes it to attribute the re-check outcome
+ // (advanced vs re-parked) to the re-key, so the wasted-re-park churn is observable.
+ rekeyWake?: boolean
// Set by hog-function action handler when it returns `finished: false` without an
// explicit `queueScheduledAt` — i.e. the reschedule is purely to move the job onto a
// dedicated queue (e.g. 'email' for SES rate-limit gating) and the next dequeue will
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index 8efb14da3b7b..2d7686554ed9 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -1266,6 +1266,243 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
})
+ // Wait conditions authored as HogQL expressions must be woken by the streams, not only by the
+ // 10-minute poll — otherwise removing the poll would silently strand them. These three cover
+ // the distinct HogQL condition shapes real production flows use; each bytecode is exactly what
+ // the Django serializer compiles for that expression (verified via compile_filters_bytecode).
+ // If HogQL compilation changes, or a stream stops carrying what the bytecode reads (e.g. the
+ // person wake dropping properties), one of these fails.
+ it('wakes a HogQL event-name wait condition via the events stream', async () => {
+ // HogQL: event = 'billing_added'
+ await createWaitUntilWorkflow({
+ condition: {
+ filters: {
+ bytecode: ['_H', 1, 32, 'billing_added', 32, 'event', 1, 1, 11],
+ properties: [{ type: 'hogql', key: "event = 'billing_added'" }],
+ },
+ },
+ max_wait_duration: '5m',
+ })
+ await triggerWorkflow(createGlobals({ event: 'custom_trigger', properties: {} }))
+ await expectParked()
+ await matcher.processBatch([createGlobals({ event: 'billing_added', properties: {} })])
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
+ })
+
+ it('wakes a HogQL event+property wait condition only on the matching event and property', async () => {
+ // HogQL: event = 'cal_booking' and properties.trigger_event = 'BOOKING_CREATED'
+ await createWaitUntilWorkflow({
+ condition: {
+ filters: {
+ bytecode: [
+ '_H',
+ 1,
+ 32,
+ 'cal_booking',
+ 32,
+ 'event',
+ 1,
+ 1,
+ 11,
+ 32,
+ 'BOOKING_CREATED',
+ 32,
+ 'trigger_event',
+ 32,
+ 'properties',
+ 1,
+ 2,
+ 11,
+ 3,
+ 2,
+ ],
+ properties: [
+ {
+ type: 'hogql',
+ key: "event = 'cal_booking' and properties.trigger_event = 'BOOKING_CREATED'",
+ },
+ ],
+ },
+ },
+ max_wait_duration: '5m',
+ })
+ await triggerWorkflow(createGlobals({ event: 'custom_trigger', properties: {} }))
+ await expectParked()
+ // Right event, wrong property — must not wake.
+ await matcher.processBatch([
+ createGlobals({ event: 'cal_booking', properties: { trigger_event: 'OTHER' } }),
+ ])
+ await new Promise((r) => setTimeout(r, 500))
+ expect(mockFetch).not.toHaveBeenCalled()
+ // Right event and property — wakes.
+ await matcher.processBatch([
+ createGlobals({ event: 'cal_booking', properties: { trigger_event: 'BOOKING_CREATED' } }),
+ ])
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
+ })
+
+ it('wakes a HogQL dynamic-key person-property wait condition via the person stream', async () => {
+ // HogQL: person.properties[concat(toString(person.properties.shop_id), '_billing_status')] = 'active'
+ await createWaitUntilWorkflow({
+ condition: {
+ filters: {
+ bytecode: [
+ '_H',
+ 1,
+ 32,
+ 'active',
+ 32,
+ 'properties',
+ 32,
+ 'person',
+ 1,
+ 2,
+ 32,
+ 'shop_id',
+ 32,
+ 'properties',
+ 32,
+ 'person',
+ 1,
+ 3,
+ 2,
+ 'toString',
+ 1,
+ 32,
+ '_billing_status',
+ 2,
+ 'concat',
+ 2,
+ 45,
+ 11,
+ ],
+ properties: [
+ {
+ type: 'hogql',
+ key: "person.properties[concat(toString(person.properties.shop_id), '_billing_status')] = 'active'",
+ },
+ ],
+ },
+ },
+ max_wait_duration: '5m',
+ })
+ // Parked person has shop_id but no billing status yet, so the condition is false and it parks.
+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([
+ {
+ id: '1',
+ uuid: 'uuid',
+ team_id: team.id,
+ properties: { shop_id: '42' },
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 1,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ distinct_id: 'distinct_id',
+ },
+ ])
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+ // clickhouse_person mutation sets 42_billing_status = 'active' with no analytics event.
+ const personMessage = {
+ value: Buffer.from(
+ JSON.stringify({
+ id: 'uuid',
+ team_id: team.id,
+ properties: JSON.stringify({ shop_id: '42', '42_billing_status': 'active' }),
+ is_deleted: 0,
+ is_identified: 1,
+ created_at: '2024-09-03 09:00:00.000',
+ timestamp: '2024-09-03 09:00:00.000',
+ version: 2,
+ })
+ ),
+ }
+ const personGlobals = await matcher._parsePersonBatch([personMessage as any])
+ await matcher.processBatch(personGlobals)
+ await waitForExpect(() => {
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ }, 10000)
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
+ })
+
+ // A parked wait keyed on an anonymous person can't be woken by the survivor's updates after a
+ // merge — the survivor's person/event updates arrive under a new person_id the wait doesn't
+ // reference. The matcher re-keys the wait off the clickhouse_person_distinct_id repoint so it
+ // follows the survivor. These two tests cover the re-key and the wake it enables.
+ // Factories (not eager consts): they read `team`, which is only assigned in beforeEach.
+ const anonPersonRow = (): any => ({
+ id: '1',
+ uuid: 'old-uuid',
+ team_id: team.id,
+ properties: { email: '[email protected]' },
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 1,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ distinct_id: 'distinct_id',
+ })
+ const distinctIdMoveMessage = (): any => ({
+ value: Buffer.from(
+ JSON.stringify({
+ team_id: team.id,
+ distinct_id: 'distinct_id',
+ person_id: 'new-uuid',
+ version: 2,
+ is_deleted: 0,
+ })
+ ),
+ })
+ // The post-merge survivor the repoint points at, now carrying the merged plan=enterprise. The
+ // re-keyed job resolves by this survivor personId (personIdRepointed), not the repointed distinct_id.
+ const survivorPersonRow = (): any => ({
+ id: '2',
+ uuid: 'new-uuid',
+ team_id: team.id,
+ properties: { email: '[email protected]', plan: 'enterprise' },
+ properties_last_updated_at: {},
+ properties_last_operation: null,
+ created_at: DateTime.utc(),
+ version: 2,
+ is_identified: true,
+ is_user_id: null,
+ last_seen_at: null,
+ })
+
+ it('re-keys a wait onto the survivor after a merge repoints its distinct_id, so the survivor wakes it', async () => {
+ await createWaitUntilWorkflow({
+ condition: { filters: personPropertyConditionFilters('plan', 'enterprise') },
+ max_wait_duration: '5m',
+ })
+ // Parked keyed on the anon person ('old-uuid'), which has no `plan`, so the wait parks on entry.
+ mockPersonRepo.fetchPersonsByDistinctIds.mockResolvedValue([anonPersonRow()])
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+
+ // The merge repoints 'distinct_id' onto survivor 'new-uuid' (version > 0). The matcher re-keys the
+ // parked wait onto the survivor and wakes it (scheduled = now). The worker then resolves the job by
+ // the survivor personId — not the repointed distinct_id — re-checks the condition against the
+ // survivor's plan=enterprise, and advances down the matched branch, firing the fetch.
+ mockPersonRepo.fetchPersonsByPersonIds.mockResolvedValue([survivorPersonRow()])
+ await matcher.processMoveBatch(matcher._parsePersonDistinctIdBatch([distinctIdMoveMessage() 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