Skip to content

: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.

feat(cdp): wake awaited workflow steps over the CDP API instead of Kafka (#101477)

Harley Alexanderca6bb8f5fb3b
diff --git a/docs/internal/workflow-ai-task-limits.md b/docs/internal/workflow-ai-task-limits.md
index c375193e1d7a..8a91af220f38 100644
--- a/docs/internal/workflow-ai-task-limits.md
+++ b/docs/internal/workflow-ai-task-limits.md
@@ -37,10 +37,13 @@ A template asks for the wait by returning an `await` object next to its result,
`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.
+The wake is keyed on the step's idempotency key, so any template that dispatches a run its owner can report on can use the same path.
+With `WORKFLOWS_STEP_RESUME_JWT_SECRET` provisioned on Django and the plugin server, the process that marks the run terminal posts the wake to the CDP API's `workflow_steps/resume` route with a scoped JWT.
+Without the key, or when the API cannot be reached, the wake is the `$workflow_step_resume` internal event, consumed by the subscription matcher.
+Provision the key only after the release that carries the route is live on the plugin server, and on every Django process that marks a run terminal: web, Celery and Temporal.
`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`.
+A wake that lands while the step is still dispatching cannot be applied, because the worker owns the job state until it parks. The `cdp_hogflow_step_resume` counter reports these as `job_running`.
+A run takes seconds to minutes to finish, so a wake meets this only as the duplicate of one already taken; the route answers 409 and the caller drops it.
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/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.ts
index 498e93817d31..dbfde2796c0d 100644
--- a/nodejs/src/cdp/cdp-api.serial.test.ts
+++ b/nodejs/src/cdp/cdp-api.serial.test.ts
@@ -1269,6 +1269,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1328,6 +1329,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1379,6 +1381,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1438,6 +1441,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1501,6 +1505,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1674,6 +1679,7 @@ describe('CDP API', () => {
countInFlightJobs: mockCountInFlightJobs,
rescheduleParkedJobs: jest.fn(),
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
}
countHogFlow = await insertHogFlow({
@@ -1767,6 +1773,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn(),
rescheduleParkedJobs: mockRescheduleParkedJobs,
cancelJobs: jest.fn(),
+ resumeParkedSteps: jest.fn(),
}
rescheduleHogFlow = await insertHogFlow({
@@ -1917,6 +1924,118 @@ describe('CDP API', () => {
})
})
+ describe('workflow step resume', () => {
+ let mockResumeParkedSteps: jest.Mock
+ const jobId = new UUIDT().toString().toLowerCase()
+ const originKey = `${jobId}:task_node:3`
+ const body = { origin_key: originKey, status: 'completed', result: { final_message: 'done' } }
+
+ // Raw audience literal and Python claim names: the wire contract with Django's
+ // WORKFLOWS_STEP_RESUME_JWT_PURPOSE, so drift on either side breaks here.
+ const mintResumeToken = (
+ teamId: number,
+ key: string,
+ { secret = 'local-dev-workflows-step-resume-jwt', audience = 'posthog:workflows:step_resume' } = {}
+ ) => jwt.sign({ team_id: teamId, origin_key: key }, secret, { audience, expiresIn: '2m' })
+ const resumeAuth = (teamId: number, key: string) => ({
+ Authorization: `Bearer ${mintResumeToken(teamId, key)}`,
+ })
+
+ beforeEach(() => {
+ mockResumeParkedSteps = jest.fn().mockResolvedValue(new Map([[jobId, 'delivered']]))
+ api['batchResolverProducer'] = {
+ createJob: jest.fn(),
+ disconnect: jest.fn(),
+ countInFlightJobs: jest.fn(),
+ rescheduleParkedJobs: jest.fn(),
+ cancelJobs: jest.fn(),
+ resumeParkedSteps: mockResumeParkedSteps,
+ }
+ })
+
+ afterEach(() => {
+ api['batchResolverProducer'] = null
+ })
+
+ it('accepts a Django-minted token and wakes the parked step', async () => {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/workflow_steps/resume`)
+ .set(resumeAuth(team.id, originKey))
+ .send(body)
+
+ expect(res.status).toEqual(200)
+ expect(res.body).toEqual({ outcome: 'delivered' })
+ expect(mockResumeParkedSteps).toHaveBeenCalledWith(team.id, [{ ...body, jobId, actionId: 'task_node' }])
+ })
+
+ it('asks the caller to retry while the worker still holds the job', async () => {
+ mockResumeParkedSteps.mockResolvedValue(new Map([[jobId, 'job_running']]))
+
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/workflow_steps/resume`)
+ .set(resumeAuth(team.id, originKey))
+ .send(body)
+
+ expect(res.status).toEqual(409)
+ expect(res.body).toEqual({ outcome: 'job_running' })
+ })
+
+ it.each([
+ ['no token', () => ({})],
+ [
+ 'a token signed with the wrong key',
+ () => ({ Authorization: `Bearer ${mintResumeToken(team.id, originKey, { secret: 'wrong-key' })}` }),
+ ],
+ [
+ "another step's token",
+ () => ({ Authorization: `Bearer ${mintResumeToken(team.id, `${jobId}:task_node:2`)}` }),
+ ],
+ ["another team's token", () => ({ Authorization: `Bearer ${mintResumeToken(team.id + 1, originKey)}` })],
+ [
+ 'a cancel-audience token',
+ () => ({
+ Authorization: `Bearer ${mintResumeToken(team.id, originKey, {
+ audience: 'posthog:workflows:cancel_invocations',
+ })}`,
+ }),
+ ],
+ ])('rejects a request with %s', async (_desc, headers) => {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/workflow_steps/resume`)
+ .set(headers())
+ .send(body)
+
+ expect(res.status).toEqual(401)
+ expect(mockResumeParkedSteps).not.toHaveBeenCalled()
+ })
+
+ it('rejects a body whose origin key is not a dispatch key', async () => {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/workflow_steps/resume`)
+ .set(resumeAuth(team.id, 'nope'))
+ .send({ ...body, origin_key: 'nope' })
+
+ expect(res.status).toEqual(400)
+ expect(mockResumeParkedSteps).not.toHaveBeenCalled()
+ })
+
+ it('fails closed when the step resume JWT key is not provisioned', async () => {
+ const savedJwt = api['stepResumeJwt']
+ api['stepResumeJwt'] = new ScopedServiceJwt(PosthogJwtAudience.WORKFLOWS_STEP_RESUME, '')
+ try {
+ const res = await supertest(app)
+ .post(`/api/projects/${team.id}/workflow_steps/resume`)
+ .set(resumeAuth(team.id, originKey))
+ .send(body)
+
+ expect(res.status).toEqual(503)
+ expect(mockResumeParkedSteps).not.toHaveBeenCalled()
+ } finally {
+ api['stepResumeJwt'] = savedJwt
+ }
+ })
+ })
+
describe('hogflow cancel invocations auth', () => {
let mockCancelJobs: jest.Mock
@@ -1943,6 +2062,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn(),
rescheduleParkedJobs: jest.fn(),
cancelJobs: mockCancelJobs,
+ resumeParkedSteps: jest.fn(),
}
})
@@ -2058,6 +2178,7 @@ describe('CDP API', () => {
countInFlightJobs: jest.fn(),
rescheduleParkedJobs: jest.fn(),
cancelJobs: mockCancelJobs,
+ resumeParkedSteps: jest.fn(),
}
})
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index dede3b9351bb..533d87a12d44 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -47,6 +47,7 @@ import {
import { HogFlowExecutorService, createHogFlowInvocation } from './services/hogflows/hogflow-executor.service'
import { HogFlowManagerService } from './services/hogflows/hogflow-manager.service'
import { matchesWaitUntilCondition } from './services/hogflows/hogflow-utils'
+import { WorkflowStepResumeSchema } from './services/hogflows/step-resume.service'
import { InvocationResultsService } from './services/invocation-results.service'
import { JobQueue } from './services/job-queue/job-queue.interface'
import { GroupsManagerService } from './services/managers/groups-manager.service'
@@ -76,6 +77,7 @@ import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering
import { buildHogFunctionInvocations } from './utils/invocation-utils'
import { PosthogJwtAudience } from './utils/jwt-utils'
import { ScopedServiceJwt } from './utils/scoped-service-jwt'
+import { parseWorkflowStepDispatchKey } from './utils/workflow-step-dispatch-key'
// Allowlist of safe content types for webhook responses to prevent XSS
const SAFE_CONTENT_TYPES = new Set([
@@ -155,6 +157,7 @@ export class CdpApi {
private rescheduleJwt: ScopedServiceJwt
private cancelInvocationsJwt: ScopedServiceJwt
private cancelBatchJwt: ScopedServiceJwt
+ private stepResumeJwt: ScopedServiceJwt
constructor(
private config: PluginsServerConfig,
@@ -218,6 +221,10 @@ export class CdpApi {
PosthogJwtAudience.WORKFLOWS_CANCEL_BATCH,
config.WORKFLOWS_CANCEL_JWT_SECRET || ''
)
+ this.stepResumeJwt = new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOWS_STEP_RESUME,
+ config.WORKFLOWS_STEP_RESUME_JWT_SECRET || ''
+ )
}
public get service(): PluginServerService {
@@ -298,6 +305,7 @@ export class CdpApi {
'/api/projects/:team_id/hog_flows/:id/batch_jobs/:batch_job_id/cancel',
asyncHandler(this.postHogFlowCancelBatchJob)
)
+ router.post('/api/projects/:team_id/workflow_steps/resume', asyncHandler(this.postWorkflowStepResume))
router.get('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.getFunctionStatus()))
router.patch('/api/projects/:team_id/hog_functions/:id/status', asyncHandler(this.patchFunctionStatus()))
router.get('/api/hog_functions/states', asyncHandler(this.getFunctionStates()))
@@ -1061,8 +1069,9 @@ export class CdpApi {
// Shared gate for the per-call scoped JWTs Django mints (reschedule, cancel): verifies the
// token and requires its claims to match the URL's team + workflow, so a leaked token can't
// touch another team or flow. Routes scoped tighter than a workflow (batch cancel) pass the
- // narrower claims via extraClaims and every one must match too. Writes the 401 itself and
- // returns false on any mismatch.
+ // narrower claims via extraClaims and every one must match too; a route without a workflow
+ // in its path (step resume) pins the job through extraClaims instead. Writes the 401 itself
+ // and returns false on any mismatch.
private verifyScopedWorkflowJwt(
jwt: ScopedServiceJwt,
req: ModifiedRequest,
@@ -1081,7 +1090,8 @@ export class CdpApi {
claims = undefined
}
const extrasMatch = !extraClaims || Object.entries(extraClaims).every(([key, value]) => claims?.[key] === value)
- if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id || !extrasMatch) {
+ const flowMatches = id === undefined || claims?.hog_flow_id === id
+ if (!claims || claims.team_id !== parseInt(team_id) || !flowMatches || !extrasMatch) {
res.status(401).json({ error: `Unauthorized: Invalid ${label} token` })
return false
}
@@ -1171,6 +1181,53 @@ export class CdpApi {
}
}
+ // Wake the parked workflow step that dispatched a task run, with the run's outcome. Django
+ // calls this from a retrying Celery task when the run reaches a terminal status. One resume
+ // per call; the outcome tells the caller whether to retry (409: the worker still holds the
+ // job) or stop (200: delivered, or the step is past this wake).
+ //
+ // Auth mirrors the cancel routes: a per-call JWT minted by Django on its own audience and key,
+ // pinned to the team and to the origin key, so a leaked token can wake exactly one step.
+ private postWorkflowStepResume = async (req: ModifiedRequest, res: express.Response): Promise<any> => {
+ try {
+ if (!this.batchResolverProducer) {
+ return res.status(503).json({
+ error: 'Cyclotron producer not initialized (CYCLOTRON_NODE_DATABASE_URL unset)',
+ })
+ }
+ if (!this.stepResumeJwt.enabled) {
+ return res.status(503).json({
+ error: 'Step resume auth not configured (WORKFLOWS_STEP_RESUME_JWT_SECRET unset)',
+ })
+ }
+ // The token pins the origin key, so read it raw for the claim check; the body is
+ // validated only once the caller is allowed to wake this step.
+ const originKey = typeof req.body?.origin_key === 'string' ? req.body.origin_key : ''
+ if (!this.verifyScopedWorkflowJwt(this.stepResumeJwt, req, res, 'step resume', { origin_key: originKey })) {
+ return
+ }
+ const parsed = WorkflowStepResumeSchema.safeParse(req.body)
+ const key = parsed.success ? parseWorkflowStepDispatchKey(parsed.data.origin_key) : null
+ if (!parsed.success || !key) {
+ return res.status(400).json({ error: 'origin_key must be a workflow step dispatch key' })
+ }
+ const teamId = parseInt(req.params.team_id)
+ const team = await this.deps.teamManager.getTeam(teamId).catch(() => null)
+ if (!team) {
+ return res.status(404).json({ error: 'Team not found' })
+ }
+
+ const outcomes = await this.batchResolverProducer.resumeParkedSteps(teamId, [{ ...parsed.data, ...key }])
+ const outcome = outcomes.get(key.jobId) ?? 'job_missing'
+ return res.status(outcome === 'job_running' ? 409 : 200).json({ outcome })
+ } catch (e) {
+ logger.error('Error resuming workflow step', {
+ error: e instanceof Error ? e.message : String(e),
+ })
+ return res.status(500).json({ error: e instanceof Error ? e.message : String(e) })
+ }
+ }
+
// Flag a workflow's in-flight cyclotron jobs for cancellation. The workers own the actual
// termination (terminal status + lifecycle row + metric + log) when they observe the flag;
// this endpoint only marks rows and wakes parked ones. See CyclotronV2Manager.cancelJobs.
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index 62feb3dc9a0f..18fa43717580 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -193,6 +193,10 @@ export type CdpConfig = ClickhouseConfig & {
// web tier mints cancels while the worker mints reschedules, so neither tier's key can forge
// the other's calls. Same comma-separated rotation and fail-closed-when-empty semantics.
WORKFLOWS_CANCEL_JWT_SECRET: string
+ // Scoped JWT keys verifying Django's step_resume calls (a finished task waking its parked
+ // workflow step). Its own key: the Celery and Temporal workers mint it, no other tier does.
+ // Same comma-separated rotation and fail-closed-when-empty semantics.
+ WORKFLOWS_STEP_RESUME_JWT_SECRET: string
// Scoped JWT keys signing the workflow engine's task-create calls to Django, with the same
// comma-separated rotation and fail-closed-when-empty semantics as the secret above.
TASKS_CREATE_JWT_SECRET: string
@@ -385,6 +389,8 @@ export function getDefaultCdpConfig(): CdpConfig {
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOWS_CANCEL_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-cancel-jwt' : '',
// Dev/test default must match Django's (posthog/settings/data_stores.py).
+ WORKFLOWS_STEP_RESUME_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-step-resume-jwt' : '',
+ // Dev/test default must match Django's (posthog/settings/data_stores.py).
TASKS_CREATE_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-tasks-create-jwt' : '',
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOW_SCOUT_RUN_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-scout-run-jwt' : '',
diff --git a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
index 89bbc5117718..d349bfa6d7e0 100644
--- a/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-hogflow-subscription-matcher.consumer.ts
@@ -1,9 +1,14 @@
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 {
+ StepResume,
+ WorkflowStepResumeSchema,
+ counterStepResume,
+ processStepResumes,
+} from '~/cdp/services/hogflows/step-resume.service'
import { parseWorkflowStepDispatchKey } from '~/cdp/utils/workflow-step-dispatch-key'
import {
KAFKA_CDP_INTERNAL_EVENTS,
@@ -184,20 +189,6 @@ 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<
@@ -869,63 +860,7 @@ export class CdpHogflowSubscriptionMatcherConsumer<
@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()
- }
+ await processStepResumes(this.cyclotronPool, resumes)
}
@instrumented('cdpHogflowSubscriptionMatcher.parseInternalEventMessages')
@@ -1498,33 +1433,6 @@ 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 should
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index e62211c37b62..d690b7eda845 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -811,6 +811,64 @@ describe('Cyclotron V2', () => {
})
})
+ describe('resumeParkedSteps', () => {
+ const parkedState = (jobId: string, actionId = 'task_node'): Buffer =>
+ Buffer.from(
+ JSON.stringify({
+ state: {
+ currentAction: { id: actionId, awaitingResume: { key: `${jobId}:${actionId}:3` } },
+ },
+ })
+ )
+ const resumeFor = (jobId: string) => ({
+ origin_key: `${jobId}:task_node:3`,
+ status: 'completed' as const,
+ result: { final_message: 'done' },
+ jobId,
+ actionId: 'task_node',
+ })
+
+ it('wakes a parked step of the team and stamps the result on it', async () => {
+ const jobId = uuidv7()
+ await manager.createJob({
+ id: jobId,
+ teamId: 1,
+ queueName: QUEUE,
+ functionId: uuidv7(),
+ scheduled: new Date(Date.now() + 3600 * 1000),
+ state: parkedState(jobId),
+ })
+
+ const outcomes = await manager.resumeParkedSteps(1, [resumeFor(jobId)])
+
+ expect(outcomes.get(jobId)).toBe('delivered')
+ expect(await jobIsDue(jobId)).toBe(true)
+ const row = await queryJob(jobId)
+ expect(parseJSON(row.state!.toString()).state.currentAction.resumeResult).toEqual({
+ key: `${jobId}:task_node:3`,
+ status: 'completed',
+ result: { final_message: 'done' },
+ })
+ })
+
+ it("reports another team's job as missing rather than waking it", async () => {
+ const jobId = uuidv7()
+ await manager.createJob({
+ id: jobId,
+ teamId: 2,
+ queueName: QUEUE,
+ functionId: uuidv7(),
+ scheduled: new Date(Date.now() + 3600 * 1000),
+ state: parkedState(jobId),
+ })
+
+ const outcomes = await manager.resumeParkedSteps(1, [resumeFor(jobId)])
+
+ expect(outcomes.get(jobId)).toBe('job_missing')
+ expect(await jobIsDue(jobId)).toBe(false)
+ })
+ })
+
describe('cancelJobs', () => {
const FAR_FUTURE = () => new Date(Date.now() + 7 * 24 * 3600 * 1000)
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index 969f2314a93a..f5bf5d68076f 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -6,6 +6,7 @@ import { isTransientPgError } from '~/common/utils/db/postgres'
import { logger } from '~/common/utils/logger'
import { sleep } from '~/common/utils/utils'
+import { StepResume, StepResumeOutcome, processStepResumes } from '../hogflows/step-resume.service'
import {
CYCLOTRON_COUNTER_MAX,
CyclotronV2CancelJobsOptions,
@@ -788,4 +789,10 @@ export class CyclotronV2Manager {
return false
}
}
+
+ // Wakes parked workflow steps with the outcome of the run they dispatched. Scoped to one team
+ // because the caller's token is; see processStepResumes for the per-job outcomes.
+ async resumeParkedSteps(teamId: number, resumes: StepResume[]): Promise<Map<string, StepResumeOutcome>> {
+ return await processStepResumes(this.pool, resumes, teamId)
+ }
}
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index b9905ff957b8..3c2c43efa276 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -1,6 +1,8 @@
import { DateTime } from 'luxon'
import { z } from 'zod'
+import { StepResume, StepResumeOutcome } from '~/cdp/services/hogflows/step-resume.service'
+
export type CyclotronV2JobStatus = 'available' | 'running' | 'completed' | 'failed' | 'canceled'
// SMALLINT ceiling. Dequeue bumps the counter while claiming a batch, so one saturated row aborts the claim for every job in it.
@@ -192,6 +194,7 @@ export interface CyclotronV2JobProducer {
countInFlightJobs(teamId: number, functionId: string): Promise<CyclotronV2InFlightCounts>
rescheduleParkedJobs(options: CyclotronV2RescheduleParkedOptions): Promise<CyclotronV2RescheduleParkedResult>
cancelJobs(options: CyclotronV2CancelJobsOptions): Promise<CyclotronV2CancelJobsResult>
+ resumeParkedSteps(teamId: number, resumes: StepResume[]): Promise<Map<string, StepResumeOutcome>>
disconnect(): Promise<void>
}
diff --git a/nodejs/src/cdp/services/hogflows/step-resume.service.ts b/nodejs/src/cdp/services/hogflows/step-resume.service.ts
new file mode 100644
index 000000000000..216aec575079
--- /dev/null
+++ b/nodejs/src/cdp/services/hogflows/step-resume.service.ts
@@ -0,0 +1,129 @@
+import { Pool } from 'pg'
+import { Counter } from 'prom-client'
+import { z } from 'zod'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
+
+export 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(),
+})
+
+export type StepResume = z.infer<typeof WorkflowStepResumeSchema> & { jobId: string; actionId: string }
+
+// `job_<status>` covers every non-parked cyclotron status; `delivered` is the only success.
+export type StepResumeOutcome = 'delivered' | 'stale_key' | 'job_missing' | `job_${string}`
+
+export const counterStepResume = new Counter({
+ name: 'cdp_hogflow_step_resume',
+ help: 'Workflow step resumes by outcome.',
+ labelNames: ['outcome'],
+})
+
+// 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.
+export 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
+ }
+}
+
+// Hands each resume to its parked job. `teamId` narrows the lookup for callers whose auth is
+// team-scoped; the matcher passes none because one Kafka batch spans teams.
+export async function processStepResumes(
+ pool: Pool,
+ resumes: StepResume[],
+ teamId?: number
+): Promise<Map<string, StepResumeOutcome>> {
+ const outcomes = new Map<string, StepResumeOutcome>()
+ if (resumes.length === 0) {
+ return outcomes
+ }
+ 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 pool.connect()
+ try {
+ await client.query('BEGIN')
+ const rows = await client.query(
+ `SELECT id, status, state FROM cyclotron_jobs WHERE id = ANY($1::uuid[])${
+ teamId === undefined ? '' : ' AND team_id = $2'
+ } ORDER BY id FOR UPDATE`,
+ teamId === undefined ? [[...byJob.keys()]] : [[...byJob.keys()], teamId]
+ )
+ 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. The caller decides whether to retry.
+ if (row.status !== 'available') {
+ outcomes.set(row.id, `job_${row.status}`)
+ 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) {
+ outcomes.set(row.id, 'stale_key')
+ continue
+ }
+ updates.push({ id: row.id, state })
+ }
+ for (const jobId of byJob.keys()) {
+ outcomes.set(jobId, 'job_missing')
+ }
+ 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'
+ RETURNING cj.id`,
+ [updates.map((update) => update.id), updates.map((update) => update.state)]
+ )
+ const written = new Set(updated.rows.map((row) => row.id))
+ for (const update of updates) {
+ outcomes.set(update.id, written.has(update.id) ? 'delivered' : 'job_missing')
+ }
+ }
+ await client.query('COMMIT')
+ } catch (err) {
+ await client.query('ROLLBACK').catch(() => {})
+ throw err
+ } finally {
+ client.release()
+ }
+ for (const outcome of outcomes.values()) {
+ counterStepResume.labels({ outcome }).inc()
+ }
+ return outcomes
+}
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 48ee6d2aa6b1..3ed1dde60b2f 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -6,6 +6,7 @@ export enum PosthogJwtAudience {
WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',
WORKFLOWS_CANCEL_INVOCATIONS = 'posthog:workflows:cancel_invocations',
WORKFLOWS_CANCEL_BATCH = 'posthog:workflows:cancel_batch',
+ WORKFLOWS_STEP_RESUME = 'posthog:workflows:step_resume',
CUSTOMER_TASKS_CREATE = 'posthog:customer-tasks:create',
TASKS_CREATE = 'posthog:tasks:create',
WORKFLOW_SCOUT_RUN = 'posthog:workflows:scout_run',
diff --git a/nodejs/src/common/api/middleware/internal-api-auth.ts b/nodejs/src/common/api/middleware/internal-api-auth.ts
index ff7c1d79f378..eb5696c253fe 100644
--- a/nodejs/src/common/api/middleware/internal-api-auth.ts
+++ b/nodejs/src/common/api/middleware/internal-api-auth.ts
@@ -34,6 +34,8 @@ const SCOPED_AUTH_PATH_PATTERNS = [
/^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/invocations\/cancel$/,
// CdpApi.postHogFlowCancelBatchJob, verified against WORKFLOWS_CANCEL_JWT_SECRET, audience-pinned.
/^\/api\/projects\/[^/]+\/hog_flows\/[^/]+\/batch_jobs\/[^/]+\/cancel$/,
+ // CdpApi.postWorkflowStepResume, verified against WORKFLOWS_STEP_RESUME_JWT_SECRET, audience-pinned.
+ /^\/api\/projects\/[^/]+\/workflow_steps\/resume$/,
]
export interface InternalApiAuthOptions {
diff --git a/posthog/cdp/test/test_workflow_step_resume.py b/posthog/cdp/test/test_workflow_step_resume.py
index a58894e0647d..7797a64cde4b 100644
--- a/posthog/cdp/test/test_workflow_step_resume.py
+++ b/posthog/cdp/test/test_workflow_step_resume.py
@@ -1,15 +1,29 @@
import json
import pytest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+
+from django.conf import settings
+from django.test import override_settings
+
+import jwt
+import requests
from posthog.cdp.workflow_step_resume import RESULT_BYTE_CAP, RESULT_STRING_CAP, emit_workflow_step_resume
_PRODUCE = "posthog.cdp.workflow_step_resume.produce_internal_event"
+_POST = "posthog.plugins.plugin_server_api.internal_requests.post"
+
+def _response(status_code: int) -> MagicMock:
+ response = MagicMock(status_code=status_code)
+ if status_code >= 400:
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code}", response=response)
+ return response
-def test_emits_the_wake_keyed_to_the_step_with_capped_strings() -> None:
- with patch(_PRODUCE) as produce:
+
+def test_posts_the_wake_with_a_scoped_jwt_and_capped_strings() -> None:
+ with patch(_POST, return_value=_response(200)) as post, patch(_PRODUCE) as produce:
emit_workflow_step_resume(
team_id=7,
origin_key="job:step:3",
@@ -17,20 +31,67 @@ def test_emits_the_wake_keyed_to_the_step_with_capped_strings() -> None:
result={"final_message": "x" * (RESULT_STRING_CAP + 1), "pr_urls": ["u"], "error_message": None},
)
+ produce.assert_not_called()
+ kwargs = post.call_args.kwargs
+ assert post.call_args.args[0].endswith("/api/projects/7/workflow_steps/resume")
+ assert kwargs["json"] == {
+ "origin_key": "job:step:3",
+ "status": "completed",
+ "result": {"final_message": "x" * RESULT_STRING_CAP, "pr_urls": ["u"]},
+ }
+ assert kwargs["timeout"] == 10
+ assert "x-internal-api-secret" not in {key.lower() for key in kwargs["headers"]}
+ claims = jwt.decode(
+ kwargs["headers"]["Authorization"].removeprefix("Bearer "),
+ settings.WORKFLOWS_STEP_RESUME_JWT_SECRETS[0],
+ audience="posthog:workflows:step_resume",
+ algorithms=["HS256"],
+ )
+ assert claims["team_id"] == 7
+ assert claims["origin_key"] == "job:step:3"
+
+
+def test_emits_the_internal_event_until_the_key_is_provisioned() -> None:
+ with (
+ override_settings(WORKFLOWS_STEP_RESUME_JWT_SECRETS=[]),
+ patch(_POST) as post,
+ patch(_PRODUCE) as produce,
+ ):
+ emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", result={"pr_urls": ["u"]})
+
+ post.assert_not_called()
produce.assert_called_once()
assert produce.call_args.kwargs["team_id"] == 7
event = produce.call_args.kwargs["event"]
assert event.event == "$workflow_step_resume"
assert event.distinct_id == "team_7"
- assert event.properties == {
- "origin_key": "job:step:3",
- "status": "completed",
- "result": {"final_message": "x" * RESULT_STRING_CAP, "pr_urls": ["u"]},
- }
+ assert event.properties == {"origin_key": "job:step:3", "status": "completed", "result": {"pr_urls": ["u"]}}
+
+
[email protected]("failure", [_response(503), requests.ConnectionError("api down")])
+def test_the_wake_falls_back_to_the_internal_event_when_the_api_cannot_take_it(failure) -> None:
+ post_kwargs = {"side_effect": failure} if isinstance(failure, Exception) else {"return_value": failure}
+ with patch(_POST, **post_kwargs), patch(_PRODUCE) as produce:
+ emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", result={"pr_urls": ["u"]})
+
+ produce.assert_called_once()
+ event = produce.call_args.kwargs["event"]
+ assert event.event == "$workflow_step_resume"
+ assert event.properties == {"origin_key": "job:step:3", "status": "completed", "result": {"pr_urls": ["u"]}}
+
+
+def test_a_wake_the_worker_cannot_take_yet_is_dropped_as_a_duplicate() -> None:
+ with patch(_POST, return_value=_response(409)), patch(_PRODUCE) as produce:
+ emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", raise_on_error=True)
+
+ produce.assert_not_called()
def test_a_failed_emit_does_not_raise() -> None:
- with patch(_PRODUCE, side_effect=RuntimeError("kafka down")):
+ with (
+ patch(_POST, side_effect=requests.ConnectionError("api down")),
+ patch(_PRODUCE, side_effect=RuntimeError("kafka down")),
+ ):
emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="failed")
@@ -44,14 +105,18 @@ def test_a_failed_emit_does_not_raise() -> None:
],
)
def test_result_fits_the_serialized_byte_budget(result) -> None:
- with patch(_PRODUCE) as produce:
+ with patch(_POST, return_value=_response(200)) as post:
emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", result=result)
- capped = produce.call_args.kwargs["event"].properties["result"]
+ capped = post.call_args.kwargs["json"]["result"]
assert len(json.dumps(capped, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) <= RESULT_BYTE_CAP
assert all(url in result["pr_urls"] for url in capped.get("pr_urls", []))
def test_delivery_activities_can_retry_a_failed_emit() -> None:
- with patch(_PRODUCE, side_effect=RuntimeError("kafka down")), pytest.raises(RuntimeError, match="kafka down"):
+ with (
+ patch(_POST, side_effect=requests.ConnectionError("api down")),
+ patch(_PRODUCE, side_effect=RuntimeError("kafka down")),
+ pytest.raises(RuntimeError, match="kafka down"),
+ ):
emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="failed", raise_on_error=True)
diff --git a/posthog/cdp/workflow_step_resume.py b/posthog/cdp/workflow_step_resume.py
index da2b687323f5..8f0b7a9208f6 100644
--- a/posthog/cdp/workflow_step_resume.py
+++ b/posthog/cdp/workflow_step_resume.py
@@ -2,9 +2,11 @@ import json
from collections.abc import Mapping
from typing import Any, Literal
+import requests
import structlog
from posthog.cdp.internal_events import WORKFLOW_STEP_RESUME_EVENT, InternalEventEvent, produce_internal_event
+from posthog.plugins.plugin_server_api import WORKFLOWS_STEP_RESUME_JWT_PURPOSE, resume_workflow_step
logger = structlog.get_logger(__name__)
@@ -50,6 +52,17 @@ def cap_value(value: Any, budget: int) -> Any:
return value if value is not None and _json_size(value) <= budget else None
+def produce_step_resume_event(*, team_id: int, origin_key: str, status: str, result: Mapping[str, Any]) -> None:
+ produce_internal_event(
+ team_id=team_id,
+ event=InternalEventEvent(
+ event=WORKFLOW_STEP_RESUME_EVENT,
+ distinct_id=f"team_{team_id}",
+ properties={"origin_key": origin_key, "status": status, "result": result},
+ ),
+ )
+
+
def emit_workflow_step_resume(
*,
team_id: int,
@@ -58,25 +71,22 @@ def emit_workflow_step_resume(
result: Mapping[str, Any] | None = None,
raise_on_error: bool = False,
) -> None:
- """Produce the internal event that wakes the step which dispatched `origin_key`.
-
- The wake is asynchronous. This call returns once the event is produced, not once the step
- resumes: the engine's subscription matcher consumes the event and schedules the parked job.
- Delivery activities can opt into retries with `raise_on_error`.
- """
+ """Wake the step which dispatched `origin_key`: one POST to the engine's API with the key
+ provisioned, else the `$workflow_step_resume` internal event. A 409 is a duplicate of a wake
+ already taken, so it is final; `raise_on_error` lets a Temporal activity retry a lost wake."""
+ capped = cap_value(result or {}, RESULT_BYTE_CAP)
try:
- produce_internal_event(
- team_id=team_id,
- event=InternalEventEvent(
- event=WORKFLOW_STEP_RESUME_EVENT,
- distinct_id=f"team_{team_id}",
- properties={
- "origin_key": origin_key,
- "status": status,
- "result": cap_value(result or {}, RESULT_BYTE_CAP),
- },
- ),
- )
+ if WORKFLOWS_STEP_RESUME_JWT_PURPOSE.enabled():
+ try:
+ response = resume_workflow_step(team_id=team_id, origin_key=origin_key, status=status, result=capped)
+ if response.status_code == 409:
+ logger.info("workflow_step_resume_not_parked", team_id=team_id, origin_key=origin_key)
+ return
+ response.raise_for_status()
+ return
+ except requests.RequestException:
+ logger.exception("workflow_step_resume_post_failed", team_id=team_id, origin_key=origin_key)
+ produce_step_resume_event(team_id=team_id, origin_key=origin_key, status=status, result=capped)
except Exception:
logger.exception("workflow_step_resume_emit_failed", team_id=team_id, origin_key=origin_key, status=status)
if raise_on_error:
diff --git a/posthog/jwt.py b/posthog/jwt.py
index fa737ceaa4a4..78b776ecf57e 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -24,6 +24,7 @@ class PosthogJwtAudience(Enum):
WORKFLOWS_RESCHEDULE_PARKED = "posthog:workflows:reschedule_parked"
WORKFLOWS_CANCEL_INVOCATIONS = "posthog:workflows:cancel_invocations"
WORKFLOWS_CANCEL_BATCH = "posthog:workflows:cancel_batch"
+ WORKFLOWS_STEP_RESUME = "posthog:workflows:step_resume"
INTEGRATION_SERVICE = "posthog:integration_service"
TASKS_CREATE = "posthog:tasks:create"
CUSTOMER_TASKS_CREATE = "posthog:customer-tasks:create"
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index 92975a2a17ea..949fe4826800 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -221,6 +221,32 @@ def cancel_hog_flow_batch_job(team_id: int, hog_flow_id: str, batch_job_id: str)
)
+WORKFLOWS_STEP_RESUME_JWT_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.WORKFLOWS_STEP_RESUME,
+ settings_name="WORKFLOWS_STEP_RESUME_JWT_SECRETS",
+ default_ttl=timedelta(minutes=2),
+)
+
+
+def _mint_step_resume_jwt(team_id: int, origin_key: str) -> str:
+ """Short-lived scoped JWT for one step_resume call, pinned to the team and the dispatch key so a
+ leaked token can wake exactly one step. Verified in the plugin server's CdpApi.postWorkflowStepResume."""
+ if not WORKFLOWS_STEP_RESUME_JWT_PURPOSE.enabled():
+ raise RuntimeError("WORKFLOWS_STEP_RESUME_JWT_SECRET is not configured — cannot call step_resume")
+ return WORKFLOWS_STEP_RESUME_JWT_PURPOSE.mint({"team_id": team_id, "origin_key": origin_key})
+
+
+def resume_workflow_step(team_id: int, origin_key: str, status: str, result: dict) -> requests.Response:
+ """Wake the parked workflow step that dispatched `origin_key`. 409 means the worker still holds the
+ job and the caller should retry; every other 2xx outcome is final."""
+ return internal_requests.post(
+ CDP_API_URL + f"/api/projects/{team_id}/workflow_steps/resume",
+ json={"origin_key": origin_key, "status": status, "result": result},
+ headers={"Authorization": f"Bearer {_mint_step_resume_jwt(team_id, origin_key)}"},
+ timeout=10,
+ )
+
+
def cancel_hog_flow_invocations(team_id: int, hog_flow_id: str, payload: dict) -> requests.Response:
"""Flag a workflow's in-flight invocations for cancellation. `payload` carries exactly one
selector: {"invocation_ids": [...]} or {"all": true}. The Node side only marks rows and wakes
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index e611f1bae4d3..30f0f57a36db 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -588,6 +588,15 @@ WORKFLOWS_CANCEL_JWT_SECRETS = get_list(
get_from_env("WORKFLOWS_CANCEL_JWT_SECRET", "local-dev-workflows-cancel-jwt" if DEBUG or TEST else "")
)
+# Scoped JWT keys for the workflow step resume route (a finished task run waking the workflow
+# step that dispatched it). The Celery and Temporal workers mint, the plugin server verifies.
+# Its own key per the one-key-per-surface rule above. Comma-separated, newest first. Empty
+# outside dev/test, in which case the wake falls back to the `$workflow_step_resume` internal
+# event. The dev/test value must match the plugin server's default (nodejs/src/cdp/config.ts).
+WORKFLOWS_STEP_RESUME_JWT_SECRETS = get_list(
+ get_from_env("WORKFLOWS_STEP_RESUME_JWT_SECRET", "local-dev-workflows-step-resume-jwt" if DEBUG or TEST else "")
+)
+
# Signs the tokens a workflow's "Create AI task" action calls back with. The dev/test value
# must match the plugin server's minting default so local workflows work with no setup.
TASKS_CREATE_JWT_SECRETS = get_list(