: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): materialize referenced email templates at save (#78272)
Harley Alexandere2742a2974d1
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 008a6232112c..e18fabd6a2a2 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -7,6 +7,7 @@ from copy import deepcopyfrom datetime import timedeltafrom typing import Any, Optional, cast+from django.conf import settingsfrom django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.signing import BadSignature, SignatureExpired, TimestampSigner@@ -80,6 +81,7 @@ from products.feature_flags.backend.user_blast_radius import (from products.messaging.backend.api.design_operations import apply_design_operationsfrom products.messaging.backend.api.design_validation import validate_designfrom products.messaging.backend.api.message_templates import DesignOperationSerializer+from products.messaging.backend.models import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_htmlfrom products.notifications.backend.facade.api import publish_resource_editedfrom products.workflows.backend.api.action_redirects import compute_action_redirects@@ -507,6 +509,96 @@ def _apply_fixed_template_id(config: dict, template_id: str, fixed_template_id:return fixed_template_id+# Email-body keys a saved library template can supply. `from`/`to` are deliberately absent:+# sender identity and the recipient expression are step-level decisions, so they always come+# from the caller.+_TEMPLATE_EMAIL_BODY_KEYS = ("subject", "text", "html", "design")++# Materialization must not persist more content than the request-body ceiling lets a caller+# send inline: many tiny steps referencing one large template would otherwise amplify a small+# request into an oversized write. Cumulative across all steps in one save.+MATERIALIZED_TEMPLATE_CONTENT_MAX_BYTES = settings.DATA_UPLOAD_MAX_MEMORY_SIZE+++def _apply_email_template_content(config: dict, team: Team, strict: bool, context: dict) -> None:+ """Materialize a referenced saved template's email body into the step's inputs at save,+ mirroring what the web editor does when a template is picked (snapshot semantics: later+ template edits don't propagate). Only fires when the caller supplied no body at all — a+ caller-authored body always wins, and then template_uuid is provenance only. Under strict+ (programmatic) validation an unresolvable reference is a 400; lenient web/internal saves+ skip it so re-saves of already-accepted drafts can't start failing."""+ template_uuid = config.get("template_uuid")+ if not template_uuid:+ return+ inputs = config.get("inputs")+ email_input = inputs.get("email") if isinstance(inputs, dict) else None+ value = email_input.get("value") if isinstance(email_input, dict) else None+ if isinstance(value, dict) and any(value.get(key) for key in _TEMPLATE_EMAIL_BODY_KEYS):+ return++ try:+ parsed_uuid = uuid_mod.UUID(str(template_uuid))+ except (ValueError, AttributeError, TypeError):+ parsed_uuid = None+ # Memoized per request: a drip sequence reuses one template across steps, and the actions+ # list validates one action at a time, so without this each step re-queries the same row.+ # The context dict is shared across the many=True action list, so the memo (and the+ # materialized-bytes counter below) span all steps in one request.+ template_cache: dict[str, Optional[MessageTemplate]] = context.setdefault("_message_template_cache", {})+ cache_key = str(parsed_uuid)+ if parsed_uuid is None:+ template = None+ elif cache_key in template_cache:+ template = template_cache[cache_key]+ else:+ template = MessageTemplate.objects.filter(team_id=team.id, id=parsed_uuid, deleted=False).first()+ template_cache[cache_key] = template+ email_content = (template.content or {}).get("email") if template else None+ if not isinstance(email_content, dict) or not any(email_content.get(key) for key in _TEMPLATE_EMAIL_BODY_KEYS):+ if strict:+ raise serializers.ValidationError(+ {+ "template_uuid": (+ f"template_uuid '{str(template_uuid)[:100]}' doesn't match a saved email template in "+ "this project. List templates with workflows-list-email-templates, or author the email "+ "inline in config.inputs.email.value."+ )+ }+ )+ return++ body = {key: email_content[key] for key in _TEMPLATE_EMAIL_BODY_KEYS if email_content.get(key)}+ # Applies on lenient saves too: the lenient path is caller-selectable (a request header),+ # so a strict-only cap would leave the amplification open.+ materialized_bytes = context.get("_materialized_template_bytes", 0) + len(json.dumps(body))+ if materialized_bytes > MATERIALIZED_TEMPLATE_CONTENT_MAX_BYTES:+ raise serializers.ValidationError(+ {+ "template_uuid": (+ "Referenced templates expand into too much email content for one workflow save. "+ "Use fewer or smaller templates, or author the email bodies inline."+ )+ }+ )+ context["_materialized_template_bytes"] = materialized_bytes+ # Body keys are template-sourced once materialization is decided: a falsy placeholder the+ # detection above just ignored (subject: null) must not clobber the template's content.+ carried_over = (+ {key: item for key, item in value.items() if key not in _TEMPLATE_EMAIL_BODY_KEYS}+ if isinstance(value, dict)+ else {}+ )+ merged_value = {**body, **carried_over}+ merged_input = dict(email_input) if isinstance(email_input, dict) else {}+ merged_input["value"] = merged_value+ # Library template content is always Liquid; only default it, never override the caller.+ merged_input.setdefault("templating", "liquid")+ if not isinstance(inputs, dict):+ inputs = {}+ config["inputs"] = inputs+ inputs["email"] = merged_input++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):@@ -1034,6 +1126,14 @@ class HogFlowActionSerializer(serializers.Serializer):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)+ # After the fixed-id coercion, so a library UUID sent as template_id (the dominant+ # authoring mistake) lands in template_uuid first and still gets materialized.+ if data.get("type") == "function_email" and config.get("template_uuid"):+ # get_team is absent when the serializer runs outside a request (internal+ # re-saves, direct construction) - no team to resolve against, so skip.+ get_team = self.context.get("get_team")+ if get_team is not None:+ _apply_email_template_content(config, get_team(), strict, self.context)template = HogFunctionTemplate.get_template(template_id)if not template:if strict:diff --git a/products/workflows/backend/api/test/test_hog_flow_action_email.py b/products/workflows/backend/api/test/test_hog_flow_action_email.pyindex 2be1680a75bc..fcdb688761a3 100644--- a/products/workflows/backend/api/test/test_hog_flow_action_email.py+++ b/products/workflows/backend/api/test/test_hog_flow_action_email.py@@ -8,6 +8,7 @@ from parameterized import parameterizedfrom posthog.cdp.templates.hog_function_template import sync_template_to_dbfrom products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES+from products.messaging.backend.models import MessageTemplatefrom products.messaging.backend.unlayer import UnlayerRenderErrorfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_revision import HogFlowRevision@@ -357,3 +358,211 @@ class TestHogFlowActionEmailAPI(APIBaseTest):assert latest is not Nonelatest_email = next(a for a in latest.content["actions"] if a["id"] == "email_1")assert latest_email["config"]["inputs"]["email"]["value"]["subject"] == "Live subject"+++class TestHogFlowEmailTemplateReference(APIBaseTest):+ def setUp(self):+ super().setUp()+ sync_template_to_db(_email_function_template())++ def _create_library_template(self, **overrides) -> MessageTemplate:+ content = {+ "templating": "liquid",+ "email": {+ "subject": "Library subject",+ "text": "Library text",+ "html": "<p>Library html</p>",+ "design": _design(),+ },+ }+ return MessageTemplate.objects.create(team=self.team, name="Welcome", content=content, **overrides)++ def _post_flow(self, email_config: dict, mcp: bool = True):+ flow = {+ "name": "Referenced Email Flow",+ "actions": [+ _trigger_action(),+ {"id": "email_1", "name": "Email step", "type": "function_email", "config": email_config},+ ],+ "edges": [{"from": "trigger_node", "to": "email_1", "type": "continue"}],+ }+ url = f"/api/projects/{self.team.id}/hog_flows"+ if mcp:+ return self.client.post(url, flow, HTTP_X_POSTHOG_CLIENT="mcp")+ return self.client.post(url, flow)++ @patch(RENDER_PATH, return_value=RENDERED_HTML)+ def test_template_uuid_materializes_body_at_create_and_step_is_patchable(self, _mock_render):+ # The incremental authoring path: reference a saved template plus the two step-level+ # keys, get a complete email step, then iterate with the surgical patch endpoint —+ # previously the whole email object had to be authored in a single graph operation.+ template = self._create_library_template()+ response = self._post_flow(+ {+ "template_id": "template-email",+ "template_uuid": str(template.id),+ "inputs": {"email": {"value": {"from": "[email protected]", "to": "{{ person.properties.email }}"}}},+ }+ )++ assert response.status_code == 201, response.json()+ flow = HogFlow.objects.get(pk=response.json()["id"])+ stored = _stored_email_value(flow)+ assert stored["subject"] == "Library subject"+ assert stored["html"] == "<p>Library html</p>"+ assert stored["design"] == _design()+ assert stored["from"] == "[email protected]"+ config = next(a for a in flow.actions if a["id"] == "email_1")["config"]+ assert config["template_uuid"] == str(template.id)++ patch_response = self.client.patch(+ f"/api/projects/{self.team.id}/hog_flows/{flow.pk}/actions/email_1/email",+ {"email_patch": {"subject": "Patched subject"}},+ HTTP_X_POSTHOG_CLIENT="mcp",+ )+ assert patch_response.status_code == 200, patch_response.json()++ def test_uuid_in_template_id_is_coerced_and_then_materialized(self):+ # The dominant authoring mistake puts the library UUID in template_id. The fixed-id+ # coercion moves it into template_uuid; materialization must run after that move so+ # the mistaken-but-resolvable reference still produces a complete step in one save.+ template = self._create_library_template()+ response = self._post_flow(+ {+ "template_id": str(template.id),+ "inputs": {"email": {"value": {"from": "[email protected]", "to": "{{ person.properties.email }}"}}},+ }+ )++ assert response.status_code == 201, response.json()+ config = next(a for a in HogFlow.objects.get(pk=response.json()["id"]).actions if a["id"] == "email_1")[+ "config"+ ]+ assert config["template_id"] == "template-email"+ assert config["template_uuid"] == str(template.id)+ assert config["inputs"]["email"]["value"]["subject"] == "Library subject"++ def test_falsy_body_placeholders_do_not_clobber_template_content(self):+ # Agents emit explicit null/empty placeholders for fields they aren't setting. The+ # materialization decision ignores falsy body keys, so the merge must too - otherwise+ # a subject: null placeholder erases the template's subject it just resolved.+ template = self._create_library_template()+ response = self._post_flow(+ {+ "template_id": "template-email",+ "template_uuid": str(template.id),+ "inputs": {+ "email": {+ "value": {+ "from": "[email protected]",+ "to": "{{ person.properties.email }}",+ "subject": None,+ "html": "",+ }+ }+ },+ }+ )++ assert response.status_code == 201, response.json()+ stored = _stored_email_value(HogFlow.objects.get(pk=response.json()["id"]))+ assert stored["subject"] == "Library subject"+ assert stored["html"] == "<p>Library html</p>"++ def test_caller_authored_body_wins_over_template_reference(self):+ # Any caller-supplied body key means the caller owns the whole body; merging template+ # content underneath it would mix two different emails.+ template = self._create_library_template()+ response = self._post_flow(+ {+ "template_id": "template-email",+ "template_uuid": str(template.id),+ "inputs": {+ "email": {+ "value": {+ "from": "[email protected]",+ "to": "{{ person.properties.email }}",+ "subject": "Caller subject",+ "html": "<p>Caller html</p>",+ }+ }+ },+ }+ )++ assert response.status_code == 201, response.json()+ stored = _stored_email_value(HogFlow.objects.get(pk=response.json()["id"]))+ assert stored["subject"] == "Caller subject"+ assert "design" not in stored++ def test_unresolvable_template_uuid_is_rejected_on_strict_save(self):+ deleted = self._create_library_template(deleted=True)+ for _name, template_uuid in [+ ("unknown", "0199aabb-ccdd-0000-1122-334455667788"),+ ("deleted", str(deleted.id)),+ ("malformed", "not-a-uuid"),+ ]:+ response = self._post_flow(+ {+ "template_id": "template-email",+ "template_uuid": template_uuid,+ "inputs": {"email": {"value": {"from": "[email protected]", "to": "[email protected]"}}},+ }+ )+ assert response.status_code == 400, (_name, response.json())+ assert "workflows-list-email-templates" in response.json()["detail"], (_name, response.json())++ def test_template_reference_still_requires_from_and_to(self):+ # The template supplies only the body; the step-level keys stay the caller's job and+ # the validator names exactly what's left to add.+ template = self._create_library_template()+ response = self._post_flow({"template_id": "template-email", "template_uuid": str(template.id)})++ assert response.status_code == 400, response.json()+ assert "'from'" in response.json()["detail"], response.json()++ def test_lenient_web_save_skips_unresolvable_template_reference(self):+ # Web drafts (and internal re-saves) stay storable mid-edit: a dangling reference is+ # only an error on the strict programmatic path.+ response = self._post_flow(+ {"template_id": "template-email", "template_uuid": "0199aabb-ccdd-0000-1122-334455667788", "inputs": {}},+ mcp=False,+ )+ assert response.status_code == 201, response.json()++ def test_materialized_template_content_is_capped_per_save(self):+ # Each body-less reference expands server-side, so without a cumulative cap a small+ # request with many steps referencing one large template amplifies into an oversized+ # write. Each step here is under the cap on its own; only the running total crosses it.+ template = self._create_library_template()+ template.content["email"]["html"] = "<p>" + "x" * 5000 + "</p>"+ template.save()+ email_config = {+ "template_id": "template-email",+ "template_uuid": str(template.id),+ "inputs": {"email": {"value": {"from": "[email protected]", "to": "[email protected]"}}},+ }+ flow = {+ "name": "Amplified Flow",+ "actions": [+ _trigger_action(),+ *(+ {"id": f"email_{i}", "name": f"Email step {i}", "type": "function_email", "config": email_config}+ for i in range(3)+ ),+ ],+ "edges": [+ {"from": "trigger_node", "to": "email_0", "type": "continue"},+ {"from": "email_0", "to": "email_1", "type": "continue"},+ {"from": "email_1", "to": "email_2", "type": "continue"},+ ],+ }++ with patch(+ "products.workflows.backend.api.hog_flow.MATERIALIZED_TEMPLATE_CONTENT_MAX_BYTES",+ 8000,+ ):+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", flow, HTTP_X_POSTHOG_CLIENT="mcp")++ assert response.status_code == 400, response.json()+ assert "author the email bodies inline" in response.json()["detail"], response.json()diff --git a/products/workflows/skills/building-workflows/references/graph-schema.md b/products/workflows/skills/building-workflows/references/graph-schema.mdindex 3ef9d1b6a739..a969f06f8cb3 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`; 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. |+| `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. When `template_uuid` is set and the value has no body keys (`subject`/`text`/`html`/`design`), the server copies the template's body into `inputs.email.value` at save (a snapshot — later template edits don't propagate); you still supply `from` and `to`. If you author any body key inline, your body wins and `template_uuid` is provenance only. `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`, 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_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). For `function_email`, referencing a template means you only author `from`/`to`: the server materializes the template's body at save (see the action-types table). `function_push` still has variable `inputs` (notably `channels`), so retrieve its `inputs_schema` even though the id is fixed.### `function_push` worked example