: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): cyclotron sweep primitive to reschedule parked runs (#71293)
Harley Alexander0488b9eed182
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.tsindex 69699825601f..acae19b8fc2c 100644--- a/nodejs/src/cdp/cdp-api.test.ts+++ b/nodejs/src/cdp/cdp-api.test.ts@@ -2,6 +2,7 @@ import { createMockJobQueue } from '../../tests/helpers/mocks/job-queue.mock'import { mockFetch } from '../../tests/helpers/mocks/request.mock'import { Server } from 'http'+import jwt from 'jsonwebtoken'import supertest from 'supertest'import express from 'ultimate-express'@@ -915,6 +916,7 @@ describe('CDP API', () => {api['batchResolverProducer'] = {createJob: createJobMock,countInFlightJobs: jest.fn().mockResolvedValue(0),+ rescheduleParkedJobs: jest.fn(),disconnect: jest.fn().mockResolvedValue(undefined),}@@ -1002,6 +1004,7 @@ describe('CDP API', () => {api['batchResolverProducer'] = {createJob: createJobMock,countInFlightJobs: jest.fn().mockResolvedValue(0),+ rescheduleParkedJobs: jest.fn(),disconnect: jest.fn().mockResolvedValue(undefined),}@@ -1063,6 +1066,7 @@ describe('CDP API', () => {api['batchResolverProducer'] = {createJob: createJobMock,countInFlightJobs: jest.fn().mockResolvedValue(0),+ rescheduleParkedJobs: jest.fn(),disconnect: jest.fn().mockResolvedValue(undefined),}@@ -1181,6 +1185,7 @@ describe('CDP API', () => {createJob: jest.fn(),disconnect: jest.fn(),countInFlightJobs: mockCountInFlightJobs,+ rescheduleParkedJobs: jest.fn(),}countHogFlow = await insertHogFlow({@@ -1244,6 +1249,185 @@ describe('CDP API', () => {})})+ describe('hogflow reschedule parked', () => {+ let rescheduleHogFlow: HogFlow+ let mockRescheduleParkedJobs: jest.Mock+ const sweepFloor = new Date('2025-06-01T00:10:00.000Z')+ const sweepUntil = new Date('2025-06-01T00:40:00.000Z')++ // Mirrors Django's mint (posthog/plugins/plugin_server_api.py) with the shared dev/test key.+ const mintToken = (teamId: number, hogFlowId: string, secret = 'local-dev-workflows-reschedule-jwt') =>+ jwt.sign({ team_id: teamId, hog_flow_id: hogFlowId }, secret, {+ audience: 'posthog:workflows:reschedule_parked',+ expiresIn: '2m',+ })+ const authFor = (teamId: number, hogFlowId: string) => ({+ Authorization: `Bearer ${mintToken(teamId, hogFlowId)}`,+ })++ beforeEach(async () => {+ mockRescheduleParkedJobs = jest.fn().mockResolvedValue({+ swept: 5,+ remaining: 2,+ done: false,+ sweepFloor,+ sweepUntil,+ })+ api['batchResolverProducer'] = {+ createJob: jest.fn(),+ disconnect: jest.fn(),+ countInFlightJobs: jest.fn(),+ rescheduleParkedJobs: mockRescheduleParkedJobs,+ }++ rescheduleHogFlow = await insertHogFlow({+ id: new UUIDT().toString(),+ name: 'test reschedule hog flow',+ status: 'active',+ version: 1,+ exit_condition: 'exit_on_conversion',+ edges: [],+ actions: [],+ trigger: {+ type: 'event',+ filters: {},+ },+ })+ })++ afterEach(() => {+ api['batchResolverProducer'] = null+ })++ it('runs a sweep slice and returns the bounds for follow-up slices', async () => {+ const res = await supertest(app)+ .post(`/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .set(authFor(rescheduleHogFlow.team_id, rescheduleHogFlow.id))+ .send({ action_ids: ['delay_1', 'wait_1'] })++ expect(res.status).toEqual(200)+ expect(res.body).toEqual({+ swept: 5,+ remaining: 2,+ done: false,+ sweep_floor: sweepFloor.toISOString(),+ sweep_until: sweepUntil.toISOString(),+ })+ expect(mockRescheduleParkedJobs).toHaveBeenCalledWith({+ teamId: rescheduleHogFlow.team_id,+ functionId: rescheduleHogFlow.id,+ actionIds: ['delay_1', 'wait_1'],+ sweepFloor: undefined,+ sweepUntil: undefined,+ })+ })++ it('parses passed-through bounds into dates', async () => {+ const res = await supertest(app)+ .post(`/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .set(authFor(rescheduleHogFlow.team_id, rescheduleHogFlow.id))+ .send({+ action_ids: ['delay_1'],+ sweep_floor: sweepFloor.toISOString(),+ sweep_until: sweepUntil.toISOString(),+ })++ expect(res.status).toEqual(200)+ expect(mockRescheduleParkedJobs).toHaveBeenCalledWith(expect.objectContaining({ sweepFloor, sweepUntil }))+ })++ it.each([+ ['missing action_ids', {}],+ ['empty action_ids', { action_ids: [] }],+ ['non-string action_ids', { action_ids: [42] }],+ ['too many action_ids', { action_ids: Array.from({ length: 101 }, (_, i) => `a${i}`) }],+ ['unparseable bounds', { action_ids: ['a'], sweep_floor: 'nope', sweep_until: 'nope' }],+ ['only one bound', { action_ids: ['a'], sweep_floor: '2025-06-01T00:10:00.000Z' }],+ [+ 'floor after until',+ {+ action_ids: ['a'],+ sweep_floor: '2025-06-01T00:40:00.000Z',+ sweep_until: '2025-06-01T00:10:00.000Z',+ },+ ],+ ])('rejects a bad body: %s', async (_desc, body) => {+ const res = await supertest(app)+ .post(`/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .set(authFor(rescheduleHogFlow.team_id, rescheduleHogFlow.id))+ .send(body)++ expect(res.status).toEqual(400)+ expect(mockRescheduleParkedJobs).not.toHaveBeenCalled()+ })++ it("errors when requesting another team's hog flow", async () => {+ const otherTeamId = await createTeam(hub.postgres, team.organization_id)++ const res = await supertest(app)+ .post(`/api/projects/${otherTeamId}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .set(authFor(otherTeamId, rescheduleHogFlow.id))+ .send({ action_ids: ['delay_1'] })++ expect(res.status).toEqual(404)+ expect(mockRescheduleParkedJobs).not.toHaveBeenCalled()+ })++ it.each([+ ['no token', () => ({})],+ [+ 'a token signed with the wrong key',+ () => ({+ Authorization: `Bearer ${mintToken(rescheduleHogFlow.team_id, rescheduleHogFlow.id, 'wrong-key')}`,+ }),+ ],+ [+ "another workflow's token",+ () => ({ Authorization: `Bearer ${mintToken(rescheduleHogFlow.team_id, new UUIDT().toString())}` }),+ ],+ [+ "another team's token",+ () => ({ Authorization: `Bearer ${mintToken(rescheduleHogFlow.team_id + 1, rescheduleHogFlow.id)}` }),+ ],+ ])('rejects a request with %s', async (_desc, headers) => {+ const res = await supertest(app)+ .post(`/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .set(headers())+ .send({ action_ids: ['delay_1'] })++ expect(res.status).toEqual(401)+ expect(mockRescheduleParkedJobs).not.toHaveBeenCalled()+ })++ it('fails closed when the reschedule JWT key is not provisioned', async () => {+ const savedJwt = api['rescheduleJwt']+ api['rescheduleJwt'] = null+ try {+ const res = await supertest(app)+ .post(+ `/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`+ )+ .set(authFor(rescheduleHogFlow.team_id, rescheduleHogFlow.id))+ .send({ action_ids: ['delay_1'] })++ expect(res.status).toEqual(503)+ expect(mockRescheduleParkedJobs).not.toHaveBeenCalled()+ } finally {+ api['rescheduleJwt'] = savedJwt+ }+ })++ it('errors if the cyclotron producer is not configured', async () => {+ api['batchResolverProducer'] = null++ const res = await supertest(app)+ .post(`/api/projects/${rescheduleHogFlow.team_id}/hog_flows/${rescheduleHogFlow.id}/reschedule_parked`)+ .send({ action_ids: ['delay_1'] })++ expect(res.status).toEqual(503)+ })+ })+// The test panel POSTs to /hog_flows/:id/invocations and runs the executor in-process —// it never enqueues into cyclotron. If the executor routes an email action onto the// dedicated email queue, nothing services that job and the workflow stalls on adiff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.tsindex 3efa13b4df35..5116168945bb 100644--- a/nodejs/src/cdp/cdp-api.ts+++ b/nodejs/src/cdp/cdp-api.ts@@ -56,6 +56,7 @@ import {sanitizeLogMessage,} from './utils'import { convertToHogFunctionFilterGlobal } from './utils/hog-function-filtering'+import { JWT, PosthogJwtAudience } from './utils/jwt-utils'// Allowlist of safe content types for webhook responses to prevent XSSconst SAFE_CONTENT_TYPES = new Set([@@ -124,6 +125,10 @@ export class CdpApi {private batchExportHogFunctionService: BatchExportHogFunctionServiceprivate groupsManager: GroupsManagerServiceprivate batchResolverProducer: CyclotronV2JobProducer | null+ // Scoped auth for the reschedule_parked route (exempted from the shared internal-secret+ // middleware): Django mints per-call JWTs pinned to a team + workflow. Null when the key+ // isn't provisioned — the route then fails closed.+ private rescheduleJwt: JWT | nullconstructor(private config: PluginsServerConfig,@@ -172,6 +177,9 @@ export class CdpApi {this.invocationResultsService)this.batchResolverProducer = batchResolverProducer+ this.rescheduleJwt = config.WORKFLOWS_RESCHEDULE_JWT_SECRET+ ? new JWT(config.WORKFLOWS_RESCHEDULE_JWT_SECRET)+ : null}public get service(): PluginServerService {@@ -239,6 +247,10 @@ export class CdpApi {)router.post('/api/projects/:team_id/hog_flows/:id/rerun', asyncHandler(this.postRerunInvocations('hog_flow')))router.get('/api/projects/:team_id/hog_flows/:id/in_flight_count', asyncHandler(this.getHogFlowInFlightCount))+ router.post(+ '/api/projects/:team_id/hog_flows/:id/reschedule_parked',+ asyncHandler(this.postHogFlowRescheduleParked)+ )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()))@@ -841,6 +853,98 @@ export class CdpApi {}}+ // Pull forward the wake times of this workflow's parked jobs after a timing edit. Django+ // calls this (via a Celery task) when a published/saved change shortened a delay or moved a+ // wait window; one call is one slice, and the caller loops with the returned bounds until+ // `done`. See CyclotronV2Manager.rescheduleParkedJobs for the sweep semantics.+ //+ // Auth: a scoped JWT minted by Django per call, pinned to this team + workflow — NOT the+ // fleet-wide internal secret (the route is exempted from that middleware). Fails closed when+ // the key isn't provisioned.+ private postHogFlowRescheduleParked = 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.rescheduleJwt) {+ return res.status(503).json({+ error: 'Reschedule auth not configured (WORKFLOWS_RESCHEDULE_JWT_SECRET unset)',+ })+ }++ const { team_id, id } = req.params++ const authHeader = req.headers['authorization']+ const token =+ typeof authHeader === 'string' && authHeader.startsWith('Bearer ') ? authHeader.slice(7) : undefined+ const claims = token+ ? (this.rescheduleJwt.verify(token, PosthogJwtAudience.WORKFLOWS_RESCHEDULE_PARKED, {+ ignoreVerificationErrors: true,+ }) as { team_id?: number; hog_flow_id?: string } | undefined)+ : undefined+ // The claims pin the token to one team + workflow, so a leaked token can't sweep anything else.+ if (!claims || claims.team_id !== parseInt(team_id) || claims.hog_flow_id !== id) {+ return res.status(401).json({ error: 'Unauthorized: Invalid reschedule token' })+ }++ const team = await this.deps.teamManager.getTeam(parseInt(team_id)).catch(() => null)+ if (!team) {+ return res.status(404).json({ error: 'Team not found' })+ }++ const hogFlow = await this.hogFlowManager.getHogFlow(id)+ if (!hogFlow || hogFlow.team_id !== team.id) {+ return res.status(404).json({ error: 'Workflow not found' })+ }++ const body = req.body ?? {}+ const actionIds = body.action_ids+ if (+ !Array.isArray(actionIds) ||+ actionIds.length === 0 ||+ actionIds.length > 100 ||+ !actionIds.every((a: unknown) => typeof a === 'string' && a.length > 0)+ ) {+ return res.status(400).json({ error: 'action_ids must be a non-empty array of up to 100 strings' })+ }+ const sweepFloor = body.sweep_floor ? new Date(body.sweep_floor) : undefined+ const sweepUntil = body.sweep_until ? new Date(body.sweep_until) : undefined+ if ((sweepFloor && isNaN(sweepFloor.getTime())) || (sweepUntil && isNaN(sweepUntil.getTime()))) {+ return res.status(400).json({ error: 'sweep_floor and sweep_until must be ISO datetimes' })+ }+ if (+ (sweepFloor === undefined) !== (sweepUntil === undefined) ||+ (sweepFloor && sweepUntil && sweepFloor >= sweepUntil)+ ) {+ return res+ .status(400)+ .json({ error: 'sweep_floor and sweep_until must be passed together, with floor before until' })+ }++ const result = await this.batchResolverProducer.rescheduleParkedJobs({+ teamId: team.id,+ functionId: id,+ actionIds,+ sweepFloor,+ sweepUntil,+ })+ return res.json({+ swept: result.swept,+ remaining: result.remaining,+ done: result.done,+ sweep_floor: result.sweepFloor.toISOString(),+ sweep_until: result.sweepUntil.toISOString(),+ })+ } catch (e) {+ logger.error('Error rescheduling parked hog flow jobs', {+ error: e instanceof Error ? e.message : String(e),+ })+ return res.status(500).json({ error: e instanceof Error ? e.message : String(e) })+ }+ }+private postHogFlowBatchInvocation = async (req: ModifiedRequest, res: express.Response): Promise<any> => {try {const { id, team_id, parent_run_id } = req.paramsdiff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.tsindex b5639e7cf1be..27e7a0996091 100644--- a/nodejs/src/cdp/config.ts+++ b/nodejs/src/cdp/config.ts@@ -150,6 +150,18 @@ export type CdpConfig = ClickhouseConfig & {// record (a give-up is lost, exactly as before this change). Flip to false to// roll back the recovery machinery instantly without a redeploy. Default true.CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: boolean+ // Timing-edit reschedule sweep (CyclotronV2Manager.rescheduleParkedJobs)+ // Scoped JWT keys authenticating Django's calls to the reschedule_parked route — comma-separated,+ // newest first (first signs, all verify). Deliberately NOT the fleet-wide INTERNAL_API_SECRET+ // (see .agents/security.md): empty in prod means the route fails closed until provisioned.+ WORKFLOWS_RESCHEDULE_JWT_SECRET: string+ CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: number+ CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: number+ CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: number+ CYCLOTRON_NODE_RESCHEDULE_MAX_WINDOW_SECONDS: number+ CYCLOTRON_NODE_RESCHEDULE_CHUNK_SIZE: number+ CYCLOTRON_NODE_RESCHEDULE_MAX_CHUNKS_PER_CALL: number+ CYCLOTRON_NODE_RESCHEDULE_CHUNK_SLEEP_MS: number}export function getDefaultCdpConfig(): CdpConfig {@@ -288,5 +300,18 @@ export function getDefaultCdpConfig(): CdpConfig {CYCLOTRON_NODE_JANITOR_MAX_TOUCH_COUNT: 3,CYCLOTRON_NODE_JANITOR_CLEANUP_GRACE_MS: 10000,CYCLOTRON_NODE_POISON_PILL_RECOVERY_ENABLED: true,+ // Floor > the hog flow cache's worst-case staleness (~6 min), so swept jobs+ // always wake against post-edit config. Rate sized well under hogflow worker+ // steady-state throughput: the past incident class here is an instantaneous+ // mass wake, so wakes are trickled (500k parked @ 200/s ≈ 42 min spread).+ // Dev/test default must match Django's (posthog/settings/data_stores.py).+ WORKFLOWS_RESCHEDULE_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflows-reschedule-jwt' : '',+ CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: 600,+ CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: 200,+ CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: 300,+ CYCLOTRON_NODE_RESCHEDULE_MAX_WINDOW_SECONDS: 14400,+ CYCLOTRON_NODE_RESCHEDULE_CHUNK_SIZE: 5000,+ CYCLOTRON_NODE_RESCHEDULE_MAX_CHUNKS_PER_CALL: 20,+ CYCLOTRON_NODE_RESCHEDULE_CHUNK_SLEEP_MS: 100,}}diff --git a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts b/nodejs/src/cdp/rerun/rerun-paginator.service.test.tsindex 91095204ce27..cf14e2631791 100644--- a/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts+++ b/nodejs/src/cdp/rerun/rerun-paginator.service.test.ts@@ -118,6 +118,10 @@ describe('RerunPaginatorService integration', () => {seededCount += rows.lengthconst expected = seededCount+ // Seed visibility rides the shared Kafka -> ClickHouse pipe, whose consumer may still be+ // chewing a backlog from whichever suite the shard ran just before this one (run order+ // shifts whenever sibling files change size). The deadline is sized for that worst case;+ // waitForExpect polls, so a healthy pipe still completes in seconds.await waitForExpect(async () => {const got = await clickhouse.query<{ c: number }>(`SELECT count() AS c FROM hog_invocation_resultsdiff --git a/nodejs/src/cdp/services/cyclotron-v2/README.md b/nodejs/src/cdp/services/cyclotron-v2/README.mdindex f972ab4571f2..d087dfe046ba 100644--- a/nodejs/src/cdp/services/cyclotron-v2/README.md+++ b/nodejs/src/cdp/services/cyclotron-v2/README.md@@ -73,9 +73,10 @@ recoverable via the standard rerun tooling rather than a bespoke table.Jobs are ephemeral (deleted after completion),so a durable activity log would give visibility into historical runswithout keeping the jobs table unbounded.-- **`action_id` column for workflows** —- an additional indexed column so scheduled workflow actions- can be queried and displayed more effectively+- **Surfacing `action_id` for workflows** —+ the column exists and parked rows are indexed by it+ (`idx_cyclotron_jobs_action_reschedule`, used by the timing-edit reschedule sweep),+ but scheduled workflow actions still aren't queryable or displayable in product(e.g. "show me all pending actions for this workflow step").- **Cancellation API** —API tooling to cancel scheduled jobs by querydiff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.tsindex d6e5ddec78d9..2dcb8e3a8baa 100644--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts@@ -300,6 +300,267 @@ describe('Cyclotron V2', () => {expect(await manager.countInFlightJobs(1, functionId)).toBe(2)})+ describe('rescheduleParkedJobs', () => {+ const FAR_FUTURE = () => new Date(Date.now() + 7 * 24 * 3600 * 1000)++ async function seedParked(+ functionId: string,+ over?: Partial<CyclotronV2JobInit> & { scheduled?: Date }+ ): Promise<string> {+ return await manager.createJob({+ teamId: 1,+ queueName: QUEUE,+ functionId,+ actionId: 'delay_1',+ scheduled: FAR_FUTURE(),+ ...over,+ })+ }++ it('sweeps only matching parked rows into the window, regardless of queue', async () => {+ const functionId = uuidv7()+ const before = Date.now()+ const sweptId = await seedParked(functionId)+ const emailQueueId = await seedParked(functionId, { queueName: 'email' })+ const otherActionId = await seedParked(functionId, { actionId: 'message_1' })+ const otherFunctionId = await seedParked(uuidv7())+ const otherTeamId = await seedParked(functionId, { teamId: 2 })+ const runningId = await seedParked(functionId)+ await assertPool.query(`UPDATE cyclotron_jobs SET status = 'running' WHERE id = $1`, [runningId])+ const wakingSoon = new Date(Date.now() + 60_000)+ const wakingSoonId = await seedParked(functionId, { scheduled: wakingSoon })++ const result = await manager.rescheduleParkedJobs({ teamId: 1, functionId, actionIds: ['delay_1'] })++ expect(result.swept).toBe(2)+ expect(result.done).toBe(true)+ // Swept rows (hogflow-queue and email-queue alike — parked waits can sit on any+ // queue) land inside [sweepFloor, sweepUntil]: never sooner than the floor, never+ // later than their original wake.+ for (const id of [sweptId, emailQueueId]) {+ const scheduled = new Date((await queryJob(id)).scheduled).getTime()+ expect(scheduled).toBeGreaterThanOrEqual(result.sweepFloor.getTime() - 1000)+ expect(scheduled).toBeLessThanOrEqual(result.sweepUntil.getTime() + 1000)+ }+ expect(result.sweepFloor.getTime()).toBeGreaterThan(before)+ // Untouched: other action/function/team, running rows, rows already waking soon+ for (const id of [otherActionId, otherFunctionId, otherTeamId, runningId]) {+ const scheduled = new Date((await queryJob(id)).scheduled).getTime()+ expect(scheduled).toBeGreaterThan(Date.now() + 6 * 24 * 3600 * 1000)+ }+ expect(new Date((await queryJob(wakingSoonId)).scheduled).getTime()).toBe(wakingSoon.getTime())+ })++ it('is idempotent: a second call with the same bounds sweeps nothing', async () => {+ const functionId = uuidv7()+ const id = await seedParked(functionId)++ const first = await manager.rescheduleParkedJobs({ teamId: 1, functionId, actionIds: ['delay_1'] })+ expect(first.swept).toBe(1)+ const scheduledAfterFirst = new Date((await queryJob(id)).scheduled).getTime()++ const second = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ sweepFloor: first.sweepFloor,+ sweepUntil: first.sweepUntil,+ })+ expect(second).toMatchObject({ swept: 0, remaining: 0, done: true })+ expect(new Date((await queryJob(id)).scheduled).getTime()).toBe(scheduledAfterFirst)+ })++ it('honors explicitly passed bounds and echoes them back', async () => {+ const functionId = uuidv7()+ const id = await seedParked(functionId)+ const sweepFloor = new Date(Date.now() + 1800_000)+ const sweepUntil = new Date(Date.now() + 3600_000)++ const result = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ sweepFloor,+ sweepUntil,+ })++ expect(result.sweepFloor).toEqual(sweepFloor)+ expect(result.sweepUntil).toEqual(sweepUntil)+ const scheduled = new Date((await queryJob(id)).scheduled).getTime()+ expect(scheduled).toBeGreaterThanOrEqual(sweepFloor.getTime())+ expect(scheduled).toBeLessThanOrEqual(sweepUntil.getTime())+ })++ it('re-sizes stale bounds instead of sweeping the remainder into the past', async () => {+ const functionId = uuidv7()+ await seedParked(functionId)+ const staleFloor = new Date(Date.now() - 3600_000)+ const staleUntil = new Date(Date.now() - 1800_000)++ const result = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ sweepFloor: staleFloor,+ sweepUntil: staleUntil,+ })++ expect(result.swept).toBe(1)+ expect(result.sweepFloor.getTime()).toBeGreaterThan(Date.now())+ const parked = await assertPool.query(+ `SELECT COUNT(*)::int AS c FROM cyclotron_jobs WHERE function_id = $1 AND scheduled <= NOW()`,+ [functionId]+ )+ expect(parked.rows[0].c).toBe(0)+ })++ it('clamps a caller-passed floor to the server floor so bounds cannot mass-wake the backlog', async () => {+ // A past floor with a still-fresh until would land the random targets in the+ // past — the floor is the sweep's safety property and is enforced server-side.+ const functionId = uuidv7()+ const id = await seedParked(functionId)++ const result = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ sweepFloor: new Date(Date.now() - 3600_000),+ sweepUntil: new Date(Date.now() + 3600_000),+ })++ expect(result.swept).toBe(1)+ // Default floor is 600s: the swept row must never wake sooner than that+ const scheduled = new Date((await queryJob(id)).scheduled).getTime()+ expect(scheduled).toBeGreaterThanOrEqual(Date.now() + 600_000 - 5000)+ expect(result.sweepFloor.getTime()).toBeGreaterThanOrEqual(Date.now() + 600_000 - 5000)+ })++ it.each([+ ['count / rate inside the clamps', 30, 30],+ ['clamped up to the min window', 5, 10],+ ['clamped down to the max window', 100, 50],+ ])('sizes the window from the parked count: %s', async (_desc, jobCount, expectedWindowSeconds) => {+ const sizingManager = createManager({+ rescheduleFloorSeconds: 60,+ rescheduleWakeRatePerSecond: 1,+ rescheduleMinWindowSeconds: 10,+ rescheduleMaxWindowSeconds: 50,+ rescheduleChunkSleepMs: 0,+ })+ await sizingManager.connect()+ try {+ const functionId = uuidv7()+ await sizingManager.bulkCreateJobs(+ Array.from({ length: jobCount }, () => ({+ teamId: 1,+ queueName: QUEUE,+ functionId,+ actionId: 'delay_1',+ scheduled: FAR_FUTURE(),+ }))+ )++ const result = await sizingManager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ })++ expect(result.sweepUntil.getTime() - result.sweepFloor.getTime()).toBe(expectedWindowSeconds * 1000)+ } finally {+ await sizingManager.disconnect()+ }+ })++ it('slices work across calls, keeping the window fixed', async () => {+ const slicingManager = createManager({+ rescheduleChunkSize: 2,+ rescheduleMaxChunksPerCall: 2,+ rescheduleChunkSleepMs: 0,+ })+ await slicingManager.connect()+ try {+ const functionId = uuidv7()+ await slicingManager.bulkCreateJobs(+ Array.from({ length: 5 }, () => ({+ teamId: 1,+ queueName: QUEUE,+ functionId,+ actionId: 'delay_1',+ scheduled: FAR_FUTURE(),+ }))+ )++ const first = await slicingManager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ })+ expect(first).toMatchObject({ swept: 4, remaining: 1, done: false })++ const second = await slicingManager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ sweepFloor: first.sweepFloor,+ sweepUntil: first.sweepUntil,+ })+ expect(second).toMatchObject({ swept: 1, remaining: 0, done: true })+ // sweepUntil is the idempotency bound and must stay fixed across slices;+ // the floor legitimately drifts forward per slice (clamped to now + floor).+ expect(second.sweepUntil).toEqual(first.sweepUntil)+ expect(second.sweepFloor.getTime()).toBeGreaterThanOrEqual(first.sweepFloor.getTime())+ } finally {+ await slicingManager.disconnect()+ }+ })++ it('skips rows locked by a concurrent transaction', async () => {+ const functionId = uuidv7()+ const lockedId = await seedParked(functionId)+ const freeId = await seedParked(functionId)++ const client = await assertPool.connect()+ try {+ await client.query('BEGIN')+ await client.query('SELECT id FROM cyclotron_jobs WHERE id = $1 FOR UPDATE', [lockedId])++ const result = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId,+ actionIds: ['delay_1'],+ })++ expect(result.swept).toBe(1)+ expect(result.done).toBe(false)+ expect(new Date((await queryJob(freeId)).scheduled).getTime()).toBeLessThanOrEqual(+ result.sweepUntil.getTime() + 1000+ )+ expect(new Date((await queryJob(lockedId)).scheduled).getTime()).toBeGreaterThan(+ Date.now() + 6 * 24 * 3600 * 1000+ )+ } finally {+ await client.query('ROLLBACK')+ client.release()+ }+ })++ it('returns done immediately when nothing is parked beyond the floor', async () => {+ const result = await manager.rescheduleParkedJobs({+ teamId: 1,+ functionId: uuidv7(),+ actionIds: ['delay_1'],+ })+ expect(result).toMatchObject({ swept: 0, remaining: 0, done: true })+ })++ it('rejects an empty action id list', async () => {+ await expect(+ manager.rescheduleParkedJobs({ teamId: 1, functionId: uuidv7(), actionIds: [] })+ ).rejects.toThrow(/at least one action id/)+ })+ })+it('backpressure throws when queue depth exceeds limit', async () => {const smallManager = createManager({ depthLimit: 2, depthCheckIntervalMs: 0 })await smallManager.connect()diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.tsindex 72f881b3dfb9..ebfc201ec568 100644--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts@@ -1,11 +1,18 @@import { Pool } from 'pg'-import { Counter } from 'prom-client'+import { Counter, Histogram } from 'prom-client'import { v7 as uuidv7 } from 'uuid'import { isTransientPgError } from '~/common/utils/db/postgres'import { logger } from '~/common/utils/logger'+import { sleep } from '~/common/utils/utils'-import { CyclotronV2JobInit, CyclotronV2JobInitSchema, CyclotronV2ManagerConfig } from './types'+import {+ CyclotronV2JobInit,+ CyclotronV2JobInitSchema,+ CyclotronV2ManagerConfig,+ CyclotronV2RescheduleParkedOptions,+ CyclotronV2RescheduleParkedResult,+} from './types'/*** Block size used to compute the fair-dequeue sort key for email queue jobs:@@ -65,6 +72,23 @@ const dbWriteFailureCounter = new Counter({labelNames: ['kind'] as const,})+const rescheduleSweptCounter = new Counter({+ name: 'cdp_cyclotron_v2_reschedule_parked_swept',+ help: 'Parked cyclotron jobs whose scheduled time was pulled forward by a timing-edit reschedule sweep.',+})++const rescheduleWindowHistogram = new Histogram({+ name: 'cdp_cyclotron_v2_reschedule_parked_window_seconds',+ help: 'Spread window sized for a timing-edit reschedule sweep (observed once per sweep, on the sizing slice).',+ buckets: [300, 600, 1800, 3600, 7200, 14400],+})++const rescheduleFailureCounter = new Counter({+ name: 'cdp_cyclotron_v2_reschedule_parked_failures',+ help: 'Failed reschedule sweep slices, split by kind=logical|transient.',+ labelNames: ['kind'] as const,+})+/*** Thrown when an `overwriteExisting` createJob / bulkCreateJobs hits a row* that's still in an active state ('available' or 'running'). Callers should@@ -89,6 +113,15 @@ export class CyclotronV2Manager {private readonly depthCheckIntervalMs: numberprivate depthCheckPromise: Promise<boolean> | null = nullprivate depthCheckExpiresAt = 0+ private readonly reschedule: {+ floorSeconds: number+ wakeRatePerSecond: number+ minWindowSeconds: number+ maxWindowSeconds: number+ chunkSize: number+ maxChunksPerCall: number+ chunkSleepMs: number+ }constructor(config: CyclotronV2ManagerConfig) {this.pool = new Pool({@@ -98,6 +131,15 @@ export class CyclotronV2Manager {})this.depthLimit = config.depthLimit ?? 1_000_000this.depthCheckIntervalMs = config.depthCheckIntervalMs ?? 10_000+ this.reschedule = {+ floorSeconds: config.rescheduleFloorSeconds ?? 600,+ wakeRatePerSecond: config.rescheduleWakeRatePerSecond ?? 200,+ minWindowSeconds: config.rescheduleMinWindowSeconds ?? 300,+ maxWindowSeconds: config.rescheduleMaxWindowSeconds ?? 14_400,+ chunkSize: config.rescheduleChunkSize ?? 5_000,+ maxChunksPerCall: config.rescheduleMaxChunksPerCall ?? 20,+ chunkSleepMs: config.rescheduleChunkSleepMs ?? 100,+ }}async connect(): Promise<void> {@@ -402,6 +444,165 @@ export class CyclotronV2Manager {return result.rows[0].count}+ /**+ * Pull forward the wake times of a workflow's parked jobs after a timing+ * edit (issue #66380): jobs parked on one of `actionIds` get+ * `scheduled = LEAST(scheduled, sweepFloor + random() * window)`, so each+ * wakes somewhere inside the window, re-reads the live config, and either+ * advances or re-parks at the recomputed target. Waking early is+ * behaviourally idempotent (the executor's live-timing-edit contract+ * tests), so this never needs to read job state or compute wake times.+ *+ * Two invariants make the sweep safe:+ * - `LEAST` never moves a wake later than its natural time.+ * - Swept rows land at or before `sweepUntil`, and the candidate predicate+ * is `scheduled > sweepUntil` — so the sweep is idempotent and naturally+ * terminating, and rows already waking within the window are untouched.+ *+ * The floor keeps the earliest sweep-induced wake beyond the hog flow+ * cache's worst-case staleness (LazyLoader refreshAge + jitter, ~6 min),+ * so a woken job always executes against the post-edit config even on a+ * worker that missed the reload pubsub. The window is sized from the+ * parked count and a wake rate: mass-waking parked jobs at once has+ * dropped jobs in past load spikes, so wakes are trickled instead.+ *+ * Callers slice large sweeps across calls (maxChunksPerCall bounds one+ * call's work) and MUST thread the returned bounds into follow-up calls —+ * resizing the window per slice would re-compress the tail of the spread.+ * Stale bounds (a retry landing after the window largely elapsed) are+ * re-sized instead of honored: honoring them would `LEAST` the remainder+ * into the past and mass-wake it.+ */+ async rescheduleParkedJobs(+ options: CyclotronV2RescheduleParkedOptions+ ): Promise<CyclotronV2RescheduleParkedResult> {+ const { teamId, functionId, actionIds } = options+ if (actionIds.length === 0) {+ throw new Error('rescheduleParkedJobs requires at least one action id')+ }++ try {+ let bounds: { sweepFloor: Date; sweepUntil: Date } | null = null+ const staleBoundsCutoff = new Date(Date.now() + this.reschedule.minWindowSeconds * 1000)+ if (options.sweepFloor && options.sweepUntil && options.sweepUntil > staleBoundsCutoff) {+ // The floor is this sweep's safety property (no sweep-induced wake sooner than+ // floorSeconds from now — the config-cache staleness bound), so it is enforced+ // server-side regardless of what bounds the caller passed: a floor in the past+ // would land the random targets in the past and mass-wake the backlog. Clamping+ // per slice only compresses the tail of the spread, never the predicate, so+ // cross-slice idempotency (scheduled > sweepUntil) is unaffected.+ const minFloor = new Date(Date.now() + this.reschedule.floorSeconds * 1000)+ const sweepFloor = options.sweepFloor > minFloor ? options.sweepFloor : minFloor+ if (sweepFloor < options.sweepUntil) {+ bounds = { sweepFloor, sweepUntil: options.sweepUntil }+ }+ }+ if (!bounds) {+ if (options.sweepUntil) {+ logger.warn('Reschedule sweep bounds are stale or unsafe, re-sizing window', {+ teamId,+ functionId,+ sweepUntil: options.sweepUntil.toISOString(),+ })+ }+ const sized = await this.sizeRescheduleWindow(teamId, functionId, actionIds)+ if (!sized) {+ const now = new Date()+ return { swept: 0, remaining: 0, done: true, sweepFloor: now, sweepUntil: now }+ }+ bounds = sized+ }+ const { sweepFloor, sweepUntil } = bounds++ let swept = 0+ for (let chunk = 0; chunk < this.reschedule.maxChunksPerCall; chunk++) {+ if (chunk > 0) {+ await sleep(this.reschedule.chunkSleepMs)+ }+ const result = await this.pool.query(+ `WITH candidates AS (+ SELECT id FROM cyclotron_jobs+ WHERE team_id = $1 AND function_id = $2 AND status = 'available'+ AND action_id = ANY($3::text[])+ AND scheduled > $5+ LIMIT $6+ FOR UPDATE SKIP LOCKED+ )+ UPDATE cyclotron_jobs j+ SET scheduled = LEAST(j.scheduled, $4::timestamptz + random() * ($5::timestamptz - $4::timestamptz))+ FROM candidates c+ WHERE j.id = c.id`,+ [teamId, functionId, actionIds, sweepFloor, sweepUntil, this.reschedule.chunkSize]+ )+ swept += result.rowCount ?? 0+ if ((result.rowCount ?? 0) < this.reschedule.chunkSize) {+ break+ }+ }+ rescheduleSweptCounter.inc(swept)++ const remainingResult = await this.pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count FROM cyclotron_jobs+ WHERE team_id = $1 AND function_id = $2 AND status = 'available'+ AND action_id = ANY($3::text[])+ AND scheduled > $4`,+ [teamId, functionId, actionIds, sweepUntil]+ )+ const remaining = remainingResult.rows[0].count++ logger.info('Reschedule sweep slice completed', {+ teamId,+ functionId,+ actionIds,+ swept,+ remaining,+ sweepFloor: sweepFloor.toISOString(),+ sweepUntil: sweepUntil.toISOString(),+ })++ return { swept, remaining, done: remaining === 0, sweepFloor, sweepUntil }+ } catch (err) {+ rescheduleFailureCounter.labels({ kind: isTransientPgError(err) ? 'transient' : 'logical' }).inc()+ throw err+ }+ }++ /**+ * Size the sweep window for the current parked backlog: floor at+ * `now + floorSeconds`, width `count / wakeRatePerSecond` clamped to+ * [minWindow, maxWindow]. Counts everything beyond the floor — a slight+ * overcount versus the final `scheduled > sweepUntil` predicate, which+ * only widens the window (conservative). Returns null when nothing is+ * parked beyond the floor.+ */+ private async sizeRescheduleWindow(+ teamId: number,+ functionId: string,+ actionIds: string[]+ ): Promise<{ sweepFloor: Date; sweepUntil: Date } | null> {+ const countResult = await this.pool.query<{ count: number }>(+ `SELECT COUNT(*)::int AS count FROM cyclotron_jobs+ WHERE team_id = $1 AND function_id = $2 AND status = 'available'+ AND action_id = ANY($3::text[])+ AND scheduled > NOW() + make_interval(secs => $4)`,+ [teamId, functionId, actionIds, this.reschedule.floorSeconds]+ )+ const count = countResult.rows[0].count+ if (count === 0) {+ return null+ }++ const windowSeconds = Math.min(+ this.reschedule.maxWindowSeconds,+ Math.max(this.reschedule.minWindowSeconds, Math.ceil(count / this.reschedule.wakeRatePerSecond))+ )+ rescheduleWindowHistogram.observe(windowSeconds)++ const sweepFloor = new Date(Date.now() + this.reschedule.floorSeconds * 1000)+ const sweepUntil = new Date(sweepFloor.getTime() + windowSeconds * 1000)+ return { sweepFloor, sweepUntil }+ }+async disconnect(): Promise<void> {await this.pool.end()}diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.tsindex 73b66b8f6f41..e36fc654a523 100644--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts@@ -92,6 +92,37 @@ export type CyclotronV2ManagerConfig = {pool: CyclotronV2PoolConfigdepthLimit?: numberdepthCheckIntervalMs?: number+ // Knobs for rescheduleParkedJobs — see that method for semantics.+ rescheduleFloorSeconds?: number+ rescheduleWakeRatePerSecond?: number+ rescheduleMinWindowSeconds?: number+ rescheduleMaxWindowSeconds?: number+ rescheduleChunkSize?: number+ rescheduleMaxChunksPerCall?: number+ rescheduleChunkSleepMs?: number+}++export type CyclotronV2RescheduleParkedOptions = {+ teamId: number+ functionId: string+ // Steps whose timing config changed: only jobs parked on one of these+ // (matched via the action_id column) are swept.+ actionIds: string[]+ // Absolute sweep bounds returned by a previous slice. Omit on the first+ // call — the manager sizes the window from the parked count and returns+ // the bounds so callers can thread them through subsequent slices.+ // Recomputing the window per slice would re-compress the tail of the+ // spread on every call.+ sweepFloor?: Date+ sweepUntil?: Date+}++export type CyclotronV2RescheduleParkedResult = {+ swept: number+ remaining: number+ done: boolean+ sweepFloor: Date+ sweepUntil: Date}/**@@ -102,6 +133,7 @@ export type CyclotronV2ManagerConfig = {export interface CyclotronV2JobProducer {createJob(input: CyclotronV2JobInit): Promise<string>countInFlightJobs(teamId: number, functionId: string): Promise<number>+ rescheduleParkedJobs(options: CyclotronV2RescheduleParkedOptions): Promise<CyclotronV2RescheduleParkedResult>disconnect(): Promise<void>}diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.tsindex e0c6c661e231..8227be7ca5f5 100644--- a/nodejs/src/cdp/utils/jwt-utils.ts+++ b/nodejs/src/cdp/utils/jwt-utils.ts@@ -2,6 +2,7 @@ import jwt from 'jsonwebtoken'export enum PosthogJwtAudience {SUBSCRIPTION_PREFERENCES = 'posthog:messaging:subscription_preferences',+ WORKFLOWS_RESCHEDULE_PARKED = 'posthog:workflows:reschedule_parked',}export class JWT {diff --git a/nodejs/src/common/api/middleware/internal-api-auth.test.ts b/nodejs/src/common/api/middleware/internal-api-auth.test.tsindex 45dbb664f9c7..715831c7d0f4 100644--- a/nodejs/src/common/api/middleware/internal-api-auth.test.ts+++ b/nodejs/src/common/api/middleware/internal-api-auth.test.ts@@ -188,6 +188,18 @@ describe('createInternalApiAuthMiddleware', () => {expect(res.status).not.toHaveBeenCalled()})+ it('should skip auth for scoped-JWT routes, which authenticate in their handler', () => {+ const middleware = createInternalApiAuthMiddleware({ secret: 'test-secret' })+ const req = mockRequest('/api/projects/1/hog_flows/some-uuid/reschedule_parked', {})+ const res = mockResponse()+ const next = jest.fn()++ middleware(req, res, next)++ expect(next).toHaveBeenCalled()+ expect(res.status).not.toHaveBeenCalled()+ })+it('should allow custom excluded path prefixes', () => {const middleware = createInternalApiAuthMiddleware({secret: 'test-secret',diff --git a/nodejs/src/common/api/middleware/internal-api-auth.ts b/nodejs/src/common/api/middleware/internal-api-auth.tsindex dab7582d7b44..99b5a99a9139 100644--- a/nodejs/src/common/api/middleware/internal-api-auth.ts+++ b/nodejs/src/common/api/middleware/internal-api-auth.ts@@ -20,6 +20,14 @@ export const INTERNAL_SERVICE_CALL_HEADER_NAME = 'X-Internal-Api-Secret'// Paths that don't require authentication (public endpoints and health checks)const PUBLIC_PATH_PREFIXES = ['/public/', '/_health', '/_ready', '/_metrics', '/metrics']+// Routes that authenticate with their own scoped JWT instead of the shared internal secret, so+// their callers never need INTERNAL_API_SECRET (the goal of retiring it). Each entry must be a+// route whose handler enforces its own auth — never add a suffix here without one.+const SCOPED_AUTH_PATH_SUFFIXES = [+ // Verified in CdpApi.postHogFlowRescheduleParked against WORKFLOWS_RESCHEDULE_JWT_SECRET.+ '/reschedule_parked',+]+export interface InternalApiAuthOptions {secret: string// Previous secrets still accepted for verification during zero-downtime rotation.@@ -47,6 +55,12 @@ export function createInternalApiAuthMiddleware(options: InternalApiAuthOptions)return}+ // Scoped-JWT routes enforce their own auth in the handler.+ if (SCOPED_AUTH_PATH_SUFFIXES.some((suffix) => req.path.endsWith(suffix))) {+ next()+ return+ }+const providedSecret =req.headers[INTERNAL_SERVICE_CALL_HEADER_NAME] ||req.headers[INTERNAL_SERVICE_CALL_HEADER_NAME.toLowerCase()] ||diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex f5beea7ef5a6..ee25ca478fc0 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -228,6 +228,13 @@ export class PluginServer implements NodeServer {const batchResolverProducer = this.config.CYCLOTRON_NODE_DATABASE_URL? new CyclotronV2Manager({pool: { dbUrl: this.config.CYCLOTRON_NODE_DATABASE_URL, maxConnections: 5 },+ rescheduleFloorSeconds: this.config.CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS,+ rescheduleWakeRatePerSecond: this.config.CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND,+ rescheduleMinWindowSeconds: this.config.CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS,+ rescheduleMaxWindowSeconds: this.config.CYCLOTRON_NODE_RESCHEDULE_MAX_WINDOW_SECONDS,+ rescheduleChunkSize: this.config.CYCLOTRON_NODE_RESCHEDULE_CHUNK_SIZE,+ rescheduleMaxChunksPerCall: this.config.CYCLOTRON_NODE_RESCHEDULE_MAX_CHUNKS_PER_CALL,+ rescheduleChunkSleepMs: this.config.CYCLOTRON_NODE_RESCHEDULE_CHUNK_SLEEP_MS,}): nullconst api = new CdpApi(diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 05fc9b2ac5b5..1161dfa1a936 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -1,6 +1,10 @@import json-from typing import Union+from datetime import UTC, datetime, timedelta+from typing import Optional, Union+from django.conf import settings++import jwtimport requestsimport structlog@@ -114,6 +118,49 @@ def get_hog_flow_in_flight_count(team_id: int, hog_flow_id: str) -> requests.Res)+def _mint_reschedule_parked_jwt(team_id: int, hog_flow_id: str) -> str:+ """Short-lived scoped JWT for one reschedule_parked call — a leaked token can only sweep this+ one team + workflow. Signed with the dedicated key (never INTERNAL_API_SECRET / SECRET_KEY /+ JWT_SIGNING_KEY, per .agents/security.md); raises when unprovisioned so the sweep fails closed.+ Verified in the plugin server's CdpApi.postHogFlowRescheduleParked."""+ secrets = settings.WORKFLOWS_RESCHEDULE_JWT_SECRETS+ if not secrets:+ raise RuntimeError("WORKFLOWS_RESCHEDULE_JWT_SECRET is not configured — cannot call reschedule_parked")+ return jwt.encode(+ {+ "team_id": team_id,+ "hog_flow_id": hog_flow_id,+ "aud": "posthog:workflows:reschedule_parked",+ "exp": datetime.now(tz=UTC) + timedelta(minutes=2),+ },+ secrets[0],+ algorithm="HS256",+ )+++def reschedule_hog_flow_parked_jobs(+ team_id: int,+ hog_flow_id: str,+ action_ids: list[str],+ sweep_floor: Optional[str] = None,+ sweep_until: Optional[str] = None,+) -> requests.Response:+ """One slice of the timing-edit reschedule sweep. Callers loop, threading the returned+ sweep_floor/sweep_until into follow-up slices, until the response says done. The timeout keeps+ a hung plugin server from pinning the calling Celery worker; the caller's retry/backoff owns+ recovery. Sized above the endpoint's worst-case slice (chunk sleeps + chunked UPDATEs)."""+ payload: dict = {"action_ids": action_ids}+ if sweep_floor and sweep_until:+ payload["sweep_floor"] = sweep_floor+ payload["sweep_until"] = sweep_until+ return internal_requests.post(+ CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/reschedule_parked",+ json=payload,+ headers={"Authorization": f"Bearer {_mint_reschedule_parked_jwt(team_id, hog_flow_id)}"},+ timeout=30,+ )++def get_hog_function_status(team_id: int, hog_function_id: UUIDT) -> requests.Response:return internal_requests.get(CDP_API_URL + f"/api/projects/{team_id}/hog_functions/{hog_function_id}/status",diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 4c62f53b7da2..48b056625bd4 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -534,6 +534,15 @@ INTERNAL_API_SECRET = get_from_env(# Receivers accept INTERNAL_API_SECRET plus these; senders always send INTERNAL_API_SECRET.INTERNAL_API_SECRET_FALLBACKS = get_list(os.getenv("INTERNAL_API_SECRET_FALLBACKS", ""))+# Scoped JWT keys for the workflows timing-reschedule sweep (Django mints, the plugin server's+# reschedule_parked route verifies) — a per-purpose secret so this caller never touches+# INTERNAL_API_SECRET. Comma-separated, newest first: the first key signs, the plugin server+# verifies against all. Empty outside dev/test, so the sweep fails closed until provisioned.+# The dev/test value must match the plugin server's default (nodejs/src/cdp/config.ts).+WORKFLOWS_RESCHEDULE_JWT_SECRETS = get_list(+ get_from_env("WORKFLOWS_RESCHEDULE_JWT_SECRET", "local-dev-workflows-reschedule-jwt" if DEBUG or TEST else "")+)+EMBEDDING_API_URL = get_from_env("EMBEDDING_API_URL", "")# Used to generate embeddings on the fly, for use with the document embeddings tablediff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 6580325cf08e..754d7a2fdf66 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -97,6 +97,12 @@ from products.workflows.backend.services.batch_audience import (use_workflows_batch_audience_query,)from products.workflows.backend.services.revisions import use_workflows_revisions+from products.workflows.backend.services.timing_reschedule import (+ get_all_timing_action_ids,+ get_timing_reschedule_action_ids,+ use_workflows_timing_reschedule,+)+from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timingfrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limitfrom products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule@@ -1619,6 +1625,8 @@ class HogFlowViewSet(else:serializer.save()+ if not route_to_draft:+ self._maybe_reschedule_timing_edits(before_update, serializer.instance)log_activity_from_viewset(self, serializer.instance, name=serializer.instance.name, previous=before_update)self._emit_resource_edited(serializer.instance)@@ -1712,11 +1720,44 @@ class HogFlowViewSet(# save() mutates and returns `locked` in place, so it's the saved HogFlow from here on.serializer.save()+ if not route_to_draft:+ self._maybe_reschedule_timing_edits(before_update, locked)log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)self._emit_resource_edited(locked)return Response(self.get_serializer(locked).data)+ def _maybe_reschedule_timing_edits(self, before: Optional[HogFlow], after: HogFlow) -> None:+ """Kick off a reschedule sweep of parked runs when a go-live config change could move+ their wake times earlier (issue #66380): shortened delays and moved wait windows.++ Called wherever the LIVE config changes - a direct save (the builder path, where save+ is go-live), the graph endpoint, or publish - and never for draft writes, which don't+ touch what runs execute. Deliberately called AFTER the writing transaction commits:+ the feature-flag check can hit the network, and must not extend the select_for_update+ row-lock hold. on_commit outside an atomic block runs the enqueue immediately, and in+ tests (where an outer transaction wraps the request) it defers to that commit.+ """+ if not before or after.status != HogFlow.State.ACTIVE:+ return+ if before.status != HogFlow.State.ACTIVE:+ # Re-enable: runs parked during the prior active period survive a disable (cancelled+ # lazily, at wake, only while the flow is inactive), and timing edits made while+ # inactive never swept - so converge every timing step rather than diffing against a+ # baseline that may predate any number of unswept edits.+ action_ids = get_all_timing_action_ids(after.actions)+ else:+ action_ids = get_timing_reschedule_action_ids(before.actions, after.actions)+ if not action_ids:+ return+ if not use_workflows_timing_reschedule(self.team):+ return+ team_id = self.team_id+ hog_flow_id = str(after.id)+ transaction.on_commit(+ lambda: reschedule_hog_flow_timing.delay(team_id=team_id, hog_flow_id=hog_flow_id, action_ids=action_ids)+ )+def _get_in_flight_run_count(self, hog_flow: HogFlow) -> Optional[int]:# Best-effort: publish must not fail because the counting service is unreachable — the count# is advisory ("N runs in flight will follow the new config"), not a gate.@@ -1785,6 +1826,7 @@ class HogFlowViewSet(locked.draft_updated_at = Nonelocked.save(update_fields=["draft", "draft_updated_at"])+ self._maybe_reschedule_timing_edits(before_update, locked)log_activity_from_viewset(self, locked, name=locked.name, previous=before_update)self._emit_resource_edited(locked)diff --git a/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py b/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.pynew file mode 100644index 000000000000..8e03a7dee4df--- /dev/null+++ b/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py@@ -0,0 +1,180 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.cdp.templates.hog_function_template import sync_template_to_db++from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow++webhook_template = MOCK_NODE_TEMPLATES[0]++TIMING_FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_timing_reschedule"+REVISIONS_FLAG_PATH = "products.workflows.backend.api.hog_flow.use_workflows_revisions"+TASK_PATH = "products.workflows.backend.api.hog_flow.reschedule_hog_flow_timing"+++def _actions(delay_duration: str = "7d", webhook_url: str = "https://example.com") -> list[dict]:+ return [+ {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ },+ {"id": "delay_1", "name": "delay_1", "type": "delay", "config": {"delay_duration": delay_duration}},+ {+ "id": "action_1",+ "name": "action_1",+ "type": "function",+ "config": {"template_id": "template-webhook", "inputs": {"url": {"value": webhook_url}}},+ },+ ]+++def _edges() -> list[dict]:+ return [+ {"from": "trigger_node", "to": "delay_1", "type": "continue"},+ {"from": "delay_1", "to": "action_1", "type": "continue"},+ ]+++class TestHogFlowTimingRescheduleTrigger(APIBaseTest):+ def setUp(self):+ super().setUp()+ sync_template_to_db(webhook_template)++ def _create_flow(self, activate: bool = True) -> str:+ create = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Flow", "actions": _actions(), "edges": _edges()},+ )+ assert create.status_code == 201, create.json()+ flow_id = create.json()["id"]+ if activate:+ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})+ assert response.status_code == 200, response.json()+ return flow_id++ def _patch_actions(self, flow_id: str, delay_duration: str, webhook_url: str = "https://example.com", **extra):+ return self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",+ {"actions": _actions(delay_duration=delay_duration, webhook_url=webhook_url)},+ **extra,+ )++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ def test_shortened_delay_on_live_save_enqueues_sweep_post_commit(self, _flag, mock_task):+ flow_id = self._create_flow()++ with self.captureOnCommitCallbacks(execute=False) as callbacks:+ response = self._patch_actions(flow_id, delay_duration="1d")+ assert response.status_code == 200, response.json()++ assert mock_task.delay.call_count == 0, "the sweep must not start before the new config is committed"+ for callback in callbacks:+ callback()+ mock_task.delay.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, action_ids=["delay_1"])++ @parameterized.expand(+ [+ ("flag_off", False, "1d", "https://example.com"),+ ("lengthened_delay", True, "30d", "https://example.com"),+ ("non_timing_edit", True, "7d", "https://changed.example.com"),+ ]+ )+ @patch(TASK_PATH)+ def test_live_save_does_not_enqueue_sweep(self, _name, flag_on, delay_duration, webhook_url, mock_task):+ flow_id = self._create_flow()++ with patch(TIMING_FLAG_PATH, return_value=flag_on):+ with self.captureOnCommitCallbacks(execute=True):+ response = self._patch_actions(flow_id, delay_duration=delay_duration, webhook_url=webhook_url)++ assert response.status_code == 200, response.json()+ mock_task.delay.assert_not_called()++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ def test_inactive_flow_save_does_not_enqueue_sweep(self, _flag, mock_task):+ flow_id = self._create_flow(activate=False)++ with self.captureOnCommitCallbacks(execute=True):+ response = self._patch_actions(flow_id, delay_duration="1d")++ assert response.status_code == 200, response.json()+ mock_task.delay.assert_not_called()++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ @patch(REVISIONS_FLAG_PATH, return_value=True)+ def test_mcp_draft_routed_edit_does_not_enqueue_sweep(self, _revisions, _timing, mock_task):+ flow_id = self._create_flow()++ with self.captureOnCommitCallbacks(execute=True):+ response = self._patch_actions(flow_id, delay_duration="1d", HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 200, response.json()+ assert HogFlow.objects.get(pk=flow_id).draft is not None+ mock_task.delay.assert_not_called()++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ @patch(REVISIONS_FLAG_PATH, return_value=True)+ def test_publish_of_timing_shortening_draft_enqueues_sweep(self, _revisions, _timing, mock_task):+ flow_id = self._create_flow()+ response = self._patch_actions(flow_id, delay_duration="1d", HTTP_X_POSTHOG_CLIENT="mcp")+ assert response.status_code == 200, response.json()+ staged_at = HogFlow.objects.get(pk=flow_id).draft_updated_at+ assert staged_at is not None+ mock_task.delay.assert_not_called()++ with self.captureOnCommitCallbacks(execute=True):+ publish = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",+ {"confirm": True, "draft_updated_at": staged_at.isoformat()},+ )++ assert publish.status_code == 200, publish.json()+ mock_task.delay.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, action_ids=["delay_1"])++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ def test_re_enable_sweeps_all_timing_steps(self, _flag, mock_task):+ # Runs parked during a prior active period survive a disable, and timing edits made while+ # disabled never sweep - so the enable transition converges every timing step.+ flow_id = self._create_flow()+ disable = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "draft"})+ assert disable.status_code == 200, disable.json()+ edit = self._patch_actions(flow_id, delay_duration="1d")+ assert edit.status_code == 200, edit.json()+ mock_task.delay.assert_not_called()++ with self.captureOnCommitCallbacks(execute=True):+ enable = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "active"})++ assert enable.status_code == 200, enable.json()+ mock_task.delay.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, action_ids=["delay_1"])++ @patch(TASK_PATH)+ @patch(TIMING_FLAG_PATH, return_value=True)+ def test_graph_operation_shortening_delay_enqueues_sweep(self, _flag, mock_task):+ flow_id = self._create_flow()++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",+ {+ "operations": [+ {"op": "update_action", "id": "delay_1", "patch": {"config": {"delay_duration": "1d"}}}+ ]+ },+ )++ assert response.status_code == 200, response.json()+ mock_task.delay.assert_called_once_with(team_id=self.team.id, hog_flow_id=flow_id, action_ids=["delay_1"])diff --git a/products/workflows/backend/services/timing_reschedule.py b/products/workflows/backend/services/timing_reschedule.pynew file mode 100644index 000000000000..8d83b596ddef--- /dev/null+++ b/products/workflows/backend/services/timing_reschedule.py@@ -0,0 +1,156 @@+import re+from typing import Any, Optional++import structlog+import posthoganalytics++from posthog.models.team.team import Team++logger = structlog.get_logger(__name__)++WORKFLOWS_TIMING_RESCHEDULE_FLAG = "workflows-timing-reschedule"++# Steps whose parked runs a timing edit can strand: delays park up to 30 days out and time+# windows up to a week. wait_until_condition currently re-parks on a 10-minute polling cap+# (so a sweep is a cheap no-op re-park), but the poll is slated for removal in favor of+# matcher wakes - after which its max-wait deadline parks for the full duration like a+# delay and shortening it strands runs without a sweep.+TIMING_ACTION_TYPES = {"delay", "wait_until_time_window", "wait_until_condition"}++# Only jobs parked on this many steps or fewer get swept; a diff touching more than this is+# pathological (the sweep endpoint caps action_ids at 100 too).+MAX_RESCHEDULE_ACTION_IDS = 100++# Mirrors the worker's duration parsing (nodejs delay.ts calculatedScheduledAt): value like+# "10d" / "1.5h" / "10m", with per-unit clamps applied before comparison so a 45d -> 35d edit+# (both clamped to 30d) doesn't trigger a pointless sweep.+_DURATION_RE = re.compile(r"^(\d*\.?\d+)([dhms])$")+_UNIT_SECONDS = {"d": 86400, "h": 3600, "m": 60, "s": 1}+_UNIT_MAX = {"d": 30, "h": 24, "m": 60, "s": 60}++_TIME_WINDOW_CONFIG_KEYS = ("day", "time", "timezone", "use_person_timezone", "fallback_timezone")+++def use_workflows_timing_reschedule(team: Team) -> bool:+ """Gates the reschedule sweep for parked runs after a timing edit; off means today's+ behavior (shortened delays only take effect at each run's old wake time).++ A raised exception is treated as "flag off" - skipping the sweep is the safe fallback,+ making the flag a kill switch for the whole feature.+ """+ try:+ return bool(+ posthoganalytics.feature_enabled(+ WORKFLOWS_TIMING_RESCHEDULE_FLAG,+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ )+ )+ except Exception:+ logger.warning(+ "workflows.timing_reschedule.feature_flag_check_failed_defaulting_off",+ team_id=team.id,+ flag=WORKFLOWS_TIMING_RESCHEDULE_FLAG,+ exc_info=True,+ )+ return False+++def parse_delay_duration_seconds(value: Any) -> Optional[float]:+ if not isinstance(value, str):+ return None+ match = _DURATION_RE.match(value)+ if not match:+ return None+ amount, unit = match.groups()+ return min(float(amount), _UNIT_MAX[unit]) * _UNIT_SECONDS[unit]+++def get_all_timing_action_ids(actions: Optional[list[dict]]) -> list[str]:+ """Every timing step's id — used when a flow is re-enabled. Runs parked during a prior active+ period survive a disable (they're only cancelled lazily, at wake, while the flow is inactive),+ and timing edits made while inactive never sweep, so there is no trustworthy diff base at+ enable time. Sweeping every timing step converges them all: early wake is a no-op re-park for+ unchanged steps."""+ action_ids = {+ a["id"] for a in actions or [] if isinstance(a, dict) and a.get("id") and a.get("type") in TIMING_ACTION_TYPES+ }+ if len(action_ids) > MAX_RESCHEDULE_ACTION_IDS:+ logger.warning(+ "workflows.timing_reschedule.too_many_timing_actions",+ changed=len(action_ids),+ cap=MAX_RESCHEDULE_ACTION_IDS,+ )+ return []+ return sorted(action_ids)+++def get_timing_reschedule_action_ids(+ before_actions: Optional[list[dict]], after_actions: Optional[list[dict]]+) -> list[str]:+ """Action ids whose timing edit could move a parked run's wake time EARLIER - the only+ case the sweep exists for. Lengthened timings self-heal: the job wakes at its old+ (earlier) time and re-parks at the recomputed later target.++ Per action id present on both sides:+ - delay: trigger on a shortened effective duration; unparseable durations trigger+ conservatively (the worker throws on them at wake, and a spurious sweep is a cheap+ no-op re-park).+ - wait_until_condition: trigger on a shortened max_wait_duration, same comparison as+ delay. Condition edits never trigger - they don't move a parked run's wake time+ (the matcher and the poll both evaluate live config at wake).+ - wait_until_time_window: trigger on any timing-config change - whether a window edit+ moves a given run's wake earlier depends on each person's timezone and position in+ the week, so it isn't statically decidable.+ - type changed across the timing boundary: parked runs' action_id still points at the+ step, and the new handler should run on the sweep's schedule, not the old wake time.+ - added/deleted actions never trigger: nothing is parked on a new step, and deleted+ steps are the graceful-exit path's concern.+ """+ before_by_id = {a["id"]: a for a in (before_actions or []) if isinstance(a, dict) and a.get("id")}+ action_ids: set[str] = set()++ for action in after_actions or []:+ if not isinstance(action, dict) or not action.get("id"):+ continue+ before = before_by_id.get(action["id"])+ if not before:+ continue++ before_type = before.get("type")+ after_type = action.get("type")+ if before_type not in TIMING_ACTION_TYPES and after_type not in TIMING_ACTION_TYPES:+ continue++ if before_type != after_type:+ action_ids.add(action["id"])+ continue++ before_config = before.get("config") or {}+ after_config = action.get("config") or {}+ if after_type in ("delay", "wait_until_condition"):+ duration_key = "delay_duration" if after_type == "delay" else "max_wait_duration"+ before_seconds = parse_delay_duration_seconds(before_config.get(duration_key))+ after_seconds = parse_delay_duration_seconds(after_config.get(duration_key))+ if before_seconds is None or after_seconds is None:+ if before_config.get(duration_key) != after_config.get(duration_key):+ action_ids.add(action["id"])+ elif after_seconds < before_seconds:+ action_ids.add(action["id"])+ elif after_type == "wait_until_time_window":+ if any(before_config.get(key) != after_config.get(key) for key in _TIME_WINDOW_CONFIG_KEYS):+ action_ids.add(action["id"])++ if len(action_ids) > MAX_RESCHEDULE_ACTION_IDS:+ logger.warning(+ "workflows.timing_reschedule.too_many_changed_actions",+ changed=len(action_ids),+ cap=MAX_RESCHEDULE_ACTION_IDS,+ )+ return []++ return sorted(action_ids)diff --git a/products/workflows/backend/tasks/hog_flows.py b/products/workflows/backend/tasks/hog_flows.pyindex 2cf105540e8d..c0ba6fedf5ad 100644--- a/products/workflows/backend/tasks/hog_flows.py+++ b/products/workflows/backend/tasks/hog_flows.py@@ -2,10 +2,11 @@ from typing import Optionalfrom django.utils import timezone+import requestsfrom celery import shared_taskfrom structlog import get_logger-from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers+from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers, reschedule_hog_flow_parked_jobsfrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.tasks.utils import CeleryQueue@@ -14,6 +15,10 @@ from products.workflows.backend.models.hog_flow.hog_flow import HogFlowlogger = get_logger(__name__)+# Backstop against a runaway slice loop; at the endpoint's per-slice work budget this is far+# beyond any real parked backlog.+MAX_RESCHEDULE_SLICES = 500+@shared_task(ignore_result=True, queue=CeleryQueue.DEFAULT.value)@skip_team_scope_audit@@ -52,3 +57,80 @@ def refresh_affected_hog_flows(team_id: Optional[int] = None, action_id: Optionareload_hog_flows_on_workers(team_id=team_id, hog_flow_ids=[str(hog_flow.id) for hog_flow in affected_hog_flows])return updates+++@shared_task(+ ignore_result=True,+ queue=CeleryQueue.DEFAULT.value,+ max_retries=5,+ autoretry_for=(requests.RequestException,),+ retry_backoff=True,+)+@skip_team_scope_audit+def reschedule_hog_flow_timing(+ team_id: int,+ hog_flow_id: str,+ action_ids: list[str],+ sweep_floor: Optional[str] = None,+ sweep_until: Optional[str] = None,+ slice_count: int = 0,+) -> None:+ """Drive the plugin server's reschedule sweep for one workflow after a timing edit.++ Each call runs one bounded slice; when the sweep isn't done, the task re-enqueues itself+ with the returned sweep bounds so the spread window stays fixed across slices. Transient+ HTTP failures autoretry with backoff; a retried or re-enqueued slice is safe because the+ sweep is idempotent for fixed bounds.+ """+ if slice_count > MAX_RESCHEDULE_SLICES:+ logger.error(+ "workflows.timing_reschedule.slice_limit_exceeded",+ team_id=team_id,+ hog_flow_id=hog_flow_id,+ slice_count=slice_count,+ )+ return++ # The flow may have been disabled or deleted between slices - its parked runs get+ # cancelled as they wake, so stop sweeping rather than waking them early to cancel.+ if not HogFlow.objects.filter(team_id=team_id, id=hog_flow_id, status="active").exists():+ logger.info(+ "workflows.timing_reschedule.flow_no_longer_active",+ team_id=team_id,+ hog_flow_id=hog_flow_id,+ slice_count=slice_count,+ )+ return++ response = reschedule_hog_flow_parked_jobs(+ team_id=team_id,+ hog_flow_id=hog_flow_id,+ action_ids=action_ids,+ sweep_floor=sweep_floor,+ sweep_until=sweep_until,+ )+ response.raise_for_status()+ result = response.json()++ logger.info(+ "workflows.timing_reschedule.slice_completed",+ team_id=team_id,+ hog_flow_id=hog_flow_id,+ action_ids=action_ids,+ slice_count=slice_count,+ swept=result.get("swept"),+ remaining=result.get("remaining"),+ )++ if not result.get("done"):+ reschedule_hog_flow_timing.apply_async(+ kwargs={+ "team_id": team_id,+ "hog_flow_id": hog_flow_id,+ "action_ids": action_ids,+ "sweep_floor": result.get("sweep_floor"),+ "sweep_until": result.get("sweep_until"),+ "slice_count": slice_count + 1,+ },+ countdown=5,+ )diff --git a/products/workflows/backend/test/test_timing_reschedule.py b/products/workflows/backend/test/test_timing_reschedule.pynew file mode 100644index 000000000000..53aa3f36b6e7--- /dev/null+++ b/products/workflows/backend/test/test_timing_reschedule.py@@ -0,0 +1,289 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.conf import settings+from django.test import SimpleTestCase++import jwt+import requests+from parameterized import parameterized++from posthog.plugins.plugin_server_api import reschedule_hog_flow_parked_jobs++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from products.workflows.backend.services.timing_reschedule import (+ get_all_timing_action_ids,+ get_timing_reschedule_action_ids,+ parse_delay_duration_seconds,+ use_workflows_timing_reschedule,+)+from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timing++RESCHEDULE_CLIENT_PATH = "products.workflows.backend.tasks.hog_flows.reschedule_hog_flow_parked_jobs"+++def _delay(action_id: str = "delay_1", duration: str = "7d") -> dict:+ return {"id": action_id, "type": "delay", "config": {"delay_duration": duration}}+++def _window(action_id: str = "wait_1", **config) -> dict:+ return {"id": action_id, "type": "wait_until_time_window", "config": {"day": "any", "time": "any", **config}}+++def _condition(action_id: str = "cond_1", max_wait: str = "7d", condition: dict | None = None) -> dict:+ return {+ "id": action_id,+ "type": "wait_until_condition",+ "config": {+ "condition": condition or {"filters": {"events": [{"id": "$pageview"}]}},+ "max_wait_duration": max_wait,+ },+ }+++class TestTimingRescheduleDiff(SimpleTestCase):+ @parameterized.expand(+ [+ ("days", "7d", 7 * 86400.0),+ ("fractional_hours", "1.5h", 5400.0),+ ("minutes", "10m", 600.0),+ ("seconds", "45s", 45.0),+ ("clamped_days", "45d", 30 * 86400.0),+ ("clamped_hours", "48h", 24 * 3600.0),+ ("garbage", "banana", None),+ ("missing_unit", "7", None),+ ("not_a_string", 7, None),+ ("none", None, None),+ ]+ )+ def test_parse_delay_duration_seconds(self, _name, value, expected):+ assert parse_delay_duration_seconds(value) == expected++ @parameterized.expand(+ [+ ("shortened", "7d", "1d", True),+ ("lengthened", "1d", "7d", False),+ ("unchanged", "7d", "7d", False),+ ("unit_equivalent", "1d", "24h", False),+ # 168h is clamped to the 24h unit max at runtime (mirroring the worker), so this+ # apparent no-op rewrite is really a shortening+ ("clamped_shortening", "7d", "168h", True),+ ("clamp_equivalent", "45d", "35d", False),+ ("unparseable_after", "7d", "banana", True),+ ("unparseable_before", "banana", "7d", True),+ ("unparseable_unchanged", "banana", "banana", False),+ ]+ )+ def test_delay_duration_edits(self, _name, before, after, expect_sweep):+ result = get_timing_reschedule_action_ids([_delay(duration=before)], [_delay(duration=after)])+ assert result == (["delay_1"] if expect_sweep else [])++ @parameterized.expand(+ [+ ("max_wait_shortened", _condition(max_wait="7d"), _condition(max_wait="1d"), True),+ ("max_wait_lengthened", _condition(max_wait="1d"), _condition(max_wait="7d"), False),+ ("max_wait_unchanged", _condition(), _condition(), False),+ ("max_wait_clamped_shortening", _condition(max_wait="7d"), _condition(max_wait="168h"), True),+ ("max_wait_unparseable_after", _condition(max_wait="7d"), _condition(max_wait="banana"), True),+ # Condition edits never move a parked run's wake time (the matcher and the poll+ # both evaluate live config), so they must not trigger a sweep+ (+ "condition_only_change",+ _condition(),+ _condition(condition={"filters": {"events": [{"id": "$identify"}]}}),+ False,+ ),+ ]+ )+ def test_wait_condition_edits(self, _name, before, after, expect_sweep):+ result = get_timing_reschedule_action_ids([before], [after])+ assert result == (["cond_1"] if expect_sweep else [])++ @parameterized.expand(+ [+ ("day_changed", {"day": "weekday"}, True),+ ("time_changed", {"time": ["09:00", "10:00"]}, True),+ ("timezone_changed", {"timezone": "Europe/Lisbon"}, True),+ ("person_timezone_toggled", {"use_person_timezone": True}, True),+ ("fallback_changed", {"fallback_timezone": "UTC"}, True),+ ("unchanged", {}, False),+ ]+ )+ def test_time_window_edits(self, _name, config_change, expect_sweep):+ result = get_timing_reschedule_action_ids([_window()], [_window(**config_change)])+ assert result == (["wait_1"] if expect_sweep else [])++ @parameterized.expand(+ [+ ("delay_to_window", _delay(action_id="a"), _window(action_id="a"), True),+ ("delay_to_function", _delay(action_id="a"), {"id": "a", "type": "function", "config": {}}, True),+ ("function_to_delay", {"id": "a", "type": "function", "config": {}}, _delay(action_id="a"), True),+ (+ "function_to_function",+ {"id": "a", "type": "function", "config": {"x": 1}},+ {"id": "a", "type": "function", "config": {"x": 2}},+ False,+ ),+ ]+ )+ def test_type_changes(self, _name, before, after, expect_sweep):+ result = get_timing_reschedule_action_ids([before], [after])+ assert result == (["a"] if expect_sweep else [])++ def test_added_and_deleted_timing_actions_do_not_sweep(self):+ assert get_timing_reschedule_action_ids([], [_delay()]) == []+ assert get_timing_reschedule_action_ids([_delay()], []) == []+ assert get_timing_reschedule_action_ids(None, None) == []++ def test_multiple_changed_actions_are_sorted_and_deduped(self):+ before = [_delay("delay_b", "7d"), _delay("delay_a", "7d"), _window("wait_1")]+ after = [_delay("delay_b", "1d"), _delay("delay_a", "1d"), _window("wait_1", day="weekend")]+ assert get_timing_reschedule_action_ids(before, after) == ["delay_a", "delay_b", "wait_1"]++ def test_pathological_diff_over_cap_sweeps_nothing(self):+ before = [_delay(f"delay_{i}", "7d") for i in range(101)]+ after = [_delay(f"delay_{i}", "1d") for i in range(101)]+ assert get_timing_reschedule_action_ids(before, after) == []++ def test_all_timing_action_ids_returns_only_timing_steps(self):+ actions = [+ _delay("delay_b"),+ _window("wait_a"),+ {"id": "fn_1", "type": "function", "config": {}},+ _condition("cond_c"),+ ]+ assert get_all_timing_action_ids(actions) == ["cond_c", "delay_b", "wait_a"]+ assert get_all_timing_action_ids(None) == []++ def test_all_timing_action_ids_over_cap_sweeps_nothing(self):+ assert get_all_timing_action_ids([_delay(f"delay_{i}") for i in range(101)]) == []+++class TestTimingRescheduleFlag(SimpleTestCase):+ def _team(self) -> MagicMock:+ return MagicMock(uuid="team-uuid", organization_id="org-id", id=1)++ @parameterized.expand([("on", True), ("off", False)])+ def test_flag_value_passthrough(self, _name, enabled):+ with patch("posthoganalytics.feature_enabled", return_value=enabled):+ assert use_workflows_timing_reschedule(self._team()) is enabled++ def test_flag_check_failure_defaults_off(self):+ with patch("posthoganalytics.feature_enabled", side_effect=Exception("flag service down")):+ assert use_workflows_timing_reschedule(self._team()) is False+++class TestRescheduleParkedJobsClient(BaseTest):+ @patch("posthog.plugins.plugin_server_api.internal_requests.post")+ def test_call_carries_a_scoped_jwt_and_timeout(self, mock_post):+ reschedule_hog_flow_parked_jobs(team_id=self.team.id, hog_flow_id="flow-uuid", action_ids=["delay_1"])++ kwargs = mock_post.call_args.kwargs+ # A hung plugin server must not pin the calling Celery worker indefinitely+ assert kwargs["timeout"] == 30+ # Auth is a scoped per-call JWT, never the fleet-wide internal secret+ assert "x-internal-api-secret" not in {k.lower() for k in kwargs["headers"]}+ token = kwargs["headers"]["Authorization"].removeprefix("Bearer ")+ claims = jwt.decode(+ token,+ settings.WORKFLOWS_RESCHEDULE_JWT_SECRETS[0],+ audience="posthog:workflows:reschedule_parked",+ algorithms=["HS256"],+ )+ assert claims["team_id"] == self.team.id+ assert claims["hog_flow_id"] == "flow-uuid"++ @patch("posthog.plugins.plugin_server_api.internal_requests.post")+ def test_call_fails_closed_when_key_unprovisioned(self, mock_post):+ with self.settings(WORKFLOWS_RESCHEDULE_JWT_SECRETS=[]):+ with self.assertRaises(RuntimeError):+ reschedule_hog_flow_parked_jobs(team_id=self.team.id, hog_flow_id="flow-uuid", action_ids=["delay_1"])+ mock_post.assert_not_called()+++class TestRescheduleHogFlowTimingTask(BaseTest):+ def _create_flow(self, status: str = "active") -> HogFlow:+ return HogFlow.objects.create(name="Test Flow", team=self.team, status=status)++ def _response(self, payload: dict, status_code: int = 200) -> MagicMock:+ response = MagicMock(status_code=status_code)+ response.json.return_value = payload+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} error", response=response)+ else:+ response.raise_for_status.return_value = None+ return response++ @patch(RESCHEDULE_CLIENT_PATH)+ def test_single_slice_when_done(self, mock_client):+ flow = self._create_flow()+ mock_client.return_value = self._response({"swept": 3, "remaining": 0, "done": True})++ with patch.object(reschedule_hog_flow_timing, "apply_async") as mock_apply:+ reschedule_hog_flow_timing(team_id=self.team.id, hog_flow_id=str(flow.id), action_ids=["delay_1"])++ mock_client.assert_called_once_with(+ team_id=self.team.id,+ hog_flow_id=str(flow.id),+ action_ids=["delay_1"],+ sweep_floor=None,+ sweep_until=None,+ )+ mock_apply.assert_not_called()++ @patch(RESCHEDULE_CLIENT_PATH)+ def test_re_enqueues_with_returned_bounds_until_done(self, mock_client):+ flow = self._create_flow()+ mock_client.return_value = self._response(+ {+ "swept": 100,+ "remaining": 40,+ "done": False,+ "sweep_floor": "2026-07-15T00:10:00Z",+ "sweep_until": "2026-07-15T00:40:00Z",+ }+ )++ with patch.object(reschedule_hog_flow_timing, "apply_async") as mock_apply:+ reschedule_hog_flow_timing(+ team_id=self.team.id, hog_flow_id=str(flow.id), action_ids=["delay_1"], slice_count=2+ )++ mock_apply.assert_called_once_with(+ kwargs={+ "team_id": self.team.id,+ "hog_flow_id": str(flow.id),+ "action_ids": ["delay_1"],+ "sweep_floor": "2026-07-15T00:10:00Z",+ "sweep_until": "2026-07-15T00:40:00Z",+ "slice_count": 3,+ },+ countdown=5,+ )++ @patch(RESCHEDULE_CLIENT_PATH)+ def test_error_response_raises_for_retry(self, mock_client):+ flow = self._create_flow()+ mock_client.return_value = self._response({}, status_code=503)++ with self.assertRaises(requests.HTTPError):+ reschedule_hog_flow_timing(team_id=self.team.id, hog_flow_id=str(flow.id), action_ids=["delay_1"])++ @parameterized.expand([("disabled", "draft"), ("archived", "archived")])+ @patch(RESCHEDULE_CLIENT_PATH)+ def test_skips_inactive_flows(self, _name, status, mock_client):+ flow = self._create_flow(status=status)++ reschedule_hog_flow_timing(team_id=self.team.id, hog_flow_id=str(flow.id), action_ids=["delay_1"])++ mock_client.assert_not_called()++ @patch(RESCHEDULE_CLIENT_PATH)+ def test_stops_at_slice_limit(self, mock_client):+ flow = self._create_flow()++ reschedule_hog_flow_timing(+ team_id=self.team.id, hog_flow_id=str(flow.id), action_ids=["delay_1"], slice_count=501+ )++ mock_client.assert_not_called()