Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): let the executor run delays up to 365 days (#120313)

Harley Alexander33974410cf92
diff --git a/nodejs/src/cdp/services/hogflows/actions/delay.test.ts b/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
index 98bd29a25d45..8c77fdf4fc6d 100644
--- a/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/delay.test.ts
@@ -5,7 +5,12 @@ import { createExampleHogFlowInvocation } from '~/cdp/_tests/fixtures-hogflows'
import { findActionByType } from '../hogflow-utils'
import { ActionHandlerResult } from './action.interface'
-import { DelayHandler, calculatedScheduledAt } from './delay'
+import {
+ DelayHandler,
+ MAX_DELAY_VALUE_FOR_DURATION_UNIT,
+ MAX_WAIT_VALUE_FOR_DURATION_UNIT,
+ calculatedScheduledAt,
+} from './delay'
describe('calculatedScheduledAt', () => {
let startedAtTimestamp: number
@@ -71,13 +76,16 @@ describe('calculatedScheduledAt', () => {
})
it.each([
- ['61s', DateTime.fromISO('2025-01-01T00:00:00.000Z').toUTC().plus({ seconds: 60 })],
- ['61m', DateTime.fromISO('2025-01-01T00:00:00.000Z').toUTC().plus({ minutes: 60 })],
- ['25h', DateTime.fromISO('2025-01-01T00:00:00.000Z').toUTC().plus({ hours: 24 })],
- ['31d', DateTime.fromISO('2025-01-01T00:00:00.000Z').toUTC().plus({ days: 30 })],
- ])('should enforce a maximum value for max delay duration', (duration, expectedTime) => {
- const result = calculatedScheduledAt(duration, startedAtTimestamp)
- expect(result).toEqual(expectedTime)
+ ['61s', MAX_WAIT_VALUE_FOR_DURATION_UNIT, { seconds: 60 }],
+ ['61m', MAX_WAIT_VALUE_FOR_DURATION_UNIT, { minutes: 60 }],
+ ['25h', MAX_WAIT_VALUE_FOR_DURATION_UNIT, { hours: 24 }],
+ ['31d', MAX_WAIT_VALUE_FOR_DURATION_UNIT, { days: 30 }],
+ ['42d', MAX_DELAY_VALUE_FOR_DURATION_UNIT, { days: 42 }],
+ ['400d', MAX_DELAY_VALUE_FOR_DURATION_UNIT, { days: 365 }],
+ ['25h', MAX_DELAY_VALUE_FOR_DURATION_UNIT, { hours: 24 }],
+ ])('should hold %s to the ceiling of its unit', (duration, ceilings, expected) => {
+ const result = calculatedScheduledAt(duration, startedAtTimestamp, undefined, ceilings)
+ expect(result).toEqual(DateTime.fromISO('2025-01-01T00:00:00.000Z').toUTC().plus(expected))
})
})
@@ -191,15 +199,15 @@ describe('DelayHandler with delay_until', () => {
expect(result.nextAction?.type).toBe('exit')
})
- // A fixed delay caps each unit ('45d' means 30 days). Carrying that into the offset would send a "45
- // days before" reminder 15 days late, and silently, so the offset keeps its full magnitude. The wait
+ // A fixed delay caps each unit ('48h' means 24 hours). Carrying that into the offset would send a "48
+ // hours before" reminder a day late, and silently, so the offset keeps its full magnitude. The wait
// stays bounded by max_delay_duration instead.
it('keeps an offset larger than a fixed delay allows', async () => {
- const result = await runDelay(delayUntil({ offset: '-45d' }), {
- trial_expiration_at: '2025-03-02T00:00:00.000Z',
+ const result = await runDelay(delayUntil({ offset: '-48h' }), {
+ trial_expiration_at: '2025-01-05T00:00:00.000Z',
})
- expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-16T00:00:00.000Z').toUTC().toISO())
+ expect(result.scheduledAt?.toUTC().toISO()).toBe(DateTime.fromISO('2025-01-03T00:00:00.000Z').toUTC().toISO())
})
// A ceiling nothing can parse must not read as zero: that puts the cap at the step's own start, so every
@@ -222,8 +230,8 @@ describe('DelayHandler with delay_until', () => {
})
// An offset whose magnitude overflows luxon's date range makes an invalid target: without a guard it
- // slips past the cap and hands the queue an unschedulable instant. It must clamp like '45d' or a
- // far-future date instead.
+ // slips past the cap and hands the queue an unschedulable instant. It must clamp like a far-future
+ // date instead.
it('clamps an offset too large to represent to the default maximum', async () => {
const result = await runDelay(delayUntil({ offset: '100000000000000000000d' }), {
trial_expiration_at: '2025-01-08T00:00:00.000Z',
@@ -233,13 +241,17 @@ describe('DelayHandler with delay_until', () => {
expect(result.nextAction).toBeUndefined()
})
- it('honours a configured maximum', async () => {
+ it.each([
+ ['2d', { days: 2 }],
+ ['90d', { days: 90 }],
+ ['400d', { days: 365 }],
+ ])('honours a configured maximum of %s', async (maxDelayDuration, expected) => {
const result = await runDelay(
- { ...delayUntil(), max_delay_duration: '2d' },
- { trial_expiration_at: '2025-01-08T00:00:00.000Z' }
+ { ...delayUntil(), max_delay_duration: maxDelayDuration },
+ { trial_expiration_at: '2027-01-01T00:00:00.000Z' }
)
- expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus({ days: 2 }).toISO())
+ expect(result.scheduledAt?.toISO()).toBe(DateTime.fromISO(NOW).toUTC().plus(expected).toISO())
})
// Failing is deliberate. Continuing would run the next step at once, which for a "before X" reminder
diff --git a/nodejs/src/cdp/services/hogflows/actions/delay.ts b/nodejs/src/cdp/services/hogflows/actions/delay.ts
index 443d5f57f737..45dba54db902 100644
--- a/nodejs/src/cdp/services/hogflows/actions/delay.ts
+++ b/nodejs/src/cdp/services/hogflows/actions/delay.ts
@@ -18,7 +18,9 @@ export class DelayHandler implements ActionHandler {
? await scheduledAtFromInstant(action, invocation)
: calculatedScheduledAt(
action.config.delay_duration ?? '',
- invocation.state.currentAction?.startedAtTimestamp
+ invocation.state.currentAction?.startedAtTimestamp,
+ undefined,
+ MAX_DELAY_VALUE_FOR_DURATION_UNIT
)
// While the delay is still pending, park WITHOUT advancing currentAction. Advancing eagerly
@@ -44,9 +46,8 @@ const MAX_UNIX_SECONDS = 253402300799
* Seconds for a signed offset, at its full magnitude.
*
* Deliberately not held to the per-unit ceilings a fixed delay uses. Those exist to bound how long a run
- * waits, which `max_delay_duration` already does here, and applying them to an offset would turn "45 days
- * before" into "30 days before" without saying so: for a date two months out that fires the message 15 days
- * late rather than not at all.
+ * waits, which `max_delay_duration` already does here, and applying them to an offset would shorten it
+ * without saying so: "48 hours before" would become "24 hours before" and fire the message a day late.
*/
function offsetSeconds(value: string): number | null {
const parsed = parseDuration(value)
@@ -62,12 +63,12 @@ function maxDelaySeconds(value: string): number | null {
if (!parsed || parsed.negative) {
return null
}
- return clampedAmount(parsed) * SECONDS_PER_DURATION_UNIT[parsed.unit]
+ return clampedAmount(parsed, MAX_DELAY_VALUE_FOR_DURATION_UNIT) * SECONDS_PER_DURATION_UNIT[parsed.unit]
}
-/** The amount a fixed delay is allowed to wait for, held to this unit's ceiling. */
-function clampedAmount(parsed: ParsedDuration): number {
- return Math.min(MAX_VALUE_FOR_DURATION_UNIT[parsed.unit], parsed.amount)
+/** The amount a step is allowed to wait for, held to this unit's ceiling. */
+function clampedAmount(parsed: ParsedDuration, ceilings: DurationCeilings): number {
+ return Math.min(ceilings[parsed.unit], parsed.amount)
}
/**
@@ -190,7 +191,19 @@ async function scheduledAtFromInstant(
const LUXON_UNIT = { d: 'days', h: 'hours', m: 'minutes', s: 'seconds' } as const
-const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {
+type DurationCeilings = Record<string, number>
+
+// How long one step may wait, per unit. A delay parks once and wakes once, so it can run to a year.
+// A wait stays registered with the subscription matcher while it parks, so it keeps the shorter cap.
+// Mirrored in products/workflows/backend/utils/durations.py.
+export const MAX_DELAY_VALUE_FOR_DURATION_UNIT: DurationCeilings = {
+ d: 365,
+ h: 24,
+ m: 60,
+ s: 60,
+}
+
+export const MAX_WAIT_VALUE_FOR_DURATION_UNIT: DurationCeilings = {
d: 30,
h: 24,
m: 60,
@@ -205,7 +218,8 @@ const MAX_VALUE_FOR_DURATION_UNIT: Record<string, number> = {
export function calculatedScheduledAt(
value: string,
startedAtTimestamp?: number,
- maxDelaySeconds?: number
+ maxDelaySeconds?: number,
+ ceilings: DurationCeilings = MAX_WAIT_VALUE_FOR_DURATION_UNIT
): DateTime | null {
const actionStartedAt = startedAtTimestamp ? DateTime.fromMillis(startedAtTimestamp).toUTC() : null
@@ -219,7 +233,7 @@ export function calculatedScheduledAt(
throw new Error(`Invalid duration: ${value}`)
}
- const duration: DurationLike = { [LUXON_UNIT[parsed.unit]]: clampedAmount(parsed) }
+ const duration: DurationLike = { [LUXON_UNIT[parsed.unit]]: clampedAmount(parsed, ceilings) }
const waitUntilTime = actionStartedAt.plus(duration)
diff --git a/products/workflows/backend/services/timing_reschedule.py b/products/workflows/backend/services/timing_reschedule.py
index 356909829bff..cdc20d63b14a 100644
--- a/products/workflows/backend/services/timing_reschedule.py
+++ b/products/workflows/backend/services/timing_reschedule.py
@@ -2,15 +2,11 @@ from typing import Optional
import structlog
-from products.workflows.backend.utils.durations import (
- MAX_VALUE_FOR_DURATION_UNIT,
- SECONDS_PER_DURATION_UNIT,
- parse_duration,
-)
+from products.workflows.backend.utils.durations import SECONDS_PER_DURATION_UNIT, ceilings_for_field, parse_duration
logger = structlog.get_logger(__name__)
-# Steps whose parked runs a timing edit can strand: delays park up to 30 days out and time
+# Steps whose parked runs a timing edit can strand: delays park up to a year out and time
# windows up to a week. A wait_until_condition parks for its whole max_wait_duration, so the
# sweep is what stops a shortened one stranding runs.
TIMING_ACTION_TYPES = {"delay", "wait_until_time_window", "wait_until_condition"}
@@ -23,13 +19,13 @@ MAX_RESCHEDULE_ACTION_IDS = 100
_TIME_WINDOW_CONFIG_KEYS = ("day", "time", "timezone", "use_person_timezone", "fallback_timezone")
-def parse_delay_duration_seconds(value: object) -> Optional[float]:
+def parse_delay_duration_seconds(value: object, field: str = "delay_duration") -> Optional[float]:
"""Seconds the worker will actually wait, with the per-unit clamps applied first so a 45d -> 35d
- edit (both clamped to 30d) does not trigger a pointless sweep."""
+ wait edit (both clamped to 30d) does not trigger a pointless sweep."""
parsed = parse_duration(value)
if parsed is None or parsed.negative:
return None
- return min(parsed.amount, MAX_VALUE_FOR_DURATION_UNIT[parsed.unit]) * SECONDS_PER_DURATION_UNIT[parsed.unit]
+ return min(parsed.amount, ceilings_for_field(field)[parsed.unit]) * SECONDS_PER_DURATION_UNIT[parsed.unit]
def get_all_timing_action_ids(actions: Optional[list[dict]]) -> list[str]:
@@ -105,8 +101,8 @@ def get_timing_reschedule_action_ids(
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))
+ before_seconds = parse_delay_duration_seconds(before_config.get(duration_key), duration_key)
+ after_seconds = parse_delay_duration_seconds(after_config.get(duration_key), 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"])
diff --git a/products/workflows/backend/test/test_timing_reschedule.py b/products/workflows/backend/test/test_timing_reschedule.py
index ac10930d9b29..63d758c29990 100644
--- a/products/workflows/backend/test/test_timing_reschedule.py
+++ b/products/workflows/backend/test/test_timing_reschedule.py
@@ -43,20 +43,22 @@ def _condition(action_id: str = "cond_1", max_wait: str = "7d", condition: dict
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),
+ ("days", "7d", "delay_duration", 7 * 86400.0),
+ ("fractional_hours", "1.5h", "delay_duration", 5400.0),
+ ("minutes", "10m", "delay_duration", 600.0),
+ ("seconds", "45s", "delay_duration", 45.0),
+ ("delay_past_the_wait_cap", "45d", "delay_duration", 45 * 86400.0),
+ ("clamped_delay_days", "400d", "delay_duration", 365 * 86400.0),
+ ("clamped_wait_days", "45d", "max_wait_duration", 30 * 86400.0),
+ ("clamped_hours", "48h", "delay_duration", 24 * 3600.0),
+ ("garbage", "banana", "delay_duration", None),
+ ("missing_unit", "7", "delay_duration", None),
+ ("not_a_string", 7, "delay_duration", None),
+ ("none", None, "delay_duration", None),
]
)
- def test_parse_delay_duration_seconds(self, _name, value, expected):
- assert parse_delay_duration_seconds(value) == expected
+ def test_parse_delay_duration_seconds(self, _name, value, field, expected):
+ assert parse_delay_duration_seconds(value, field) == expected
@parameterized.expand(
[
@@ -67,7 +69,8 @@ class TestTimingRescheduleDiff(SimpleTestCase):
# 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),
+ ("shortened_past_the_wait_cap", "45d", "35d", True),
+ ("clamp_equivalent", "450d", "400d", False),
("unparseable_after", "7d", "banana", True),
("unparseable_before", "banana", "7d", True),
("unparseable_unchanged", "banana", "banana", False),
@@ -83,6 +86,7 @@ class TestTimingRescheduleDiff(SimpleTestCase):
("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_clamp_equivalent", _condition(max_wait="45d"), _condition(max_wait="35d"), False),
("max_wait_unparseable_after", _condition(max_wait="7d"), _condition(max_wait="banana"), True),
# An edited condition must re-evaluate against parked runs promptly (e.g. fixing a
# filter that could never match) - the sweep wake replaces the poll re-check
diff --git a/products/workflows/backend/utils/durations.py b/products/workflows/backend/utils/durations.py
index 975c2d31567d..2ee7b15bacb1 100644
--- a/products/workflows/backend/utils/durations.py
+++ b/products/workflows/backend/utils/durations.py
@@ -26,10 +26,12 @@ DurationUnit = Literal["d", "h", "m", "s"]
SECONDS_PER_DURATION_UNIT: dict[str, float] = {"d": 86400, "h": 3600, "m": 60, "s": 1}
MINUTES_PER_DURATION_UNIT: dict[str, float] = {"d": 1440, "h": 60, "m": 1, "s": 1 / 60}
-# What a single fixed delay is allowed to wait for, per unit. Mirrors the executor's clamp in
-# nodejs/src/cdp/services/hogflows/actions/delay.ts. It bounds a delay step only: a conversion window
-# takes its value whole, and 'd': 30 there would turn a 365-day window into 30 days without saying so.
-MAX_VALUE_FOR_DURATION_UNIT: dict[str, float] = {"d": 30, "h": 24, "m": 60, "s": 60}
+# How long one step may wait, per unit. Mirrors the executor's clamp in
+# nodejs/src/cdp/services/hogflows/actions/delay.ts. A delay parks once and wakes once, so it can run to a
+# year. A wait stays registered with the subscription matcher while it parks, so it keeps the shorter cap.
+# These bound steps only: a conversion window takes its value whole.
+MAX_DELAY_VALUE_FOR_DURATION_UNIT: dict[str, float] = {"d": 365, "h": 24, "m": 60, "s": 60}
+MAX_WAIT_VALUE_FOR_DURATION_UNIT: dict[str, float] = {"d": 30, "h": 24, "m": 60, "s": 60}
DURATION_EXAMPLES = "'30s', '30m', '2h', '1.5d'"
@@ -76,5 +78,9 @@ def duration_minutes(value: str) -> Optional[float]:
return parsed.amount * MINUTES_PER_DURATION_UNIT[parsed.unit]
+def ceilings_for_field(field: str) -> dict[str, float]:
+ return MAX_WAIT_VALUE_FOR_DURATION_UNIT if field == "max_wait_duration" else MAX_DELAY_VALUE_FOR_DURATION_UNIT
+
+
def duration_error(field: str) -> str:
return f"{field} must be a duration string such as {DURATION_EXAMPLES}. ISO-8601 formats are not supported."