: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
chore(workflows): add follow-live contract tests for live edits mid-run (#71057)
Harley Alexandere008c2c82077
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.tsindex 090693bbe5d0..7ac850ae882f 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@@ -1468,6 +1468,64 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {},]+ // Follow-live contract: a parked job carries no copy of its wait condition - the matcher+ // must evaluate the flow's live config on every event. Guards against a refactor that+ // stamps the condition (or its bytecode) into job state at park time, which would make+ // edits to a wait condition silently ignored for everyone already parked on it.+ it('after a wait-condition edit, only the new condition wakes a parked job', async () => {+ matcher.findRows = [+ {+ id: 'job-1',+ team_id: 1,+ function_id: 'flow-1',+ action_id: 'wait_node',+ distinct_id: 'user-1',+ person_id: null,+ },+ ]+ matcher.wakeRows = [{ ...matcher.findRows[0], state: stateBuffer({ currentAction: { id: 'wait_node' } }) }]+ matcher.updateRowCount = 1+ // The job parked while the wait subscribed to 'old_wake_event'; the flow has since+ // been edited to wait for 'new_wake_event'+ matcher.setHogFlows({+ 'flow-1': makeHogFlow({+ id: 'flow-1',+ actions: [+ {+ id: 'trigger_node',+ name: 'Trigger',+ type: 'trigger',+ config: { type: 'event', filters: {} },+ },+ {+ id: 'wait_node',+ name: 'Wait',+ type: 'wait_until_condition',+ config: {+ max_wait_duration: '5m',+ events: [+ {+ filters: {+ bytecode: eventBytecode('new_wake_event'),+ events: [{ id: 'new_wake_event' }],+ },+ },+ ],+ },+ },+ { id: 'exit_node', name: 'Exit', type: 'exit', config: {} },+ ],+ } as any),+ })++ await matcher.runWake([wakeWith('old_wake_event')])+ expect(matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))).toBeUndefined()++ matcher.calls = []+ await matcher.runWake([wakeWith('new_wake_event')])+ expect(matcher.calls.find((c) => c.sql.startsWith('UPDATE cyclotron_jobs'))).toBeDefined()+ })+it.each(cases)('$name -> woken: $woken', async ({ config, event, woken }) => {matcher.findRows = [{diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 67aa60390be7..25de57614c42 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -1,5 +1,5 @@// sort-imports-ignore-import { DateTime } from 'luxon'+import { DateTime, Duration } from 'luxon'import { FixtureHogFlowBuilder, SimpleHogFlowRepresentation } from '~/cdp/_tests/builders/hogflow.builder'import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegration } from '~/cdp/_tests/fixtures'@@ -620,6 +620,261 @@ describe('Hogflow Executor', () => {})})+ // The follow-live contract: the worker re-reads live config on every wake, so edits made+ // while a run is parked take effect the next time that run executes. These tests pin the+ // per-edit-type semantics down as a contract rather than emergent behavior. Note the wake+ // itself still happens at the originally scheduled time - only what happens ON wake is+ // recomputed from the edited config.+ describe('follow-live contract: edits picked up on wake', () => {+ const parkAt = (+ hogFlow: HogFlow,+ actionId: string,+ agoMs: number+ ): ReturnType<typeof createExampleHogFlowInvocation> => {+ const invocation = createExampleHogFlowInvocation(hogFlow)+ invocation.state.currentAction = {+ id: actionId,++ startedAtTimestamp: DateTime.now().minus({ milliseconds: agoMs }).toMillis(),+ }+ return invocation+ }++ const editFlow = (hogFlow: HogFlow, mutate: (hogFlow: HogFlow) => void): void => {+ mutate(hogFlow)+ hogFlow.updated_at = DateTime.now().toMillis()+ }++ describe('delay duration edits', () => {+ const buildDelayFlow = (duration: string): HogFlow =>+ createHogFlow({+ actions: { delay: { type: 'delay', config: { delay_duration: duration } } },+ edges: [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'exit', type: 'continue' },+ ],+ })++ it.each([+ // parkedAgo is relative to the fixed test clock; expectedParkOffsetMs is relative+ // to the step's startedAtTimestamp (null = the run advances instead of re-parking)+ {+ name: 'a shortened delay that has already elapsed advances on wake with no extra wait',+ initial: '7d',+ edited: '1d',+ parkedAgo: { days: 3 },+ expectedParkOffsetMs: null,+ },+ {+ name: 'a shortened delay still pending re-parks at startedAt + new duration',+ initial: '7d',+ edited: '5d',+ parkedAgo: { days: 3 },+ expectedParkOffsetMs: 5 * 24 * 60 * 60 * 1000,+ },+ {+ name: 'a lengthened delay woken at its old expiry re-parks for the remainder',+ initial: '1d',+ edited: '7d',+ parkedAgo: { days: 1, minutes: 1 },+ expectedParkOffsetMs: 7 * 24 * 60 * 60 * 1000,+ },+ ])('$name', async ({ initial, edited, parkedAgo, expectedParkOffsetMs }) => {+ const hogFlow = buildDelayFlow(initial)+ const invocation = parkAt(hogFlow, 'delay', Duration.fromObject(parkedAgo).toMillis())+ editFlow(hogFlow, (flow) => {+ const delayAction = flow.actions.find((a) => a.id === 'delay')!+ ;(delayAction.config as any).delay_duration = edited+ })++ const result = await executor.execute(invocation)++ if (expectedParkOffsetMs === null) {+ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ expect(result.invocation.queueScheduledAt).toBeUndefined()+ expect(result.invocation.state.currentAction?.id).toBe('exit')+ } else {+ expect(result.finished).toBe(false)+ expect(result.invocation.queueScheduledAt?.toMillis()).toBe(+ invocation.state.currentAction!.startedAtTimestamp + expectedParkOffsetMs+ )+ // Parked without advancing: the run is still standing on the delay step+ expect(result.invocation.state.currentAction?.id).toBe('delay')+ }+ })+ })++ describe('wait_until_time_window edits', () => {+ // The fixed test clock is 2025-01-01T00:00:00Z (a Wednesday)+ const buildWindowFlow = (config: Record<string, any>): HogFlow =>+ createHogFlow({+ actions: { window: { type: 'wait_until_time_window', config } },+ edges: [+ { from: 'trigger', to: 'window', type: 'continue' },+ { from: 'window', to: 'exit', type: 'continue' },+ ],+ })++ it.each([+ {+ name: 'a window edited to be open now advances on wake',+ edited: { time: 'any', day: 'any', timezone: 'UTC' },+ expectedParkIso: null,+ },+ {+ name: 'an edited window re-parks at the new window start',+ edited: { time: ['05:00', '06:00'], day: 'any', timezone: 'UTC' },+ expectedParkIso: '2025-01-01T05:00:00.000Z',+ },+ ])('$name', async ({ edited, expectedParkIso }) => {+ // Parked on a window that is closed at the fixed test time+ const hogFlow = buildWindowFlow({ time: ['10:00', '11:00'], day: 'any', timezone: 'UTC' })+ const invocation = parkAt(hogFlow, 'window', 60 * 60 * 1000)+ editFlow(hogFlow, (flow) => {+ const windowAction = flow.actions.find((a) => a.id === 'window')!+ windowAction.config = edited as any+ })++ const result = await executor.execute(invocation)++ if (expectedParkIso === null) {+ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ expect(result.invocation.state.currentAction?.id).toBe('exit')+ } else {+ expect(result.finished).toBe(false)+ expect(result.invocation.queueScheduledAt?.toUTC().toISO()).toBe(expectedParkIso)+ expect(result.invocation.state.currentAction?.id).toBe('window')+ }+ })+ })++ describe('graph edits around the run position', () => {+ const buildFlow = (): HogFlow =>+ createHogFlow({+ actions: {},+ edges: [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'exit', type: 'continue' },+ ],+ })++ const addDelayAction = (hogFlow: HogFlow, id: string): void => {+ hogFlow.actions.push({+ id,+ name: id,+ description: id,+ type: 'delay',+ config: { delay_duration: '2h' },+ created_at: Date.now(),+ updated_at: Date.now(),+ on_error: 'continue',+ } as any)+ }++ it('a step inserted after the run position executes when reached (live edges are followed)', async () => {+ const hogFlow = buildFlow()+ // Parked on the (2h) delay long enough that it advances on wake+ const invocation = parkAt(hogFlow, 'delay', 3 * 60 * 60 * 1000)+ editFlow(hogFlow, (flow) => {+ addDelayAction(flow, 'delay_b')+ flow.edges = [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'delay_b', type: 'continue' },+ { from: 'delay_b', to: 'exit', type: 'continue' },+ ]+ })++ const result = await executor.execute(invocation)++ // The run advanced onto the inserted step and parked there for its full duration+ expect(result.finished).toBe(false)+ expect(result.invocation.state.currentAction?.id).toBe('delay_b')+ expect(result.invocation.queueScheduledAt?.toMillis()).toBe(+ DateTime.now().plus({ hours: 2 }).toMillis()+ )+ })++ it('a step inserted behind the run position never executes for it (the past does not re-run)', async () => {+ const hogFlow = buildFlow()+ const invocation = parkAt(hogFlow, 'delay', 3 * 60 * 60 * 1000)+ editFlow(hogFlow, (flow) => {+ addDelayAction(flow, 'delay_early')+ flow.edges = [+ { from: 'trigger', to: 'delay_early', type: 'continue' },+ { from: 'delay_early', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'exit', type: 'continue' },+ ]+ })++ const result = await executor.execute(invocation)++ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ expect(result.invocation.queueScheduledAt).toBeUndefined()+ expect(result.logs.map((l) => l.message).join('\n')).not.toContain('delay_early')+ })+ })++ it('an in-progress function step completes with the inputs rendered before the edit', async () => {+ // Two fetches so the function pauses mid-execution: the run parks between them+ // with its rendered inputs stored in hogFunctionState+ await insertHogFunctionTemplate(hub.postgres, {+ id: 'template-test-follow-live-paused',+ name: 'Prints an input before and after an async pause',+ code: `+ print('Rendered as', inputs.name);+ fetch('https://posthog.com');+ fetch('https://posthog.com');+ print('Still', inputs.name);`,+ inputs_schema: [{ key: 'name', type: 'string', required: true }],+ })++ const hogFlow = createHogFlow({+ actions: {+ function_1: {+ type: 'function',+ config: {+ template_id: 'template-test-follow-live-paused',+ inputs: {+ name: { value: 'Original', bytecode: await compileHog(`return 'Original'`) },+ },+ },+ },+ },+ edges: [+ { from: 'trigger', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })++ const invocation = createExampleHogFlowInvocation(hogFlow)++ // First execution renders the inputs and pauses inside the function at the fetch+ const pausedResult = await executor.execute(invocation)+ expect(pausedResult.finished).toBe(false)+ expect(pausedResult.invocation.state.currentAction?.hogFunctionState).toEqual(expect.any(Object))+ expect(pausedResult.logs.map((l) => l.message).join('\n')).toContain('Rendered as, Original')++ // Edit the input while the run is paused inside the step+ editFlow(hogFlow, (flow) => {+ const action = flow.actions.find((a) => a.id === 'function_1')!+ ;(action.config as any).inputs.name.value = 'Edited'+ })+ ;(hogFlow.actions.find((a) => a.id === 'function_1')!.config as any).inputs.name.bytecode =+ await compileHog(`return 'Edited'`)++ // The continuation completes as prepared: inputs were rendered at step entry+ const result = await executor.execute(pausedResult.invocation)+ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ const messages = result.logs.map((l) => l.message).join('\n')+ expect(messages).toContain('Still, Original')+ expect(messages).not.toContain('Edited')+ })+ })+describe('early exit conditions', () => {let hogFlow: HogFlowdiff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 21dd677dd41f..3396ce3198ea 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -575,6 +575,168 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)})})+ describe('live edit while a run is parked (follow-live contract)', () => {+ // The runs park on a 2m delay so they cannot wake before the edit lands; the tests then+ // pull the wake forward explicitly (the same scheduled-time update the subscription+ // matcher performs), so there is no race between the park deadline and the edit.++ /** Wait until a job is parked in the future (a delay/wait step was hit) */+ async function waitForParkedJob(): Promise<void> {+ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ expect(jobs.some((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)+ }, 5000)+ }++ /** Persist an edited actions/edges graph and bust the worker's config cache, like Django's save + pub/sub would */+ async function applyLiveEdit(flow: HogFlow): Promise<void> {+ await hub.postgres.query(+ PostgresUse.COMMON_WRITE,+ `UPDATE posthog_hogflow SET actions = $2, edges = $3, updated_at = NOW() WHERE id = $1`,+ [flow.id, JSON.stringify(flow.actions), JSON.stringify(flow.edges)],+ 'liveEditHogFlow'+ )+ ;(hogflowWorker as any).hogFlowManager.lazyLoader.markForRefresh(flow.id)+ }++ /** Pull parked jobs' scheduled time forward so the worker picks them up now */+ async function wakeParkedJobsNow(): Promise<void> {+ await cyclotronPool.query(+ `UPDATE cyclotron_jobs SET scheduled = NOW() WHERE ${statusColumn} = 'available' AND scheduled > NOW()`+ )+ }++ /** Shorten the flow's delay so the woken run advances instead of re-parking */+ function shortenDelay(flow: HogFlow, actionId: string): void {+ const delay = flow.actions.find((a) => a.id === actionId)!+ ;(delay.config as any).delay_duration = '1s'+ }++ it('a content edit made while parked on an upstream delay is honored on wake', async () => {+ const flow = await createWorkflowFlow({+ actions: {+ trigger: trigger(),+ delay_1: delayAction('2m'),+ function_1: fetchAction('https://example.com/content-v1'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'delay_1', type: 'continue' },+ { from: 'delay_1', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })+ await triggerWorkflow(createGlobals())+ await waitForParkedJob()++ const functionAction = flow.actions.find((a) => a.id === 'function_1')!+ ;(functionAction.config as any).inputs.url.value = 'https://example.com/content-v2'+ shortenDelay(flow, 'delay_1')+ await applyLiveEdit(flow)+ await wakeParkedJobsNow()++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/content-v2', expect.anything())+ })++ it("rerouting the parked step's edge does not re-run earlier steps or run the old target", async () => {+ const flow = await createWorkflowFlow({+ actions: {+ trigger: trigger(),+ function_a: fetchAction('https://example.com/step-a'),+ delay_1: delayAction('2m'),+ function_b: fetchAction('https://example.com/step-b'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'function_a', type: 'continue' },+ { from: 'function_a', to: 'delay_1', type: 'continue' },+ { from: 'delay_1', to: 'function_b', type: 'continue' },+ { from: 'function_b', to: 'exit', type: 'continue' },+ ],+ })+ await triggerWorkflow(createGlobals())+ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/step-a', expect.anything())+ }, 10000)+ await waitForParkedJob()++ // Reroute the delay's continue edge onto a newly added step+ const functionB = flow.actions.find((a) => a.id === 'function_b')!+ flow.actions.push({+ ...functionB,+ id: 'function_c',+ config: {+ ...(functionB.config as any),+ inputs: { url: { value: 'https://example.com/step-c' }, method: { value: 'POST' } },+ },+ })+ flow.edges = [+ { from: 'trigger', to: 'function_a', type: 'continue' },+ { from: 'function_a', to: 'delay_1', type: 'continue' },+ { from: 'delay_1', to: 'function_c', type: 'continue' },+ { from: 'function_c', to: 'exit', type: 'continue' },+ ]+ shortenDelay(flow, 'delay_1')+ await applyLiveEdit(flow)+ await wakeParkedJobsNow()++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/step-c', expect.anything())+ }, 10000)++ // Exactly one send per executed step: the step behind the run did not re-run, the old+ // target never ran, the new target ran once+ const urls = mockFetch.mock.calls.map((call) => call[0])+ expect(urls.filter((u) => u === 'https://example.com/step-a')).toHaveLength(1)+ expect(urls.filter((u) => u === 'https://example.com/step-b')).toHaveLength(0)+ expect(urls.filter((u) => u === 'https://example.com/step-c')).toHaveLength(1)+ })++ it('deleting the step a run is parked on exits the run gracefully on wake', async () => {+ const flow = await createWorkflowFlow({+ actions: {+ trigger: trigger(),+ delay_1: delayAction('2m'),+ function_1: fetchAction('https://example.com/should-not-fire'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'delay_1', type: 'continue' },+ { from: 'delay_1', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })+ await triggerWorkflow(createGlobals())+ await waitForParkedJob()++ flow.actions = flow.actions.filter((a) => a.id !== 'delay_1')+ flow.edges = [+ { from: 'trigger', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ]+ await applyLiveEdit(flow)+ await wakeParkedJobsNow()++ // The parked run wakes, finds its step gone, and finishes as a deliberate exit+ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ expect(jobs.filter((j: any) => j.status === 'completed')).toHaveLength(1)+ }, 10000)+ expect(mockFetch).not.toHaveBeenCalled()++ await waitForExpect(() => {+ const metricNames = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ .map((m: any) => m.value.metric_name)+ expect(metricNames).toContain('exited_workflow_changed')+ expect(metricNames).not.toContain('failed')+ }, 5000)+ })+ })+describe('multiple workflows matching same event', () => {const simpleFetchWorkflow = (url: string) => ({actions: {