: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): park the AI task and scout steps until the run finishes (#94051)
Harley Alexanderb247086195bc
diff --git a/docs/internal/workflow-ai-task-limits.md b/docs/internal/workflow-ai-task-limits.mdindex 4537a3d5a454..5ea795a455fd 100644--- a/docs/internal/workflow-ai-task-limits.md+++ b/docs/internal/workflow-ai-task-limits.md@@ -12,3 +12,22 @@ Staff can override either limit for a project in Django admin under **Team workfWhen a limit blocks task creation, the Create AI task step records the API reason as an error. The workflow then follows the step's `on_error` configuration.Keep both limits enabled when raising capacity. Set the per-workflow limit for the expected trigger volume and retain a higher project-wide ceiling as the final spend guardrail.++## Waiting for the task to finish++A workflow run pauses at an AI task step or a scout step until the run it started reaches a terminal status.+After success, the next step sees the dispatch IDs, `status: completed`, and a capped `final_message` (tasks) or `summary` (scouts). The result also includes `pr_urls` when present.+A failed or cancelled run fails the step. The step's `on_error` setting decides whether the workflow continues.+With `on_error: continue`, the dispatch IDs remain available. The failed step does not store the terminal status, message, or `error_message` in its result.++A template asks for the wait by returning an `await` object next to its result, for example `{ 'id': ..., 'run_id': ..., 'await': { 'max_wait': '190m', 'label': 'task' } }`.+`max_wait` is set by the template's author, never by the workflow author, and the engine caps it at 24 hours.+The task template uses 190 minutes and the scout template 35 minutes: each product's own runtime cap plus slack, so the product's own timeout wake lands before the step's deadline.+A step that reaches its deadline without a wake fails with a timeout.+The wake arrives through the `$workflow_step_resume` internal event, keyed on the step's idempotency key, so any template that dispatches a run its owner can report on can use the same path.+`CDP_HOGFLOW_AWAITED_STEPS_ENABLED` on the plugin server enables new waits. Existing waits still receive their results when this flag is off.+A wake that lands while the step is still dispatching is counted and dropped, because the worker owns the job state until it parks.+That step then fails at its own deadline. The `cdp_hogflow_step_resume` counter reports these as `job_running`.+Leave the flag off until the API that emits the wake is deployed.+A task that ends through the agent's `finish` tool completes a few seconds before its final message is saved.+The step waits for that message (up to 30 seconds) rather than continuing with an empty one.diff --git a/nodejs/src/cdp/async-functions/create-task.ts b/nodejs/src/cdp/async-functions/create-task.tsindex cf10a1899ceb..1017f1f02857 100644--- a/nodejs/src/cdp/async-functions/create-task.ts+++ b/nodejs/src/cdp/async-functions/create-task.ts@@ -7,6 +7,7 @@ import { defaultConfig } from '~/common/config/config'import { registerAsyncFunction } from '../async-function-registry'import { PosthogJwtAudience } from '../utils/jwt-utils'import { ScopedServiceJwt } from '../utils/scoped-service-jwt'+import { workflowStepDispatchKeyFromInvocation } from '../utils/workflow-step-dispatch-key'// The token rides the staged fetch verbatim through every engine retry (executeFetch re-queues// the identical request), so its lifetime must cover the whole backoff chain plus queue lag,@@ -29,12 +30,12 @@ registerAsyncFunction('postHogCreateTask', {}// Both come from the flow-spawned invocation, never from step inputs: the hog_flow_id- // claim is what the endpoint trusts to resolve the workflow owner, and the action id- // makes the idempotency key step-scoped (the run id alone is shared by every step in- // the run, so two task steps in one workflow would dedupe against each other).+ // claim is what the endpoint trusts to resolve the workflow owner, and the dispatch key+ // scopes the idempotency key to this step and visit (the run id alone is shared by every+ // step in the run, so two task steps in one workflow would dedupe against each other).const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- const actionId = context.invocation.state.actionId- if (!hogFlow?.id || !actionId) {+ const idempotencyKey = workflowStepDispatchKeyFromInvocation(context.invocation)+ if (!hogFlow?.id || !idempotencyKey) {throw new Error('postHogCreateTask only runs inside a workflow')}@@ -54,7 +55,7 @@ registerAsyncFunction('postHogCreateTask', {},body: JSON.stringify({...payload,- idempotency_key: `${context.invocation.id}:${actionId}`,+ idempotency_key: idempotencyKey,}),})},diff --git a/nodejs/src/cdp/async-functions/run-scout.ts b/nodejs/src/cdp/async-functions/run-scout.tsindex b48f330444db..f52e38cf3c13 100644--- a/nodejs/src/cdp/async-functions/run-scout.ts+++ b/nodejs/src/cdp/async-functions/run-scout.ts@@ -7,6 +7,7 @@ import { defaultConfig } from '~/common/config/config'import { registerAsyncFunction } from '../async-function-registry'import { PosthogJwtAudience } from '../utils/jwt-utils'import { ScopedServiceJwt } from '../utils/scoped-service-jwt'+import { workflowStepDispatchKeyFromInvocation } from '../utils/workflow-step-dispatch-key'// The token rides the staged fetch verbatim through every engine retry (executeFetch re-queues// the identical request), so its lifetime must cover the whole backoff chain plus queue lag,@@ -31,12 +32,12 @@ registerAsyncFunction('postHogRunScout', {}// Both come from the flow-spawned invocation, never from step inputs: the hog_flow_id- // claim is what the endpoint trusts to resolve the calling workflow, and the action id- // makes the idempotency key step-scoped (the run id alone is shared by every step in- // the run, so two run-scout steps in one workflow would dedupe against each other).+ // claim is what the endpoint trusts to resolve the calling workflow, and the dispatch key+ // scopes the idempotency key to this step and visit (the run id alone is shared by every+ // step in the run, so two run-scout steps in one workflow would dedupe against each other).const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow- const actionId = context.invocation.state.actionId- if (!hogFlow?.id || !actionId) {+ const idempotencyKey = workflowStepDispatchKeyFromInvocation(context.invocation)+ if (!hogFlow?.id || !idempotencyKey) {throw new Error('postHogRunScout only runs inside a workflow')}@@ -58,7 +59,7 @@ registerAsyncFunction('postHogRunScout', {},body: JSON.stringify({skill_name: payload.skill_name,- idempotency_key: `${context.invocation.id}:${actionId}`,+ idempotency_key: idempotencyKey,}),})},diff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 5795706af52b..1b3b04e320f1 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -152,6 +152,7 @@ export type CdpCoreServicesConfig = Pick<| 'CDP_WATCHER_STATE_LOCK_TTL'| 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_TIME_MS'| 'CDP_WATCHER_OBSERVE_RESULTS_BUFFER_MAX_RESULTS'+ | 'CDP_HOGFLOW_AWAITED_STEPS_ENABLED'| 'SES_ACCESS_KEY_ID'| 'SES_SECRET_ACCESS_KEY'| 'SES_REGION'@@ -526,7 +527,8 @@ export function createCdpCoreServices(cohortMembershipRepository,deps.integrationManager,hogFlowDuplicateObserver,- cdpUsageReporter+ cdpUsageReporter,+ { awaitedStepsEnabled: config.CDP_HOGFLOW_AWAITED_STEPS_ENABLED })const hogFunctionMonitoringService = new HogFunctionMonitoringService(outputs)diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex e7e05e8d96df..87ef65cd8b63 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -59,6 +59,8 @@ export type CdpConfig = ClickhouseConfig & {CDP_CYCLOTRON_COMPRESS_VM_STATE: booleanCDP_CYCLOTRON_USE_BULK_COPY_JOB: booleanCDP_CYCLOTRON_COMPRESS_KAFKA_DATA: boolean+ // Off until Django emits `$workflow_step_resume`, or parked steps never wake.+ CDP_HOGFLOW_AWAITED_STEPS_ENABLED: booleanCDP_REDIS_HOST: stringCDP_REDIS_PORT: numberCDP_REDIS_PASSWORD: string@@ -259,6 +261,7 @@ export function getDefaultCdpConfig(): CdpConfig {CDP_CYCLOTRON_COMPRESS_VM_STATE: isProdEnv() ? false : true,CDP_CYCLOTRON_USE_BULK_COPY_JOB: isProdEnv() ? false : true,CDP_CYCLOTRON_COMPRESS_KAFKA_DATA: true,+ CDP_HOGFLOW_AWAITED_STEPS_ENABLED: isProdEnv() ? false : true,CDP_REDIS_HOST: '127.0.0.1',CDP_REDIS_PORT: 6379,CDP_REDIS_PASSWORD: '',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 68626f4a6b68..e388f7a1c487 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@@ -123,6 +123,7 @@ class MatcherUnderTest extends CdpHogflowSubscriptionMatcherConsumer {public claimedWatcherIds: string[] | null = nullpublic wakeRows: MockRow[] = []public moveRows: MockRow[] = []+ public resumeRows: { id: string; status: string; state?: Buffer | null }[] = []public updateRowCount = 0constructor() {@@ -153,6 +154,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, status, state FROM cyclotron_jobs')) {+ return Promise.resolve({ rows: this.resumeRows, rowCount: this.resumeRows.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 })}@@ -1848,4 +1852,99 @@ describe('CdpHogflowSubscriptionMatcherConsumer', () => {}})})++ describe('step resumes', () => {+ const jobId = 'b1f0c2d4-0000-4000-8000-000000000001'+ const originKey = `${jobId}:task_node:3`+ const rawResume = (properties: Record<string, any>, team_id = 2): any => ({+ value: Buffer.from(+ JSON.stringify({+ team_id,+ event: {+ uuid: 'evt-uuid-resume',+ event: '$workflow_step_resume',+ distinct_id: `team_${team_id}`,+ properties,+ timestamp: '2024-01-01T00:00:00Z',+ },+ })+ ),+ })+ const parkedState = (key = originKey): Buffer =>+ stateBuffer({+ actionStepCount: 3,+ currentAction: {+ id: 'task_node',+ startedAtTimestamp: 1,+ awaitingResume: { key, deadlineAt: 'x', dispatch: {} },+ },+ })+ const resume = { origin_key: originKey, status: 'completed', result: { final_message: 'done' } }+ const resumeUpdate = () =>+ matcher.calls.find(+ (c) => c.sql.startsWith('UPDATE cyclotron_jobs') && c.sql.includes('SET scheduled = NOW(), state')+ )+ const writtenState = (): any => parseJSON(resumeUpdate()!.params[1][0].toString('utf-8'))++ it('routes a resume out of the events stream even for a team with no wait steps', () => {+ const other = { value: Buffer.from(JSON.stringify({ team_id: 2, event: { event: 'other' } })) }++ const { resumes, rest } = matcher._splitStepResumes([rawResume(resume), other])++ expect(resumes).toEqual([{ ...resume, jobId, actionId: 'task_node' }])+ expect(rest).toEqual([other])+ })++ it.each([+ 'nope',+ 'not-a-uuid:task:3',+ `${jobId}::3`,+ `${jobId}:task:-1`,+ `${jobId}:task:3.r0`,+ `${jobId}:task:NaN`,+ ])('drops an invalid key: %s', (origin_key) => {+ const { resumes, rest } = matcher._splitStepResumes([rawResume({ ...resume, origin_key })])++ expect(resumes).toEqual([])+ expect(rest).toEqual([])+ })++ it('wakes a parked job and stamps the result on its step', async () => {+ matcher.resumeRows = [{ id: jobId, status: 'available', state: parkedState() }]++ await matcher.processStepResumes([{ ...resume, status: 'completed', jobId, actionId: 'task_node' }])++ expect(resumeUpdate()!.params[0]).toEqual([jobId])+ expect(writtenState().state.currentAction.resumeResult).toEqual({+ key: originKey,+ status: 'completed',+ result: { final_message: 'done' },+ })+ })++ it.each([+ ['the job is still running', 'running', parkedState()],+ ['the job already finished', 'completed', parkedState()],+ ['the job failed', 'failed', parkedState()],+ ['the wake belongs to an earlier visit', 'available', parkedState(`${jobId}:task_node:2`)],+ ])('wakes nothing when %s', async (_, status, state) => {+ matcher.resumeRows = [{ id: jobId, status, state }]++ await matcher.processStepResumes([{ ...resume, status: 'completed', jobId, actionId: 'task_node' }])++ expect(resumeUpdate()).toBeUndefined()+ })++ it('applies the current wake when a stale one shares the batch', async () => {+ matcher.resumeRows = [{ id: jobId, status: 'available', state: parkedState() }]+ const parsedResume = { ...resume, status: 'completed' as const, jobId, actionId: 'task_node' }++ await matcher.processStepResumes([+ { ...parsedResume, origin_key: `${jobId}:task_node:2`, status: 'failed' },+ parsedResume,+ ])++ expect(writtenState().state.currentAction.resumeResult.key).toBe(originKey)+ })+ })})diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.tsindex 1d1966a4325b..f93b89ef2d2b 100644--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts@@ -1,8 +1,10 @@import { Message } from 'node-rdkafka'import { Pool } from 'pg'import { Counter, Gauge, Histogram } from 'prom-client'+import { z } from 'zod'import { HogFlow, HogFlowAction } from '~/cdp/schema/hogflow'+import { parseWorkflowStepDispatchKey } from '~/cdp/utils/workflow-step-dispatch-key'import {KAFKA_CDP_INTERNAL_EVENTS,KAFKA_EVENTS_JSON,@@ -179,6 +181,23 @@ type MatchedJob = {type FilterGlobals = ReturnType<typeof convertToHogFunctionFilterGlobal>+// Emitted by Django when a run a workflow step dispatched ends; `origin_key` names the parked job.+export const WORKFLOW_STEP_RESUME_EVENT = '$workflow_step_resume'++const WorkflowStepResumeSchema = z.object({+ origin_key: z.string().min(1),+ status: z.enum(['completed', 'failed', 'cancelled']),+ result: z.record(z.string(), z.unknown()).optional().nullable(),+})++type StepResume = z.infer<typeof WorkflowStepResumeSchema> & { jobId: string; actionId: string }++const counterStepResume = new Counter({+ name: 'cdp_hogflow_step_resume',+ help: 'Workflow step resumes by outcome.',+ labelNames: ['outcome'],+})+// Wakes parked hogflow jobs when an event matches a `wait_until_condition` step// or a workflow conversion goal.export class CdpHogflowSubscriptionMatcherConsumer<@@ -816,6 +835,94 @@ export class CdpHogflowSubscriptionMatcherConsumer<return events}+ // Step resumes name their job, so they skip the person and team gates the event parser applies.+ public _splitStepResumes(messages: Message[]): { resumes: StepResume[]; rest: Message[] } {+ const resumes: StepResume[] = []+ const rest: Message[] = []+ for (const message of messages) {+ let parsed+ try {+ parsed = CdpInternalEventSchema.parse(parseJSON(message.value!.toString()))+ } catch {+ rest.push(message)+ continue+ }+ if (parsed.event.event !== WORKFLOW_STEP_RESUME_EVENT) {+ rest.push(message)+ continue+ }+ const props = WorkflowStepResumeSchema.safeParse(parsed.event.properties)+ const key = props.success ? parseWorkflowStepDispatchKey(props.data.origin_key) : null+ if (!props.success || !key) {+ counterStepResume.labels({ outcome: 'parse_error' }).inc()+ continue+ }+ resumes.push({ ...props.data, ...key })+ }+ return { resumes, rest }+ }++ @instrumented('cdpHogflowSubscriptionMatcher.processStepResumes')+ public async processStepResumes(resumes: StepResume[]): Promise<void> {+ if (resumes.length === 0) {+ return+ }+ const byJob = new Map<string, StepResume[]>()+ for (const resume of resumes) {+ const pending = byJob.get(resume.jobId) ?? []+ pending.push(resume)+ byJob.set(resume.jobId, pending)+ }+ const client = await this.cyclotronPool.connect()+ try {+ await client.query('BEGIN')+ const rows = await client.query(+ `SELECT id, status, state FROM cyclotron_jobs WHERE id = ANY($1::uuid[]) ORDER BY id FOR UPDATE`,+ [[...byJob.keys()]]+ )+ const updates: { id: string; state: Buffer }[] = []+ for (const row of rows.rows) {+ const jobResumes = byJob.get(row.id)!+ byJob.delete(row.id)+ // A job that is not parked yet cannot take the wake: the worker owns `state` while it+ // runs, so its flush would drop the write. That step falls back to its own deadline.+ if (row.status !== 'available') {+ counterStepResume.labels({ outcome: `job_${row.status}` }).inc()+ continue+ }+ // One batch can carry a stale wake from an earlier visit next to the current one.+ const state = row.state+ ? jobResumes.reduce<Buffer | null>(+ (applied, resume) => applied ?? applyStepResumeToState(row.state, resume),+ null+ )+ : null+ if (!state) {+ counterStepResume.labels({ outcome: 'stale_key' }).inc()+ continue+ }+ updates.push({ id: row.id, state })+ }+ counterStepResume.labels({ outcome: 'job_missing' }).inc(byJob.size)+ if (updates.length > 0) {+ const updated = await client.query(+ `UPDATE cyclotron_jobs cj+ SET scheduled = NOW(), state = u.state+ FROM (SELECT unnest($1::uuid[]) AS id, unnest($2::bytea[]) AS state) u+ WHERE cj.id = u.id AND cj.status = 'available'`,+ [updates.map((update) => update.id), updates.map((update) => update.state)]+ )+ counterStepResume.labels({ outcome: 'delivered' }).inc(updated.rowCount ?? 0)+ }+ await client.query('COMMIT')+ } catch (err) {+ await client.query('ROLLBACK').catch(() => {})+ throw err+ } finally {+ client.release()+ }+ }+@instrumented('cdpHogflowSubscriptionMatcher.parseInternalEventMessages')public async _parseInternalEventsBatch(messages: Message[]): Promise<HogFunctionInvocationGlobals[]> {const events: HogFunctionInvocationGlobals[] = []@@ -1122,11 +1229,13 @@ export class CdpHogflowSubscriptionMatcherConsumer<}),this.internalEventsKafkaConsumer.connect(async (messages) => {return await instrumentFn('cdpHogflowSubscriptionMatcher.handleInternalEventsBatch', async () => {+ const { resumes, rest } = this._splitStepResumes(messages)+ const events = await this._parseInternalEventsBatch(rest)return {- backgroundTask: this.processBatch(- await this._parseInternalEventsBatch(messages),- 'internal_events'- ),+ backgroundTask: Promise.all([+ this.processBatch(events, 'internal_events'),+ this.processStepResumes(resumes),+ ]).then(() => undefined),}})}),@@ -1382,6 +1491,33 @@ function rewriteStatePersonId(}}+// Stamps the resume onto the parked step. Returns null when the job is not waiting on this exact+// key: the step already advanced, or the wake belongs to an earlier visit of the same step.+function applyStepResumeToState(stateBuffer: Buffer, resume: StepResume): Buffer | null {+ try {+ const parsed = parseJSON(stateBuffer.toString('utf-8'))+ const currentAction = parsed.state?.currentAction+ if (currentAction?.id !== resume.actionId || currentAction.awaitingResume?.key !== resume.origin_key) {+ return null+ }+ parsed.state = {+ ...parsed.state,+ currentAction: {+ ...currentAction,+ resumeResult: {+ key: resume.origin_key,+ status: resume.status,+ result: resume.result ?? undefined,+ },+ },+ }+ return Buffer.from(JSON.stringify(parsed))+ } catch (err) {+ logger.warn('Failed to parse state during step resume', { jobId: resume.jobId, err })+ return null+ }+}+type MatchOutcome = { state: Buffer; wake: boolean }// Applies a batch match to a parked job's state. Returns the new state plus whether the job shoulddiff --git a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.tsindex 23964715cfa9..dddb7588293d 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.replay-fidelity.test.ts@@ -86,6 +86,8 @@ describe('RerunPaginatorService replay fidelity (hog_flow)', () => {currentAction: {id: 'send_email',startedAtTimestamp: 999,+ awaitingResume: { key: 'old-key', deadlineAt: '2020-01-01T00:00:00Z', dispatch: { id: 'old-task' } },+ resumeResult: { key: 'old-key', status: 'failed' },hogFunctionState: {globals: { event: { uuid: 'evt-1' }, source: { name: 'Email', url: '' } },timings: [],diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.tsindex bdfc5a2dfc98..ba65985840bb 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.ts@@ -795,7 +795,12 @@ export class RerunPaginatorService {// with "No recipient identifier found". Dropping it makes the// action re-enter fresh, so inputs re-render against the current// config, which is what a rerun intends anyway.- const { hogFunctionState: _stripped, ...restoredCurrentAction } = persistedState.currentAction ?? {}+ const {+ hogFunctionState: _stripped,+ awaitingResume: _awaitingResume,+ resumeResult: _resumeResult,+ ...restoredCurrentAction+ } = persistedState.currentAction ?? {}invocation.id = row.invocation_idinvocation.parentRunId = row.parent_run_id || nulldiff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex e723157e082f..61d6ab47621d 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -9,6 +9,7 @@ import { HogFlowAction } from '~/cdp/schema/hogflow'import { createInvocationResult } from '~/cdp/utils/invocation-utils'import { PosthogJwtAudience } from '~/cdp/utils/jwt-utils'import { ScopedServiceJwt } from '~/cdp/utils/scoped-service-jwt'+import { workflowStepDispatchKeyFromInvocation } from '~/cdp/utils/workflow-step-dispatch-key'import { closeHub, createHub } from '~/common/utils/db/hub'import { parseJSON } from '~/common/utils/json-parse'import { createTestTeamFixture } from '~/tests/helpers/sql'@@ -649,4 +650,293 @@ describe('HogFunctionHandler', () => {})})})++ describe('awaited templates', () => {+ let TASK_TEMPLATE_ID: string+ let awaitingHandler: HogFunctionHandler+ let dispatchKey: string++ const buildTaskFlow = (inputs: Record<string, { value: unknown }> = {}): void => {+ const hogFlow = new FixtureHogFlowBuilder()+ .withTeamId(team.id)+ .withWorkflow({+ actions: {+ task: { type: 'function', config: { template_id: TASK_TEMPLATE_ID, inputs } },+ exit: { type: 'exit', config: {} },+ },+ edges: [{ from: 'task', to: 'exit', type: 'continue' }],+ })+ .build()+ action = findActionByType(hogFlow, 'function')!+ invocation = createExampleHogFlowInvocation(hogFlow)+ invocation.state.actionStepCount = 3+ invocation.state.currentAction = { id: action.id, startedAtTimestamp: DateTime.utc().toMillis() }+ dispatchKey = `${invocation.id}:${action.id}:3`+ }++ const execute = async (handler: HogFunctionHandler = awaitingHandler) => {+ const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {+ queue: 'hog',+ queuePriority: 0,+ })+ const handlerResult = await handler.execute({ invocation, action, result: invocationResult })+ return { handlerResult, invocationResult }+ }++ beforeEach(async () => {+ TASK_TEMPLATE_ID = `template-awaited-step-${team.id}`+ await insertHogFunctionTemplate(hub.postgres, {+ id: TASK_TEMPLATE_ID,+ name: 'Create task',+ code: `if (inputs.skip) { return { 'skipped': true, 'reason': 'over the cap' } } return { 'id': 't1', 'run_id': 'r1', 'await': { 'max_wait': '190m', 'label': 'task' } }`,+ inputs_schema: [{ key: 'skip', type: 'boolean', required: false }],+ })+ awaitingHandler = new HogFunctionHandler(+ mockHogFlowFunctionsService,+ mockRecipientPreferencesService,+ mockEmailValidationService,+ 'fetch',+ undefined,+ { awaitedStepsEnabled: true }+ )+ buildTaskFlow()+ })++ it.each([+ { rerunAttempts: 0, legacyDispatch: false },+ { rerunAttempts: 1, legacyDispatch: false },+ { rerunAttempts: 2, legacyDispatch: false },+ { rerunAttempts: 1, legacyDispatch: true },+ ])('uses the dispatch key when parking: %j', async ({ rerunAttempts, legacyDispatch }) => {+ invocation.state.rerunAttempts = rerunAttempts+ const originalBuild =+ mockHogFlowFunctionsService.buildHogFunctionInvocation.bind(mockHogFlowFunctionsService)+ const buildSpy = jest.spyOn(mockHogFlowFunctionsService, 'buildHogFunctionInvocation')+ if (legacyDispatch) {+ buildSpy.mockImplementationOnce(async (...args) => {+ const child = await originalBuild(...args)+ delete child.state.rerunAttempts+ invocation.state.currentAction!.hogFunctionState = child.state+ return originalBuild(...args)+ })+ }+ const { invocationResult } = await execute()+ const child = await buildSpy.mock.results[0].value++ expect(child.state.rerunAttempts).toBe(legacyDispatch ? undefined : rerunAttempts)+ expect(workflowStepDispatchKeyFromInvocation(child)).toBe(+ invocationResult.invocation.state.currentAction?.awaitingResume?.key+ )+ expect(invocationResult.invocation.state.currentAction?.awaitingResume?.key).toBe(+ `${dispatchKey}${rerunAttempts && !legacyDispatch ? `.r${rerunAttempts}` : ''}`+ )+ })++ it('parks after the dispatch until the task finishes', async () => {+ const before = DateTime.now()+ const { handlerResult, invocationResult } = await execute()++ expect(handlerResult.nextAction).toBeUndefined()+ expect(handlerResult.scheduledAt!.diff(before).as('minutes')).toBeGreaterThanOrEqual(190)+ expect(handlerResult.result).toEqual({ id: 't1', run_id: 'r1' })+ expect(invocationResult.invocation.state.currentAction?.awaitingResume).toEqual({+ key: dispatchKey,+ deadlineAt: handlerResult.scheduledAt!.toISO(),+ dispatch: { id: 't1', run_id: 'r1' },+ label: 'task',+ })+ expect(invocationResult.metrics.map((m) => m.metric_name)).toContain('billable_invocation')+ expect(invocationResult.logs.map((l) => l.message)).toContainEqual(+ expect.stringContaining('Waiting for the task to finish')+ )+ })++ it.each([+ ['the template asks for no wait', { skip: { value: true } }, true],+ ['waiting is turned off', {}, false],+ ])('advances without waiting when %s', async (_, inputs, awaitedStepsEnabled) => {+ buildTaskFlow(inputs)+ const handler = new HogFunctionHandler(+ mockHogFlowFunctionsService,+ mockRecipientPreferencesService,+ mockEmailValidationService,+ 'fetch',+ undefined,+ { awaitedStepsEnabled }+ )++ const { handlerResult, invocationResult } = await execute(handler)++ expect(handlerResult.nextAction?.id).toBe('exit')+ expect(invocationResult.invocation.state.currentAction?.awaitingResume).toBeUndefined()+ })++ it.each([+ ['clamps a wait past the ceiling', { max_wait: '99d', label: 'export' }, 24 * 60, 'Waiting for the export'],+ [+ 'continues and logs when it cannot parse the wait',+ { max_wait: '190min' },+ null,+ `Ignored the template's wait request: await.max_wait must be a duration like '190m' or '2h', got "190min"`,+ ],+ ])('%s', async (_, awaitRequest, expectedMinutes, expectedLog) => {+ jest.spyOn(mockHogFlowFunctionsService, 'executeWithAsyncFunctions').mockResolvedValueOnce({+ finished: true,+ execResult: { id: 'x1', await: awaitRequest },+ invocation: invocation as any,+ logs: [],+ metrics: [],+ capturedPostHogEvents: [],+ warehouseWebhookPayloads: [],+ messageAssets: [],+ conversionWatchers: [],+ })+ const before = DateTime.now()++ const { handlerResult, invocationResult } = await execute()++ if (expectedMinutes === null) {+ expect(handlerResult.nextAction?.id).toBe('exit')+ expect(invocationResult.invocation.state.currentAction?.awaitingResume).toBeUndefined()+ } else {+ expect(Math.round(handlerResult.scheduledAt!.diff(before).as('minutes'))).toBe(expectedMinutes)+ expect(handlerResult.result).toEqual({ id: 'x1' })+ }+ expect(invocationResult.logs.map((l) => l.message)).toContainEqual(expect.stringContaining(expectedLog))+ })++ describe('on resume', () => {+ let executeSpy: jest.SpyInstance+ const deadlineAt = DateTime.now().plus({ hours: 1 }).toISO()!++ beforeEach(() => {+ executeSpy = jest.spyOn(mockHogFlowFunctionsService, 'executeWithAsyncFunctions')+ invocation.state.currentAction!.awaitingResume = {+ key: dispatchKey,+ deadlineAt,+ dispatch: { id: 't1', run_id: 'r1' },+ label: 'task',+ }+ })++ it.each([true, false])('resumes without dispatch when the flag is %s', async (awaitedStepsEnabled) => {+ delete invocation.state.currentAction!.awaitingResume+ const { invocationResult: parked } = await execute()+ expect(executeSpy).toHaveBeenCalledTimes(1)+ executeSpy.mockClear()+ invocation = parked.invocation+ invocation.state.currentAction!.resumeResult = {+ key: dispatchKey,+ status: 'completed',+ result: { final_message: 'done' },+ }+ const handler = new HogFunctionHandler(+ mockHogFlowFunctionsService,+ mockRecipientPreferencesService,+ mockEmailValidationService,+ 'fetch',+ undefined,+ { awaitedStepsEnabled }+ )++ const { handlerResult } = await execute(handler)++ expect(executeSpy).not.toHaveBeenCalled()+ expect(handlerResult.nextAction?.id).toBe('exit')+ expect(handlerResult.result).toMatchObject({ status: 'completed', final_message: 'done' })+ })++ it('advances with the dispatch and the run result merged, without re-running the step', async () => {+ invocation.state.currentAction!.resumeResult = {+ key: dispatchKey,+ status: 'completed',+ result: { final_message: 'x'.repeat(5000), pr_urls: ['https://example.com/pr/1'] },+ }++ const { handlerResult, invocationResult } = await execute()++ expect(executeSpy).not.toHaveBeenCalled()+ expect(handlerResult.nextAction?.id).toBe('exit')+ expect(handlerResult.result).toEqual({+ id: 't1',+ run_id: 'r1',+ status: 'completed',+ final_message: 'x'.repeat(1500),+ pr_urls: ['https://example.com/pr/1'],+ })+ expect(invocationResult.invocation.state.currentAction?.awaitingResume).toBeUndefined()+ expect(invocationResult.invocation.state.currentAction?.resumeResult).toBeUndefined()+ })++ it.each([4000, 4700])('fits the resumed result with %s bytes of existing variables', async (usedBytes) => {+ action.output_variable = { key: 'task_result' }+ invocation.state.variables = { ticket_body: 'y'.repeat(usedBytes - '{"ticket_body":""}'.length) }+ invocation.state.currentAction!.resumeResult = {+ key: dispatchKey,+ status: 'completed',+ result: { final_message: 'x'.repeat(5000), pr_urls: ['u'] },+ }++ const { handlerResult } = await execute()++ const stored = handlerResult.result as Record<string, unknown>+ expect(stored.pr_urls).toEqual(['u'])+ expect(+ Buffer.byteLength(JSON.stringify({ ...invocation.state.variables, task_result: stored }))+ ).toBeLessThanOrEqual(5120)+ })++ it('continues past a completed task whose output is off, and warns in the run log', async () => {+ invocation.state.currentAction!.resumeResult = {+ key: dispatchKey,+ status: 'completed',+ result: { output: { verdict: 'ship' }, warnings: ["'score' is a required property"] },+ }++ const { handlerResult, invocationResult } = await execute()++ expect(handlerResult.nextAction?.id).toBe('exit')+ expect(handlerResult.result).toMatchObject({ output: { verdict: 'ship' } })+ expect(invocationResult.logs).toContainEqual(+ expect.objectContaining({+ level: 'warn',+ message: expect.stringContaining("'score' is a required property"),+ })+ )+ })++ it('fails the step when the task did not complete', async () => {+ invocation.state.currentAction!.resumeResult = {+ key: dispatchKey,+ status: 'failed',+ result: { error_message: 'sandbox crashed' },+ }++ await expect(execute()).rejects.toThrow('The task failed: sandbox crashed')+ expect(executeSpy).not.toHaveBeenCalled()+ })++ it('ignores a wake for an earlier visit and keeps waiting', async () => {+ invocation.state.currentAction!.resumeResult = {+ key: `${invocation.id}:${action.id}:1`,+ status: 'completed',+ }++ const { handlerResult, invocationResult } = await execute()++ expect(handlerResult.nextAction).toBeUndefined()+ expect(handlerResult.scheduledAt!.toISO()).toBe(deadlineAt)+ expect(invocationResult.invocation.state.currentAction?.resumeResult).toBeUndefined()+ expect(invocationResult.invocation.state.currentAction?.awaitingResume?.key).toBe(dispatchKey)+ })++ it('fails the step when the deadline passes without a wake', async () => {+ invocation.state.currentAction!.awaitingResume!.deadlineAt = DateTime.now()+ .minus({ minutes: 1 })+ .toISO()!++ await expect(execute()).rejects.toThrow('Timed out waiting for the task to finish')+ })+ })+ })})diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex e7e9ad05700c..c4f62ae317bb 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -1,12 +1,19 @@-import { DateTime } from 'luxon'+import { DateTime, Duration } from 'luxon'+import { Counter } from 'prom-client'import { HogFlowAction } from '~/cdp/schema/hogflow'+import {+ buildWorkflowStepDispatchKey,+ workflowStepDispatchKeyFromInvocation,+} from '~/cdp/utils/workflow-step-dispatch-key'+import { capWorkflowStepResult } from '~/cdp/utils/workflow-step-result'import { instrumentFn } from '~/common/tracing/tracing-utils'import {CyclotronJobInvocationHogFlow,CyclotronJobInvocationHogFunction,CyclotronJobInvocationResult,+ HogFlowInvocationContext,MinimalLogEntry,} from '../../../types'import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'@@ -23,13 +30,63 @@ type FunctionActionType = 'function' | 'function_email' | 'function_sms'type Action = Extract<HogFlowAction, { type: FunctionActionType }>+type AwaitingResume = NonNullable<NonNullable<HogFlowInvocationContext['currentAction']>['awaitingResume']>++// A template parks the step by returning `{ ..., 'await': { 'max_wait': '190m', 'label': 'task' } }`.+type AwaitRequest = { maxWait: Duration; label: string }++const AWAIT_DURATION_REGEX = /^(\d*\.?\d+)([dhms])$/+const SECONDS_PER_UNIT: Record<string, number> = { d: 86400, h: 3600, m: 60, s: 1 }+const AWAIT_MAX_WAIT_CEILING = Duration.fromObject({ hours: 24 })++// A malformed request throws rather than returning null, so the step logs why it did not wait.+const parseAwaitRequest = (execResult: unknown): AwaitRequest | null => {+ const request = (execResult as { await?: unknown } | undefined)?.await+ if (request === undefined || request === null) {+ return null+ }+ if (typeof request !== 'object') {+ throw new Error(`await must be an object, got ${typeof request}`)+ }+ const { max_wait: maxWait, label } = request as { max_wait?: unknown; label?: unknown }+ const match = typeof maxWait === 'string' ? AWAIT_DURATION_REGEX.exec(maxWait) : null+ if (!match) {+ throw new Error(`await.max_wait must be a duration like '190m' or '2h', got ${JSON.stringify(maxWait)}`)+ }+ const requested = Duration.fromObject({ seconds: parseFloat(match[1]) * SECONDS_PER_UNIT[match[2]] })+ return {+ maxWait: requested > AWAIT_MAX_WAIT_CEILING ? AWAIT_MAX_WAIT_CEILING : requested,+ label: typeof label === 'string' && label ? label : 'run',+ }+}++const humanDuration = (duration: Duration): string => duration.rescale().toHuman()++// Read off the raw resume result, before the variable cap, so a long warning is not cut.+const readWarnings = (resumeResult: unknown): string[] => {+ const warnings = (resumeResult as { warnings?: unknown } | undefined)?.warnings+ return Array.isArray(warnings) ? warnings.filter((warning): warning is string => typeof warning === 'string') : []+}++// Unlabelled: how often a step degrades fleet-wide. Which flow and field goes to the warn log.+const counterAwaitedStepResumedWithWarnings = new Counter({+ name: 'cdp_hogflow_awaited_step_resumed_with_warnings',+ help: 'A parked step resumed and continued, but the product that ran the job reported a warning.',+})++const counterAwaitedStepStaleResume = new Counter({+ name: 'cdp_hogflow_awaited_step_stale_resume',+ help: 'A parked step received a wake keyed to an earlier visit of the same step and kept waiting.',+})+export class HogFunctionHandler implements ActionHandler {constructor(private hogFlowFunctionsService: HogFlowFunctionsService,private recipientPreferencesService: RecipientPreferencesService,private emailValidationService: EmailValidationService,private hogFlowActionBillingType: 'fetch' | 'email' | 'push',- private usageReporter?: CdpUsageReporterService+ private usageReporter?: CdpUsageReporterService,+ private options: { awaitedStepsEnabled?: boolean } = {}) {}async execute({@@ -38,6 +95,13 @@ export class HogFunctionHandler implements ActionHandler {result,hogExecutorOptions,}: ActionHandlerOptions<Action>): Promise<ActionHandlerResult> {+ const awaitedStepsEnabled = this.options.awaitedStepsEnabled ?? false+ const awaiting = invocation.state.currentAction?.awaitingResume+ // Resume before anything else: the dispatch already ran and was billed.+ if (awaiting) {+ return this.resumeAwaitedStep(invocation, action, result, awaiting)+ }+// 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 runif (!invocation.state.currentAction?.hogFunctionState) {@@ -115,6 +179,31 @@ export class HogFunctionHandler implements ActionHandler {}}+ let awaitRequest: AwaitRequest | null = null+ if (awaitedStepsEnabled && !functionResult.error) {+ try {+ awaitRequest = parseAwaitRequest(functionResult.execResult)+ } catch (error) {+ // The template asked to wait but the request is unusable. Continue instead of parking+ // on a guess, and say so in the run log.+ result.logs.push({+ level: 'warn',+ timestamp: DateTime.now(),+ message: `${actionIdForLogging(action)} Ignored the template's wait request: ${(error as Error).message}`,+ })+ }+ }+ if (awaitRequest) {+ return this.parkForAwaitedRun(+ invocation,+ action,+ result,+ awaitRequest,+ functionResult.execResult,+ workflowStepDispatchKeyFromInvocation(functionResult.invocation)+ )+ }+return {nextAction: findContinueAction(invocation),result: functionResult.execResult,@@ -122,6 +211,97 @@ export class HogFunctionHandler implements ActionHandler {}}+ private parkForAwaitedRun(+ invocation: CyclotronJobInvocationHogFlow,+ action: Action,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>,+ awaitRequest: AwaitRequest,+ execResult: unknown,+ dispatchKey: string | null+ ): ActionHandlerResult {+ const { await: _await, ...dispatch } = execResult as Record<string, unknown>+ const key =+ dispatchKey ??+ buildWorkflowStepDispatchKey(+ invocation.id,+ action.id,+ invocation.state.actionStepCount,+ invocation.state.rerunAttempts+ )+ const deadline = DateTime.now().plus(awaitRequest.maxWait)+ result.invocation.state.currentAction!.awaitingResume = {+ key,+ deadlineAt: deadline.toISO()!,+ dispatch,+ label: awaitRequest.label,+ }+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `${actionIdForLogging(action)} Waiting for the ${awaitRequest.label} to finish (up to ${humanDuration(awaitRequest.maxWait)})`,+ })+ // Stored now so a step that later fails still leaves the ids for `on_error: continue`.+ return { scheduledAt: deadline, result: dispatch }+ }++ private resumeAwaitedStep(+ invocation: CyclotronJobInvocationHogFlow,+ action: Action,+ result: CyclotronJobInvocationResult<CyclotronJobInvocationHogFlow>,+ awaiting: AwaitingResume+ ): ActionHandlerResult {+ const currentAction = result.invocation.state.currentAction!+ const label = awaiting.label ?? 'run'+ const resume = currentAction.resumeResult+ if (resume?.key === awaiting.key) {+ delete currentAction.awaitingResume+ delete currentAction.resumeResult+ const payload = capWorkflowStepResult(+ { ...awaiting.dispatch, status: resume.status },+ resume.result ?? {},+ result.invocation.state.variables ?? {},+ action.output_variable+ )+ if (resume.status !== 'completed') {+ const detail = typeof payload.error_message === 'string' ? `: ${payload.error_message}` : ''+ const outcome = resume.status === 'cancelled' ? 'was cancelled' : 'failed'+ throw new Error(`The ${label} ${outcome}${detail}`)+ }+ result.logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `${actionIdForLogging(action)} The ${label} finished`,+ })+ // The product that ran the job reports what went wrong short of failing it, such as+ // an agent whose output misses a field. The step continues; the author reads the log.+ const warnings = readWarnings(resume.result)+ if (warnings.length > 0) {+ counterAwaitedStepResumedWithWarnings.inc()+ }+ for (const warning of warnings) {+ result.logs.push({+ level: 'warn',+ timestamp: DateTime.now(),+ message: `${actionIdForLogging(action)} ${warning}`,+ })+ }+ return {+ nextAction: findContinueAction(invocation),+ result: payload,+ }+ }+ if (resume) {+ delete currentAction.resumeResult+ counterAwaitedStepStaleResume.inc()+ }+ const deadline = DateTime.fromISO(awaiting.deadlineAt)+ if (DateTime.now() >= deadline) {+ throw new Error(`Timed out waiting for the ${label} to finish`)+ }+ // Woken early with nothing (clock skew): park again.+ return { scheduledAt: deadline }+ }+private async executeHogFunction(invocation: CyclotronJobInvocationHogFlow,action: Action,diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 524f536dc866..754895bbbccd 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -119,7 +119,8 @@ export class HogFlowExecutorService {cohortMembershipRepository: CohortMembershipRepository,integrationManager: SlackAppLookup,duplicateObserver?: HogFlowDuplicateObserverService,- usageReporter?: CdpUsageReporterService+ usageReporter?: CdpUsageReporterService,+ options: { awaitedStepsEnabled?: boolean } = {}) {this.hogFlowFunctionsService = hogFlowFunctionsServicethis.duplicateObserver = duplicateObserver ?? null@@ -128,7 +129,8 @@ export class HogFlowExecutorService {recipientPreferencesService,emailValidationService,'fetch',- usageReporter+ usageReporter,+ options)const hogFunctionEmailHandler = new HogFunctionHandler(hogFlowFunctionsService,@@ -1002,6 +1004,9 @@ export class HogFlowExecutorService {? ` (woken by [Event:${wakeEventUuid}|${wakeEvent.replaceAll('|', '')}|${wakeEventTimestamp}])`: ` (woken by event: ${wakeEvent.replaceAll('|', '')})`}+ if (hasCurrentAction && invocation.state.currentAction?.resumeResult) {+ triggeredByEvent += ' (woken by the run finishing)'+ }return {level: 'info',diff --git a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.tsindex b74cfc750494..16157f58b4a7 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-functions.service.ts@@ -119,6 +119,8 @@ export class HogFlowFunctionsService {timings: [],attempts: 0,actionId: invocation.state.currentAction?.id,+ actionStepCount: invocation.state.actionStepCount,+ rerunAttempts: invocation.state.rerunAttempts,},}diff --git a/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.test.tsindex 2a3c1f585b55..929e54ce882b 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.test.ts@@ -28,7 +28,7 @@ describe('posthog run scout template', () => {expect(parseJSON(params.body!)).toEqual({skill_name: 'signals-scout-error-tracking',- idempotency_key: `${response.invocation.id}:action_1`,+ idempotency_key: `${response.invocation.id}:action_1:0`,})const token = (params.headers?.['Authorization'] ?? '').replace('Bearer ', '')@@ -64,7 +64,11 @@ describe('posthog run scout template', () => {expect(response.error).toBeUndefined()expect(response.finished).toBe(true)- expect(response.execResult).toEqual({ scout: 'signals-scout-error-tracking', workflow_id: 'wf-1' })+ expect(response.execResult).toEqual({+ scout: 'signals-scout-error-tracking',+ workflow_id: 'wf-1',+ await: { max_wait: '35m', label: 'scout run' },+ })})it('skips instead of failing on a 409 response', async () => {diff --git a/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.tsindex 1a6940139705..e3d13f2f5c85 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_signals/posthog-run-scout.template.ts@@ -31,7 +31,12 @@ if (response.status >= 400) {throw Error(f'Failed to run scout ({response.status}): {apiErrorMessage(response)}')}-return response.body+let run := response.body+if (not empty(run.workflow_id)) {+ // Park the workflow step until the run finishes: the scout runtime cap plus slack for its wake.+ run.await := { 'max_wait': '35m', 'label': 'scout run' }+}+return run`,inputs_schema: [{diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.tsindex 2540ba8c570d..7cd11339e500 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.test.ts@@ -82,7 +82,7 @@ describe('posthog create task template', () => {posthog_mcp_scopes: 'full',max_parallel_tasks: 3,event: defaultEventBody,- idempotency_key: `${invocation.id}:action_1`,+ idempotency_key: `${invocation.id}:action_1:0`,})const token = (params.headers?.['Authorization'] ?? '').replace('Bearer ', '')@@ -105,7 +105,7 @@ describe('posthog create task template', () => {posthog_mcp_scopes: 'read_only',max_parallel_tasks: 5,event: defaultEventBody,- idempotency_key: `${invocation.id}:action_1`,+ idempotency_key: `${invocation.id}:action_1:0`,})})@@ -178,7 +178,21 @@ describe('posthog create task template', () => {expect(response.error).toBeUndefined()expect(response.finished).toBe(true)- expect(response.execResult).toEqual({ id: 'task-1', run_id: 'run-1' })+ expect(response.execResult).toEqual({+ id: 'task-1',+ run_id: 'run-1',+ await: { max_wait: '190m', label: 'task' },+ })+ })++ it('asks for no wait when no run started', async () => {+ let response = await tester.invoke(fullInputs, undefined, workflowOptions)+ response = await tester.invokeFetchResponse(response.invocation, {+ status: 201,+ body: { id: 'task-1', run_id: null },+ })++ expect(response.execResult).toEqual({ id: 'task-1', run_id: null })})it('fails with the limit reason when the parallel task limit is hit', async () => {diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.tsindex fb5f79b528b3..f9ac0e8055ff 100644--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts@@ -71,7 +71,12 @@ if (response.status >= 400) {throw Error(f'Failed to create task ({response.status}): {apiErrorMessage(response)}')}-return response.body+let task := response.body+if (not empty(task.run_id)) {+ // Park the workflow step until the run finishes: the tasks runtime cap plus slack for its wake.+ task.await := { 'max_wait': '190m', 'label': 'task' }+}+return task`,inputs_schema: [{diff --git a/nodejs/src/cdp/templates/test/test-helpers.ts b/nodejs/src/cdp/templates/test/test-helpers.tsindex 7f1b8a810814..8f0b0883b0fd 100644--- a/nodejs/src/cdp/templates/test/test-helpers.ts+++ b/nodejs/src/cdp/templates/test/test-helpers.ts@@ -316,6 +316,7 @@ export class TemplateTester {}if (_options?.actionId) {invocation.state.actionId = _options.actionId+ invocation.state.actionStepCount = 0}const transformationFunctions = getTransformationFunctions(this.geoIp!)const extraFunctions = invocation.hogFunction.type === 'transformation' ? transformationFunctions : {}diff --git a/nodejs/src/cdp/types.ts b/nodejs/src/cdp/types.tsindex 1d1ba47fee61..b506b05714d8 100644--- a/nodejs/src/cdp/types.ts+++ b/nodejs/src/cdp/types.ts@@ -382,8 +382,11 @@ export type CyclotronJobInvocationHogFunctionContext = {// version (a retry's scheduled time) and lose the original.firstScheduledAt?: stringactionId?: string // The hogflow action node ID, used for metrics instance_id when executing within a workflow+ actionStepCount?: number}+export type WorkflowStepResumeStatus = 'completed' | 'failed' | 'cancelled'+export type CyclotronJobInvocationHogFunction = CyclotronJobInvocation & {state: CyclotronJobInvocationHogFunctionContexthogFunction: HogFunctionType@@ -474,6 +477,9 @@ export type HogFlowInvocationContext = {// the cdp_hogflow_wait_poll_only_advance metric — the signal that proves whether the poll// ever catches a wake the subscription streams missed, gating its eventual removal.pollReparked?: boolean+ // A step parked on an external run: cleared when the matcher writes a matching `resumeResult`.+ awaitingResume?: { key: string; deadlineAt: string; dispatch: Record<string, unknown>; label?: string }+ resumeResult?: { key: string; status: WorkflowStepResumeStatus; result?: Record<string, unknown> }}// Set by the subscription matcher consumer when an incoming event matched the// workflow's event-based conversion goals. shouldExitEarly reads and clears it.diff --git a/nodejs/src/cdp/utils/workflow-step-dispatch-key.test.ts b/nodejs/src/cdp/utils/workflow-step-dispatch-key.test.tsnew file mode 100644index 000000000000..4df52d25d2f2--- /dev/null+++ b/nodejs/src/cdp/utils/workflow-step-dispatch-key.test.ts@@ -0,0 +1,30 @@+import { buildWorkflowStepDispatchKey, parseWorkflowStepDispatchKey } from './workflow-step-dispatch-key'++describe('workflow step dispatch keys', () => {+ const jobId = 'b1f0c2d4-0000-4000-8000-000000000001'++ it.each([0, 1, 2])('round trips an action with colons for rerun %s', (rerunAttempts) => {+ const key = buildWorkflowStepDispatchKey(jobId, 'task:node', 3, rerunAttempts)+ expect(parseWorkflowStepDispatchKey(key)).toEqual({ jobId, actionId: 'task:node' })+ expect(key).toBe(`${jobId}:task:node:3${rerunAttempts ? `.r${rerunAttempts}` : ''}`)+ expect(buildWorkflowStepDispatchKey(jobId, 'task:node', 3, rerunAttempts)).toBe(key)+ expect(buildWorkflowStepDispatchKey(jobId, 'task:node', 4, rerunAttempts)).not.toBe(key)+ expect(buildWorkflowStepDispatchKey(jobId, 'task:node', 3, rerunAttempts + 1)).not.toBe(key)+ })++ it.each([+ 'nope',+ 'bad:task:3',+ `${jobId}::3`,+ `${jobId}:task:`,+ `${jobId}:task:-1`,+ `${jobId}:task:1.5`,+ `${jobId}:task:NaN`,+ `${jobId}:task:3.r0`,+ `${jobId}:task:3.r-1`,+ `${jobId}:task:9007199254740992`,+ `${jobId}:task:3.r9007199254740992`,+ ])('rejects an invalid key: %s', (key) => {+ expect(parseWorkflowStepDispatchKey(key)).toBeNull()+ })+})diff --git a/nodejs/src/cdp/utils/workflow-step-dispatch-key.ts b/nodejs/src/cdp/utils/workflow-step-dispatch-key.tsnew file mode 100644index 000000000000..b0e94117ce8e--- /dev/null+++ b/nodejs/src/cdp/utils/workflow-step-dispatch-key.ts@@ -0,0 +1,33 @@+import { CyclotronJobInvocationHogFunction } from '../types'++export const buildWorkflowStepDispatchKey = (+ jobId: string,+ actionId: string,+ actionStepCount: number,+ rerunAttempts = 0+): string => `${jobId}:${actionId}:${actionStepCount}${rerunAttempts > 0 ? `.r${rerunAttempts}` : ''}`++export const parseWorkflowStepDispatchKey = (key: string): { jobId: string; actionId: string } | null => {+ const parts = key.split(':')+ const step = /^(0|[1-9]\d*)(?:\.r([1-9]\d*))?$/.exec(parts[parts.length - 1])+ const actionId = parts.slice(1, -1).join(':')+ if (+ parts.length < 3 ||+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(parts[0]) ||+ !actionId.trim() ||+ !step ||+ !Number.isSafeInteger(Number(step[1])) ||+ (step[2] !== undefined && !Number.isSafeInteger(Number(step[2])))+ ) {+ return null+ }+ return { jobId: parts[0].toLowerCase(), actionId }+}++export const workflowStepDispatchKeyFromInvocation = (invocation: CyclotronJobInvocationHogFunction): string | null => {+ const { actionId, actionStepCount } = invocation.state+ if (!actionId || actionStepCount === undefined) {+ return null+ }+ return buildWorkflowStepDispatchKey(invocation.id, actionId, actionStepCount, invocation.state.rerunAttempts)+}diff --git a/nodejs/src/cdp/utils/workflow-step-result.test.ts b/nodejs/src/cdp/utils/workflow-step-result.test.tsnew file mode 100644index 000000000000..0b448b2c4171--- /dev/null+++ b/nodejs/src/cdp/utils/workflow-step-result.test.ts@@ -0,0 +1,56 @@+import { get } from 'lodash'++import { HogFlowAction } from '../schema/hogflow'+import { capWorkflowStepResult } from './workflow-step-result'++describe('workflow step result byte budget', () => {+ const dispatch = { id: 'task-1', run_id: 'run-1', status: 'completed' }++ it.each([+ { final_message: '😀'.repeat(1500) },+ { final_message: '漢'.repeat(1500), summary: '字'.repeat(1500) },+ { final_message: '\\"\n'.repeat(1500), nested: { summary: '😀'.repeat(1500) } },+ { pr_urls: Array.from({ length: 1000 }, (_, index) => `https://example.com/pr/${index}`) },+ ])('fits Unicode, escaped text, nested values, and URL lists: %j', (payload) => {+ const variables = { existing: 'x'.repeat(3500) }+ const result = capWorkflowStepResult(dispatch, payload, variables, { key: 'result' })++ expect(Buffer.byteLength(JSON.stringify({ ...variables, result }))).toBeLessThanOrEqual(5120)+ expect(result).toMatchObject(dispatch)+ for (const url of (result.pr_urls ?? []) as string[]) {+ expect(payload.pr_urls).toContain(url)+ }+ })++ it.each<HogFlowAction['output_variable']>([+ { key: 'result' },+ { key: 'result', spread: true },+ { key: 'result', result_path: 'nested', spread: true },+ [{ key: 'first' }, { key: 'second' }],+ { key: 'result', result_path: 'final_message' },+ ])('accounts for the selected output mapping: %j', (outputVariable) => {+ const variables: Record<string, unknown> = { existing: 'x'.repeat(4000), result: 'old output'.repeat(80) }+ const payload = { final_message: '😀'.repeat(1500), nested: { summary: '漢'.repeat(1500) } }+ const result = capWorkflowStepResult(dispatch, payload, variables, outputVariable)+ const stored = { ...variables }+ for (const output of Array.isArray(outputVariable) ? outputVariable : [outputVariable!]) {+ const resolved = output.result_path ? get(result, output.result_path) : result+ if (output.spread && resolved && typeof resolved === 'object' && !Array.isArray(resolved)) {+ Object.assign(+ stored,+ Object.fromEntries(Object.entries(resolved).map(([key, value]) => [`${output.key}_${key}`, value]))+ )+ } else {+ stored[output.key] = resolved+ }+ }+ expect(Buffer.byteLength(JSON.stringify(stored))).toBeLessThanOrEqual(5120)+ expect(variables.result).toBe('old output'.repeat(80))+ })++ it('reports when even the fixed run identifiers cannot fit', () => {+ expect(() => capWorkflowStepResult(dispatch, {}, { existing: 'x'.repeat(5100) }, { key: 'result' })).toThrow(+ 'Workflow variables exceed the 5KB limit'+ )+ })+})diff --git a/nodejs/src/cdp/utils/workflow-step-result.ts b/nodejs/src/cdp/utils/workflow-step-result.tsnew file mode 100644index 000000000000..8ff275e55ec7--- /dev/null+++ b/nodejs/src/cdp/utils/workflow-step-result.ts@@ -0,0 +1,84 @@+import { get } from 'lodash'++import { HogFlowAction } from '../schema/hogflow'++const VARIABLES_BYTE_CAP = 5120+const RESULT_STRING_CAP = 1500++const jsonBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), 'utf8')++const truncateValues = (value: unknown, cap: number): unknown => {+ if (typeof value === 'string') {+ return cap ? Array.from(value).slice(0, cap).join('') : undefined+ }+ if (Array.isArray(value)) {+ return value.slice(0, cap).flatMap((item) => {+ if (typeof item === 'string') {+ return Array.from(item).length <= cap ? [item] : []+ }+ const truncated = truncateValues(item, cap)+ return truncated === undefined ? [] : [truncated]+ })+ }+ if (value && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value)+ .map(([key, item]) => [key, truncateValues(item, cap)])+ .filter(([, item]) => item !== undefined)+ )+ }+ return value+}++export const capWorkflowStepResult = (+ dispatch: Record<string, unknown>,+ payload: Record<string, unknown>,+ variables: Record<string, unknown>,+ outputVariable: HogFlowAction['output_variable']+): Record<string, unknown> => {+ const { run_id: runId, ...content } = payload+ const fixed = { ...dispatch, ...(runId === undefined ? {} : { run_id: runId }) }+ const outputVariables = Array.isArray(outputVariable) ? outputVariable : outputVariable ? [outputVariable] : []++ const fits = (candidate: Record<string, unknown>): boolean => {+ if (jsonBytes(candidate) > VARIABLES_BYTE_CAP) {+ return false+ }+ const stored = { ...variables }+ for (const output of outputVariables) {+ if (!output.key) {+ continue+ }+ const resolved = output.result_path ? get(candidate, output.result_path) : candidate+ if (output.spread && resolved && typeof resolved === 'object' && !Array.isArray(resolved)) {+ for (const [key, value] of Object.entries(resolved)) {+ stored[`${output.key}_${key}`] = value+ }+ } else {+ stored[output.key] = resolved+ }+ }+ return jsonBytes(stored) <= VARIABLES_BYTE_CAP+ }++ let lower = 0+ let upper = RESULT_STRING_CAP+ let result: Record<string, unknown> | undefined+ while (lower <= upper) {+ const midpoint = Math.floor((lower + upper) / 2)+ const candidate = { ...(truncateValues(content, midpoint) as Record<string, unknown>), ...fixed }+ if (fits(candidate)) {+ result = candidate+ lower = midpoint + 1+ } else {+ upper = midpoint - 1+ }+ }+ if (result) {+ return result+ }+ if (!fits(fixed)) {+ throw new Error('Workflow variables exceed the 5KB limit. Store fewer result fields.')+ }+ return fixed+}diff --git a/nodejs/src/cdp/workflows-e2e.serial.test.ts b/nodejs/src/cdp/workflows-e2e.serial.test.tsindex 57866c2ef5bc..7c416424c34d 100644--- a/nodejs/src/cdp/workflows-e2e.serial.test.ts+++ b/nodejs/src/cdp/workflows-e2e.serial.test.ts@@ -2424,12 +2424,15 @@ describe('Workflows E2E (postgres-v2)', () => {non_failure_status_codes: { value: [409] },},},+ output_variable: { key: 'task' },},+ function_2: fetchAction('https://example.com/task-done'),exit: exitAction(),},edges: [{ from: 'trigger', to: 'function_1', type: 'continue' },- { from: 'function_1', to: 'exit', type: 'continue' },+ { from: 'function_1', to: 'function_2', type: 'continue' },+ { from: 'function_2', to: 'exit', type: 'continue' },],})flowId = flow.id@@ -2470,7 +2473,7 @@ describe('Workflows E2E (postgres-v2)', () => {event: '$pageview',uuid: 'b3a1fe86-b10c-43cc-acaf-d208977608d0',}),- idempotency_key: expect.stringMatching(/^[0-9a-f-]{36}:function_1$/),+ idempotency_key: expect.stringMatching(/^[0-9a-f-]{36}:function_1:0$/),})// The endpoint trusts these claims to resolve the workflow owner, so the token has to@@ -2486,9 +2489,52 @@ describe('Workflows E2E (postgres-v2)', () => {expect(claims.team_id).toEqual(team.id)expect(claims.hog_flow_id).toEqual(flowId)+ // The step parks until Django wakes it with the task's outcome.+ let originKey = ''+ await waitForExpect(async () => {+ const { rows } = await cyclotronPool.query(`SELECT id, status, state FROM cyclotron_jobs`)+ expect(rows).toHaveLength(1)+ expect(rows[0].status).toEqual('available')+ const state = parseJSON(rows[0].state.toString('utf-8')).state+ expect(state.currentAction.awaitingResume.key).toEqual(`${rows[0].id}:function_1:0`)+ originKey = state.currentAction.awaitingResume.key+ }, 10000)+ expect(mockFetch).toHaveBeenCalledTimes(1)+ expect(runMetricNames()).not.toContain('failed')++ // Django reports the run finished: the same internal event it produces, through the+ // matcher's own parser, wakes the parked step and the workflow moves on.+ const matcher = new CdpHogflowSubscriptionMatcherConsumer({ ...hub }, deps)+ const { resumes } = matcher._splitStepResumes([+ {+ value: Buffer.from(+ JSON.stringify({+ team_id: team.id,+ event: {+ uuid: 'a5c2d9e1-3f4b-4c8d-9e0f-1a2b3c4d5e6f',+ event: '$workflow_step_resume',+ distinct_id: `team_${team.id}`,+ properties: {+ origin_key: originKey,+ status: 'completed',+ result: { run_id: 'run-1', final_message: 'Found the cause' },+ },+ timestamp: '2024-01-01T00:00:00Z',+ },+ })+ ),+ } as any,+ ])+ await matcher.processStepResumes(resumes)+await waitForExpect(() => {- expect(runMetricNames()).toContain('succeeded')+ expect(mockFetch).toHaveBeenCalledTimes(2)}, 10000)+ expect(mockFetch.mock.calls[1][0]).toEqual('https://example.com/task-done')+ const logs = mockProducerObserver+ .getProducedKafkaMessagesForTopic(KAFKA_LOG_ENTRIES)+ .map((m: any) => m.value.message as string)+ expect(logs).toContainEqual(expect.stringContaining('[Action:function_1] The task finished'))expect(runMetricNames()).not.toContain('failed')})@@ -2507,7 +2553,8 @@ describe('Workflows E2E (postgres-v2)', () => {expect(runMetricNames()).toContain('failed')}, 10000)// 409 is terminal for the step: one request, no retry burning the engine's budget.- expect(mockFetch).toHaveBeenCalledTimes(1)+ const taskCreates = mockFetch.mock.calls.filter(([url]) => (url as string).includes('/workflow_tasks/'))+ expect(taskCreates).toHaveLength(1)})})diff --git a/nodejs/tests/fixtures/hog-bytecode/5066aa735c6550589b6fc1a07f2e1f63c254ba40361cd9345f7448438593efd2.json b/nodejs/tests/fixtures/hog-bytecode/5066aa735c6550589b6fc1a07f2e1f63c254ba40361cd9345f7448438593efd2.jsonnew file mode 100644index 000000000000..11e90a73b7cc--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/5066aa735c6550589b6fc1a07f2e1f63c254ba40361cd9345f7448438593efd2.json@@ -0,0 +1 @@+["_H",1,32,"skip",32,"inputs",1,2,40,10,32,"skipped",29,32,"reason",32,"over the cap",42,2,38,32,"id",32,"t1",32,"run_id",32,"r1",32,"await",32,"max_wait",32,"190m",32,"label",32,"task",42,2,42,3,38]diff --git a/nodejs/tests/fixtures/hog-bytecode/64a1eec5d51e36e6a22377d5499dd6a45c3dee433bc37fe47202251146dd1749.json b/nodejs/tests/fixtures/hog-bytecode/64a1eec5d51e36e6a22377d5499dd6a45c3dee433bc37fe47202251146dd1749.jsonnew file mode 100644index 000000000000..4586342f6969--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/64a1eec5d51e36e6a22377d5499dd6a45c3dee433bc37fe47202251146dd1749.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"prompt",32,"inputs",1,2,2,"empty",1,40,6,32,"Instructions are required",2,"Error",1,49,32,"prompt",32,"prompt",32,"inputs",1,2,32,"event",32,"event",1,1,42,2,32,"title",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"title",32,"title",32,"inputs",1,2,46,32,"model",32,"inputs",1,2,2,"empty",1,5,32,"model",32,"model",32,"inputs",1,3,2,"empty",1,5,3,2,40,40,36,1,32,"model",32,"model",32,"model",32,"inputs",1,3,46,32,"reasoning_effort",32,"model",32,"inputs",1,3,2,"empty",1,5,40,13,36,1,32,"reasoning_effort",32,"reasoning_effort",32,"model",32,"inputs",1,3,46,32,"repository",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"repository",32,"repository",32,"inputs",1,2,46,32,"connectors",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"connectors",32,"connectors",32,"inputs",1,2,46,32,"skills",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"skills",32,"skills",32,"inputs",1,2,46,32,"posthog_mcp_scopes",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"posthog_mcp_scopes",32,"posthog_mcp_scopes",32,"inputs",1,2,46,32,"max_parallel_tasks",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"max_parallel_tasks",32,"max_parallel_tasks",32,"inputs",1,2,46,30,32,"reply_in_slack_thread",32,"inputs",1,2,12,32,"$slack_message_received",32,"event",32,"event",1,2,11,32,"channel",32,"properties",32,"event",1,3,2,"empty",1,5,32,"ts",32,"properties",32,"event",1,3,2,"empty",1,5,3,4,40,102,36,1,32,"slack_context",32,"integration_id",32,"integration_id",32,"properties",32,"event",1,3,32,"channel",32,"channel",32,"properties",32,"event",1,3,32,"thread_ts",32,"thread_ts",32,"properties",32,"event",1,3,47,9,35,32,"ts",32,"properties",32,"event",1,3,32,"message_ts",32,"ts",32,"properties",32,"event",1,3,32,"slack_user_id",32,"user",32,"properties",32,"event",1,3,47,3,35,32,"",32,"slack_team_id",32,"slack_team_id",32,"properties",32,"event",1,3,47,3,35,32,"",32,"is_ext_shared_channel",32,"is_ext_shared_channel",32,"properties",32,"event",1,3,47,2,35,30,42,7,46,36,1,2,"postHogCreateTask",1,33,409,36,2,32,"status",45,11,40,29,32,"Task not created: ",36,2,36,0,54,1,2,"concat",2,2,"print",1,35,32,"skipped",29,32,"reason",36,2,36,0,54,1,42,2,38,33,400,36,2,32,"status",45,14,40,22,32,"Failed to create task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,36,2,32,"body",45,36,3,32,"run_id",45,2,"empty",1,5,40,15,36,3,32,"await",32,"max_wait",32,"190m",32,"label",32,"task",42,2,46,36,3,38,35,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/8b7a0eb7271c8c79b94cda9917be70ac115d954dc321603d1280cdadbc0d3573.json b/nodejs/tests/fixtures/hog-bytecode/8b7a0eb7271c8c79b94cda9917be70ac115d954dc321603d1280cdadbc0d3573.jsonnew file mode 100644index 000000000000..534b083acf5c--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/8b7a0eb7271c8c79b94cda9917be70ac115d954dc321603d1280cdadbc0d3573.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"skill_name",32,"inputs",1,2,2,"empty",1,40,6,32,"A scout is required",2,"Error",1,49,32,"skill_name",32,"skill_name",32,"inputs",1,2,42,1,2,"postHogRunScout",1,33,409,36,1,32,"status",45,11,40,29,32,"Scout not run: ",36,1,36,0,54,1,2,"concat",2,2,"print",1,35,32,"skipped",29,32,"reason",36,1,36,0,54,1,42,2,38,33,400,36,1,32,"status",45,14,40,22,32,"Failed to run scout (",36,1,32,"status",45,32,"): ",36,1,36,0,54,1,2,"concat",4,2,"Error",1,49,36,1,32,"body",45,36,2,32,"workflow_id",45,2,"empty",1,5,40,15,36,2,32,"await",32,"max_wait",32,"35m",32,"label",32,"scout run",42,2,46,36,2,38,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/96db3e08715d4a50c6031923acf40ddbf61c8013bcadee032baa6debdd836d6e.json b/nodejs/tests/fixtures/hog-bytecode/96db3e08715d4a50c6031923acf40ddbf61c8013bcadee032baa6debdd836d6e.jsonnew file mode 100644index 000000000000..0480f22d4bff--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/96db3e08715d4a50c6031923acf40ddbf61c8013bcadee032baa6debdd836d6e.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"prompt",32,"inputs",1,2,2,"empty",1,40,6,32,"Instructions are required",2,"Error",1,49,32,"prompt",32,"prompt",32,"inputs",1,2,32,"event",32,"event",1,1,42,2,32,"title",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"title",32,"title",32,"inputs",1,2,46,32,"model",32,"inputs",1,2,2,"empty",1,5,32,"model",32,"model",32,"inputs",1,3,2,"empty",1,5,3,2,40,40,36,1,32,"model",32,"model",32,"model",32,"inputs",1,3,46,32,"reasoning_effort",32,"model",32,"inputs",1,3,2,"empty",1,5,40,13,36,1,32,"reasoning_effort",32,"reasoning_effort",32,"model",32,"inputs",1,3,46,32,"repository",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"repository",32,"repository",32,"inputs",1,2,46,32,"connectors",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"connectors",32,"connectors",32,"inputs",1,2,46,32,"posthog_mcp_scopes",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"posthog_mcp_scopes",32,"posthog_mcp_scopes",32,"inputs",1,2,46,32,"max_parallel_tasks",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"max_parallel_tasks",32,"max_parallel_tasks",32,"inputs",1,2,46,30,32,"reply_in_slack_thread",32,"inputs",1,2,12,32,"$slack_message_received",32,"event",32,"event",1,2,11,32,"channel",32,"properties",32,"event",1,3,2,"empty",1,5,32,"ts",32,"properties",32,"event",1,3,2,"empty",1,5,3,4,40,102,36,1,32,"slack_context",32,"integration_id",32,"integration_id",32,"properties",32,"event",1,3,32,"channel",32,"channel",32,"properties",32,"event",1,3,32,"thread_ts",32,"thread_ts",32,"properties",32,"event",1,3,47,9,35,32,"ts",32,"properties",32,"event",1,3,32,"message_ts",32,"ts",32,"properties",32,"event",1,3,32,"slack_user_id",32,"user",32,"properties",32,"event",1,3,47,3,35,32,"",32,"slack_team_id",32,"slack_team_id",32,"properties",32,"event",1,3,47,3,35,32,"",32,"is_ext_shared_channel",32,"is_ext_shared_channel",32,"properties",32,"event",1,3,47,2,35,30,42,7,46,36,1,2,"postHogCreateTask",1,33,409,36,2,32,"status",45,11,40,29,32,"Task not created: ",36,2,36,0,54,1,2,"concat",2,2,"print",1,35,32,"skipped",29,32,"reason",36,2,36,0,54,1,42,2,38,33,400,36,2,32,"status",45,14,40,22,32,"Failed to create task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,36,2,32,"body",45,36,3,32,"run_id",45,2,"empty",1,5,40,15,36,3,32,"await",32,"max_wait",32,"190m",32,"label",32,"task",42,2,46,36,3,38,35,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/9826f20f73523edc8b73471b7890447e202ba974208d596de6f4bfd91c28a523.json b/nodejs/tests/fixtures/hog-bytecode/9826f20f73523edc8b73471b7890447e202ba974208d596de6f4bfd91c28a523.jsonnew file mode 100644index 000000000000..a99927d4fb18--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/9826f20f73523edc8b73471b7890447e202ba974208d596de6f4bfd91c28a523.json@@ -0,0 +1 @@+["_H",1,52,"apiErrorMessage",1,0,28,36,0,32,"body",45,32,"error",45,47,9,35,36,0,32,"body",45,32,"detail",45,47,6,35,36,0,32,"body",45,38,53,0,32,"prompt",32,"inputs",1,2,2,"empty",1,40,6,32,"Instructions are required",2,"Error",1,49,32,"prompt",32,"prompt",32,"inputs",1,2,32,"event",32,"event",1,1,42,2,32,"title",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"title",32,"title",32,"inputs",1,2,46,32,"model",32,"inputs",1,2,2,"empty",1,5,32,"model",32,"model",32,"inputs",1,3,2,"empty",1,5,3,2,40,40,36,1,32,"model",32,"model",32,"model",32,"inputs",1,3,46,32,"reasoning_effort",32,"model",32,"inputs",1,3,2,"empty",1,5,40,13,36,1,32,"reasoning_effort",32,"reasoning_effort",32,"model",32,"inputs",1,3,46,32,"repository",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"repository",32,"repository",32,"inputs",1,2,46,32,"connectors",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"connectors",32,"connectors",32,"inputs",1,2,46,32,"skills",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"skills",32,"skills",32,"inputs",1,2,46,32,"posthog_mcp_scopes",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"posthog_mcp_scopes",32,"posthog_mcp_scopes",32,"inputs",1,2,46,32,"max_parallel_tasks",32,"inputs",1,2,2,"empty",1,5,40,11,36,1,32,"max_parallel_tasks",32,"max_parallel_tasks",32,"inputs",1,2,46,30,32,"reply_in_slack_thread",32,"inputs",1,2,12,32,"$slack_message_received",32,"event",32,"event",1,2,11,32,"channel",32,"properties",32,"event",1,3,2,"empty",1,5,32,"ts",32,"properties",32,"event",1,3,2,"empty",1,5,3,4,40,102,36,1,32,"slack_context",32,"integration_id",32,"integration_id",32,"properties",32,"event",1,3,32,"channel",32,"channel",32,"properties",32,"event",1,3,32,"thread_ts",32,"thread_ts",32,"properties",32,"event",1,3,47,9,35,32,"ts",32,"properties",32,"event",1,3,32,"message_ts",32,"ts",32,"properties",32,"event",1,3,32,"slack_user_id",32,"user",32,"properties",32,"event",1,3,47,3,35,32,"",32,"slack_team_id",32,"slack_team_id",32,"properties",32,"event",1,3,47,3,35,32,"",32,"is_ext_shared_channel",32,"is_ext_shared_channel",32,"properties",32,"event",1,3,47,2,35,30,42,7,46,36,1,2,"postHogCreateTask",1,33,400,36,2,32,"status",45,14,40,22,32,"Failed to create task (",36,2,32,"status",45,32,"): ",36,2,36,0,54,1,2,"concat",4,2,"Error",1,49,36,2,32,"body",45,36,3,32,"run_id",45,2,"empty",1,5,40,15,36,3,32,"await",32,"max_wait",32,"190m",32,"label",32,"task",42,2,46,36,3,38,35,35,35,35]diff --git a/nodejs/tests/fixtures/hog-bytecode/98842691250e52fb687db2dbbaefb63abbe30f646fba662ac0f1dfa26055755c.json b/nodejs/tests/fixtures/hog-bytecode/98842691250e52fb687db2dbbaefb63abbe30f646fba662ac0f1dfa26055755c.jsonnew file mode 100644index 000000000000..b766b48ee372--- /dev/null+++ b/nodejs/tests/fixtures/hog-bytecode/98842691250e52fb687db2dbbaefb63abbe30f646fba662ac0f1dfa26055755c.json@@ -0,0 +1 @@+["_H",1,32,"skip",32,"inputs",1,2,40,10,32,"skipped",29,32,"reason",32,"over the cap",42,2,38,32,"id",32,"t1",32,"run_id",32,"r1",42,2,38]diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex caa0bfe6a04d..f2f395449d4b 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2708,6 +2708,14 @@ def update_task_run(# marking it failed or cancelled frees the per-run idempotency slot. The workflow and the# run's own agent write status through paths that do not pass through here.validated_data.pop("status")+ if (+ "status" in validated_data+ and not caller_is_agent+ and run.task.origin_product == Task.OriginProduct.WORKFLOW+ and validated_data["status"] != TaskRun.Status.CANCELLED+ ):+ # A finished status wakes the workflow step with this run's output, so only the agent may set it.+ validated_data.pop("status")has_output_merge = "output" in validated_data and isinstance(validated_data["output"], dict)has_state_merge = "state" in validated_data and isinstance(validated_data["state"], dict)diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.pyindex ed8f7f2139e1..0225dcb8a32d 100644--- a/products/tasks/backend/tests/test_workflow_tasks_api.py+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py@@ -641,6 +641,24 @@ class TestWorkflowTasksAPI(APIBaseTest):assert Task.objects.filter(team=self.team).filter(task_visibility_q(teammate.id)).filter(id=task_id).exists()assert Task.objects.filter(team=self.team).filter(task_control_q(teammate.id)).filter(id=task_id).exists()+ def test_a_teammate_cannot_finish_a_workflow_run_on_the_workflows_behalf(self) -> None:+ task = self._seed_workflow_task(TaskRun.Status.IN_PROGRESS)+ run = task.latest_run+ assert run is not None+ self.client.force_login(self._create_user("[email protected]"))++ with patch("products.tasks.backend.facade.api.resume_workflow_step_for_run") as resume:+ response = self.client.patch(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/",+ {"status": "completed", "output": {"final_message": "forged"}},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ run.refresh_from_db()+ assert run.status == TaskRun.Status.IN_PROGRESS+ resume.assert_not_called()+def test_a_request_without_a_prompt_is_rejected(self) -> None:response = self.client.post(self.url,