: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
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}
# 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'"
@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 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 exceeds_unit_cap(field: str, value: object) -> bool:
"""True for a duration whose amount is above what the executor waits for in that unit."""
parsed = parse_duration(value)
return parsed is not None and parsed.amount > ceilings_for_field(field)[parsed.unit]
def duration_cap_error(field: str) -> str:
max_days = int(ceilings_for_field(field)["d"])
return (
f"{field} can be at most {max_days}d, 24h, 60m or 60s, and a longer value only waits that long. "
"Use a larger unit, for example '1.5d' instead of '36h'."
)
def duration_error(field: str) -> str:
return f"{field} must be a duration string such as {DURATION_EXAMPLES}. ISO-8601 formats are not supported."