: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): infer fixed template_id and coerce UUID references (#78208)
Harley Alexanderceb9196ed23d
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 27d78d54874e..008a6232112c 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -468,6 +468,45 @@ def _looks_like_uuid(value: str) -> bool:return False+def _parse_uuid_or_none(value: Any) -> Optional[uuid_mod.UUID]:+ try:+ return uuid_mod.UUID(str(value))+ except (ValueError, AttributeError, TypeError):+ return None+++def _apply_fixed_template_id(config: dict, template_id: str, fixed_template_id: str) -> str:+ """template_id on fixed-template steps is fully determined by the step type, so infer it when+ omitted instead of rejecting for leaving out a constant, and move a UUID-shaped value (a saved+ library template reference, the dominant authoring mistake) into config.template_uuid where it+ belongs. Returns the template_id the step should resolve."""+ if not template_id:+ config["template_id"] = fixed_template_id+ return fixed_template_id+ if template_id == fixed_template_id:+ return template_id+ library_uuid = _parse_uuid_or_none(template_id)+ if library_uuid is None:+ return template_id+ if config.get("template_uuid") and _parse_uuid_or_none(config["template_uuid"]) != library_uuid:+ raise serializers.ValidationError(+ {+ "template_id": (+ f"Ambiguous template reference: template_id holds UUID '{template_id}' but "+ f"config.template_uuid is already '{config['template_uuid']}'. Set template_id "+ f"to the literal '{fixed_template_id}' and keep the saved template's UUID in "+ "config.template_uuid."+ )+ }+ )+ # Persist the canonical hyphenated form: uuid.UUID also accepts 32-hex, braced, and URN+ # forms, but the CDP worker validates function_push's template_uuid with a strict UUID+ # schema, so a non-canonical form would save fine and then fail the worker's parse.+ config["template_uuid"] = str(library_uuid)+ config["template_id"] = fixed_template_id+ return fixed_template_id++def _describe_unknown_template(action: dict, template_id: str) -> str:fixed_id = _FIXED_TEMPLATE_IDS.get(action.get("type", ""))if fixed_id and _looks_like_uuid(template_id):@@ -990,7 +1029,11 @@ class HogFlowActionSerializer(serializers.Serializer):raise serializers.ValidationError({"config": "Invalid trigger type"})if "function" in data.get("type", "") or trigger_is_function:- template_id = data.get("config", {}).get("template_id", "")+ config = data.setdefault("config", {})+ template_id = config.get("template_id", "")+ fixed_template_id = _FIXED_TEMPLATE_IDS.get(data.get("type", ""))+ if fixed_template_id:+ template_id = _apply_fixed_template_id(config, template_id, fixed_template_id)template = HogFunctionTemplate.get_template(template_id)if not template:if strict:diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 91f05453cbdc..a378146d7f74 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -52,6 +52,38 @@ class _StubAccountAudienceProvider:return self.group_type+def _email_function_template() -> dict:+ template = deepcopy(webhook_template)+ template["id"] = "template-email"+ template["name"] = "Email"+ template["inputs_schema"] = [+ {+ "key": "email",+ "type": "native_email",+ "label": "Email",+ "secret": False,+ "hidden": False,+ "required": True,+ "templating": "liquid",+ }+ ]+ return template+++def _valid_email_inputs() -> dict:+ return {+ "email": {+ "value": {+ "to": "{{ person.properties.email }}",+ "from": "[email protected]",+ "subject": "Hello",+ "html": "<p>Hello</p>",+ },+ "templating": "liquid",+ }+ }++_SECRET_TEMPLATE_ID = "template-secret-webhook"@@ -252,25 +284,24 @@ class TestHogFlowAPI(APIBaseTest):@parameterized.expand([- (- "uuid_in_email_template_id",- "function_email",- "0199aabb-ccdd-0000-1122-334455667788",- ["template-email", "template_uuid"],- ),("uuid_in_generic_function","function","0199aabb-ccdd-0000-1122-334455667788",["template-webhook", "not a UUID"],),+ (+ "wrong_literal_on_fixed_step",+ "function_email",+ "template-does-not-exist",+ ["must be the literal 'template-email'"],+ ),])def test_unknown_template_id_error_names_the_expected_form(self, _name, action_type, template_id, fragments):- # Agents keep putting saved-email-template UUIDs (from the template library) into- # config.template_id, where only the fixed literal is valid - the bare "Template not- # found" left them retrying formats blind. The error must name the literal and point- # UUID-holders at config.template_uuid.+ # A bare "Template not found" left agents retrying formats blind. The error must name+ # the expected form: the fixed literal for fixed-template steps, and the non-UUID+ # template-id shape for generic function steps.hog_flow, action = self._create_hog_flow_with_action({"template_id": template_id, "inputs": {}})action["type"] = action_type@@ -281,6 +312,98 @@ class TestHogFlowAPI(APIBaseTest):for fragment in fragments:assert fragment in detail, (fragment, detail)+ def test_fixed_template_id_is_inferred_from_step_type(self):+ # template_id on fixed-template steps is a constant of the step type; omitting the+ # constant used to bounce the create with "Template not found".+ sync_template_to_db(_email_function_template())+ hog_flow, action = self._create_hog_flow_with_action({"inputs": _valid_email_inputs()})+ action["type"] = "function_email"++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 201, response.json()+ stored = HogFlow.objects.get(pk=response.json()["id"])+ email_action = next(a for a in stored.actions if a["type"] == "function_email")+ assert email_action["config"]["template_id"] == "template-email"++ def test_uuid_template_id_is_coerced_into_template_uuid(self):+ # The dominant authoring mistake: a saved library template's UUID in template_id.+ # It belongs in config.template_uuid, so move it there instead of bouncing the request.+ sync_template_to_db(_email_function_template())+ library_uuid = "0199aabb-ccdd-0000-1122-334455667788"+ hog_flow, action = self._create_hog_flow_with_action(+ {"template_id": library_uuid, "inputs": _valid_email_inputs()}+ )+ action["type"] = "function_email"++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 201, response.json()+ stored = HogFlow.objects.get(pk=response.json()["id"])+ config = next(a for a in stored.actions if a["type"] == "function_email")["config"]+ assert config["template_id"] == "template-email"+ assert config["template_uuid"] == library_uuid++ @parameterized.expand(+ [+ # uuid.UUID also accepts these, but the CDP worker validates function_push's+ # template_uuid with a strict hyphenated-form schema - persisting the raw string+ # would save a workflow the worker then rejects at parse time.+ ("hex_without_hyphens", "0199aabbccdd00001122334455667788"),+ ("urn_form", "urn:uuid:0199aabb-ccdd-0000-1122-334455667788"),+ ]+ )+ def test_non_canonical_uuid_template_id_is_canonicalized(self, _name, template_id):+ sync_template_to_db(_email_function_template())+ hog_flow, action = self._create_hog_flow_with_action(+ {"template_id": template_id, "inputs": _valid_email_inputs()}+ )+ action["type"] = "function_email"++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 201, response.json()+ stored = HogFlow.objects.get(pk=response.json()["id"])+ config = next(a for a in stored.actions if a["type"] == "function_email")["config"]+ assert config["template_uuid"] == "0199aabb-ccdd-0000-1122-334455667788"++ def test_equivalent_uuid_representations_do_not_conflict(self):+ # The same saved template referenced in two spellings is one reference, not a conflict.+ sync_template_to_db(_email_function_template())+ hog_flow, action = self._create_hog_flow_with_action(+ {+ "template_id": "0199aabbccdd00001122334455667788",+ "template_uuid": "0199aabb-ccdd-0000-1122-334455667788",+ "inputs": _valid_email_inputs(),+ }+ )+ action["type"] = "function_email"++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 201, response.json()+ stored = HogFlow.objects.get(pk=response.json()["id"])+ config = next(a for a in stored.actions if a["type"] == "function_email")["config"]+ assert config["template_uuid"] == "0199aabb-ccdd-0000-1122-334455667788"++ def test_uuid_template_id_conflicting_with_template_uuid_is_rejected(self):+ # Coercion would silently overwrite one of two different saved-template references;+ # that ambiguity is the caller's to resolve.+ sync_template_to_db(_email_function_template())+ hog_flow, action = self._create_hog_flow_with_action(+ {+ "template_id": "0199aabb-ccdd-0000-1122-334455667788",+ "template_uuid": "11112222-3333-4444-5555-666677778888",+ "inputs": _valid_email_inputs(),+ }+ )+ action["type"] = "function_email"++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 400, response.json()+ assert "Ambiguous" in response.json()["detail"], response.json()+def test_stale_update_is_rejected_with_409(self):flow_id = self._create_simple_flow()flow = HogFlow.objects.get(pk=flow_id)diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex 35dc5c676eb6..3ef9d1b6a739 100644--- a/products/workflows/skills/building-workflows/references/graph-schema.md+++ b/products/workflows/skills/building-workflows/references/graph-schema.md@@ -38,19 +38,19 @@ Every action object has these common fields plus a type-specific `config`:Use **only** these `type` values — they are the complete supported set. An unknown or unsupported `type` breaks the editor's parse for the entire graph.-| `type` | `config` |-| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |-| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |-| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |-| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |-| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |-| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |-| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |-| `function_email` | `{ "template_id": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email` — reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id`. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |-| `function_sms` | `{ "template_id": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`. |-| `function_push` | `{ "template_id": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |-| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |+| `type` | `config` |+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `trigger` | a trigger config (see below). Exactly one trigger node per workflow. |+| `delay` | `{ "delay_duration": "30m" }` — see duration rules below. |+| `conditional_branch` | `{ "conditions": [ { "filters": {"properties": [<cond>]}, "name?": "" } ] }`. Index N pairs with the `branch` edge `index: N`. |+| `random_cohort_branch` | `{ "cohorts": [ { "percentage": 50, "name?": "A" } ] }`. Percentages are relative weights and should sum to 100, but a total above or below 100 still splits traffic in the given proportions. |+| `wait_until_condition` | `{ "condition?": {"filters": {"properties": [<cond>]}}, "events?": [{"filters": {...}, "name?": ""}], "max_wait_duration": "7d" }`. `condition` is optional: an **events-only** wait is valid (server seeds a missing `condition` as `{filters: null}`). Duration rules as `delay`. |+| `wait_until_time_window` | `{ "timezone": "UTC", "use_person_timezone?": false, "day": <"weekday" / "weekend" / "any" / ["monday",...]>, "time": <"any" / ["10:00","11:00"]> }`. |+| `function` | `{ "template_id": "<live template id>", "inputs": { ... }, "mappings?": [] }`. Don't guess the id or its inputs — discover them live (see below). |+| `function_email` | `{ "template_id?": "template-email", "template_uuid?": "<saved template UUID>", "inputs": {"email": {"value": {...}}}, "message_category_type?": <"marketing" / "transactional">, "tracking_enabled?": <bool> }`. `template_id` is the **literal** `template-email`; omit it and the server infers it from the step type. Reference a saved library template (from `workflows-list-email-templates`) by putting its UUID in `template_uuid`, never in `template_id` — a UUID sent as `template_id` is moved into `template_uuid` automatically. `tracking_enabled` defaults to true; when false, no open pixel is injected and links are not rewritten, so opens/clicks are not recorded for this step (delivery/bounce/unsubscribe still are). |+| `function_sms` | `{ "template_id?": "template-twilio", "inputs": { ... }, "message_category_type?": "..." }`. `template_id` is the **literal** `template-twilio`; omit it and the server infers it. |+| `function_push` | `{ "template_id?": "template-native-push", "inputs": { ... }, "message_category_type?": <"marketing" / "transactional"> }`. `template_id` is the **literal** `template-native-push`; omit it and the server infers it. Sends a mobile push notification via FCM/APNs. Its `inputs` are richer than email's — `title`, `body`, and a `channels` list of the FCM/APNs integration ids to send through — so retrieve the `template-native-push` `inputs_schema` (as with `function`) for the exact keys, and use the project's push integration ids for `channels`. |+| `exit` | `{ "reason?": "Done" }`. Usually one terminal exit node. |### Branch and wait condition filters (the `filters` wrapper is mandatory)@@ -125,7 +125,7 @@ The set of available `function` templates and their required inputs is **live da2. `cdp-function-templates-retrieve` with that id to read its **`inputs_schema`** — the exact keys, types, and which are required.3. Build `inputs` from that schema. A `template_id` not in the live list fails with "Template not found".-`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push` (required by the editor), so you don't look the `template_id` up. A saved email template's UUID goes in `template_uuid` alongside the literal, never in `template_id`. `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.+`function_email`, `function_sms`, and `function_push` are the exception — their `template_id` is the fixed literal `template-email` / `template-twilio` / `template-native-push`, so you don't look the `template_id` up, and you can omit it entirely: the server infers the literal from the step type. A saved email template's UUID goes in `template_uuid` alongside the literal, never in `template_id` (a UUID sent as `template_id` is moved into `template_uuid` automatically). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.### `function_push` worked example