: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): reject wait conditions that only a re-check could satisfy (#75453)
Daniel Marchukb796ef978d9e
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 79a2b38acc96..212278e97833 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -47,6 +47,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import log_activity_from_viewsetfrom posthog.auth import InternalAPIAuthentication+from posthog.cdp.filters import compile_filters_exprfrom posthog.cdp.validation import (HogFunctionFiltersSerializer,InputsSchemaItemSerializer,@@ -113,6 +114,7 @@ from products.workflows.backend.services.timing_reschedule import (get_timing_reschedule_action_ids,use_workflows_timing_reschedule,)+from products.workflows.backend.services.wait_clock_conditions import find_clock_functionfrom 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@@ -147,6 +149,85 @@ DRAFT_CONTENT_FIELDS = ()+# Compiled from the author's filters rather than written by them, and only present once a condition has+# been through validation. Comparing them would make an unchanged condition look edited.+_DERIVED_FILTER_KEYS = ("bytecode", "bytecode_error", "source")+++def _authored_condition(condition: Optional[dict]) -> Optional[dict]:+ """The parts of a wait condition a person actually wrote, with compiler output dropped."""+ if not isinstance(condition, dict):+ return condition+ filters = condition.get("filters")+ if not isinstance(filters, dict):+ return condition+ return {+ **condition,+ "filters": {key: value for key, value in filters.items() if key not in _DERIVED_FILTER_KEYS},+ }+++def _wait_condition_already_stored(action: dict, context: dict) -> bool:+ """+ True when this wait's condition matches the one already persisted for the same action.++ The gate exists to stop *new* clock-based waits, not to make an existing workflow un-editable.+ Every strict save re-validates the whole actions array, so without this an unrelated edit (or+ simply resuming a paused flow) would be refused over a condition that was already accepted.+ """+ stored = context.get("stored_wait_conditions")+ if not stored:+ return False+ action_id = action.get("id")+ if action_id not in stored:+ return False+ return _authored_condition(stored[action_id]) == _authored_condition((action.get("config") or {}).get("condition"))+++def _reject_clock_based_wait(config: dict, team: Team) -> None:+ """+ Refuse a wait whose condition depends on the clock rather than on something happening.++ Nothing notifies the matcher when time passes, so such a wait can only be advanced by the+ periodic re-check. Rejecting it at save time is what allows that re-check to be removed.+ """+ filters = (config.get("condition") or {}).get("filters")+ if not filters:+ return++ try:+ expr = compile_filters_expr(filters, team)+ except Exception as e:+ # Fail closed. Nothing else inspects a wait's condition at save time, so swallowing this would+ # let an unwakeable wait through whenever compilation trips on something the shape serializer+ # doesn't check - a condition referencing a deleted action raises Action.DoesNotExist here, for+ # instance. If we can't read the condition we can't claim a stream will wake it.+ logger.warning("workflows.wait_condition_uncompilable", error=str(e))+ raise serializers.ValidationError(+ {+ "config": (+ "This wait's condition could not be read, so we can't tell how it would be woken. "+ "Check the events, actions and properties it refers to still exist."+ )+ }+ )++ clock_function = find_clock_function(expr)+ if not clock_function:+ return++ raise serializers.ValidationError(+ {+ "config": (+ f"This wait uses {clock_function}(), so it depends on the current time rather than on "+ "something happening, and it can only advance once the workflow checks it again. "+ "To wait for a point in time, use a delay step, then add this condition to the step "+ "after it."+ )+ }+ )++def snapshot_flow_content(flow: HogFlow) -> dict:snapshot = {field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS}# The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize@@ -1002,6 +1083,8 @@ class HogFlowActionSerializer(serializers.Serializer):else:serializer.is_valid(raise_exception=True)event_config["filters"] = serializer.validated_data+ if strict and not _wait_condition_already_stored(data, self.context):+ _reject_clock_based_wait(data["config"], self.context["get_team"]())if data.get("type") == "delay":delay_duration = data.get("config", {}).get("delay_duration")@@ -1581,6 +1664,15 @@ class HogFlowSerializer(HogFlowMinimalSerializer):# binds `self.instance`, so fall back to the flow passed in via context so recovery still works.instance = cast(Optional[HogFlow], self.instance) or self.context.get("instance")+ # Wait conditions the live flow already carries, so per-action validation can tell a newly+ # introduced clock condition from one we have been storing all along. Seeded here because+ # nested action validation runs during field processing, before validate() is reached.+ self.context["stored_wait_conditions"] = {+ action["id"]: (action.get("config") or {}).get("condition")+ for action in ((instance.actions if instance else None) or [])+ if isinstance(action, dict) and action.get("id") and action.get("type") == "wait_until_condition"+ }+status = data.get("status")if status is None and instance:status = instance.statusdiff --git a/products/workflows/backend/api/test/test_hog_flow_clock_waits.py b/products/workflows/backend/api/test/test_hog_flow_clock_waits.pynew file mode 100644index 000000000000..9b4b094cbb4d--- /dev/null+++ b/products/workflows/backend/api/test/test_hog_flow_clock_waits.py@@ -0,0 +1,166 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized++from products.workflows.backend.models.hog_flow.hog_flow import HogFlow++TRIGGER = {+ "id": "trigger_node",+ "name": "trigger",+ "type": "trigger",+ "config": {+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+}+++def wait_on(hogql: str) -> dict:+ return {+ "id": "wait_1",+ "name": "wait_1",+ "type": "wait_until_condition",+ "config": {+ "condition": {"filters": {"properties": [{"key": hogql, "type": "hogql", "value": None}]}},+ "max_wait_duration": "20d",+ },+ }+++class TestClockBasedWaitRejection(APIBaseTest):+ def _post(self, wait: dict) -> tuple[int, dict]:+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {"name": "Test Flow", "status": "active", "actions": [TRIGGER, wait]},+ )+ return response.status_code, response.json()++ @parameterized.expand(+ [+ ("now_comparison", "now() >= toDateTime(person.properties.expires_at)"),+ ("unix_wrapped", "toUnixTimestamp(now()) >= toUnixTimestamp(person.properties.expires_at)"),+ ("date_diff", "dateDiff('day', toDateTime(person.properties.last_seen_at), now()) >= 14"),+ ("today", "today() >= toDate(person.properties.expires_at)"),+ # Nested inside arithmetic rather than compared directly, so a top-level-only check misses it.+ ("nested_in_arithmetic", "person.properties.count > toUnixTimestamp(now()) - 86400"),+ # Combined with a stream-observable predicate: one clock term is enough to make the whole+ # condition unwakeable, so an AND must not launder it past the gate.+ (+ "anded_with_a_person_property",+ "person.properties.plan == 'pro' and now() >= toDateTime(person.properties.expires_at)",+ ),+ ]+ )+ def test_rejects_a_wait_that_depends_on_the_clock(self, _name: str, hogql: str):+ # Nothing notifies the matcher when time passes, so these can only advance on a re-check.+ # Each shape has to be caught wherever the clock call sits, not just at the top level.+ status, body = self._post(wait_on(hogql))++ assert status == 400, body+ assert "depends on the current time" in str(body)++ @parameterized.expand(+ [+ ("person_property", "person.properties.plan == 'enterprise'"),+ ("event_name", "event == 'subscription created'"),+ ("property_with_a_date_value", "toDateTime(person.properties.expires_at) > toDateTime('2026-01-01')"),+ ]+ )+ def test_accepts_a_wait_a_stream_can_wake(self, _name: str, hogql: str):+ # The complement, and the part worth guarding: a date comparison is fine as long as both sides+ # are fixed. Rejecting those too would block ordinary conditions and push people off the feature.+ status, body = self._post(wait_on(hogql))++ assert status == 201, body++ def test_accepts_an_events_only_wait(self):+ # No condition to inspect: the wait is woken by its own events entry.+ wait = {+ "id": "wait_1",+ "name": "wait_1",+ "type": "wait_until_condition",+ "config": {+ "events": [+ {"filters": {"events": [{"id": "purchase", "name": "purchase", "type": "events", "order": 0}]}}+ ],+ "max_wait_duration": "1h",+ },+ }++ status, body = self._post(wait)++ assert status == 201, body++ def test_a_draft_from_the_builder_can_still_be_saved(self):+ # Drafts from the web builder stay lenient so a half-built graph saves. The gate applies when+ # the flow is activated, which is the point at which the wait would actually run.+ response = self.client.post(+ f"/api/projects/{self.team.id}/hog_flows",+ {+ "name": "Test Flow",+ "status": "draft",+ "actions": [TRIGGER, wait_on("now() >= toDateTime(person.properties.expires_at)")],+ },+ )++ assert response.status_code == 201, response.json()+++class TestGrandfatheredClockWaits(APIBaseTest):+ """A clock condition that predates the gate must not make its workflow un-editable."""++ def _legacy_flow(self, status: str = "active") -> HogFlow:+ # Written straight to the model, as a pre-gate flow would have been.+ return HogFlow.objects.create(+ team=self.team,+ name="legacy",+ status=status,+ trigger={+ "type": "event",+ "filters": {"events": [{"id": "$pageview", "name": "$pageview", "type": "events", "order": 0}]},+ },+ actions=[TRIGGER, wait_on("now() >= toDateTime(person.properties.expires_at)")],+ edges=[{"from": "trigger_node", "to": "wait_1", "type": "continue"}],+ )++ def test_an_unrelated_edit_still_saves(self):+ # The case that would otherwise lock a customer out: touching the description re-validates the+ # whole actions array, including a condition that was already accepted.+ flow = self._legacy_flow()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",+ {"description": "unrelated edit", "actions": flow.actions},+ )++ assert response.status_code == 200, response.json()++ def test_a_paused_flow_can_be_resumed(self):+ # Activation re-runs the stored actions with full checks and submits no actions of its own.+ flow = self._legacy_flow(status="draft")++ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow.id}", {"status": "active"})++ assert response.status_code == 200, response.json()++ def test_editing_the_clock_condition_itself_is_still_refused(self):+ # The grandfathering is per-condition, not per-workflow: change the condition and it has to+ # meet the new rule, otherwise the exemption would become a permanent loophole.+ flow = self._legacy_flow()+ edited = [TRIGGER, wait_on("now() >= toDateTime(person.properties.something_else)")]++ response = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow.id}", {"actions": edited})++ assert response.status_code == 400, response.json()+ assert "depends on the current time" in str(response.json())++ def test_adding_a_second_clock_wait_is_still_refused(self):+ # Grandfathering one action must not license new ones alongside it.+ flow = self._legacy_flow()+ added = dict(wait_on("now() >= toDateTime(person.properties.other_at)"), id="wait_2", name="wait_2")++ response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}", {"actions": [*flow.actions, added]}+ )++ assert response.status_code == 400, response.json()diff --git a/products/workflows/backend/services/wait_clock_conditions.py b/products/workflows/backend/services/wait_clock_conditions.pynew file mode 100644index 000000000000..4dc59d641fa6--- /dev/null+++ b/products/workflows/backend/services/wait_clock_conditions.py@@ -0,0 +1,37 @@+"""+Detects `wait_until_condition` conditions that only the polling re-check could ever satisfy.++A wait is woken by the subscription matcher when a message arrives on one of its streams: an event,+a person change, an internal event, a distinct_id repoint. A condition that compares against the+clock produces no message at all, so nothing wakes it. The 10-minute polling re-check is what has+been covering that gap, and it re-parks every wait in the fleet to do it.++Rejecting these at save time is what lets the poll go: express the same intent with a delay step and+a condition that guards it, and the wait is woken by something that actually happens.+"""++from typing import Optional++from posthog.hogql import ast+from posthog.hogql.visitor import TraversingVisitor++# Zero-argument functions whose value advances with wall-clock time. A condition built on one of+# these changes truth value without anything happening, which is exactly what no stream can report.+CLOCK_FUNCTIONS = {"now", "today"}+++class _ClockCallFinder(TraversingVisitor):+ def __init__(self) -> None:+ self.found: Optional[str] = None++ def visit_call(self, node: ast.Call) -> None:+ if self.found is None and node.name in CLOCK_FUNCTIONS:+ self.found = node.name+ super().visit_call(node)+++def find_clock_function(condition_expr: ast.Expr) -> Optional[str]:+ """Name of the first clock function the expression calls, or None if it calls none."""+ finder = _ClockCallFinder()+ finder.visit(condition_expr)+ return finder.found