: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
feat(workflows): warn when a step references a variable the run does not have (#71060)
Harley Alexanderce6736dd2661
diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex deef580c38f1..78fbeef671aa 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -252,6 +252,62 @@ describe('HogFunctionHandler', () => {})})+ describe('missing variable references', () => {+ beforeEach(() => {+ // {variables.coupon} compiled to hog bytecode; the run has no `coupon` variable+ action.config.inputs.name = {+ value: '{variables.coupon}',+ templating: 'hog',+ bytecode: ['_H', 1, 32, 'coupon', 32, 'variables', 1, 2],+ }+ invocation.state.variables = {}+ })++ it('warns in the run log when an input references a variable the run does not have', async () => {+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {+ queue: 'hog',+ queuePriority: 0,+ })++ const handlerResult = await hogFunctionHandler.execute({ invocation, action, result: invocationResult })++ const warnings = invocationResult.logs.filter(+ (l) => l.level === 'warn' && l.message.includes('not set for this run')+ )+ expect(warnings).toHaveLength(1)+ expect(warnings[0].message).toContain('coupon')+ // Rendering is unchanged: the step still executes, with the reference rendered empty+ expect(handlerResult.error).toBeUndefined()+ expect(mockFetch).toHaveBeenCalled()+ })++ it('does not warn again on a continuation that reuses already-rendered state', async () => {+ const firstResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {+ queue: 'hog',+ queuePriority: 0,+ })+ await hogFunctionHandler.execute({ invocation, action, result: firstResult })++ // Simulate a continuation: the rendered function state is carried on the action,+ // exactly as the handler persists it for a paused function+ invocation.state.currentAction!.hogFunctionState = {+ globals: { ...createExampleHogFlowInvocation(invocation.hogFlow).state.event, inputs: {} } as any,+ timings: [],+ attempts: 0,+ } as any++ const continuationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {+ queue: 'hog',+ queuePriority: 0,+ })+ await hogFunctionHandler.execute({ invocation, action, result: continuationResult })++ expect(+ continuationResult.logs.filter((l) => l.level === 'warn' && l.message.includes('not set for this run'))+ ).toHaveLength(0)+ })+ })+it('should throw an error if template is not found', async () => {const action = findActionByType(invocation.hogFlow, 'function')!action.config.template_id = 'template_123'diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex 3a92bced7751..d2195e90063e 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -15,6 +15,7 @@ import { RecipientPreferencesService } from '../../messaging/recipient-preferencimport { trackHogFlowBillableInvocation } from '../billing-utils'import { HogFlowFunctionsService } from '../hogflow-functions.service'import { actionIdForLogging, findContinueAction } from '../hogflow-utils'+import { observeMissingVariableReferences } from '../hogflow-variable-usage'import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'type FunctionActionType = 'function' | 'function_email' | 'function_sms'@@ -35,6 +36,12 @@ export class HogFunctionHandler implements ActionHandler {result,hogExecutorOptions,}: ActionHandlerOptions<Action>): Promise<ActionHandlerResult> {+ // Inputs are rendered once, on fresh entry into the action (continuations reuse the+ // rendered state in hogFunctionState) - so this also fires at most once per step per run+ if (!invocation.state.currentAction?.hogFunctionState) {+ observeMissingVariableReferences(invocation, action, result)+ }+const functionResult = await this.executeHogFunction(invocation, action, hogExecutorOptions)// Add all logsdiff --git a/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.test.tsnew file mode 100644index 000000000000..c9852fdfcae0--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.test.ts@@ -0,0 +1,95 @@+import { findMissingVariableReferences } from './hogflow-variable-usage'++describe('findMissingVariableReferences', () => {+ it.each([+ {+ name: 'hog format string referencing an unset variable',+ config: { inputs: { subject: { value: 'Your code: {variables.coupon}' } } },+ variables: {},+ expected: ['coupon'],+ },+ {+ name: 'liquid template referencing an unset variable',+ config: { inputs: { body: { value: 'Hi {{ variables.first_name }}!' } } },+ variables: {},+ expected: ['first_name'],+ },+ {+ name: 'bracket-form reference',+ config: { inputs: { body: { value: "{{ variables['my-var'] }}" } } },+ variables: {},+ expected: ['my-var'],+ },+ {+ name: 'bracket-form reference with whitespace',+ config: { inputs: { body: { value: '{{ variables [ "spaced" ] }}' } } },+ variables: {},+ expected: ['spaced'],+ },+ {+ name: 'reference nested inside object and array input values',+ config: {+ inputs: {+ payload: { value: { items: [{ text: '{variables.deep}' }] } },+ },+ },+ variables: {},+ expected: ['deep'],+ },+ {+ name: 'references in mappings',+ config: { mappings: [{ inputs: { url: { value: '{variables.link}' } } }] },+ variables: {},+ expected: ['link'],+ },+ {+ name: 'variable set on the run',+ config: { inputs: { subject: { value: '{variables.coupon}' } } },+ variables: { coupon: 'SAVE10' },+ expected: [],+ },+ {+ name: 'variable declared with a null default is not missing',+ config: { inputs: { subject: { value: '{variables.coupon}' } } },+ variables: { coupon: null },+ expected: [],+ },+ {+ name: 'no variable references',+ config: { inputs: { subject: { value: 'Hello {person.properties.name}' } } },+ variables: {},+ expected: [],+ },+ {+ name: 'compiled bytecode alongside the value does not produce false positives',+ config: {+ inputs: {+ subject: {+ value: 'plain text',+ bytecode: ['_H', 1, 32, 'variables', 32, 'coupon', 1, 2],+ },+ },+ },+ variables: {},+ expected: [],+ },+ {+ name: 'multiple missing references come back sorted and unique',+ config: {+ inputs: {+ a: { value: '{variables.zeta} and {variables.alpha} and {variables.zeta}' },+ },+ },+ variables: {},+ expected: ['alpha', 'zeta'],+ },+ {+ name: 'undefined variables map treats every reference as missing',+ config: { inputs: { subject: { value: '{variables.coupon}' } } },+ variables: undefined,+ expected: ['coupon'],+ },+ ])('$name', ({ config, variables, expected }) => {+ expect(findMissingVariableReferences(config, variables)).toEqual(expected)+ })+})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.ts b/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.tsnew file mode 100644index 000000000000..92e6152e11b0--- /dev/null+++ b/nodejs/src/cdp/services/hogflows/hogflow-variable-usage.ts@@ -0,0 +1,91 @@+import { DateTime } from 'luxon'+import { Counter } from 'prom-client'++import { HogFlowAction } from '~/cdp/schema/hogflow'+import { CyclotronJobInvocationHogFlow, CyclotronJobInvocationResult } from '~/cdp/types'+import { logger } from '~/common/utils/logger'++import { actionIdForLogging } from './hogflow-utils'++const counterMissingVariableReference = new Counter({+ name: 'cdp_hogflow_missing_variable_reference',+ help: 'A workflow step referenced a variable that is not set for the run, so it renders empty',+ labelNames: ['hog_flow_id'],+})++// Both templating modes reference workflow variables textually: `{variables.foo}` (hog) and+// `{{ variables.foo }}` (liquid), plus the bracket form `variables['my-var']`. A regex scan over+// the raw template strings covers both without parsing either language. Compiled hog bytecode+// never matches (it stores 'variables' and the key as separate string constants), so scanning a+// whole config is safe.+const DOT_REFERENCE_REGEX = /\bvariables\.([A-Za-z_$][A-Za-z0-9_$]*)/g+// Whitespace allowed around the brackets and quotes - liquid accepts `variables[ 'x' ]`+const BRACKET_REFERENCE_REGEX = /\bvariables\s*\[\s*['"]([^'"\]]+)['"]\s*\]/g++const collectReferences = (value: unknown, into: Set<string>): void => {+ if (typeof value === 'string') {+ for (const regex of [DOT_REFERENCE_REGEX, BRACKET_REFERENCE_REGEX]) {+ for (const match of value.matchAll(regex)) {+ into.add(match[1])+ }+ }+ return+ }+ if (Array.isArray(value)) {+ value.forEach((item) => collectReferences(item, into))+ return+ }+ if (value && typeof value === 'object') {+ Object.values(value).forEach((item) => collectReferences(item, into))+ }+}++/**+ * Names of workflow variables referenced anywhere in the action's inputs/mappings that are not+ * present on the run's variable map. Declared variables are always seeded onto the run (with a+ * null default), so an absent key means the run genuinely never had the variable: it was renamed+ * or removed after the run started, or an output_variable whose producing step never ran for+ * this run. Those references render empty - this makes that observable.+ */+export function findMissingVariableReferences(+ config: { inputs?: unknown; mappings?: unknown },+ variables: Record<string, any> | undefined+): string[] {+ const referenced = new Set<string>()+ collectReferences(config.inputs, referenced)+ collectReferences(config.mappings, referenced)++ const available = variables ?? {}+ return [...referenced].filter((name) => !(name in available)).sort()+}++/**+ * Warn (run log + operational log + metric) when a step is about to render inputs referencing+ * variables the run does not have. Detection only - rendering is unchanged.+ */+export function observeMissingVariableReferences(+ invocation: CyclotronJobInvocationHogFlow,+ action: HogFlowAction,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>+): void {+ const missing = findMissingVariableReferences(+ action.config as { inputs?: unknown; mappings?: unknown },+ invocation.state.variables+ )+ if (missing.length === 0) {+ return+ }++ result.logs.push({+ level: 'warn',+ timestamp: DateTime.now(),+ message: `${actionIdForLogging(action)} References variable(s) that are not set for this run: ${missing.join(', ')}. They will render empty.`,+ })+ logger.warn('[HogFlowVariableUsage] Step references variables the run does not have', {+ teamId: invocation.teamId,+ hogFlowId: invocation.hogFlow.id,+ actionId: action.id,+ missing,+ })+ counterMissingVariableReference.labels({ hog_flow_id: invocation.hogFlow.id }).inc()+}