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(workflows): hold every duration field to one grammar (#101188)

Daniel Marchuk136fc5de81e6
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 09c1b056d400..7ba52d813baa 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -187,31 +187,18 @@ from products.workflows.backend.services.workflow_email_health import (
)
from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timing
from products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit
+from products.workflows.backend.utils.durations import (
+ DURATION_PATTERN,
+ duration_error,
+ duration_minutes,
+ is_duration,
+ is_signed_duration,
+)
from products.workflows.backend.utils.email_sending_tiers import max_email_sending_tier, resolve_team_email_sending_tier
from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule
logger = structlog.get_logger(__name__)
-# Delay durations are strings like "30s", "30m", "2h", "1.5d". Must match the regex in the Node.js
-# executor (nodejs/src/cdp/services/hogflows/actions/delay.ts) that throws at runtime on mismatch.
-# wait_until_condition's max_wait_duration reaches the same parser via conditional_branch.ts, so it
-# is held to the same format.
-DELAY_DURATION_REGEX = re.compile(r"^\d*\.?\d+[dhms]$")
-
-# A delay_until offset is the same shape, signed, so it can point before the date it is offsetting.
-DELAY_OFFSET_REGEX = re.compile(r"^-?\d*\.?\d+[dhms]$")
-
-
-def _is_valid_duration(value: Any) -> bool:
- return isinstance(value, str) and bool(DELAY_DURATION_REGEX.match(value))
-
-
-def _duration_error(field: str) -> str:
- return (
- f"{field} must be a string matching ^\\d*\\.?\\d+[dhms]$ "
- "(e.g. '30s', '30m', '2h', '1.5d'). ISO-8601 formats are not supported."
- )
-
# The content of a workflow: everything the draft cycle stages and publish promotes, and nothing
# else. Metadata (name, description) and lifecycle (status) always apply to the live row. The draft
@@ -1787,10 +1774,22 @@ class HogFlowActionSerializer(serializers.Serializer):
if strict and not _wait_condition_already_stored(data, self.context):
_reject_clock_based_wait(data["config"], self.context["get_team"]())
max_wait_duration = data.get("config", {}).get("max_wait_duration")
- # A falsy timeout means "wait indefinitely": conditional_branch.ts skips the parse
- # entirely for it, so only a value that actually reaches the parser needs the format.
- if strict and max_wait_duration and not _is_valid_duration(max_wait_duration):
- raise serializers.ValidationError({"config": _duration_error("max_wait_duration")})
+ # Absent or empty never reaches the parser: conditional_branch.ts skips the re-park and
+ # continues to the next action, so only a value the parser sees needs the format. It does
+ # not wait indefinitely, whatever the field name suggests. Test emptiness rather than
+ # truthiness, because {} and [] are falsy here and truthy in the worker, which would hand
+ # the parser a container and throw on every run.
+ if strict and max_wait_duration not in (None, "") and not is_duration(max_wait_duration):
+ raise serializers.ValidationError({"config": duration_error("max_wait_duration")})
+
+ if is_conditional_branch:
+ # A branch that matches no condition re-parks on this optional delay, which
+ # conditional_branch.ts hands to the same parser as max_wait_duration above. Absent or
+ # empty means "do not re-park", so only a value that actually reaches the parser needs the
+ # format, and emptiness is the test for the same reason as above.
+ delay_duration = data.get("config", {}).get("delay_duration")
+ if strict and delay_duration not in (None, "") and not is_duration(delay_duration):
+ raise serializers.ValidationError({"config": duration_error("delay_duration")})
if data.get("type") == "delay":
self._validate_delay(data, strict)
@@ -1803,8 +1802,8 @@ class HogFlowActionSerializer(serializers.Serializer):
delay_until = config.get("delay_until")
if delay_until is None:
- if strict and not _is_valid_duration(config.get("delay_duration")):
- raise serializers.ValidationError({"config": _duration_error("delay_duration")})
+ if strict and not is_duration(config.get("delay_duration")):
+ raise serializers.ValidationError({"config": duration_error("delay_duration")})
return
if config.get("delay_duration"):
@@ -1827,19 +1826,19 @@ class HogFlowActionSerializer(serializers.Serializer):
return
offset = delay_until.get("offset")
- if strict and offset is not None and not (isinstance(offset, str) and DELAY_OFFSET_REGEX.match(offset)):
+ if strict and offset is not None and not is_signed_duration(offset):
raise serializers.ValidationError(
{
"config": (
- "delay_until.offset must be a string matching ^-?\\d*\\.?\\d+[dhms]$ "
+ "delay_until.offset must be a duration string, optionally signed "
"(e.g. '-1d' for a day before the date, '2h' for two hours after)."
)
}
)
max_delay_duration = config.get("max_delay_duration")
- if strict and max_delay_duration is not None and not _is_valid_duration(max_delay_duration):
- raise serializers.ValidationError({"config": _duration_error("max_delay_duration")})
+ if strict and max_delay_duration is not None and not is_duration(max_delay_duration):
+ raise serializers.ValidationError({"config": duration_error("max_delay_duration")})
use_person_timezone = delay_until.get("use_person_timezone")
if strict and use_person_timezone is not None and not isinstance(use_person_timezone, bool):
@@ -1941,26 +1940,10 @@ class HogFlowConversionEventSerializer(serializers.Serializer):
)
-# Duration strings as the workflow's delay steps already express them, so one convention covers both.
-# The alternation keeps each digit run owned by one quantifier. The obvious `\d*\.?\d+` lets `\d*` and
-# `\d+` both claim the same digits, so a long non-matching value backtracks quadratically, which lets an
-# authenticated caller burn a web process with one request. This form matches the same strings linearly.
-# Use `[0-9]`, not `\d`: Python's `\d` also matches Unicode digits (e.g. '٧', '7') and `float()` parses
-# them, so `\d` would store a window the Node worker's ASCII regex cannot parse, and the worker would
-# then fall back to its default window with no error. `[0-9]` holds the API to the same ASCII grammar the
-# worker and the generated clients enforce.
-CONVERSION_WINDOW_REGEX = r"^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)[dhms]$"
-
-_MINUTES_PER_DURATION_UNIT = {"d": 1440, "h": 60, "m": 1, "s": 1 / 60}
-
MAX_CONVERSION_WINDOW_MINUTES = 365 * 24 * 60
MAX_LEGACY_WINDOW_MINUTES = 90 * 24 * 60
-def _duration_minutes(value: str) -> float:
- return float(value[:-1]) * _MINUTES_PER_DURATION_UNIT[value[-1]]
-
-
class HogFlowConversionSerializer(serializers.Serializer):
filters = serializers.ListField(
child=serializers.DictField(),
@@ -1977,7 +1960,7 @@ class HogFlowConversionSerializer(serializers.Serializer):
help_text="Event-based conversion goals: [{filters: {events: [{id, name, type: 'events'}], ...}}].",
)
window = serializers.RegexField(
- regex=CONVERSION_WINDOW_REGEX,
+ regex=DURATION_PATTERN,
# A real window is a handful of characters ('365d', '31536000s'); the cap keeps the regex and the
# float parse off arbitrarily long input and flows a bound into the generated client schemas.
max_length=32,
@@ -2009,10 +1992,10 @@ class HogFlowConversionSerializer(serializers.Serializer):
def validate_window(self, value: str | None) -> str | None:
if value is None:
return value
- minutes = _duration_minutes(value)
+ minutes = duration_minutes(value)
# A zero window measures nothing. The worker cannot honor it either, so it would fall back to
# the default and give the workflow a 90-day window nobody asked for.
- if minutes <= 0:
+ if minutes is None or minutes <= 0:
raise serializers.ValidationError("The conversion window must be longer than zero.")
if minutes > MAX_CONVERSION_WINDOW_MINUTES:
raise serializers.ValidationError("The conversion window cannot be longer than 365d.")
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index e06a4469139c..6a7b3ba20d56 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -773,6 +773,11 @@ class TestHogFlowAPI(APIBaseTest):
("unit_and_duration_shape", {"unit": "days", "duration": 3}),
("unsupported_unit", {"delay_duration": "30w"}),
("empty_string", {"delay_duration": ""}),
+ # The worker's parser is ASCII-only, so a value Python's `\d` would accept throws on the run.
+ ("unicode_digits", {"delay_duration": "\u0665d"}),
+ ("negative", {"delay_duration": "-5d"}),
+ # `$` matches before a final newline, so this reached float() and 500ed.
+ ("trailing_newline", {"delay_duration": "1d\n"}),
]
)
def test_hog_flow_delay_validation_rejects_malformed_config(self, _name, bad_config):
@@ -782,8 +787,8 @@ class TestHogFlowAPI(APIBaseTest):
"attr": "actions__1__config",
"code": "invalid_input",
"detail": (
- "delay_duration must be a string matching ^\\d*\\.?\\d+[dhms]$ "
- "(e.g. '30s', '30m', '2h', '1.5d'). ISO-8601 formats are not supported."
+ "delay_duration must be a duration string such as '30s', '30m', '2h', '1.5d'. "
+ "ISO-8601 formats are not supported."
),
"type": "validation_error",
}
@@ -826,6 +831,9 @@ class TestHogFlowAPI(APIBaseTest):
("unsupported_unit", "10x"),
("iso_8601", "P30D"),
("numeric", 1800),
+ # Falsy in Python, truthy in the worker, which would hand the parser a container.
+ ("empty_object", {}),
+ ("empty_array", []),
]
)
def test_hog_flow_wait_validation_rejects_malformed_max_wait_duration(self, _name, max_wait_duration):
@@ -837,8 +845,8 @@ class TestHogFlowAPI(APIBaseTest):
"attr": "actions__1__config",
"code": "invalid_input",
"detail": (
- "max_wait_duration must be a string matching ^\\d*\\.?\\d+[dhms]$ "
- "(e.g. '30s', '30m', '2h', '1.5d'). ISO-8601 formats are not supported."
+ "max_wait_duration must be a duration string such as '30s', '30m', '2h', '1.5d'. "
+ "ISO-8601 formats are not supported."
),
"type": "validation_error",
}
@@ -857,6 +865,66 @@ class TestHogFlowAPI(APIBaseTest):
response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", self._make_wait_flow(max_wait_duration))
assert response.status_code == 201, response.json()
+ def _make_conditional_branch_flow(self, config: dict) -> dict:
+ flow = self._make_delay_flow({"delay_duration": "5m"})
+ flow["actions"][1] = {
+ "id": "c1",
+ "name": "c1",
+ "type": "conditional_branch",
+ "config": {
+ "conditions": [{"filters": {"properties": [{"key": "email", "value": "[email protected]"}]}}],
+ **config,
+ },
+ }
+ return flow
+
+ @parameterized.expand(
+ [
+ ("no_unit", "5"),
+ ("unsupported_unit", "10x"),
+ ("iso_8601", "P30D"),
+ ("numeric", 1800),
+ ("unicode_digits", "\u0665d"),
+ # Falsy in Python, truthy in the worker, which would hand the parser a container.
+ ("empty_object", {}),
+ ("empty_array", []),
+ ]
+ )
+ def test_hog_flow_conditional_branch_validation_rejects_malformed_delay_duration(self, _name, delay_duration):
+ # A branch that matches nothing re-parks on delay_duration through the same parser as a delay
+ # step, so a value only that parser rejects has to be rejected at write time too
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ self._make_conditional_branch_flow({"delay_duration": delay_duration}),
+ )
+ assert response.status_code == 400, response.json()
+ assert response.json() == {
+ "attr": "actions__1__config",
+ "code": "invalid_input",
+ "detail": (
+ "delay_duration must be a duration string such as '30s', '30m', '2h', '1.5d'. "
+ "ISO-8601 formats are not supported."
+ ),
+ "type": "validation_error",
+ }
+
+ @parameterized.expand(
+ [
+ ("seconds", {"delay_duration": "30s"}),
+ ("fractional_days", {"delay_duration": "1.5d"}),
+ # The re-park is optional, and every branch the editor writes omits it, so a branch with
+ # no delay must keep saving
+ ("absent", {}),
+ ("null", {"delay_duration": None}),
+ ("empty_string", {"delay_duration": ""}),
+ ]
+ )
+ def test_hog_flow_conditional_branch_validation_accepts_canonical_delay_duration(self, _name, config):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows", self._make_conditional_branch_flow(config)
+ )
+ assert response.status_code == 201, response.json()
+
@parameterized.expand(
[
("bare_string", "greeting", {"key": "greeting"}),
diff --git a/products/workflows/backend/services/timing_reschedule.py b/products/workflows/backend/services/timing_reschedule.py
index c633d533062e..a71f5e4cbf69 100644
--- a/products/workflows/backend/services/timing_reschedule.py
+++ b/products/workflows/backend/services/timing_reschedule.py
@@ -1,8 +1,13 @@
-import re
-from typing import Any, Optional
+from typing import Optional
import structlog
+from products.workflows.backend.utils.durations import (
+ MAX_VALUE_FOR_DURATION_UNIT,
+ SECONDS_PER_DURATION_UNIT,
+ 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
@@ -15,24 +20,17 @@ TIMING_ACTION_TYPES = {"delay", "wait_until_time_window", "wait_until_condition"
# 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 parse_delay_duration_seconds(value: Any) -> Optional[float]:
- if not isinstance(value, str):
- return None
- match = _DURATION_RE.match(value)
- if not match:
+def parse_delay_duration_seconds(value: object) -> 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."""
+ parsed = parse_duration(value)
+ if parsed is None or parsed.negative:
return None
- amount, unit = match.groups()
- return min(float(amount), _UNIT_MAX[unit]) * _UNIT_SECONDS[unit]
+ return min(parsed.amount, MAX_VALUE_FOR_DURATION_UNIT[parsed.unit]) * SECONDS_PER_DURATION_UNIT[parsed.unit]
def get_all_timing_action_ids(actions: Optional[list[dict]]) -> list[str]:
diff --git a/products/workflows/backend/utils/durations.py b/products/workflows/backend/utils/durations.py
new file mode 100644
index 000000000000..975c2d31567d
--- /dev/null
+++ b/products/workflows/backend/utils/durations.py
@@ -0,0 +1,80 @@
+import re
+from typing import Literal, Optional, cast
+
+from posthog.dataclasses import frozen
+
+# One grammar for every duration a workflow expresses: '10d', '1.5h', '30m', '45s'. It is the format
+# the Node worker parses (nodejs/src/cdp/services/hogflows/duration.ts), so a value this module accepts
+# and the worker rejects is a step that validates on save and throws on the run.
+#
+# The alternation keeps each digit run owned by one quantifier. The obvious `\d*\.?\d+` lets `\d*` and
+# `\d+` both claim the same digits, so a long non-matching value backtracks quadratically and one
+# request can burn a web process. This form matches the same strings linearly.
+#
+# `[0-9]`, not `\d`: Python's `\d` also matches Unicode digits ('٧', '7') and `float()` parses them,
+# so `\d` accepts a value the worker's ASCII regex cannot read.
+_DURATION_BODY = r"(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)[dhms]"
+
+DURATION_PATTERN = rf"^{_DURATION_BODY}$"
+# A delay_until offset is the same shape, signed, so it can point before the date it offsets.
+SIGNED_DURATION_PATTERN = rf"^-?{_DURATION_BODY}$"
+
+_SIGNED_DURATION_REGEX = re.compile(SIGNED_DURATION_PATTERN)
+
+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}
+
+DURATION_EXAMPLES = "'30s', '30m', '2h', '1.5d'"
+
+
+@frozen
+class ParsedDuration:
+ amount: float
+ unit: DurationUnit
+ negative: bool
+
+
+def parse_duration(value: object) -> Optional[ParsedDuration]:
+ """The parts of a duration string, or None when it is not one.
+
+ Returns the parts rather than a total because each caller bounds them differently: a fixed delay
+ clamps the amount per unit, an offset keeps its sign, and a conversion window takes the value whole.
+ """
+ # fullmatch, not match: Python's `$` also matches before a final newline, so `match` would accept
+ # "1d\n" and hand "1d" to float() below. The pattern keeps `$` because it is also the OpenAPI
+ # pattern for the `window` field, where `\Z` is not a regex the generated clients can read.
+ if not isinstance(value, str) or not _SIGNED_DURATION_REGEX.fullmatch(value):
+ return None
+ negative = value.startswith("-")
+ body = value[1:] if negative else value
+ return ParsedDuration(amount=float(body[:-1]), unit=cast(DurationUnit, body[-1]), negative=negative)
+
+
+def is_duration(value: object) -> bool:
+ """True for an unsigned duration string."""
+ parsed = parse_duration(value)
+ return parsed is not None and not parsed.negative
+
+
+def is_signed_duration(value: object) -> bool:
+ """True for a duration string that may point backwards, as a delay_until offset may."""
+ return parse_duration(value) is not None
+
+
+def duration_minutes(value: str) -> Optional[float]:
+ """Minutes for an unsigned duration string, or None when it is not one."""
+ parsed = parse_duration(value)
+ if parsed is None or parsed.negative:
+ return None
+ return parsed.amount * MINUTES_PER_DURATION_UNIT[parsed.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."
diff --git a/products/workflows/backend/utils/test_durations.py b/products/workflows/backend/utils/test_durations.py
new file mode 100644
index 000000000000..26bbec08df59
--- /dev/null
+++ b/products/workflows/backend/utils/test_durations.py
@@ -0,0 +1,57 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.workflows.backend.utils.durations import duration_minutes, is_duration, is_signed_duration, parse_duration
+
+
+class TestDurations(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("whole", "10d", 10.0, "d", False),
+ ("fractional", "1.5h", 1.5, "h", False),
+ ("leading_point", ".5m", 0.5, "m", False),
+ ("seconds", "45s", 45.0, "s", False),
+ ("negative", "-1d", 1.0, "d", True),
+ ]
+ )
+ def test_parses_a_duration(self, _name, value, amount, unit, negative):
+ parsed = parse_duration(value)
+ assert parsed is not None
+ assert (parsed.amount, parsed.unit, parsed.negative) == (amount, unit, negative)
+
+ @parameterized.expand(
+ [
+ ("no_unit", "10"),
+ ("unsupported_unit", "10w"),
+ ("uppercase_unit", "10D"),
+ ("iso_8601", "P30D"),
+ ("empty", ""),
+ ("trailing_point", "5.d"),
+ ("not_a_string", 1800),
+ # Python's `\d` matches these and float() parses them, so a permissive grammar stores a
+ # value the worker's ASCII parser rejects at runtime.
+ ("arabic_indic_digits", "٥d"),
+ ("fullwidth_digits", "10d"),
+ # `$` matches before a final newline, so these reach float() unless the match is anchored.
+ ("trailing_newline", "1d\n"),
+ ("signed_trailing_newline", "-1d\n"),
+ ("leading_newline", "\n1d"),
+ ]
+ )
+ def test_rejects_a_non_duration(self, _name, value):
+ assert parse_duration(value) is None
+ assert not is_duration(value)
+ assert not is_signed_duration(value)
+
+ def test_only_the_signed_check_accepts_a_negative(self):
+ assert is_signed_duration("-1d")
+ assert not is_duration("-1d")
+
+ @parameterized.expand([("days", "2d", 2880.0), ("hours", "1.5h", 90.0), ("seconds", "30s", 0.5)])
+ def test_converts_to_minutes(self, _name, value, minutes):
+ assert duration_minutes(value) == minutes
+
+ @parameterized.expand([("trailing_newline", "2d\n"), ("negative", "-2d"), ("not_a_duration", "2w")])
+ def test_gives_no_minutes_for_a_non_duration(self, _name, value):
+ assert duration_minutes(value) is None