: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
chore(workflows): route message assets and public templates through the product (#109408)
Harley Alexander235271eb7cde
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex cfa7b4e23e1a..45e77e714128 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -90,10 +90,10 @@ from products.ai_training.backend.facade.api import queue_person_training_deletifrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuidfrom products.workflows.backend.facade.api import get_workflow_names+from products.workflows.backend.facade.message_assets import fetch_message_assets_for_personfrom products.workflows.backend.presentation.views.message_assets import (MessageAssetSerializer,PersonMessageAssetsRequestSerializer,- fetch_message_assets_for_person,)logger = structlog.get_logger(__name__)diff --git a/posthog/urls.py b/posthog/urls.pyindex 7ac138be06a0..d84bfbe16ec4 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -75,7 +75,7 @@ from products.surveys.backend.api.survey import public_survey_pagefrom products.tasks.backend.facade.agent_proxy import agent_proxy_callbackfrom products.tasks.backend.presentation.views.gateway_generation_requests import gateway_generation_requestfrom products.warehouse_sources.backend.presentation.views.public_source_configs import PublicSourceConfigViewSet-from products.workflows.backend.presentation.views import hog_flow, hog_flow_template+from products.workflows.backend.presentation.views import hog_flowfrom .utils import opt_slash_pathfrom .views import (@@ -203,10 +203,6 @@ urlpatterns = ["api/public_hog_function_templates",hog_function_template.PublicHogFunctionTemplateViewSet.as_view({"get": "list"}),),- opt_slash_path(- "api/public_hog_flow_templates",- hog_flow_template.PublicHogFlowTemplateViewSet.as_view({"get": "list"}),- ),opt_slash_path("api/public_source_configs",PublicSourceConfigViewSet.as_view({"get": "list"}),diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 431d3b6e0859..2410f4d53a26 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -326,6 +326,24 @@ class TwilioAccount(TypedDict, total=False):sid: str+@frozen+class MessageAsset:+ invocation_id: str+ action_id: str+ function_id: str+ parent_run_id: str+ kind: str+ distinct_id: str+ person_id: str+ recipient: str+ subject: str+ status: str+ sent_at: datetime+ # Human-readable workflow name; enriched by the endpoint before serialization.+ # Left blank when the workflow no longer exists so the frontend falls back to function_id.+ function_name: str = ""++@frozenclass WorkflowRevisionSummary:"""One entry of a workflow's version history, without the content snapshot."""diff --git a/products/workflows/backend/facade/message_assets.py b/products/workflows/backend/facade/message_assets.pynew file mode 100644index 000000000000..590b3f4f061a--- /dev/null+++ b/products/workflows/backend/facade/message_assets.py@@ -0,0 +1,13 @@+"""Message assets: the emails and push notifications that workflow steps sent, read from ClickHouse."""++from products.workflows.backend.services.message_assets import (+ fetch_message_asset_html,+ fetch_message_assets,+ fetch_message_assets_for_person,+)++__all__ = [+ "fetch_message_asset_html",+ "fetch_message_assets",+ "fetch_message_assets_for_person",+]diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex cf69ab77c08f..4aa40b09c371 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -160,6 +160,7 @@ from products.workflows.backend.facade.email_health import (team_email_sending_allowance,)from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus+from products.workflows.backend.facade.message_assets import fetch_message_asset_html, fetch_message_assetsfrom products.workflows.backend.facade.proposals import (HOG_FLOW_VERSION_APP_SOURCE,PROPOSAL_MERGE_BY_ID_FIELDS,@@ -235,8 +236,6 @@ from products.workflows.backend.presentation.views.message_assets import (MessageAssetContentRequestSerializer,MessageAssetSerializer,MessageAssetsRequestSerializer,- fetch_message_asset_html,- fetch_message_assets,)from products.workflows.backend.presentation.views.publish_impact import build_publish_impactfrom products.workflows.backend.services.timing_reschedule import (diff --git a/products/workflows/backend/presentation/views/message_assets.py b/products/workflows/backend/presentation/views/message_assets.pyindex c94af30bab3e..4679784a637c 100644--- a/products/workflows/backend/presentation/views/message_assets.py+++ b/products/workflows/backend/presentation/views/message_assets.py@@ -1,61 +1,5 @@-import dataclasses-from datetime import UTC, datetime-from typing import Any, Optional, cast-from rest_framework import serializers-from posthog.clickhouse.client.execute import sync_execute--# `latest_` prefix on the argMax aliases prevents collision with the raw column-# names in any outer WHERE — ClickHouse resolves the bare name to the aggregate-# and errors otherwise.-_COLLAPSED_AGGREGATES = """- invocation_id,- action_id,- argMax(function_id, version) AS latest_function_id,- argMax(parent_run_id, version) AS latest_parent_run_id,- argMax(kind, version) AS latest_kind,- argMax(distinct_id, version) AS latest_distinct_id,- argMax(person_id, version) AS latest_person_id,- argMax(recipient, version) AS latest_recipient,- argMax(subject, version) AS latest_subject,- argMax(status, version) AS latest_status,- argMax(sent_at, version) AS latest_sent_at,- argMax(is_deleted, version) AS latest_is_deleted-""".strip()--_OUTER_COLUMNS = """- invocation_id,- action_id,- latest_function_id,- latest_parent_run_id,- latest_kind,- latest_distinct_id,- latest_person_id,- latest_recipient,- latest_subject,- latest_status,- latest_sent_at-""".strip()--[email protected](frozen=True)-class MessageAsset:- invocation_id: str- action_id: str- function_id: str- parent_run_id: str- kind: str- distinct_id: str- person_id: str- recipient: str- subject: str- status: str- sent_at: datetime- # Human-readable workflow name; enriched by the endpoint before serialization.- # Left blank when the workflow no longer exists so the frontend falls back to function_id.- function_name: str = ""-class MessageAssetSerializer(serializers.Serializer):invocation_id = serializers.CharField(help_text="The workflow run this email was sent in.")@@ -174,183 +118,3 @@ class PersonMessageAssetsRequestSerializer(serializers.Serializer):min_value=0,help_text="Number of assets to skip, for pagination.",)---def _build_asset(row: tuple) -> MessageAsset:- return MessageAsset(- invocation_id=row[0],- action_id=row[1],- function_id=row[2],- parent_run_id=row[3],- kind=row[4],- distinct_id=row[5],- person_id=row[6],- recipient=row[7],- subject=row[8],- status=row[9],- sent_at=row[10],- )---def _escape_like(value: str) -> str:- return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")---def fetch_message_assets(- team_id: int,- function_kind: str,- function_id: str,- limit: int,- offset: int = 0,- parent_run_id: Optional[str] = None,- action_id: Optional[str] = None,- invocation_id: Optional[str] = None,- distinct_id: Optional[str] = None,- search: Optional[str] = None,- after: Optional[datetime] = None,- before: Optional[datetime] = None,-) -> list[MessageAsset]:- where = [- "team_id = %(team_id)s",- "function_kind = %(function_kind)s",- "function_id = %(function_id)s",- ]- kwargs: dict[str, Any] = {- "team_id": team_id,- "function_kind": function_kind,- "function_id": function_id,- "limit": limit,- "offset": offset,- }-- # Filter stable-across-versions fields pre-aggregation to hit the bloom-filter- # skip indexes. `is_deleted` flips per version, so it's filtered post-collapse.- if parent_run_id is not None:- where.append("parent_run_id = %(parent_run_id)s")- kwargs["parent_run_id"] = parent_run_id- if action_id:- where.append("action_id = %(action_id)s")- kwargs["action_id"] = action_id- if invocation_id:- where.append("invocation_id = %(invocation_id)s")- kwargs["invocation_id"] = invocation_id- if distinct_id:- where.append("distinct_id = %(distinct_id)s")- kwargs["distinct_id"] = distinct_id- if search:- where.append("(recipient ILIKE %(search)s OR subject ILIKE %(search)s)")- kwargs["search"] = f"%{_escape_like(search)}%"- if after:- where.append("sent_at >= toDateTime64(%(after)s, 6)")- kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")- if before:- where.append("sent_at <= toDateTime64(%(before)s, 6)")- kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")-- # Sends can share a sent_at down to the millisecond. The (invocation_id, action_id) tiebreak gives- # them a stable order, so offset pages neither repeat a send nor skip one at a page boundary.- query = f"""- SELECT {_OUTER_COLUMNS}- FROM (- SELECT {_COLLAPSED_AGGREGATES}- FROM message_assets- WHERE {" AND ".join(where)}- GROUP BY invocation_id, action_id- )- WHERE latest_is_deleted = 0- ORDER BY latest_sent_at DESC, invocation_id, action_id- LIMIT %(limit)s OFFSET %(offset)s- """-- results = cast(list, sync_execute(query, kwargs))- return [_build_asset(row) for row in results]---def fetch_message_assets_for_person(- team_id: int,- person_id: str,- limit: int,- offset: int = 0,- after: Optional[datetime] = None,- before: Optional[datetime] = None,- kind: str = "email",-) -> list[MessageAsset]:- where = [- "team_id = %(team_id)s",- "person_id = %(person_id)s",- # Standalone hog_function email destinations aren't surfaced anywhere yet,- # so this endpoint only returns workflow-step rows.- "function_kind = 'hog_flow'",- # One channel per call. The person view shows email and push in separate tabs, each with- # columns shaped for its channel, so returning both from one call would misrepresent whichever- # tab it landed in.- "kind = %(kind)s",- ]- kwargs: dict[str, Any] = {- "team_id": team_id,- "person_id": person_id,- "kind": kind,- "limit": limit,- "offset": offset,- }- if after:- where.append("sent_at >= toDateTime64(%(after)s, 6)")- kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")- if before:- where.append("sent_at <= toDateTime64(%(before)s, 6)")- kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")-- query = f"""- SELECT {_OUTER_COLUMNS}- FROM (- SELECT {_COLLAPSED_AGGREGATES}- FROM message_assets- WHERE {" AND ".join(where)}- GROUP BY invocation_id, action_id- )- WHERE latest_is_deleted = 0- ORDER BY latest_sent_at DESC- LIMIT %(limit)s OFFSET %(offset)s- """-- results = cast(list, sync_execute(query, kwargs))- return [_build_asset(row) for row in results]---def fetch_message_asset_html(- team_id: int,- function_kind: str,- function_id: str,- invocation_id: str,- action_id: str,-) -> Optional[str]:- kwargs = {- "team_id": team_id,- "function_kind": function_kind,- "function_id": function_id,- "invocation_id": invocation_id,- "action_id": action_id,- }- # GROUP BY so a no-match query returns zero rows — a bare aggregate would- # return one default-valued row and the action would serve HTTP 200 + empty.- query = """- SELECT latest_html- FROM (- SELECT- argMax(html, version) AS latest_html,- argMax(is_deleted, version) AS latest_is_deleted- FROM message_assets- WHERE team_id = %(team_id)s- AND function_kind = %(function_kind)s- AND function_id = %(function_id)s- AND invocation_id = %(invocation_id)s- AND action_id = %(action_id)s- GROUP BY invocation_id, action_id- )- WHERE latest_is_deleted = 0- """-- results = cast(list, sync_execute(query, kwargs))- if not results:- return None- return results[0][0]diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.pyindex b84eb3a1f678..2040bcf0b3b3 100644--- a/products/workflows/backend/routes.py+++ b/products/workflows/backend/routes.py@@ -39,3 +39,8 @@ def register_routes(routers: RouterRegistry) -> None:"project_hog_flow_templates",["team_id"],)+ routers.root.register(+ r"public_hog_flow_templates",+ hog_flow_template.PublicHogFlowTemplateViewSet,+ "public_hog_flow_templates",+ )diff --git a/products/workflows/backend/services/message_assets.py b/products/workflows/backend/services/message_assets.pynew file mode 100644index 000000000000..bd3e6727bc8c--- /dev/null+++ b/products/workflows/backend/services/message_assets.py@@ -0,0 +1,218 @@+from datetime import UTC, datetime+from typing import Any, Optional, cast++from posthog.clickhouse.client.execute import sync_execute++from products.workflows.backend.facade.contracts import MessageAsset++# `latest_` prefix on the argMax aliases prevents collision with the raw column+# names in any outer WHERE - ClickHouse resolves the bare name to the aggregate+# and errors otherwise.+_COLLAPSED_AGGREGATES = """+ invocation_id,+ action_id,+ argMax(function_id, version) AS latest_function_id,+ argMax(parent_run_id, version) AS latest_parent_run_id,+ argMax(kind, version) AS latest_kind,+ argMax(distinct_id, version) AS latest_distinct_id,+ argMax(person_id, version) AS latest_person_id,+ argMax(recipient, version) AS latest_recipient,+ argMax(subject, version) AS latest_subject,+ argMax(status, version) AS latest_status,+ argMax(sent_at, version) AS latest_sent_at,+ argMax(is_deleted, version) AS latest_is_deleted+""".strip()++_OUTER_COLUMNS = """+ invocation_id,+ action_id,+ latest_function_id,+ latest_parent_run_id,+ latest_kind,+ latest_distinct_id,+ latest_person_id,+ latest_recipient,+ latest_subject,+ latest_status,+ latest_sent_at+""".strip()+++def _build_asset(row: tuple) -> MessageAsset:+ return MessageAsset(+ invocation_id=row[0],+ action_id=row[1],+ function_id=row[2],+ parent_run_id=row[3],+ kind=row[4],+ distinct_id=row[5],+ person_id=row[6],+ recipient=row[7],+ subject=row[8],+ status=row[9],+ sent_at=row[10],+ )+++def _escape_like(value: str) -> str:+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+++def fetch_message_assets(+ team_id: int,+ function_kind: str,+ function_id: str,+ limit: int,+ offset: int = 0,+ parent_run_id: Optional[str] = None,+ action_id: Optional[str] = None,+ invocation_id: Optional[str] = None,+ distinct_id: Optional[str] = None,+ search: Optional[str] = None,+ after: Optional[datetime] = None,+ before: Optional[datetime] = None,+) -> list[MessageAsset]:+ where = [+ "team_id = %(team_id)s",+ "function_kind = %(function_kind)s",+ "function_id = %(function_id)s",+ ]+ kwargs: dict[str, Any] = {+ "team_id": team_id,+ "function_kind": function_kind,+ "function_id": function_id,+ "limit": limit,+ "offset": offset,+ }++ # Filter stable-across-versions fields pre-aggregation to hit the bloom-filter+ # skip indexes. `is_deleted` flips per version, so it's filtered post-collapse.+ if parent_run_id is not None:+ where.append("parent_run_id = %(parent_run_id)s")+ kwargs["parent_run_id"] = parent_run_id+ if action_id:+ where.append("action_id = %(action_id)s")+ kwargs["action_id"] = action_id+ if invocation_id:+ where.append("invocation_id = %(invocation_id)s")+ kwargs["invocation_id"] = invocation_id+ if distinct_id:+ where.append("distinct_id = %(distinct_id)s")+ kwargs["distinct_id"] = distinct_id+ if search:+ where.append("(recipient ILIKE %(search)s OR subject ILIKE %(search)s)")+ kwargs["search"] = f"%{_escape_like(search)}%"+ if after:+ where.append("sent_at >= toDateTime64(%(after)s, 6)")+ kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if before:+ where.append("sent_at <= toDateTime64(%(before)s, 6)")+ kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")++ # Sends can share a sent_at down to the millisecond. The (invocation_id, action_id) tiebreak gives+ # them a stable order, so offset pages neither repeat a send nor skip one at a page boundary.+ query = f"""+ SELECT {_OUTER_COLUMNS}+ FROM (+ SELECT {_COLLAPSED_AGGREGATES}+ FROM message_assets+ WHERE {" AND ".join(where)}+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ ORDER BY latest_sent_at DESC, invocation_id, action_id+ LIMIT %(limit)s OFFSET %(offset)s+ """++ results = cast(list, sync_execute(query, kwargs))+ return [_build_asset(row) for row in results]+++def fetch_message_assets_for_person(+ team_id: int,+ person_id: str,+ limit: int,+ offset: int = 0,+ after: Optional[datetime] = None,+ before: Optional[datetime] = None,+ kind: str = "email",+) -> list[MessageAsset]:+ where = [+ "team_id = %(team_id)s",+ "person_id = %(person_id)s",+ # Standalone hog_function email destinations aren't surfaced anywhere yet,+ # so this endpoint only returns workflow-step rows.+ "function_kind = 'hog_flow'",+ # One channel per call. The person view shows email and push in separate tabs, each with+ # columns shaped for its channel, so returning both from one call would misrepresent whichever+ # tab it landed in.+ "kind = %(kind)s",+ ]+ kwargs: dict[str, Any] = {+ "team_id": team_id,+ "person_id": person_id,+ "kind": kind,+ "limit": limit,+ "offset": offset,+ }+ if after:+ where.append("sent_at >= toDateTime64(%(after)s, 6)")+ kwargs["after"] = after.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")+ if before:+ where.append("sent_at <= toDateTime64(%(before)s, 6)")+ kwargs["before"] = before.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S")++ query = f"""+ SELECT {_OUTER_COLUMNS}+ FROM (+ SELECT {_COLLAPSED_AGGREGATES}+ FROM message_assets+ WHERE {" AND ".join(where)}+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ ORDER BY latest_sent_at DESC+ LIMIT %(limit)s OFFSET %(offset)s+ """++ results = cast(list, sync_execute(query, kwargs))+ return [_build_asset(row) for row in results]+++def fetch_message_asset_html(+ team_id: int,+ function_kind: str,+ function_id: str,+ invocation_id: str,+ action_id: str,+) -> Optional[str]:+ kwargs = {+ "team_id": team_id,+ "function_kind": function_kind,+ "function_id": function_id,+ "invocation_id": invocation_id,+ "action_id": action_id,+ }+ # GROUP BY so a no-match query returns zero rows - a bare aggregate would+ # return one default-valued row and the action would serve HTTP 200 + empty.+ query = """+ SELECT latest_html+ FROM (+ SELECT+ argMax(html, version) AS latest_html,+ argMax(is_deleted, version) AS latest_is_deleted+ FROM message_assets+ WHERE team_id = %(team_id)s+ AND function_kind = %(function_kind)s+ AND function_id = %(function_id)s+ AND invocation_id = %(invocation_id)s+ AND action_id = %(action_id)s+ GROUP BY invocation_id, action_id+ )+ WHERE latest_is_deleted = 0+ """++ results = cast(list, sync_execute(query, kwargs))+ if not results:+ return None+ return results[0][0]