: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): re-read the person uncached when a wait step first evaluates (#88025)
Daniel Marchukd70f1e554149
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex 4a7b30ce3665..d751e4a13171 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -193,14 +193,36 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {variables: hogFlowInvocationState.variables || {},})- loadedInvocations.push({+ const loaded: CyclotronJobInvocationHogFlow = {...item,state: hogFlowInvocationState,hogFlow,person: person ?? undefined,groups,filterGlobals,- })+ }++ if (personIdOrDistinctId) {+ loaded.refreshPerson = async () => {+ const fresh = await this.personsManager.getCyclotronPerson(+ hogFlow.team_id,+ personIdOrDistinctId,+ kind,+ { forceFresh: true }+ )+ return {+ person: fresh ?? undefined,+ filterGlobals: convertToHogFunctionFilterGlobal({+ event: hogFlowInvocationState.event,+ person: fresh ?? undefined,+ groups,+ variables: hogFlowInvocationState.variables || {},+ }),+ }+ }+ }++ loadedInvocations.push(loaded)}))diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.tsindex ac8904d5d5c9..4c9288bf40e2 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.test.ts@@ -191,6 +191,37 @@ describe('CdpCyclotronWorkerHogFlow', () => {.build()))++ hogFlows.push(+ await insertHogFlow(+ hub.postgres,+ new FixtureHogFlowBuilder()+ .withName('Test Hog Flow with a wait')+ .withTeamId(team.id)+ .withStatus('active')+ .withWorkflow({+ actions: {+ trigger: {+ type: 'trigger',+ config: { type: 'event', filters: {} },+ },+ wait: {+ type: 'wait_until_condition',+ config: {+ condition: { filters: { properties: [{ key: 'email', type: 'person' }] } },+ max_wait_duration: '1h',+ } as any,+ },+ exit: { type: 'exit', config: {} },+ },+ edges: [+ { from: 'trigger', to: 'wait', type: 'continue' },+ { from: 'wait', to: 'exit', type: 'continue' },+ ],+ } as any)+ .build()+ )+ )})afterEach(async () => {@@ -370,6 +401,34 @@ describe('CdpCyclotronWorkerHogFlow', () => {expect(results[3].invocation.state.personId).toBeUndefined()})+ it('supplies a refreshPerson hook that re-reads uncached and rebuilds the filter globals', async () => {+ // A wait step calls this before its first evaluation. Without it the wait evaluates the+ // person the dequeue cached, and a run that parks on a stale read has nothing left to wake it.+ const results = (await processor.processInvocations([+ createSerializedHogFlowInvocation(hogFlows[2], {+ event: { distinct_id: 'distinct_A_1', properties: {} } as any,+ }),+ ])) as CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>[]++ const getPerson = jest.spyOn(processor['personsManager'], 'getCyclotronPerson').mockResolvedValue({+ id: 'dd3d6f80-60ad-45c3-bd61-e2300f2ba7e1',+ properties: { name: 'Person A 1', email: '[email protected]' },+ name: 'Person A 1',+ url: 'http://localhost:8000/project/1/person/distinct_A_1',+ distinct_id: 'distinct_A_1',+ })++ const refreshed = await results[0].invocation.refreshPerson!()++ expect(getPerson).toHaveBeenCalledWith(expect.any(Number), 'distinct_A_1', 'distinct_id', {+ forceFresh: true,+ })+ expect(refreshed.filterGlobals.person?.properties).toEqual({+ name: 'Person A 1',+ email: '[email protected]',+ })+ })+it('terminates invocations as canceled when the workflow is disabled after being queued', async () => {const hogFlow = hogFlows[0]diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.tsindex dd9522de3587..dfa54cabc025 100644--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.test.ts@@ -219,6 +219,53 @@ describe('action.conditional_branch', () => {counterHogflowRekeyWake.reset()})+ it('evaluates a first wait against the refreshed person, on the invocation and the result alike', async () => {+ // The result carries a shallow clone, so both have to land on the fresh person: whichever+ // one a later reader picks up must not still hold the person the dequeue cached.+ const freshPerson = { id: 'p1', properties: { email: '[email protected]' } }+ waitInvocation.refreshPerson = jest.fn().mockResolvedValue({+ person: freshPerson,+ filterGlobals: { ...waitInvocation.filterGlobals, person: freshPerson },+ })+ const result = createInvocationResult<CyclotronJobInvocationHogFlow>(waitInvocation)++ await handler.execute({ invocation: waitInvocation, action: waitAction, result })++ expect(waitInvocation.refreshPerson).toHaveBeenCalledTimes(1)+ expect(waitInvocation.filterGlobals.person?.properties).toEqual(freshPerson.properties)+ expect(result.invocation.filterGlobals.person?.properties).toEqual(freshPerson.properties)+ expect(result.invocation.person).toEqual(freshPerson)+ })++ it('keeps the person it already had when the refresh comes back empty', async () => {+ // The refresh adds freshness; it must not drop a person because one lookup found nothing.+ const before = waitInvocation.person+ waitInvocation.refreshPerson = jest+ .fn()+ .mockResolvedValue({ person: undefined, filterGlobals: { person: null } as any })+ const result = createInvocationResult<CyclotronJobInvocationHogFlow>(waitInvocation)++ await handler.execute({ invocation: waitInvocation, action: waitAction, result })++ expect(waitInvocation.person).toEqual(before)+ expect(waitInvocation.filterGlobals.person).not.toBeNull()+ })++ it('keeps the cached person on a re-check of a wait that already parked', async () => {+ const refreshPerson = jest.fn().mockResolvedValue(undefined)+ waitInvocation.refreshPerson = refreshPerson+ // Set once the wait parks; its re-checks run 10 minutes apart, by when the cache expired.+ waitInvocation.state.currentAction!.pollReparked = true++ await handler.execute({+ invocation: waitInvocation,+ action: waitAction,+ result: createInvocationResult(waitInvocation),+ })++ expect(refreshPerson).not.toHaveBeenCalled()+ })+it('advances to the matched branch and clears eventMatched', async () => {waitInvocation.state.currentAction!.eventMatched = truewaitInvocation.state.currentAction!.eventMatchedEvent = 'subscription created'diff --git a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.tsindex 3b5cb9f9b005..075d74dfcca5 100644--- a/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts+++ b/nodejs/src/cdp/services/hogflows/actions/conditional_branch.ts@@ -37,6 +37,7 @@ export class ConditionalBranchHandler implements ActionHandler {async execute({invocation,action,+ result,}: ActionHandlerOptions<Extract<HogFlowAction, { type: 'conditional_branch' | 'wait_until_condition' }>>): Promise<ActionHandlerResult> {@@ -61,6 +62,26 @@ export class ConditionalBranchHandler implements ActionHandler {}}+ // The person the worker read at dequeue can predate a write this wait is waiting for, and a+ // wait that parks on that read is stuck: the write already happened, so no person message+ // follows to wake it. Re-read before the first evaluation of each wait — including a wait+ // reached later in the same dequeue. Re-checks of a wait that already parked run 10 minutes+ // apart, by when the cache has expired, so they keep the cheaper read.+ if (action.type === 'wait_until_condition' && !invocation.state?.currentAction?.pollReparked) {+ const refreshed = await invocation.refreshPerson?.()+ // A refresh that finds no person keeps the dequeue's read. The refresh exists to make a+ // just-written property visible, not to drop a person: a lookup that comes back empty+ // (replica lag, a transient miss) would otherwise evaluate the condition against nothing.+ if (refreshed?.person) {+ invocation.person = refreshed.person+ invocation.filterGlobals = refreshed.filterGlobals+ // The result carries a shallow clone, so rebinding only `invocation` would leave it+ // pointing at the pre-refresh globals for anything that reads it later.+ result.invocation.person = refreshed.person+ result.invocation.filterGlobals = refreshed.filterGlobals+ }+ }+const conditionResult = await checkConditions(invocation,action.type === 'conditional_branch'diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts b/nodejs/src/cdp/services/managers/persons-manager.service.test.tsindex f4d98ec07847..f6a66e4a5379 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.test.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.test.ts@@ -264,6 +264,32 @@ describe('PersonsManagerService', () => {})})+ describe('forceFresh', () => {+ it('re-reads a cached person, so a write made after it was cached is visible', async () => {+ // A hogflow run enrolling just after a person write evaluates its first wait against this+ // read. Serving the pre-write cache entry there parks the run with nothing left to wake it.+ const cachedRead = await manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id')+ expect(cachedRead?.properties).toEqual({ foo: '1' })++ jest.spyOn(repo, 'fetchPersonsByDistinctIds').mockResolvedValue([+ {+ uuid: TEST_PERSONS[0].uuid,+ team_id: TEAM_1,+ distinct_id: 'distinct_id_A_1',+ properties: { foo: 'written-after-caching' },+ },+ ] as any)++ expect((await manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id'))?.properties).toEqual({+ foo: '1',+ })+ expect(+ (await manager.getCyclotronPerson(TEAM_1, 'distinct_id_A_1', 'distinct_id', { forceFresh: true }))+ ?.properties+ ).toEqual({ foo: 'written-after-caching' })+ })+ })+describe('getCyclotronPerson with person_id', () => {it('returns a person by UUID and resolves distinct_id', async () => {const result = await manager.getCyclotronPerson(TEAM_1, TEST_PERSONS[0].uuid, 'person_id')diff --git a/nodejs/src/cdp/services/managers/persons-manager.service.ts b/nodejs/src/cdp/services/managers/persons-manager.service.tsindex 67476902648b..e9ca215f58e4 100644--- a/nodejs/src/cdp/services/managers/persons-manager.service.ts+++ b/nodejs/src/cdp/services/managers/persons-manager.service.ts@@ -59,10 +59,20 @@ export class PersonsManagerService {public async getCyclotronPerson(teamId: number,id: string,- kind: 'distinct_id' | 'person_id'+ kind: 'distinct_id' | 'person_id',+ options?: { forceFresh?: boolean }): Promise<CyclotronPerson | null> {const key = toKey({ teamId, id })+ if (options?.forceFresh) {+ // Callers that would otherwise act on a stale read in a way nothing can correct later.+ if (kind === 'distinct_id') {+ this.lazyLoaderByDistinctId.markForRefresh(key)+ } else {+ this.lazyLoaderByPersonId.markForRefresh(key)+ }+ }+const [team, dbPerson] = await Promise.all([this.teamManager.getTeam(teamId),kind === 'distinct_id' ? this.lazyLoaderByDistinctId.get(key) : this.lazyLoaderByPersonId.get(key),diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex eda18f37ce73..eea5a1f32c79 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -367,6 +367,10 @@ export type CyclotronJobInvocationHogFlow = CyclotronJobInvocation & {person?: CyclotronPersongroups?: HogFunctionInvocationGlobals['groups']filterGlobals: HogFunctionFilterGlobals+ // Re-reads the person uncached and rebuilds filterGlobals from it. The worker supplies this; a+ // wait step calls it before its first evaluation, where a stale person parks the run for good.+ // It returns the values rather than mutating, so it stays correct on a cloned invocation.+ refreshPerson?: () => Promise<{ person?: CyclotronPerson; filterGlobals: HogFunctionFilterGlobals }>}export type HogFlowInvocationContext = {