: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): fill branch conditions in ideas from person properties (#121550)
Daniel Marchuk75715549e440
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.pyindex ad9a7fd8c511..c5a23d347abb 100644--- a/products/access_control/backend/facade/api.py+++ b/products/access_control/backend/facade/api.py@@ -198,6 +198,15 @@ def team_has_property_access_rules(*, team_id: int) -> bool:return PropertyAccessControl.objects.filter(team_id=team_id, property_definition__isnull=False).exists()+def person_property_names_with_access_rules(*, team_id: int) -> frozenset[str]:+ """Person properties with any access rule on the team, for callers that share a result across users."""+ return frozenset(+ PropertyAccessControl.objects.filter(+ team_id=team_id, property_definition__type=PropertyDefinition.Type.PERSON+ ).values_list("property_definition__name", flat=True)+ )++def team_has_public_sharing_access_rules(*, team_id: int) -> bool:return (AccessControl.objects.filter(diff --git a/products/workflows/backend/services/data_suggestions/builder.py b/products/workflows/backend/services/data_suggestions/builder.pyindex 4823891807ca..e08ec5fd8bac 100644--- a/products/workflows/backend/services/data_suggestions/builder.py+++ b/products/workflows/backend/services/data_suggestions/builder.py@@ -1,4 +1,5 @@import re+import dataclassesfrom collections import dequefrom typing import Any@@ -12,6 +13,7 @@ from products.workflows.backend.services.data_suggestions.email_design import Emfrom products.workflows.backend.services.data_suggestions.planner import (MAX_PLANNED_STEPS,Channel,+ PlannedBranch,PlannedStep,PlannedWorkflow,WorkflowIdea,@@ -50,6 +52,8 @@ class BuildContext:once_per_person: bool = Falseevent_properties: frozenset[str] = frozenset()weekly_count: int = 0+ # Person property name to the values seen for it, the only ones a branch condition may use.+ person_properties: dict[str, tuple[str, ...]] = dataclasses.field(default_factory=dict)push_integration_ids: tuple[int, ...] = ()@@ -306,9 +310,10 @@ def _build_step(step: PlannedStep, action_id: str, context: BuildContext) -> dicreturn Nonereturn _action(step, action_id, "wait_until_condition", _wait_config(step))case "conditional_branch":- # Empty filters, like a branch added in the editor, which rejects null filters. The step's note asks the- # team to set each condition.- conditions = [{"filters": {}, "name": clean_copy(branch.label)[:60]} for branch in step.branches or []]+ conditions = [+ {"filters": _branch_filters(branch, context), "name": clean_copy(branch.label)[:60]}+ for branch in step.branches or []+ ]return _action(step, action_id, "conditional_branch", {"conditions": conditions})case "random_split":branches = step.branches or []@@ -324,6 +329,19 @@ def _build_step(step: PlannedStep, action_id: str, context: BuildContext) -> dicreturn _action(step, action_id, "exit", {"reason": clean_copy(step.name)[:100] or "Exit"})+def _branch_filters(branch: PlannedBranch, context: BuildContext) -> dict[str, Any]:+ # A property or value the project does not send leaves the filters empty, like a branch added in the editor,+ # which rejects null filters. The step's note then asks the team to set the condition.+ values = context.person_properties.get(branch.person_property or "", ())+ if branch.property_value not in values:+ return {}+ return {+ "properties": [+ {"key": branch.person_property, "value": [branch.property_value], "operator": "exact", "type": "person"}+ ]+ }++def _slack_config(step: PlannedStep, context: BuildContext) -> dict[str, Any]:inputs: dict[str, Any] = {"channel": {"templating": "hog"}}if context.slack_integration_id is not None:diff --git a/products/workflows/backend/services/data_suggestions/event_volume.py b/products/workflows/backend/services/data_suggestions/event_volume.pyindex db150aa6fdac..0b2f809dc18a 100644--- a/products/workflows/backend/services/data_suggestions/event_volume.py+++ b/products/workflows/backend/services/data_suggestions/event_volume.py@@ -1,5 +1,7 @@-"""How often each of the project's events fired in the last week, sampled for large teams."""+"""How often each of the project's events fired in the last week, sampled for large teams, and the values its person+properties take."""+import jsonimport mathfrom collections.abc import Iterable@@ -12,6 +14,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.models import Team+from posthog.models.event.new_events_schema import use_new_events_schema# Above this many events a week the counts are sampled. The estimate itself reads 1 in 100 events.FULL_SCAN_MAX_WEEKLY_EVENTS = 20_000_000@@ -22,6 +25,9 @@ _COUNT_TIMEOUT_SECONDS = 30# result, which still ranks the events and clears the minimum weekly count._COUNT_MAX_BYTES = 2_000_000_000MAX_EVENTS = 5000+_MAX_BRANCH_VALUES = 6+# Longer values are free text. The cap also bounds the size of the planner prompt.+_MAX_BRANCH_VALUE_LENGTH = 60# A share needs far fewer events than a ranking, so its scan reads about this many whatever the project's size._SHARE_SAMPLE_EVENTS = 1_000_000# PostHog's own events that mark a real moment, unlike the generic `$` events the planner must skip.@@ -100,6 +106,74 @@ def _count_events(team: Team, sample_denominator: int, *, skip: frozenset[str])return {str(row[0]): int(row[1]) * sample_denominator for row in response.results or [] if int(row[1]) > 0}+def person_property_values(team: Team, names: Iterable[str]) -> dict[str, tuple[str, ...]]:+ """The values seen on recent events for each person property in `names`. Only properties with a few short values,+ like a plan or a status, are kept: a branch splits on one of them, and a property with many or long values is an id+ or free text."""+ keys = list(names)+ if not keys:+ return {}+ values, found_any = _person_property_values(team, keys, sampled=True)+ if found_any:+ return values+ # Sampling is by distinct ID, so a small project whose active people all fall outside the sample shows no values.+ return _person_property_values(team, keys, sampled=False)[0]+++def _person_property_values(team: Team, keys: list[str], *, sampled: bool) -> tuple[dict[str, tuple[str, ...]], bool]:+ """The kept values for each property, and whether the scan saw any value at all."""+ query = parse_select("SELECT 1 FROM events WHERE timestamp >= now() - INTERVAL 1 DAY")+ if not isinstance(query, ast.SelectQuery) or query.select_from is None:+ return {}, False+ query.select = []+ for key in keys:+ # Aggregates skip NULL, so blank values never take one of the capped slots.+ value = ast.Call(+ name="nullIf",+ args=[+ ast.Call(+ name="nullIf",+ args=[+ ast.Call(name="toString", args=[ast.Field(chain=["person", "properties", key])]),+ ast.Constant(value=""),+ ],+ ),+ ast.Constant(value="null"),+ ],+ )+ query.select.append(+ ast.Call(name="groupUniqArray", params=[ast.Constant(value=_MAX_BRANCH_VALUES + 1)], args=[value])+ )+ query.select.append(ast.Call(name="max", args=[ast.Call(name="length", args=[value])]))+ if sampled:+ query.select_from.sample = _sample(_ESTIMATE_SAMPLE_DENOMINATOR)+ response = _run_count(team, query, "workflows_data_suggestions_person_properties")+ row = (response.results or [[]])[0]+ native_json = use_new_events_schema(team.pk, response.modifiers)+ values: dict[str, tuple[str, ...]] = {}+ found_any = False+ for index, key in enumerate(keys):+ seen, longest = row[2 * index : 2 * index + 2] or ([], None)+ found_any = found_any or bool(seen)+ decoded = list(seen or []) if native_json else _decoded(seen or [])+ if 0 < len(decoded) <= _MAX_BRANCH_VALUES and (longest or 0) <= _MAX_BRANCH_VALUE_LENGTH:+ values[key] = tuple(sorted(decoded))+ return values, found_any+++def _decoded(raw_values: Iterable[str]) -> list[str]:+ # On the legacy events schema, person property reads strip the JSON quotes but keep escapes like `\"`, and a branch+ # filter compares against the decoded value. A value that does not decode is left out, since its filter could+ # never match. The native JSON schema returns decoded strings already.+ decoded = []+ for raw in raw_values:+ try:+ decoded.append(json.loads(f'"{raw}"'))+ except ValueError:+ continue+ return decoded++def _strings(values: Iterable[str]) -> ast.Tuple:return ast.Tuple(exprs=[ast.Constant(value=value) for value in sorted(values)])diff --git a/products/workflows/backend/services/data_suggestions/planner.py b/products/workflows/backend/services/data_suggestions/planner.pyindex 7638ecb43dc4..8e880ac81583 100644--- a/products/workflows/backend/services/data_suggestions/planner.py+++ b/products/workflows/backend/services/data_suggestions/planner.py@@ -1,3 +1,4 @@+import dataclassesfrom typing import Any, Literalfrom pydantic import BaseModel, Field@@ -57,6 +58,13 @@ class PlannedBranch(BaseModel):label: str = Field(description="Short name of this path, like 'Finished onboarding' or 'Group A'.")percentage: int | None = Field(description="For a random_split: this path's share in percent, else null.")next: str | None = Field(description="The id of the first step on this path, or null to end the workflow.")+ person_property: str | None = Field(+ description="For a conditional_branch: the person property from person_properties this path checks, else null."+ )+ property_value: str | None = Field(+ description="For a conditional_branch: the value of person_property that sends a person down this path, "+ "copied exactly from person_properties, else null."+ )class PlannedStep(BaseModel):@@ -128,6 +136,8 @@ class StepsContext:has_slack: bool# The trigger event's own properties, like a product name or an amount, that an email can show.event_properties: tuple[str, ...] = ()+ # Person properties with few values, like a plan or a status, that a branch can split on.+ person_properties: dict[str, tuple[str, ...]] = dataclasses.field(default_factory=dict)mobile_first: bool = False@@ -178,20 +188,21 @@ Step types:- delay: wait a fixed time.- wait_until_time_window: wait for a time of day or day of the week the team picks.- wait_until_event: wait until the person does one of the project's events, at most duration.-- conditional_branch: split on person properties the team defines. It cannot check what the person did.+- conditional_branch: split on the value of a person property from person_properties. It cannot check what the \+person did.- random_split: split people at random into paths, such as for an A/B test.- exit: end the workflow early with a reason.Rules:- Steps form a graph: next, branches and wait_event_next point at step ids. Never point back at an earlier step.-- Leave settings you cannot know blank: API keys, URLs, channels, phone numbers, property filters and \-recipients. The team fills them in. Say what is left in setup_note.+- Leave settings you cannot know blank: API keys, URLs, channels, phone numbers and recipients. The team fills them in. Say what is left in setup_note.- A wait_until_event step waits for the event that shows the workflow reached its goal for this person, like a \successful payment after a failed one, or an order after an abandoned cart. Use it only when an event in the list \clearly means that. Another event of the same kind is not enough: a paid invoice from the person's own customer is not \their subscription payment. When no event means it, use a delay instead.- To check whether the person did something, like started a chat or placed an order, wait for that event with a \wait_until_event step. Never use a delay followed by a conditional_branch for it, which the team would have to set up.+- {{branch_rule}}- {{personalization_rule}}- Never promise a discount, offer or gift. The team adds one if it has one.- {{email_rule}}@@ -272,6 +283,12 @@ def plan_steps(if context.event_propertieselse "Do not mention a product name, price or amount you cannot know.")+ branch_rule = (+ "Each conditional_branch path checks one person property from person_properties for one of its listed "+ "values. Use a conditional_branch only when a listed property and value fit the split."+ if context.person_properties+ else "Do not use conditional_branch. The project has no person properties to split on."+ )idea = context.ideahuman = as_untrusted_data("workflow",@@ -292,6 +309,12 @@ def plan_steps(list(context.event_properties),source="property names this project sends on the trigger event",)+ if context.person_properties:+ human += "\n\n" + as_untrusted_data(+ "person_properties",+ [f"{name}: {', '.join(values)}" for name, values in context.person_properties.items()],+ source="person property names and values this project sends",+ )human += "\n\n" + as_untrusted_data("step_catalog",[@@ -321,11 +344,16 @@ def plan_steps(channel_rule=_channel_rule(context.channels, context.mobile_first),slack_rule=slack_rule,personalization_rule=personalization_rule,+ branch_rule=branch_rule,max_steps=MAX_PLANNED_STEPS,),excluded_values=_missing_channels(context.channels),# An empty enum would make every wait_until_event step impossible, so the list is only set when there is one.- allowed_values={"wait_event": context.events} if context.events else None,+ allowed_values={+ **({"wait_event": context.events} if context.events else {}),+ **({"person_property": list(context.person_properties)} if context.person_properties else {}),+ }+ or None,human=human,analytics_client=analytics_client,)diff --git a/products/workflows/backend/services/data_suggestions/service.py b/products/workflows/backend/services/data_suggestions/service.pyindex 2f71d6085385..f74758371587 100644--- a/products/workflows/backend/services/data_suggestions/service.py+++ b/products/workflows/backend/services/data_suggestions/service.py@@ -426,6 +426,11 @@ def _plan_and_build(step_templates = tuple(list_step_templates(team))channels = _offered_channels(team, mobile_first)event_properties = team_context.event_property_names(team, suggestion.trigger_event)+ try:+ person_properties = team_context.person_properties(team)+ except _GENERATION_ERRORS:+ # Without them a branch keeps an empty condition for the team to set, which is no reason to fail the build.+ person_properties = {}context = BuildContext(allowed_events=frozenset({suggestion.trigger_event, *events}),step_template_ids=frozenset(template.template_id for template in step_templates),@@ -436,6 +441,7 @@ def _plan_and_build(once_per_person=suggestion.stage in _ONCE_PER_PERSON_STAGES,event_properties=frozenset(event_properties),weekly_count=suggestion.weekly_count,+ person_properties=person_properties,push_integration_ids=team_context.push_integration_ids(team),)built = None@@ -453,6 +459,7 @@ def _plan_and_build(channels=channels,has_slack=slack_integration_id is not None,event_properties=event_properties,+ person_properties=person_properties,mobile_first=mobile_first,),analytics_client=analytics_client,diff --git a/products/workflows/backend/services/data_suggestions/team_context.py b/products/workflows/backend/services/data_suggestions/team_context.pyindex e7f7c07592bd..b04e098576c8 100644--- a/products/workflows/backend/services/data_suggestions/team_context.py+++ b/products/workflows/backend/services/data_suggestions/team_context.py@@ -3,20 +3,23 @@import refrom typing import Any-from django.db.models import BigIntegerField, F+from django.db.models import BigIntegerField, F, IntegerFieldfrom django.db.models.functions import Coalesce-from posthog.models import EventProperty, Team+from posthog.models import EventProperty, PropertyDefinition, Teamfrom posthog.models.integration import Integration+from products.access_control.backend.facade.api import person_property_names_with_access_rulesfrom products.messaging.backend.facade.api import EmailTemplateSummary, list_email_templatesfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfigfrom products.workflows.backend.services.data_suggestions.builder import EmailSender+from products.workflows.backend.services.data_suggestions.event_volume import person_property_valuesfrom products.workflows.backend.services.data_suggestions.planner import Channel_TEMPLATES_LIMIT = 20_EVENT_PROPERTIES_LIMIT = 15+_PERSON_PROPERTIES_LIMIT = 30# Only plain names, so the email's Liquid variable needs no quoting._PLAIN_PROPERTY_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")@@ -130,3 +133,29 @@ def event_property_names(team: Team, event: str) -> tuple[str, ...]:.values_list("property", flat=True)[:100])return tuple(name for name in names if _PLAIN_PROPERTY_NAME.match(name))[:_EVENT_PROPERTIES_LIMIT]+++def person_properties(team: Team) -> dict[str, tuple[str, ...]]:+ """The project's own person properties that a branch can split on, like a plan or a status, with their values."""+ names = (+ # Both expressions match the leading columns of `index_property_def_query_proj`, so the ordering reads the index.+ PropertyDefinition.objects.alias(+ effective_project_id=Coalesce(F("project_id"), F("team_id"), output_field=BigIntegerField()),+ group_type_index_key=Coalesce(F("group_type_index"), -1, output_field=IntegerField()),+ )+ .filter(+ effective_project_id=team.project_id,+ type=PropertyDefinition.Type.PERSON,+ group_type_index_key=-1,+ property_type__in=("String", "Boolean"),+ )+ .exclude(name__startswith="$")+ .order_by(F("query_usage_30_day").desc(nulls_last=True), "name")+ .values_list("name", flat=True)[:100]+ )+ # Built ideas are shared across the team, so a property that any member may not read is left out.+ restricted = person_property_names_with_access_rules(team_id=team.id)+ plain = [name for name in names if _PLAIN_PROPERTY_NAME.match(name) and name not in restricted][+ :_PERSON_PROPERTIES_LIMIT+ ]+ return person_property_values(team, plain)diff --git a/products/workflows/backend/test/test_data_suggestions.py b/products/workflows/backend/test/test_data_suggestions.pyindex 9d7d2dff74f1..1a9dfb62a0e3 100644--- a/products/workflows/backend/test/test_data_suggestions.py+++ b/products/workflows/backend/test/test_data_suggestions.py@@ -71,8 +71,20 @@ def plan(*steps: PlannedStep, first_step: str | None = None) -> PlannedWorkflow:return PlannedWorkflow(first_step=first_step or (steps[0].id if steps else "email_1"), steps=list(steps))-def branch(label: str, next_id: str | None, percentage: int | None = None) -> PlannedBranch:- return PlannedBranch(label=label, percentage=percentage, next=next_id)+def branch(+ label: str,+ next_id: str | None,+ percentage: int | None = None,+ person_property: str | None = None,+ property_value: str | None = None,+) -> PlannedBranch:+ return PlannedBranch(+ label=label,+ percentage=percentage,+ next=next_id,+ person_property=person_property,+ property_value=property_value,+ )def context(**overrides: Any) -> BuildContext:@@ -333,6 +345,41 @@ class TestDataSuggestions(SimpleTestCase):("action_1_delay", "action_2_email", "continue", None),]+ @parameterized.expand(+ [+ (+ "a sent property and value",+ "plan",+ "pro",+ [{"key": "plan", "value": ["pro"], "operator": "exact", "type": "person"}],+ ),+ ("a value the project does not send", "plan", "enterprise", None),+ ("a property the project does not send", "secret", "pro", None),+ ]+ )+ def test_build_workflow_fills_branch_conditions_from_sent_person_properties(+ self, _name: str, person_property: str, property_value: str, expected: list | None+ ) -> None:+ built = build_workflow(+ IDEA,+ plan(+ step(+ "check",+ type="conditional_branch",+ branches=[+ branch("Pro plan", "nudge", person_property=person_property, property_value=property_value)+ ],+ ),+ step("nudge"),+ ),+ context(person_properties={"plan": ("free", "pro")}),+ )+ assert built is not None+ condition = built.workflow["actions"][1]["config"]["conditions"][0]+ assert condition["filters"] == ({"properties": expected} if expected else {})+ unset = {item.field for item in missing_inputs(built.workflow, {})}+ assert ("Condition: Pro plan" in unset) is (expected is None)+@parameterized.expand([("quiet trigger", 50_000, None), ("busy trigger", 1_000_000, 5), ("flood", 9_000_000, 1)])def test_build_workflow_starts_a_busy_trigger_on_a_sample(self, _name: str, weekly_count: int, share: int | Nonediff --git a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py b/products/workflows/backend/tests/api/test_workflow_data_suggestions.pyindex 3e3bfc47c054..648dadedbe68 100644--- a/products/workflows/backend/tests/api/test_workflow_data_suggestions.py+++ b/products/workflows/backend/tests/api/test_workflow_data_suggestions.py@@ -17,6 +17,7 @@ from parameterized import parameterizedfrom posthog.errors import InternalCHQueryErrorfrom posthog.event_usage import EventSourcefrom posthog.exceptions import ClickHouseQueryTimeOut+from posthog.models import PropertyDefinitionfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKey, hash_key_value@@ -24,6 +25,8 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal+from products.access_control.backend.facade.contracts import PropertyAccessLevel+from products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.cdp.backend.templates.hog_function_template import sync_template_to_dbfrom products.messaging.backend.facade.testing import create_message_template_for_testfrom products.workflows.backend.facade.contracts import DataSuggestionsResult@@ -55,6 +58,7 @@ from products.workflows.backend.services.data_suggestions.stages import StageClafrom products.workflows.backend.services.data_suggestions.team_context import (email_sender,has_verified_email_sender,+ person_properties,saved_workflow_actions,)from products.workflows.backend.services.email_sending_controls import ensure_workflows_config@@ -290,6 +294,24 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):assert set(names) <= set(weekly_counts(self.team))+ def test_person_properties_with_an_access_rule_are_not_offered(self) -> None:+ for name in ("plan", "tier"):+ PropertyDefinition.objects.create(+ team=self.team, name=name, property_type="String", type=PropertyDefinition.Type.PERSON+ )+ _create_event(+ team=self.team, event="signed_up", distinct_id="person-1", person_properties={"plan": "pro", "tier": "gold"}+ )+ flush_persons_and_events()+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=PropertyDefinition.objects.get(team=self.team, name="tier"),+ organization_member=self.organization_membership,+ access_level=PropertyAccessLevel.NONE.value,+ )++ assert person_properties(self.team) == {"plan": ("pro",)}+@patch(f"{SERVICE}.suggest_ideas")def test_a_queued_retry_reads_building_not_the_old_failure(self, suggest_ideas: MagicMock) -> None:suggest_ideas.return_value = [_idea("trial_started")]@@ -459,7 +481,15 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):_step("check","conditional_branch",- branches=[PlannedBranch(label="Is on a paid plan", percentage=None, next=None)],+ branches=[+ PlannedBranch(+ label="Is on a paid plan",+ percentage=None,+ next=None,+ person_property=None,+ property_value=None,+ )+ ],next="nudge",),_email_step("nudge", "Ready to upgrade?"),@@ -558,7 +588,15 @@ class TestWorkflowDataSuggestions(ClickhouseTestMixin, APIBaseTest):_step("check","conditional_branch",- branches=[PlannedBranch(label="Is on a paid plan", percentage=None, next=None)],+ branches=[+ PlannedBranch(+ label="Is on a paid plan",+ percentage=None,+ next=None,+ person_property=None,+ property_value=None,+ )+ ],)],),