: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): exit runs gracefully when their step is edited away (#70740)
Harley Alexander1cce99c37c6a
diff --git a/nodejs/src/cdp/schema/hogflow.ts b/nodejs/src/cdp/schema/hogflow.tsindex 8ae3f3cff980..f5c0068ce36c 100644--- a/nodejs/src/cdp/schema/hogflow.ts+++ b/nodejs/src/cdp/schema/hogflow.ts@@ -277,6 +277,9 @@ export const HogFlowSchema = z.object({edges: z.array(HogFlowEdgeSchema),variables: z.array(CyclotronJobInputSchemaTypeSchema).optional().nullable(),billable_action_types: z.array(z.string()).optional().nullable(),+ // Selected by the worker (HOG_FLOW_FIELDS); pg returns timestamptz as a Date, fixtures use+ // epoch millis. Used to distinguish live edits from malformed-from-birth graphs.+ updated_at: z.union([z.number(), z.string(), z.date()]).optional(),})// NOTE: these are purposefully exported as interfaces to support kea typegendiff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 49833555ff1c..67aa60390be7 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -554,6 +554,72 @@ describe('Hogflow Executor', () => {.build()}+ describe('workflow definition changed mid-run', () => {+ const buildFlow = (): HogFlow =>+ createHogFlow({+ actions: {},+ edges: [+ { from: 'trigger', to: 'delay', type: 'continue' },+ { from: 'delay', to: 'exit', type: 'continue' },+ ],+ })++ it.each([+ [+ 'the current action was deleted',+ (hogFlow: HogFlow) => {+ hogFlow.actions = hogFlow.actions.filter((action) => action.id !== 'delay')+ },+ ],+ [+ 'the current action no longer has a continue edge',+ (hogFlow: HogFlow) => {+ hogFlow.edges = hogFlow.edges.filter((edge) => edge.from !== 'delay')+ },+ ],+ ])('exits gracefully when %s', async (_desc, mutateFlow) => {+ const hogFlow = buildFlow()+ const invocation = createExampleHogFlowInvocation(hogFlow)+ // Parked on the delay long enough that it has elapsed, so the handler advances+ invocation.state.currentAction = {+ id: 'delay',+ startedAtTimestamp: DateTime.now().minus({ hours: 3 }).toMillis(),+ }+ mutateFlow(hogFlow)+ // The flow was edited after the run arrived at the step - the live-edit case+ hogFlow.updated_at = DateTime.now().toMillis()++ const result = await executor.execute(invocation)++ expect(result.finished).toBe(true)+ expect(result.error).toBeUndefined()+ const exitMetric = result.metrics.find((m) => m.metric_name === 'exited_workflow_changed')+ expect(exitMetric).toMatchObject({ metric_kind: 'other', instance_id: 'delay' })+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('failed')+ expect(result.logs.filter((l) => l.level === 'error')).toEqual([])+ expect(result.logs.map((l) => l.message).join('\n')).toContain('Workflow exited')+ })++ it('still fails the run when the graph was malformed all along (no edit since the step started)', async () => {+ const hogFlow = buildFlow()+ const invocation = createExampleHogFlowInvocation(hogFlow)+ invocation.state.currentAction = {+ id: 'delay',+ startedAtTimestamp: DateTime.now().minus({ hours: 3 }).toMillis(),+ }+ hogFlow.edges = hogFlow.edges.filter((edge) => edge.from !== 'delay')+ // No edit since the run arrived: the missing edge is a bad definition, not a live edit+ hogFlow.updated_at = DateTime.now().minus({ hours: 4 }).toMillis()++ const result = await executor.execute(invocation)++ expect(result.finished).toBe(true)+ expect(result.error).toBe('No next action found for action delay')+ expect(result.metrics.map((m) => m.metric_name)).toContain('failed')+ expect(result.metrics.map((m) => m.metric_name)).not.toContain('exited_workflow_changed')+ })+ })+describe('early exit conditions', () => {let hogFlow: HogFlowdiff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex eed473ce55ac..0bc9267aec41 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -34,6 +34,7 @@ import { WaitUntilTimeWindowHandler } from './actions/wait_until_time_window'import { HogFlowDuplicateObserverService } from './hogflow-duplicate-observer.service'import { HogFlowFunctionsService } from './hogflow-functions.service'import {+ WorkflowChangedError,actionIdForLogging,ensureCurrentAction,findContinueAction,@@ -493,16 +494,47 @@ export class HogFlowExecutorService {this.goToNextAction(result, currentAction, handlerResult.nextAction, 'succeeded')}} catch (err) {- // Add logs and metric specifically for this action- this.logAction(result, currentAction, 'error', `Errored: ${String(err)}`) // TODO: Is this enough detail?- this.trackActionMetric(result, currentAction, 'failed')+ // A live-edit WorkflowChangedError is not this action failing - the graph moved+ // underneath the run - so it skips the failure log/metric and is classified by the+ // outer catch. The same error from an untouched flow is a malformed definition and+ // keeps the failure treatment.+ if (!this.isLiveEditWorkflowChange(err, invocation)) {+ // Add logs and metric specifically for this action+ this.logAction(result, currentAction, 'error', `Errored: ${String(err)}`) // TODO: Is this enough detail?+ this.trackActionMetric(result, currentAction, 'failed')+ }throw err}} catch (err) {+ // The workflow was edited underneath this run and its current step (or that step's next+ // edge) no longer exists. That's a user action, not a defect: finish the run as a+ // deliberate exit - no result.error, so it doesn't count towards the workflow's failure+ // rate - with its own metric so exits are attributable per workflow.+ if (this.isLiveEditWorkflowChange(err, invocation)) {+ result.finished = true+ this.log(+ result,+ 'info',+ `Workflow exited: the workflow was edited and this run's current step no longer exists (${err.message})`+ )+ result.metrics.push({+ team_id: invocation.hogFlow.team_id,+ app_source_id: invocation.parentRunId ?? invocation.hogFlow.id,+ instance_id: invocation.state.currentAction?.id,+ metric_kind: 'other',+ metric_name: 'exited_workflow_changed',+ count: 1,+ })++ return result+ }+// The final catch - in this case we are always just logging the final outcomeresult.error = err.messageresult.finished = true // Explicitly set to true to prevent infinite loops+ // (a WorkflowChangedError from an untouched flow lands here too: the graph was malformed+ // all along, so it stays a failure the author can see rather than a quiet exit)this.maybeContinueToNextActionOnError(result)@@ -516,6 +548,19 @@ export class HogFlowExecutorService {return result}+ // A structural lookup miss only counts as a live edit when the flow was actually updated after+ // the run arrived at its current step. Otherwise the graph was malformed from the start (a bad+ // save, a lenient draft in a test run) and hiding it as a deliberate exit would bury the defect.+ private isLiveEditWorkflowChange(err: unknown, invocation: CyclotronJobInvocationHogFlow): boolean {+ if (!(err instanceof WorkflowChangedError)) {+ return false+ }+ const stepStartedAt = invocation.state.currentAction?.startedAtTimestamp+ // updated_at is a Date from pg in production and epoch millis in fixtures - normalize+ const updatedAt = invocation.hogFlow.updated_at ? new Date(invocation.hogFlow.updated_at).getTime() : null+ return Boolean(stepStartedAt && updatedAt && updatedAt > stepStartedAt)+ }+private goToNextAction(result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>,currentAction: HogFlowAction,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-utils.ts b/nodejs/src/cdp/services/hogflows/hogflow-utils.tsindex 3ac99c4efd7e..ae83444f87f4 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-utils.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-utils.ts@@ -8,10 +8,15 @@ import { filterFunctionInstrumented } from '~/cdp/utils/hog-function-filtering'import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'+// The run's position (or the edge it needs next) no longer exists in the flow's graph - the+// workflow was edited underneath an in-flight run. This is a user action, not a defect: the+// executor catches it and finishes the run as a graceful exit instead of a failure.+export class WorkflowChangedError extends Error {}+export const findActionById = (hogFlow: HogFlow, id: string): HogFlowAction => {const action = hogFlow.actions.find((action) => action.id === id)if (!action) {- throw new Error(`Action ${id} not found`)+ throw new WorkflowChangedError(`Action ${id} not found`)}return action@@ -41,7 +46,7 @@ export const findNextAction = (hogFlow: HogFlow, currentActionId: string, edgeIn}if (!nextActionId) {- throw new Error(`No next action found for action ${currentActionId}`)+ throw new WorkflowChangedError(`No next action found for action ${currentActionId}`)}return findActionById(hogFlow, nextActionId)diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.tsindex 28b929577849..e9b61c00938f 100644--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts@@ -94,7 +94,10 @@ describe('RecipientPreferencesService', () => {{} as Record<string, any>)- return createExampleInvocation(hogFlow, { inputs })+ // HogFlow only overlaps HogFunctionType structurally; updated_at diverges (Date|number vs string)+ return createExampleInvocation(hogFlow as unknown as Parameters<typeof createExampleInvocation>[0], {+ inputs,+ })}describe('shouldSkipAction', () => {diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex a605b2fa5453..81d9e1c332f7 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -245,6 +245,7 @@ export type MinimalAppMetric = {| 'push_skipped'| 'quota_limited'| 'conversion'+ | 'exited_workflow_changed'count: number}