: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
fix(workflows): reject a wait that reads a group property (#105854)
Daniel Marchuk8e7d48a6381c
diff --git a/products/workflows/backend/facade/validation.py b/products/workflows/backend/facade/validation.pyindex 0f706882585f..d60598f2610b 100644--- a/products/workflows/backend/facade/validation.py+++ b/products/workflows/backend/facade/validation.py@@ -4,7 +4,7 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.workflows.backend.facade.contracts import RealtimeAudienceCohortfrom products.workflows.backend.services import batch_audience_cohortsfrom products.workflows.backend.services.batch_audience_cohorts import find_behavioral_cohort_name-from products.workflows.backend.services.wait_clock_conditions import find_clock_function+from products.workflows.backend.services.wait_clock_conditions import find_clock_function, find_group_fieldfrom products.workflows.backend.utils.durations import (DURATION_PATTERN,duration_cap_error,@@ -52,6 +52,7 @@ __all__ = ["exceeds_unit_cap","find_behavioral_cohort_name","find_clock_function",+ "find_group_field","find_realtime_behavioral_cohort","is_duration","is_signed_duration",diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 33c404fd8a00..fd14b82ee905 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -298,6 +298,7 @@ from products.workflows.backend.facade.validation import (exceeds_unit_cap,find_behavioral_cohort_name,find_clock_function,+ find_group_field,find_realtime_behavioral_cohort,is_duration,is_signed_duration,@@ -408,8 +409,8 @@ 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.+ Every strict save re-validates the whole actions array, so without this an unrelated edit to an+ active flow would be refused over a condition that was already accepted."""stored = context.get("stored_wait_conditions")if not stored:@@ -513,10 +514,12 @@ def _actions_reference_cohorts(actions: Any) -> bool:def _reject_clock_based_wait(config: dict, team: Team) -> None:"""- Refuse a wait whose condition depends on the clock rather than on something happening.+ Refuse a wait the subscription matcher could never wake.- 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.+ Two conditions qualify: one that depends on the clock rather than on something happening, and+ one that reads a group property, which arrives on no stream the matcher keys parked jobs by.+ Either can only be advanced by the periodic re-check. Rejecting them at save time is what+ allows that re-check to be removed."""filters = (config.get("condition") or {}).get("filters")if not filters:@@ -539,6 +542,18 @@ def _reject_clock_based_wait(config: dict, team: Team) -> None:})+ group_field = find_group_field(expr)+ if group_field:+ raise serializers.ValidationError(+ {+ "config": (+ "This wait's condition uses a group property. A group change does not identify the "+ "people waiting on it, so nothing can advance this wait and it would run to its "+ "maximum wait time. Use a person property, or wait for an event instead."+ )+ }+ )+clock_function = find_clock_function(expr)if not clock_function:return@@ -3512,9 +3527,11 @@ class HogFlowSerializer(HogFlowMinimalSerializer):# 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.+ # Only an active flow's conditions count: a draft's actions come from lenient builder saves,+ # so exempting them would let enabling a draft skip the check.self.context["stored_wait_conditions"] = {action["id"]: (action.get("config") or {}).get("condition")- for action in ((instance.actions if instance else None) or [])+ for action in ((instance.actions if instance and instance.status == HogFlowState.ACTIVE else None) or [])if isinstance(action, dict) and action.get("id") and action.get("type") == "wait_until_condition"}diff --git a/products/workflows/backend/services/wait_clock_conditions.py b/products/workflows/backend/services/wait_clock_conditions.pyindex 7eb14c9cb576..d33766ab182f 100644--- a/products/workflows/backend/services/wait_clock_conditions.py+++ b/products/workflows/backend/services/wait_clock_conditions.py@@ -11,6 +11,7 @@ delay step and a condition that guards it, and the wait is woken by something thhappens."""+import refrom typing import Optionalfrom posthog.hogql import ast@@ -36,3 +37,38 @@ def find_clock_function(condition_expr: ast.Expr) -> Optional[str]:finder = _ClockCallFinder()finder.visit(condition_expr)return finder.found+++# The matcher keys its streams on person and distinct_id only, so a group change carries nothing it+# can look a parked job up by.+GROUP_FIELD_RE = re.compile(r"^group_\d+$")+++class _GroupFieldFinder(TraversingVisitor):+ def __init__(self) -> None:+ self.found: Optional[str] = None+ # A lambda argument can shadow a group name, as in arrayExists(group_0 -> group_0 = 'pro', xs).+ self.bound: set[str] = set()++ def visit_lambda(self, node: ast.Lambda) -> None:+ added = {arg for arg in node.args if arg not in self.bound}+ self.bound |= added+ try:+ super().visit_lambda(node)+ finally:+ self.bound -= added++ def visit_field(self, node: ast.Field) -> None:+ # Any unbound group root is group data the matcher cannot observe: a property, the key, or+ # the whole group passed into another expression. Bracket access wraps the same bare field.+ root = str(node.chain[0])+ if self.found is None and root not in self.bound and GROUP_FIELD_RE.match(root):+ self.found = root+ super().visit_field(node)+++def find_group_field(condition_expr: ast.Expr) -> Optional[str]:+ """Name of the first group field the expression reads, or None if it reads none."""+ finder = _GroupFieldFinder()+ finder.visit(condition_expr)+ return finder.founddiff --git a/products/workflows/backend/tests/api/test_hog_flow_clock_waits.py b/products/workflows/backend/tests/api/test_hog_flow_clock_waits.pyindex 9b4b094cbb4d..7e864de958b2 100644--- a/products/workflows/backend/tests/api/test_hog_flow_clock_waits.py+++ b/products/workflows/backend/tests/api/test_hog_flow_clock_waits.py@@ -2,6 +2,8 @@ from posthog.test.base import APIBaseTestfrom parameterized import parameterized+from posthog.test.test_utils import create_group_type_mapping_without_created_at+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowTRIGGER = {@@ -27,7 +29,7 @@ def wait_on(hogql: str) -> dict:}-class TestClockBasedWaitRejection(APIBaseTest):+class TestUnwakeableWaitRejection(APIBaseTest):def _post(self, wait: dict) -> tuple[int, dict]:response = self.client.post(f"/api/projects/{self.team.id}/hog_flows",@@ -35,6 +37,44 @@ class TestClockBasedWaitRejection(APIBaseTest):)return response.status_code, response.json()+ @parameterized.expand(+ [+ ("direct", "group_0.properties.plan == 'pro'"),+ ("higher_index", "group_2.properties.seats > 5"),+ ("bracket_notation", "group_0['properties']['plan'] == 'pro'"),+ # The groups join carries more than properties, and key is as unobservable as the rest.+ ("group_key", "group_0.key == 'acme'"),+ ("bracket_key", "group_0['key'] == 'acme'"),+ # One group term is enough, so an AND with a person property must not launder it past.+ ("anded_with_a_person_property", "person.properties.plan == 'pro' and group_0.properties.seats > 5"),+ ("passed_into_a_lambda", "arrayExists(g -> g.properties.plan == 'pro', [group_0])"),+ ]+ )+ def test_rejects_a_wait_that_reads_a_group_property(self, _name: str, hogql: str):+ # A group change carries no person or distinct_id, so the matcher can look up no parked job+ # for it and the wait would only ever hit its maximum wait time.+ status, body = self._post(wait_on(hogql))++ assert status == 400, body+ assert "uses a group property" in str(body)++ @parameterized.expand(+ [+ ("dotted", "organization.properties.plan == 'pro'"),+ ("bracket_notation", "organization['properties']['plan'] == 'pro'"),+ ]+ )+ def test_rejects_a_wait_that_reads_a_group_by_its_type_name(self, _name: str, hogql: str):+ # Real-time filters see only group_N, so a type-name alias fails to compile and the save fails.+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )++ status, body = self._post(wait_on(hogql))++ assert status == 400, body+ assert "cannot read organization" in str(body)+@parameterized.expand([("now_comparison", "now() >= toDateTime(person.properties.expires_at)"),@@ -59,6 +99,19 @@ class TestClockBasedWaitRejection(APIBaseTest):assert status == 400, bodyassert "depends on the current time" in str(body)+ @parameterized.expand(+ [+ # A lambda argument shadowing a group name is a local, not a group property read.+ ("lambda_local", "arrayExists(group_0 -> group_0 == 'pro', ['pro']) and person.properties.plan == 'pro'"),+ # A bare group reference is not a property read either.+ ("bare_group_name", "person.properties.group_0 == 'pro'"),+ ]+ )+ def test_accepts_a_wait_whose_group_name_is_not_a_group_property(self, _name: str, hogql: str):+ status, body = self._post(wait_on(hogql))++ assert status == 201, body+@parameterized.expand([("person_property", "person.properties.plan == 'enterprise'"),@@ -135,13 +188,15 @@ class TestGrandfatheredClockWaits(APIBaseTest):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.+ def test_enabling_a_draft_still_checks_its_stored_condition(self):+ # Builder saves of a draft are lenient, so a draft's stored condition was never checked.+ # Exempting it would let any wait through by saving it as a draft and enabling it after.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()+ assert response.status_code == 400, response.json()+ assert "depends on the current time" in str(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