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.

fix(cdp): Delay and time-window steps no longer advance while still pending (#63214)

Daniel Marchuk34bddbf6e1fc
diff --git a/nodejs/src/cdp/services/hogflows/actions/delay.ts b/nodejs/src/cdp/services/hogflows/actions/delay.ts
index 8c9201000f28..a502791b5da7 100644
--- a/nodejs/src/cdp/services/hogflows/actions/delay.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/delay.ts
@@ -14,10 +14,16 @@ export class DelayHandler implements ActionHandler {
invocation.state.currentAction?.startedAtTimestamp
)
- return {
- nextAction: findContinueAction(invocation),
- scheduledAt: nextScheduledAt ?? undefined,
+ // While the delay is still pending, park WITHOUT advancing currentAction. Advancing eagerly
+ // (returning nextAction alongside scheduledAt) made the job look like it was already at the
+ // next step for the whole delay, so the subscription matcher could wake it — e.g. when the
+ // next step is a wait_until_condition whose event fires — and collapse the delay. Advance only
+ // once the delay has elapsed (calculatedScheduledAt returns null).
+ if (nextScheduledAt) {
+ return { scheduledAt: nextScheduledAt }
}
+
+ return { nextAction: findContinueAction(invocation) }
}
}
diff --git a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
index 0f66f0559b01..9b7c5d62b983 100644
--- a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.test.ts
@@ -52,10 +52,18 @@ describe('HogFlowActionRunnerWaitUntilTimeWindow', () => {
)
})
- it('should handle "any" time', () => {
+ it('should advance immediately for "any" time on a valid day', () => {
+ action.config.time = 'any' // day is 'any', so today is always valid -> window is open now
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('should wait for the next valid day for "any" time when today is not valid', () => {
+ jest.setSystemTime(new Date('2025-01-01T10:00:00.000Z')) // a Wednesday
action.config.time = 'any'
+ action.config.day = 'weekend'
const result = getWaitUntilTime(action)
- expect(result).toEqual(DateTime.utc().plus({ days: 1 }).startOf('day'))
+ expect(result).not.toBeNull()
+ expect([6, 7]).toContain(result!.weekday) // Saturday or Sunday
})
it('should handle time window spanning midnight', () => {
@@ -65,6 +73,57 @@ describe('HogFlowActionRunnerWaitUntilTimeWindow', () => {
expect(result).toEqual(DateTime.utc().set({ hour: 23, minute: 0, second: 0, millisecond: 0 }))
})
+ it('should advance immediately in the evening half of a window spanning midnight', () => {
+ action.config.time = ['23:00', '01:00']
+ jest.setSystemTime(new Date('2025-01-01T23:30:00.000Z')) // Inside, before midnight
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('should advance immediately in the morning half of a window spanning midnight', () => {
+ action.config.time = ['23:00', '01:00']
+ jest.setSystemTime(new Date('2025-01-02T00:30:00.000Z')) // Inside, after midnight
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('should wait for tonight when a window spanning midnight is not currently open', () => {
+ action.config.time = ['23:00', '01:00']
+ jest.setSystemTime(new Date('2025-01-01T02:00:00.000Z')) // After last night's window, before tonight's
+ expect(getWaitUntilTime(action)).toEqual(
+ DateTime.utc().set({ hour: 23, minute: 0, second: 0, millisecond: 0 })
+ )
+ })
+
+ it('anchors the morning half of a midnight-spanning window to the day it opened', () => {
+ action.config.day = ['wednesday']
+ action.config.time = ['23:00', '01:00']
+ // Thursday 00:30 is still inside the window that opened Wednesday 23:00
+ jest.setSystemTime(new Date('2025-01-02T00:30:00.000Z'))
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('handles the morning half of a spanning window in a non-UTC timezone', () => {
+ action.config.timezone = 'America/New_York'
+ action.config.time = ['23:00', '01:00']
+ jest.setSystemTime(new Date('2025-01-15T05:30:00.000Z')) // 00:30 in New York
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('handles the morning half of a spanning window on a DST fall-back night', () => {
+ action.config.timezone = 'America/New_York'
+ action.config.time = ['23:00', '01:00']
+ // 2025-11-02 is the US fall-back date; 04:30 UTC is 00:30 in New York, inside the window
+ jest.setSystemTime(new Date('2025-11-02T04:30:00.000Z'))
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
+ it('handles the evening half of a spanning window on a DST spring-forward night', () => {
+ action.config.timezone = 'America/New_York'
+ action.config.time = ['23:00', '01:00']
+ // 2025-03-09 is the US spring-forward date; 03:30 UTC on the 10th is 23:30 on the 9th in New York
+ jest.setSystemTime(new Date('2025-03-10T03:30:00.000Z'))
+ expect(getWaitUntilTime(action)).toBeNull()
+ })
+
it('should handle time window with minutes', () => {
action.config.time = ['14:30', '15:45']
const result = getWaitUntilTime(action)
diff --git a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
index 650eadb3979e..4125787c0046 100644
--- a/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/wait_until_time_window.ts
@@ -17,10 +17,15 @@ export class WaitUntilTimeWindowHandler implements ActionHandler {
action,
}: ActionHandlerOptions<Extract<HogFlowAction, { type: 'wait_until_time_window' }>>): ActionHandlerResult {
const nextTime = getWaitUntilTime(action, invocation.person)
- return {
- nextAction: findContinueAction(invocation),
- scheduledAt: nextTime ?? undefined,
+
+ // Same as the delay handler: while still waiting for the window, park WITHOUT advancing
+ // currentAction, so the job doesn't look like it has reached the next step (which the
+ // subscription matcher could wake early). Advance only once the window has opened.
+ if (nextTime) {
+ return { scheduledAt: nextTime }
}
+
+ return { nextAction: findContinueAction(invocation) }
}
}
@@ -85,25 +90,37 @@ export const getWaitUntilTime = (
const config = action.config
if (config.time === 'any') {
- return getNextValidDay(now, config.day)
+ // Any time on a valid day: if today is valid the window is already open, so return null to
+ // advance now. Returning null is the only signal to advance — the handler re-parks otherwise.
+ return isValidDay(now, config.day) ? null : getNextValidDay(now, config.day)
}
const [startTime, endTime] = config.time
const [startHours, startMinutes] = startTime.split(':').map(Number)
const [endHours, endMinutes] = endTime.split(':').map(Number)
- // Try today first
- let nextTime = now.set({ hour: startHours, minute: startMinutes, second: 0, millisecond: 0 })
- const endTimeToday = now.set({ hour: endHours, minute: endMinutes, second: 0, millisecond: 0 })
+ const startToday = now.set({ hour: startHours, minute: startMinutes, second: 0, millisecond: 0 })
+ const endToday = now.set({ hour: endHours, minute: endMinutes, second: 0, millisecond: 0 })
+
+ // A window whose end is not strictly after its start wraps past midnight (e.g. 23:00 -> 01:00).
+ // It is open in two pieces: the evening piece [start, midnight) opened today, and the
+ // early-morning piece [midnight, end] opened the previous day - so day validity for the morning
+ // piece is checked against yesterday, the day the window actually started.
+ const wrapsMidnight = endToday <= startToday
+
+ const isOpen = wrapsMidnight
+ ? (now >= startToday && isValidDay(now, config.day)) ||
+ (now <= endToday && isValidDay(now.minus({ days: 1 }), config.day))
+ : now >= startToday && now <= endToday && isValidDay(now, config.day)
- // If we're within the time window today, execute immediately
- if (now >= nextTime && now <= endTimeToday && isValidDay(now, config.day)) {
+ if (isOpen) {
return null
}
- // If time has passed or day doesn't match, find next valid day
- if (nextTime <= now || !isValidDay(nextTime, config.day)) {
- nextTime = getNextValidDay(now, config.day).set({
+ // Not open: park at the next start of the window on a valid day.
+ let nextStart = startToday
+ if (nextStart <= now || !isValidDay(nextStart, config.day)) {
+ nextStart = getNextValidDay(now, config.day).set({
hour: startHours,
minute: startMinutes,
second: 0,
@@ -111,5 +128,5 @@ export const getWaitUntilTime = (
})
}
- return nextTime
+ return nextStart
}
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index 0df1e9a766b6..9dd031701847 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -1042,7 +1042,8 @@ describe('Hogflow Executor', () => {
{
finished: false,
scheduledAt: DateTime.fromISO('2025-01-01T02:00:00.000Z').toUTC(),
- nextActionId: 'exit',
+ // Still pending, so the delay parks without advancing currentAction
+ nextActionId: 'delay',
},
],
[
diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.ts
index fe5e626598a7..7bbcbc05e665 100644
--- a/nodejs/src/cdp/workflows-e2e.test.ts
+++ b/nodejs/src/cdp/workflows-e2e.test.ts
@@ -837,6 +837,46 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
expect(mockFetch).toHaveBeenCalledWith('https://example.com/condition-matched', expect.anything())
})
+ it('does not collapse a delay before a wait when the wait event fires during the delay', async () => {
+ // trigger -> delay(5m) -> wait_until_condition(wakeup_event) -> matched / timeout. The
+ // wait's event firing DURING the delay must not wake the job: the delay handler no longer
+ // pre-advances currentAction to the wait, so while parked the job is at the delay (not the
+ // wait) and the matcher leaves it alone. The delay is honored.
+ await createWorkflow({
+ actions: {
+ trigger: trigger(),
+ delay: { type: 'delay', config: { delay_duration: '5m' } },
+ wait_condition: {
+ type: 'wait_until_condition',
+ config: {
+ events: [eventNameFilter('wakeup_event')],
+ condition: { filters: null },
+ max_wait_duration: '5m',
+ },
+ },
+ function_matched: fetchAction('https://example.com/matched'),
+ exit: exitAction(),
+ },
+ edges: [
+ { from: 'trigger', to: 'delay', type: 'continue' },
+ { from: 'delay', to: 'wait_condition', type: 'continue' },
+ { from: 'wait_condition', to: 'function_matched', type: 'branch', index: 0 },
+ { from: 'wait_condition', to: 'exit', type: 'continue' },
+ { from: 'function_matched', to: 'exit', type: 'continue' },
+ ],
+ })
+ await triggerWorkflow(createGlobals())
+ await expectParked()
+
+ // The wait's event fires during the delay — the job must stay parked in the delay.
+ await matcher.processBatch([createGlobals({ event: 'wakeup_event' })])
+
+ await new Promise((resolve) => setTimeout(resolve, 1000))
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.every((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+
it('does not run the next step early when a conversion event fires during a delay', async () => {
// trigger -> delay -> fetch, with an event-based conversion goal used only for
// measurement (exit_only_at_end). A conversion event arriving while the job is parked
@@ -948,10 +988,10 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
globals = createGlobals()
})
- it('should reschedule to the time window start and execute after it opens', async () => {
+ it('parks until the window opens and does not advance early on a premature resume', async () => {
await triggerWorkflow(globals)
- // Job should be rescheduled to the future time window
+ // Job should be rescheduled to the future time window.
await waitForExpect(async () => {
const jobs = await queryCyclotronJobs()
const rescheduled = jobs.filter(
@@ -959,18 +999,47 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)
)
expect(rescheduled.length).toBe(1)
}, 5000)
-
- // Fetch should NOT be called yet
expect(mockFetch).not.toHaveBeenCalled()
- // Fast-forward: set the scheduled time to now so the worker picks it up
+ // A premature resume (the window is still in the future) must re-park, not advance to the
+ // next step. The handler stays at the wait_until_time_window step and reschedules, so the
+ // step that follows the window never runs early.
await cyclotronPool.query(`UPDATE cyclotron_jobs SET scheduled = NOW() WHERE ${statusColumn} = 'available'`)
+ await waitForExpect(async () => {
+ const jobs = await queryCyclotronJobs()
+ expect(jobs.some((j: any) => j.status === 'available' && new Date(j.scheduled) > new Date())).toBe(true)
+ }, 10000)
+ expect(mockFetch).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('wait_until_time_window: window currently open', () => {
+ it('advances through the window and runs the next step', async () => {
+ // day: 'any', time: 'any' is always open, so the step must advance and run the next action
+ // instead of parking forever.
+ await createWorkflow({
+ actions: {
+ trigger: trigger(),
+ wait_window: {
+ type: 'wait_until_time_window',
+ config: { timezone: 'UTC', day: 'any', time: 'any' },
+ },
+ function_1: fetchAction('https://example.com/window-open'),
+ exit: exitAction(),
+ },
+ edges: [
+ { from: 'trigger', to: 'wait_window', type: 'continue' },
+ { from: 'wait_window', to: 'function_1', type: 'continue' },
+ { from: 'function_1', to: 'exit', type: 'continue' },
+ ],
+ })
+
+ await triggerWorkflow(createGlobals())
await waitForExpect(() => {
expect(mockFetch).toHaveBeenCalledTimes(1)
}, 10000)
-
- expect(mockFetch).toHaveBeenCalledWith('https://example.com/after-time-window', expect.anything())
+ expect(mockFetch).toHaveBeenCalledWith('https://example.com/window-open', expect.anything())
})
})
@@ -1982,24 +2051,15 @@ describe('Workflows E2E (email queue)', () => {
expect(logMessages.filter((msg) => msg.includes('Email sent to [email protected]'))).toHaveLength(1)
- // The delay's pause log MUST fire — this is the regression guard against
- // over-suppression. The only routing pause in this workflow (email_1 hopping onto
- // the email queue) is sub-millisecond and silenced. So exactly one pause line
- // should appear, and it must be the delay's.
+ // The delay is a genuine pause and must still be logged; the email's routing hop onto
+ // the email queue must NOT add a duplicate. Assert exactly one pause and one resume line
+ // overall, independent of which action each references — so the guard tests the
+ // suppression's intent and stays valid regardless of whether the delay advances
+ // currentAction before parking.
const pauseLogs = logMessages.filter((msg) => msg.startsWith('Workflow will pause until'))
expect(pauseLogs).toHaveLength(1)
-
- // The delay-wake Resuming log MUST fire — the workflow really did pause and resume.
- // The delay handler returns `{ scheduledAt, nextAction: email_1 }` on the rescheduling
- // dequeue, so `currentAction` is advanced to email_1 *before* the next dequeue. On
- // wake we therefore see "Resuming workflow execution at [Action:email_1]", NOT at
- // [Action:delay_1] — the delay is finished, email_1 is what's about to run. This must
- // appear exactly once (the real wake from delay). The email's routing-continuation
- // Resuming would be a SECOND identical line; the fix suppresses it, so length stays 1.
- const resumingEmailLogs = logMessages.filter(
- (msg) => msg.includes('Resuming workflow execution at') && msg.includes('[Action:email_1]')
- )
- expect(resumingEmailLogs).toHaveLength(1)
+ const resumeLogs = logMessages.filter((msg) => msg.includes('Resuming workflow execution at'))
+ expect(resumeLogs).toHaveLength(1)
})
it('wakes a wait_until_condition parked on the email queue after an email step', async () => {