Skip to content

: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.

feat(workflows): read an applied suggestion's outcome per published version (#107879)

Daniel Marchuk6a483773cf00
diff --git a/products/workflows/CONTRIBUTING.md b/products/workflows/CONTRIBUTING.md
index 45a376779c4a..4e7ad1296a5d 100644
--- a/products/workflows/CONTRIBUTING.md
+++ b/products/workflows/CONTRIBUTING.md
@@ -316,9 +316,10 @@ The versioned series is always keyed by the **flow**, even where the version-agn
Batch and broadcast runs put the run id in `app_source_id` so per-run views group by the run, but a per-version rollup has to key on the flow itself — otherwise every run of a broadcast mints a fresh key and its versions never aggregate.
So `hog_flow` reads stay exactly as they are, and `hog_flow_version` is always `<flow id>/<version>`.
-Nothing reads the versioned series yet.
-`/metrics` and `/metrics/totals` always return the version-agnostic one, and adding a filter to them is the natural next step.
-Until then, query it directly in HogQL, where the table is exposed as `app_metrics` (the HogQL name maps to the `app_metrics2` table; raw ClickHouse separately has a deprecated v1 table literally named `app_metrics`):
+`/metrics` and `/metrics/totals` read the versioned series when you pass `?version=<n>`, and the version-agnostic one otherwise.
+Because batch and broadcast runs key the version-agnostic rows on the run, a version's numbers are not a subset of the unversioned read: compare versions with each other.
+Any other metrics endpoint answers `?version=` with a 400, since nothing mirrors hog function metrics per version.
+To query the series directly, HogQL exposes the table as `app_metrics` (the HogQL name maps to the `app_metrics2` table; raw ClickHouse separately has a deprecated v1 table literally named `app_metrics`):
```sql
SELECT metric_name, sum(count)
diff --git a/products/workflows/backend/metrics.py b/products/workflows/backend/metrics.py
index 49932580ffbb..b5a6896589fb 100644
--- a/products/workflows/backend/metrics.py
+++ b/products/workflows/backend/metrics.py
@@ -24,6 +24,16 @@ TARGET_UNTRACKED_METRIC = "email_untracked"
GUARDRAIL_METRICS = ("email_blocked", "email_bounced")
GUARDRAIL_LABELS = {"email_blocked": "complaint rate", "email_bounced": "bounce rate"}
+# What a suggestion can aim at, and how each one is read: the metric counted, whether it divides by
+# tracked sends (an untracked send can record neither an open nor a click) or by every send, and the
+# name a person reads. A suggestion that names anything else is measured on opens, the default.
+TARGET_METRICS: dict[str, tuple[str, bool, str]] = {
+ TARGET_OPEN_METRIC: (TARGET_OPEN_METRIC, True, "email open rate"),
+ TARGET_CLICK_METRIC: (TARGET_CLICK_METRIC, True, "click rate"),
+ "email_bounced": ("email_bounced", False, "bounce rate"),
+ "email_blocked": ("email_blocked", False, "complaint rate"),
+}
+
# `email_unsubscribed` exists only as a name in the worker's metric union with no producer. Named so
# the surfaces can say the number is missing rather than imply a zero.
UNAVAILABLE_GUARDRAILS = ("unsubscribe rate",)
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index e0a58615623e..665338cff401 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -4,7 +4,7 @@ import json
import uuid as uuid_mod
import hashlib
import dataclasses
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from copy import deepcopy
from datetime import datetime, timedelta
from time import monotonic
@@ -49,10 +49,14 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.parser import parse_expr
from posthog.api.app_metrics2 import (
+ AppMetricResponseSerializer,
AppMetricsMixin,
+ AppMetricsRequestSerializer,
+ AppMetricsTotalsResponseSerializer,
fetch_app_metric_totals,
fetch_app_metric_totals_by_source,
fetch_app_metric_totals_by_team_and_source,
+ fetch_app_metrics_trends,
)
from posthog.api.documentation import _FallbackSerializer
from posthog.api.hog_invocation_cancel import (
@@ -157,6 +161,7 @@ from products.workflows.backend.metrics import (
HOG_FLOW_VERSION_APP_SOURCE,
MIN_EVIDENCE_SAMPLE,
TARGET_CLICK_METRIC,
+ TARGET_METRICS,
TARGET_OPEN_METRIC,
TARGET_SEND_METRIC,
TARGET_UNTRACKED_METRIC,
@@ -3729,9 +3734,7 @@ class WorkflowProposalEvidenceField(serializers.JSONField):
class HogFlowOptimizationSerializer(serializers.Serializer):
- enabled = serializers.BooleanField(
- help_text="Whether PostHog may read this workflow's metrics and suggest changes to it."
- )
+ enabled = serializers.BooleanField(help_text="Whether PostHog may suggest changes to this workflow.")
class WorkflowProposalSerializer(serializers.ModelSerializer):
@@ -3741,7 +3744,7 @@ class WorkflowProposalSerializer(serializers.ModelSerializer):
is_stale = serializers.SerializerMethodField(
help_text=(
"Whether approving this would undo an edit made since it was proposed. False while the "
- "workflow only changed elsewhere, because approving merges per step."
+ "workflow only changed elsewhere, because approving merges only what the proposal changes."
)
)
@@ -3793,12 +3796,11 @@ class WorkflowProposalCreateSerializer(serializers.Serializer):
help_text="The metric numbers behind the proposal, so a human can judge it without re-deriving them.",
)
base_version = serializers.IntegerField(
- required=False,
+ min_value=1,
help_text=(
- "Workflow version this was authored against. Required when the proposal changes actions, "
- "edges or variables: it is the snapshot approve compares against to tell whether someone "
- "edited the same steps since, and a defaulted version would read as current however long "
- "the producer took. Defaults to the current live version otherwise."
+ "Workflow version this was authored against, as read from the workflow. It is the snapshot "
+ "approve compares against to tell whether someone edited the same steps or fields since, "
+ "and a defaulted version would read as current however long the producer took."
),
)
step_id = serializers.CharField(
@@ -3823,8 +3825,14 @@ class WorkflowProposalCreateSerializer(serializers.Serializer):
)
def validate_evidence(self, value: Any) -> dict:
- if not isinstance(value, dict) or not value:
- return value or {}
+ if value is None:
+ return {}
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError(
+ "Send `evidence` as an object whose fields name the metric and its reading, not a bare value."
+ )
+ if not value:
+ return {}
# The panel reads these back by name; a producer's own key would render as "no data".
if not isinstance(value.get("metric"), str) or not value["metric"].strip():
raise exceptions.ValidationError(
@@ -3878,21 +3886,6 @@ class WorkflowProposalCreateSerializer(serializers.Serializer):
_validate_merge_keys(field, value.get(field))
return value
- def validate(self, attrs: dict) -> dict:
- changes_the_graph = any(
- field in attrs.get("content", {}) for field in (*PROPOSAL_WHOLE_LIST_FIELDS, *PROPOSAL_MERGE_BY_ID_FIELDS)
- )
- if changes_the_graph and attrs.get("base_version") is None:
- raise exceptions.ValidationError(
- {
- "base_version": (
- "Send the workflow version you read, so approving this can tell whether the "
- "workflow moved on while you were writing it."
- )
- }
- )
- return attrs
-
class WorkflowProposalApproveRequestSerializer(serializers.Serializer):
overwrite = serializers.BooleanField(
@@ -3934,9 +3927,43 @@ class WorkflowProposalMetricSerializer(serializers.Serializer):
)
+class WorkflowVersionChangeSerializer(serializers.Serializer):
+ step_name = serializers.CharField(
+ allow_null=True, help_text="Step the field belongs to, or null for a workflow field."
+ )
+ field = serializers.CharField(help_text="What changed, as a person reads it, e.g. 'email > subject'.")
+ before = serializers.CharField(allow_null=True, help_text="Value in the version before this one.")
+ after = serializers.CharField(allow_null=True, help_text="Value this version published.")
+ from_suggestion = serializers.BooleanField(help_text="Whether the suggestion is what changed this field.")
+
+
class WorkflowProposalVersionOutcomeSerializer(serializers.Serializer):
version = serializers.IntegerField(help_text="Workflow version these numbers belong to.")
+ applied = serializers.BooleanField(required=False, help_text="Whether the suggestion went live as this version.")
+ proposed_against = serializers.BooleanField(
+ required=False, help_text="Whether the suggestion was written against this version."
+ )
+ carries_change = serializers.BooleanField(
+ required=False, help_text="Whether this version still holds what the suggestion changed."
+ )
+ other_changes = serializers.BooleanField(
+ required=False,
+ help_text="Whether this version also changed something the suggestion did not, which the numbers cannot separate.",
+ )
+ changes = WorkflowVersionChangeSerializer(
+ many=True, required=False, help_text="What this version changed against the version before it."
+ )
+ published_at = serializers.DateTimeField(allow_null=True, required=False, help_text="When this version went live.")
+ published_by = UserBasicSerializer(allow_null=True, required=False, help_text="Who published this version.")
+ versions = serializers.ListField(
+ child=serializers.IntegerField(),
+ required=False,
+ help_text="Every version summed into these numbers. The after side runs on while later versions keep the change.",
+ )
target = WorkflowProposalMetricSerializer(help_text="The metric the suggestion aimed at.")
+ secondary = WorkflowProposalMetricSerializer(
+ required=False, help_text="The rate read beside the target, so a lift in one is visible against the other."
+ )
click_through = WorkflowProposalMetricSerializer(
help_text="Click-through rate over the same window and denominator, since opens alone can move without clicks."
)
@@ -3946,12 +3973,22 @@ class WorkflowProposalVersionOutcomeSerializer(serializers.Serializer):
class WorkflowProposalOutcomeSerializer(serializers.Serializer):
- window = serializers.CharField(help_text="Relative window both sides were measured over.")
+ versions = WorkflowProposalVersionOutcomeSerializer(
+ many=True,
+ help_text=(
+ "Every published version around the change, each read over its own time live, so a later edit shows up "
+ "as its own point rather than ending the comparison."
+ ),
+ )
before = WorkflowProposalVersionOutcomeSerializer(
allow_null=True, help_text="The version the change was proposed against."
)
after = WorkflowProposalVersionOutcomeSerializer(
- allow_null=True, help_text="The version it went live as. Null until the proposal is applied."
+ allow_null=True, help_text="The versions that carried the change. Null until the proposal is applied."
+ )
+ change_ended_at_version = serializers.IntegerField(
+ allow_null=True,
+ help_text="The version that changed what the suggestion changed, which is where the after side stops. Null while the change is still live.",
)
unavailable_guardrails = serializers.ListField(
child=serializers.CharField(),
@@ -3980,6 +4017,12 @@ class ProposalNotRunnableError(exceptions.APIException):
super().__init__(detail)
+class WorkflowNotLiveError(exceptions.APIException):
+ status_code = status.HTTP_409_CONFLICT
+ default_detail = "Suggestions need a live workflow. Enable it first."
+ default_code = "workflow_not_live"
+
+
class WorkflowNotOptimisedError(exceptions.APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = (
@@ -3993,7 +4036,7 @@ class ProposalOutOfDateError(exceptions.APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = (
"Someone changed this workflow where the suggestion changes it, so approving it would undo "
- "their edit. Ask for a fresh suggestion."
+ "their edit. Reject it, and the scout can suggest again from the current version on its next run."
)
default_code = "proposal_out_of_date"
@@ -4004,6 +4047,13 @@ class ProposalOutOfDateError(exceptions.APIException):
super().__init__(detail)
+# How far past the applied version the after side will look for versions that kept the change.
+OUTCOME_VERSION_LIMIT = 20
+
+# Written by the serializer on publish, not by whoever edited the workflow.
+DERIVED_STEP_KEYS = frozenset({"bytecode", "order", "transpiled"})
+
+
def merge_proposal_content(live_content: dict, proposal_content: dict) -> dict:
"""Live content with the proposal applied. Whole-list fields replace; `actions` merges per step
and, within a step, per field, so a proposal that rewrites one subject line leaves the rest of
@@ -4051,7 +4101,8 @@ def _validate_merge_keys(field: str, items: Any) -> None:
def describe_steps(hog_flow: HogFlow, step_ids: list[str]) -> list[str]:
- """Step names for a person to read. A step deleted since has no name left, so it keeps its id."""
+ """Step names for a person to read. A step deleted since has no name left, so it keeps its id,
+ and a field name is already readable."""
names = {_item_id(item): item.get("name") for item in snapshot_flow_content(hog_flow).get("actions") or []}
return [names.get(step_id) or step_id for step_id in step_ids]
@@ -4138,6 +4189,160 @@ def proposal_changes(proposal: WorkflowProposal, base_content: dict | None) -> d
_ABSENT = object()
+# Wrapper keys every step input carries. A person reads "email > subject", not the path to it.
+SILENT_PATH_SEGMENTS = frozenset({"config", "inputs", "value"})
+
+# Long bodies and HTML would drown the list; the field name plus a taste of the value is the point.
+CHANGE_VALUE_LIMIT = 120
+
+
+def _describe_value(value: Any) -> Optional[str]:
+ if value is _ABSENT or value is None:
+ return None
+ text = value if isinstance(value, str) else json.dumps(value, default=str)
+ return text if len(text) <= CHANGE_VALUE_LIMIT else f"{text[:CHANGE_VALUE_LIMIT]}…"
+
+
+def _describe_path(path: Sequence[str]) -> str:
+ spoken = [segment for segment in path if segment not in SILENT_PATH_SEGMENTS]
+ return " › ".join(spoken or list(path))
+
+
+# `trigger` is derived from the trigger action, so a change to it already reads as a step change.
+# Counting it again at workflow level reads as an edit nobody made.
+DERIVED_WORKFLOW_FIELDS = frozenset({"trigger"})
+
+
+def describe_version_changes(previous: dict, current: dict, proposed: Mapping) -> list[dict]:
+ """Every field this version published differently from the one before it.
+
+ Derived keys are skipped: publishing recompiles inputs, and nobody edited those.
+ """
+
+ def from_suggestion(key: tuple, value: Any) -> bool:
+ # Membership first: a cleared field reads as absent, and so does a field the proposal never
+ # named, so comparing values alone calls an unrelated clear a suggested change.
+ return key in proposed and proposed[key] == value
+
+ changes: list[dict] = []
+ was_steps = {_item_id(item): item for item in previous.get("actions") or []}
+ now_steps = {_item_id(item): item for item in current.get("actions") or []}
+ for step in current.get("actions") or []:
+ step_id = _item_id(step)
+ was = was_steps.get(step_id)
+ if was is None:
+ changes.append(
+ {
+ "step_name": step.get("name") or step_id,
+ "field": "step added",
+ "before": None,
+ "after": _describe_value(step.get("type")),
+ "from_suggestion": any(key[0] == step_id for key in proposed),
+ }
+ )
+ continue
+ paths = {
+ path
+ for item in (step, was)
+ for path in _patch_paths({key: value for key, value in item.items() if key != "id"})
+ }
+ for path in sorted(paths):
+ if path[-1] in DERIVED_STEP_KEYS:
+ continue
+ after, before = _leaf(step, path), _leaf(was, path)
+ if after == before:
+ continue
+ changes.append(
+ {
+ "step_name": step.get("name") or step_id,
+ "field": _describe_path(path),
+ "before": _describe_value(before),
+ "after": _describe_value(after),
+ "from_suggestion": from_suggestion((step_id, path), after),
+ }
+ )
+ for step_id, was in was_steps.items():
+ if step_id in now_steps:
+ continue
+ changes.append(
+ {
+ "step_name": was.get("name") or step_id,
+ "field": "step removed",
+ "before": _describe_value(was.get("type")),
+ "after": None,
+ "from_suggestion": False,
+ }
+ )
+ for field in sorted({*current, *previous}):
+ if field in PROPOSAL_MERGE_BY_ID_FIELDS or field in DERIVED_WORKFLOW_FIELDS:
+ continue
+ value, before = current.get(field, _ABSENT), previous.get(field, _ABSENT)
+ if value == before:
+ continue
+ changes.append(
+ {
+ "step_name": None,
+ "field": _describe_path([field]),
+ "before": _describe_value(before),
+ "after": _describe_value(value),
+ "from_suggestion": from_suggestion((None, (field,)), value),
+ }
+ )
+ return changes
+
+
+def target_metric_of(proposal: WorkflowProposal) -> str:
+ """The metric the suggestion aimed at. Anything the surfaces cannot read is measured on opens."""
+ named = (proposal.evidence or {}).get("metric") if isinstance(proposal.evidence, dict) else None
+ return named if named in TARGET_METRICS else TARGET_OPEN_METRIC
+
+
+def _outcome_from_totals(totals: Mapping[str, float], version: int, target: str = TARGET_OPEN_METRIC) -> dict:
+ sends = int(totals.get(TARGET_SEND_METRIC, 0))
+ # Untracked sends can never record an open, so opens read against tracked sends; guardrails keep every send.
+ tracked_sends = max(0, sends - int(totals.get(TARGET_UNTRACKED_METRIC, 0)))
+
+ def rate(count: int, label: str, denominator: int) -> dict:
+ return {
+ "metric": label,
+ "value": (count / denominator) if denominator else None,
+ "n": denominator,
+ "below_minimum_sample": denominator < MIN_EVIDENCE_SAMPLE,
+ }
+
+ def reading(metric: str) -> dict:
+ name, over_tracked, label = TARGET_METRICS[metric]
+ return rate(int(totals.get(name, 0)), label, tracked_sends if over_tracked else sends)
+
+ # The rate to read beside the target: opens, unless opens are the target.
+ secondary = TARGET_CLICK_METRIC if target == TARGET_OPEN_METRIC else TARGET_OPEN_METRIC
+ return {
+ "version": version,
+ "versions": [version],
+ "target": reading(target),
+ "secondary": reading(secondary),
+ # Same denominator as opens: a send with tracking off can record neither.
+ "click_through": reading(TARGET_CLICK_METRIC),
+ "guardrails": [rate(int(totals.get(name, 0)), GUARDRAIL_LABELS[name], sends) for name in GUARDRAIL_METRICS],
+ }
+
+
+def carries_proposal_change(content: dict, changes: dict) -> bool:
+ """Whether this published content still holds every value the proposal set."""
+ steps = {_item_id(item): item for item in content.get("actions") or []}
+ for item in changes.get("actions") or []:
+ step = steps.get(_item_id(item))
+ patch = {key: value for key, value in item.items() if key != "id"}
+ if step is None or _changed_leaves(step, patch) is not _ABSENT:
+ return False
+ for field, value in changes.items():
+ if field in PROPOSAL_MERGE_BY_ID_FIELDS:
+ continue
+ if _changed_leaves(content.get(field), value) is not _ABSENT:
+ return False
+ return True
+
+
def _changed_leaves(base: Any, patch: Any) -> Any:
"""`patch` without every leaf that already reads the same in `base`, read the way `_deep_merge`
writes it; `_ABSENT` when nothing is left."""
@@ -4180,19 +4385,60 @@ def _leaf(item: Any, path: tuple[str, ...]) -> Any:
return _ABSENT if item is None else item
+def _as_the_serializer_stores_it(content: dict, validated: Mapping) -> dict:
+ """The proposal's own values, in the shape a publish would write them.
+
+ A field validator can rewrite what a producer sent: a bare `output_variable` string is stored as
+ `{"key": ...}`. The published workflow then holds the rewritten shape, so a raw value kept here
+ would make every later comparison read the change as already gone.
+ """
+ aligned = deepcopy(content)
+ validated_steps = {_item_id(item): item for item in validated.get("actions") or []}
+ for item in aligned.get("actions") or []:
+ step = validated_steps.get(_item_id(item))
+ if step is None:
+ continue
+ for path in _patch_paths({key: value for key, value in item.items() if key != "id"}):
+ stored = _leaf(step, path)
+ if stored is not _ABSENT:
+ _write_leaf(item, path, stored)
+ for field in list(aligned):
+ if field in PROPOSAL_MERGE_BY_ID_FIELDS or field not in validated:
+ continue
+ aligned[field] = validated[field]
+ return aligned
+
+
+def _write_leaf(item: dict, path: tuple[str, ...], value: Any) -> None:
+ for key in path[:-1]:
+ nested = item.get(key)
+ if not isinstance(nested, dict):
+ return
+ item = nested
+ item[path[-1]] = value
+
+
def unstage_workflow_proposals(hog_flow: HogFlow) -> None:
- """Put every approved suggestion back in the queue, because the draft it was approved into is
- about to be replaced.
-
- Approved means one thing here: this suggestion is what sits in the draft. Discarding the draft,
- restoring a revision, approving a different suggestion or editing over it all replace that
- draft, and publish reads approved as "this is what shipped", so it must not record one against
- a version that never carried it. A suggestion whose change survives the replacement comes back
- to the queue too, which costs a person one more approval rather than a wrong history entry.
+ """Put back in the queue any approved suggestion whose change the draft no longer carries.
+
+ Approved means one thing here: this suggestion's change sits in the draft. Discarding the draft,
+ restoring a revision, approving a different suggestion or editing over the draft can take that
+ change out again, so the suggestion is pending again - and publish, which reads approved as
+ "this is what shipped", must not record it as applied against a version that never carried it.
+ An edit that leaves the change in place, elsewhere on the same step or not, changes nothing here.
"""
- WorkflowProposal.objects.filter(hog_flow=hog_flow, status=WorkflowProposal.Status.APPROVED).update(
- status=WorkflowProposal.Status.SUGGESTED, resolved_at=None, resolved_by=None
- )
+ approved = WorkflowProposal.objects.filter(hog_flow=hog_flow, status=WorkflowProposal.Status.APPROVED)
+ draft = hog_flow.draft
+ gone = [
+ proposal.id
+ for proposal in approved
+ if draft is None
+ or merge_proposal_content(draft, proposal_changes(proposal, base_content_of(hog_flow, proposal))) != draft
+ ]
+ if gone:
+ WorkflowProposal.objects.filter(team_id=hog_flow.team_id, id__in=gone).update(
+ status=WorkflowProposal.Status.SUGGESTED, resolved_at=None, resolved_by=None
+ )
class CommaSeparatedListFilter(BaseInFilter, CharFilter):
@@ -4336,7 +4582,7 @@ class HogFlowFilterSet(FilterSet):
# Off keeps its row, so "on" is a row still enabled. Archived workflows drop out: nothing runs there.
if not value:
return queryset.exclude(optimization__enabled=True)
- return queryset.filter(optimization__enabled=True).exclude(status=HogFlow.State.ARCHIVED)
+ return queryset.filter(optimization__enabled=True, status=HogFlow.State.ACTIVE)
class HogFlowPagination(LimitOffsetPagination):
@@ -4445,8 +4691,25 @@ def mint_audience_confirm_token(
WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogFlowSerializer.Meta.read_only_fields)
+class HogFlowVersionMetricsRequestSerializer(AppMetricsRequestSerializer):
+ """The versioned metrics request: the shared parameters plus the version to read."""
+
+ version = serializers.IntegerField(
+ required=True,
+ help_text=(
+ "Read one workflow version's series: every run of that version, keyed on the workflow. "
+ "The unversioned read keys batch and broadcast runs on the run instead, so it is not the "
+ "sum of the versions; compare versions with each other, not with it."
+ ),
+ )
+
+
@extend_schema(extensions={"x-product": "workflows"})
@extend_schema_view(
+ metrics=extend_schema(parameters=[AppMetricsRequestSerializer], responses=AppMetricResponseSerializer),
+ metrics_totals=extend_schema(
+ parameters=[AppMetricsRequestSerializer], responses=AppMetricsTotalsResponseSerializer
+ ),
list=extend_schema(
parameters=[
OpenApiParameter(
@@ -4490,7 +4753,7 @@ WRITABLE_DRAFT_CONTENT_FIELDS = frozenset(DRAFT_CONTENT_FIELDS) - frozenset(HogF
),
),
]
- )
+ ),
)
class HogFlowViewSet(
TeamAndOrgViewSetMixin, AccessControlViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet
@@ -4501,6 +4764,7 @@ class HogFlowViewSet(
"retrieve",
"logs",
"metrics",
+ "metrics_version",
"metrics_totals",
"metrics_global",
"team_reputation",
@@ -4543,6 +4807,37 @@ class HogFlowViewSet(
function_kind = "hog_flow"
_workflow_last_runs: dict[uuid_mod.UUID, WorkflowLastRunDTO] | None = None
+ @extend_schema(parameters=[HogFlowVersionMetricsRequestSerializer], responses=AppMetricResponseSerializer)
+ @action(detail=True, methods=["GET"], url_path="metrics/version")
+ def metrics_version(self, request: Request, *args, **kwargs):
+ """One published version's series. Every hog flow metric is mirrored under
+ `hog_flow_version` with the version appended to the id, which is what makes "before and
+ after this change" answerable at all. The unversioned read keys batch and broadcast runs on
+ the run instead, so it is not the sum of the versions."""
+ hog_flow = self.get_object()
+ param_serializer = HogFlowVersionMetricsRequestSerializer(data=request.query_params)
+ param_serializer.is_valid(raise_exception=True)
+ params = param_serializer.validated_data
+
+ tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
+
+ after_date, _, _ = relative_date_parse_with_delta_mapping(params.get("after", "-7d"), self.team.timezone_info)
+ before_date, _, _ = relative_date_parse_with_delta_mapping(params.get("before", "-0d"), self.team.timezone_info)
+
+ data = fetch_app_metrics_trends(
+ team_id=self.team_id,
+ app_source=HOG_FLOW_VERSION_APP_SOURCE,
+ app_source_id=f"{hog_flow.id}/{params['version']}",
+ instance_id=params.get("instance_id"),
+ interval=params.get("interval", "day"),
+ after=after_date,
+ before=before_date,
+ breakdown_by=params.get("breakdown_by"),
+ name=params["name"].split(",") if params.get("name") else None,
+ kind=params["kind"].split(",") if params.get("kind") else None,
+ )
+ return Response(AppMetricResponseSerializer(instance=data).data)
+
def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:
# Dual-method custom actions need method-aware scopes — the action-name-based read/write
# lists above can't distinguish GET (read) from POST (write) on the same action. Without
@@ -4553,10 +4848,11 @@ class HogFlowViewSet(
return ["hog_flow:read"]
return ["hog_flow:write"]
if self.action == "proposals":
- # Reading is workflow-read; authoring stages content into the draft, so it is a workflow write.
+ # Listing is workflow-read. Authoring takes its own narrow scope, so a producer can suggest without
+ # being able to publish.
if request.method in ("GET", "HEAD", "OPTIONS"):
return ["hog_flow:read"]
- return ["hog_flow:write"]
+ return ["hog_flow_proposal:write"]
if self.action in ("batch_jobs", "schedules"):
# Dispatching (or scheduling) fans out to persons and renders person properties into
# outbound messages, so it's person-data access on top of the workflow write - same
@@ -5725,7 +6021,17 @@ class HogFlowViewSet(
if retry_of:
return Response(WorkflowProposalSerializer(retry_of).data, status=status.HTTP_200_OK)
+ # A version the workflow has not reached names nothing, and the outcome read spans versions.
+ if params["base_version"] > (instance.version or 1):
+ raise exceptions.ValidationError(
+ {
+ "base_version": f"This workflow is on version {instance.version or 1}, so there is nothing later to read."
+ }
+ )
+
# Reading the queue stays open while the flag is on; the workflow's opt-in only gates producing a new one.
+ if instance.status != HogFlow.State.ACTIVE:
+ raise WorkflowNotLiveError()
if not HogFlowOptimization.objects.filter(hog_flow=instance, enabled=True).exists():
raise WorkflowNotOptimisedError()
@@ -5749,15 +6055,41 @@ class HogFlowViewSet(
]
}
)
+ # Publish revalidates the draft with the workflow serializer; run it here, where the producer can fix what it refuses.
+ # Validation recovers stored secrets into the inputs it is given, and the merge shares
+ # the dicts of steps the proposal adds, so a shallow copy would leak a draft secret.
+ draft_serializer = self.get_serializer(instance, data=deepcopy(merged), partial=True)
+ if not draft_serializer.is_valid():
+ raise exceptions.ValidationError(
+ {
+ "content": [
+ "Publishing this change would be refused, so it cannot be suggested as it is.",
+ *_flatten_graph_errors(serializers.ValidationError(dict(draft_serializer.errors))),
+ ]
+ }
+ )
+ content = _as_the_serializer_stores_it(content, draft_serializer.validated_data)
+
+ step_id = params.get("step_id") or None
+ if step_id:
+ # The reading and the outcome are keyed on this step, so it has to exist.
+ known_steps = {_item_id(item) for item in snapshot_flow_content(instance).get("actions") or []}
+ added_steps = {_item_id(item) for item in content.get("actions") or []}
+ if step_id not in known_steps and step_id not in added_steps:
+ raise exceptions.ValidationError(
+ {"step_id": "Name a step this workflow has, or one the suggestion adds."}
+ )
+
+ evidence = dict(params.get("evidence") or {})
proposal = WorkflowProposal(
hog_flow=instance,
title=params["title"],
rationale=params["rationale"],
content=content,
- evidence=params.get("evidence") or {},
- step_id=params.get("step_id") or None,
- base_version=params.get("base_version") or instance.version or 1,
+ evidence=evidence,
+ step_id=step_id,
+ base_version=params["base_version"],
source_id=source_id,
)
try:
@@ -5880,7 +6212,6 @@ class HogFlowViewSet(
OpenApiParameter(
"proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to read outcomes for."
),
- OpenApiParameter("window", OpenApiTypes.STR, description="Relative window, e.g. -7d. Defaults to -7d."),
],
responses={200: WorkflowProposalOutcomeSerializer},
)
@@ -5902,63 +6233,187 @@ class HogFlowViewSet(
self._require_self_optimising_enabled()
instance = self.get_object()
proposal = self._get_proposal_or_404(instance, proposal_id)
- window = request.query_params.get("window") or "-7d"
- after_date, _, _ = relative_date_parse_with_delta_mapping(window, self.team.timezone_info)
- # Both reads below go to ClickHouse, which refuses an untagged query.
+ # The read below goes to ClickHouse, which refuses an untagged query.
tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
+ carrying, ended_at = self._versions_carrying_change(instance, proposal)
+ charted = self._outcome_versions(instance, proposal, carrying)
+ totals = self._version_totals(instance, charted, proposal.step_id)
+ history = self._version_history(instance, proposal, charted)
+ target = target_metric_of(proposal)
+ versions = [
+ {
+ **_outcome_from_totals(counts, version, target),
+ "applied": version == proposal.applied_version,
+ "proposed_against": version == proposal.base_version,
+ "carries_change": version in carrying,
+ **history.get(version, {"other_changes": False, "changes": []}),
+ }
+ for version, counts in sorted(totals.items())
+ ]
+ after_totals: dict[str, float] = {}
+ for version in carrying:
+ for name, count in totals.get(version, {}).items():
+ after_totals[name] = after_totals.get(name, 0) + count
return Response(
WorkflowProposalOutcomeSerializer(
{
- "window": window,
- "before": self._version_outcome(instance, proposal.base_version, after_date, proposal.step_id),
- "after": self._version_outcome(instance, proposal.applied_version, after_date, proposal.step_id),
+ "versions": versions,
+ "before": _outcome_from_totals(
+ totals.get(proposal.base_version, {}), proposal.base_version, target
+ ),
+ "after": (
+ {**_outcome_from_totals(after_totals, carrying[0], target), "versions": carrying}
+ if carrying
+ else None
+ ),
+ "change_ended_at_version": ended_at,
"unavailable_guardrails": list(UNAVAILABLE_GUARDRAILS),
}
).data
)
- def _version_outcome(
- self, hog_flow: HogFlow, version: Optional[int], after: Any, step_id: Optional[str] = None
- ) -> Optional[dict]:
- if version is None:
- return None
- # Scoped to the step the suggestion names; several email steps would otherwise share one denominator.
- totals = fetch_app_metric_totals(
- team_id=self.team_id,
- app_source=HOG_FLOW_VERSION_APP_SOURCE,
- app_source_id=f"{hog_flow.id}/{version}",
- breakdown_by="name",
- after=after,
- instance_id=step_id or None,
- name=[
- TARGET_SEND_METRIC,
- TARGET_OPEN_METRIC,
- TARGET_CLICK_METRIC,
- TARGET_UNTRACKED_METRIC,
- *GUARDRAIL_METRICS,
- ],
- ).totals
- sends = int(totals.get(TARGET_SEND_METRIC, 0))
- # Untracked sends can never record an open, so opens read against tracked sends; guardrails keep every send.
- tracked_sends = max(0, sends - int(totals.get(TARGET_UNTRACKED_METRIC, 0)))
-
- def rate(count: int, label: str, denominator: int) -> dict:
- return {
- "metric": label,
- "value": (count / denominator) if denominator else None,
- "n": denominator,
- "below_minimum_sample": denominator < MIN_EVIDENCE_SAMPLE,
+ def _outcome_versions(
+ self, hog_flow: HogFlow, proposal: WorkflowProposal, carrying: Sequence[int] = ()
+ ) -> list[int]:
+ """The versions the card charts: the one the suggestion was written against, the one it went
+ live as, and everything published since, so a later edit is visible as its own point.
+
+ A version the after side sums is always in here. Past the recent range it would otherwise be
+ fetched for nobody and counted as zero, which reads as a change that stopped working.
+ """
+ newest = hog_flow.version or proposal.base_version
+ oldest = min(proposal.base_version, proposal.applied_version or proposal.base_version)
+ pinned = {oldest, proposal.base_version, *carrying}
+ if proposal.applied_version is not None:
+ pinned.add(proposal.applied_version)
+ return sorted({*range(max(oldest, newest - OUTCOME_VERSION_LIMIT + 1), newest + 1), *pinned})
+
+ def _version_history(self, hog_flow: HogFlow, proposal: WorkflowProposal, versions: list[int]) -> dict[int, dict]:
+ """What each version changed against the one before it, and who published it.
+
+ A version's numbers hold every change that shipped in it, and no window separates them, so
+ the card says what else was in there rather than leaving a move unexplained.
+ """
+ if not versions:
+ return {}
+ # Each revision holds a whole workflow snapshot, so a suggestion filed against v1 of a
+ # workflow on v1000 would read a thousand of them to describe twenty.
+ wanted = set(versions) | {version - 1 for version in versions}
+ revisions = {
+ revision.version: revision
+ for revision in HogFlowRevision.objects.filter(hog_flow=hog_flow, version__in=sorted(wanted))
+ .order_by("version")
+ .select_related("created_by")
+ }
+ contents = {version: revision.content for version, revision in revisions.items()}
+ if hog_flow.version in versions:
+ contents.setdefault(hog_flow.version, snapshot_flow_content(hog_flow))
+ changed = proposal_changes(proposal, base_content_of(hog_flow, proposal))
+ proposed = {
+ (_item_id(item), path): _leaf(item, path)
+ for item in changed.get("actions") or []
+ for path in _patch_paths({key: value for key, value in item.items() if key != "id"})
+ } | {(None, (field,)): value for field, value in changed.items() if field not in PROPOSAL_MERGE_BY_ID_FIELDS}
+ history: dict[int, dict] = {}
+ for version in versions:
+ previous, current = contents.get(version - 1), contents.get(version)
+ changes = (
+ describe_version_changes(previous, current, proposed)
+ if previous is not None and current is not None
+ else []
+ )
+ revision = revisions.get(version)
+ history[version] = {
+ "changes": changes,
+ "other_changes": any(not change["from_suggestion"] for change in changes),
+ "published_at": revision.created_at if revision else None,
+ "published_by": revision.created_by if revision else None,
}
+ return history
+ def _version_totals(self, hog_flow: HogFlow, versions: list[int], step_id: Optional[str]) -> dict[int, dict]:
+ """Raw metric counts per version. Each version's series only ever collects while that
+ version is live, so there is no window to choose."""
return {
- "version": version,
- "target": rate(int(totals.get(TARGET_OPEN_METRIC, 0)), "email open rate", tracked_sends),
- # Same denominator as opens: a send with tracking off can record neither.
- "click_through": rate(int(totals.get(TARGET_CLICK_METRIC, 0)), "click rate", tracked_sends),
- "guardrails": [rate(int(totals.get(name, 0)), GUARDRAIL_LABELS[name], sends) for name in GUARDRAIL_METRICS],
+ version: fetch_app_metric_totals(
+ team_id=self.team_id,
+ app_source=HOG_FLOW_VERSION_APP_SOURCE,
+ app_source_id=f"{hog_flow.id}/{version}",
+ breakdown_by="name",
+ # Scoped to the step the suggestion names; several email steps would otherwise share one denominator.
+ instance_id=step_id or None,
+ name=[
+ TARGET_SEND_METRIC,
+ TARGET_OPEN_METRIC,
+ TARGET_CLICK_METRIC,
+ TARGET_UNTRACKED_METRIC,
+ *GUARDRAIL_METRICS,
+ ],
+ ).totals
+ for version in versions
}
+ def _versions_carrying_change(
+ self, hog_flow: HogFlow, proposal: WorkflowProposal
+ ) -> tuple[list[int], Optional[int]]:
+ """The versions the change ran on, and the version that ended it.
+
+ A later publish keeps the change unless it touches what the suggestion set, so the after side
+ runs on across those versions. The first version that sets one of those values to something
+ else ends the comparison: what shipped after that is a different change, not this one.
+ """
+ applied = proposal.applied_version
+ if applied is None:
+ return [], None
+ changes = proposal_changes(proposal, base_content_of(hog_flow, proposal))
+ contents = {
+ revision.version: revision.content
+ for revision in HogFlowRevision.objects.filter(hog_flow=hog_flow, version__gte=applied).order_by("version")[
+ :OUTCOME_VERSION_LIMIT
+ ]
+ }
+ # One revision row per publish, so a gap between the last one read and the live version means
+ # the slice stopped short. Reading the live version across that gap would call the change
+ # survived without looking at the publishes in between.
+ live_version = hog_flow.version or applied
+ if live_version >= applied and (not contents or live_version <= max(contents) + 1):
+ contents.setdefault(live_version, snapshot_flow_content(hog_flow))
+ carrying: list[int] = []
+ for version in sorted(contents):
+ if not carries_proposal_change(contents[version], changes):
+ return carrying or [applied], version
+ carrying.append(version)
+ return carrying or [applied], None
+
+ def _version_outcome(
+ self, hog_flow: HogFlow, versions: Sequence[Optional[int]], after: Any, step_id: Optional[str] = None
+ ) -> Optional[dict]:
+ read = [version for version in versions if version is not None]
+ if not read:
+ return None
+ totals: dict[str, float] = {}
+ for version in read:
+ # Scoped to the step the suggestion names; several email steps would otherwise share one denominator.
+ version_totals = fetch_app_metric_totals(
+ team_id=self.team_id,
+ app_source=HOG_FLOW_VERSION_APP_SOURCE,
+ app_source_id=f"{hog_flow.id}/{version}",
+ breakdown_by="name",
+ after=after,
+ instance_id=step_id or None,
+ name=[
+ TARGET_SEND_METRIC,
+ TARGET_OPEN_METRIC,
+ TARGET_CLICK_METRIC,
+ TARGET_UNTRACKED_METRIC,
+ *GUARDRAIL_METRICS,
+ ],
+ ).totals
+ for name, count in version_totals.items():
+ totals[name] = totals.get(name, 0) + count
+ return {**_outcome_from_totals(totals, read[0]), "versions": read}
+
@extend_schema(
parameters=[
OpenApiParameter("proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to reject.")
@@ -5995,10 +6450,10 @@ class HogFlowViewSet(
@extend_schema(request=HogFlowOptimizationSerializer, responses={200: HogFlowOptimizationSerializer})
@action(detail=True, methods=["GET", "POST"], url_path="optimization", filter_backends=[])
def optimization(self, request: Request, *args, **kwargs):
- """Whether PostHog may look at this workflow and suggest changes to it.
+ """Whether PostHog may suggest changes to this workflow.
- Turning it off stops a producer reading the workflow. Suggestions already made are left
- alone: someone still has them to resolve.
+ Turning it off stops new suggestions. Suggestions already made are left alone: someone
+ still has them to resolve.
"""
self._require_self_optimising_enabled()
instance = self.get_object()
@@ -6009,6 +6464,8 @@ class HogFlowViewSet(
param_serializer = HogFlowOptimizationSerializer(data=request.data)
param_serializer.is_valid(raise_exception=True)
enabled = param_serializer.validated_data["enabled"]
+ if enabled and instance.status != HogFlow.State.ACTIVE:
+ raise WorkflowNotLiveError()
if row is None:
# Turning it off for a workflow nobody turned on is a no-op, not a row saying "no".
changed = enabled
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 80442901f253..2b70347e158a 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -33,6 +33,7 @@ from posthog.test.fixtures import create_app_metric2
from products.access_control.backend.models.access_control import AccessControl
from products.actions.backend.models.action import Action
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
+from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cohorts.backend.models.cohort import Cohort
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.facade.contracts import WorkflowLastRunDTO
@@ -5344,6 +5345,80 @@ class TestHogFlowAPI(APIBaseTest):
assert "type" not in serializer.errors
+class TestHogFlowVersionedMetrics(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.flow = HogFlow.objects.create(team=self.team, name="Versioned flow")
+
+ def _seed(self, app_source: str, app_source_id: str, succeeded: int) -> None:
+ create_app_metric2(
+ team_id=self.team.pk,
+ app_source=app_source,
+ app_source_id=app_source_id,
+ metric_kind="success",
+ metric_name="succeeded",
+ count=succeeded,
+ )
+
+ def _succeeded(self, response) -> int:
+ return sum(sum(series["values"]) for series in response.json()["series"] if series["name"] == "success")
+
+ def test_a_version_reads_only_its_own_series(self):
+ self._seed("hog_flow_version", f"{self.flow.id}/1", succeeded=3)
+ self._seed("hog_flow_version", f"{self.flow.id}/2", succeeded=5)
+ self._seed("hog_flow", str(self.flow.id), succeeded=7)
+ base = f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}"
+
+ version_one = self.client.get(f"{base}/metrics/version?version=1")
+ version_two = self.client.get(f"{base}/metrics/version?version=2")
+ whole = self.client.get(f"{base}/metrics")
+
+ assert version_one.status_code == 200, version_one.json()
+ assert self._succeeded(version_one) == 3
+ assert self._succeeded(version_two) == 5
+ # The unversioned read keys batch runs on the run, so it is its own series rather than a sum.
+ assert self._succeeded(whole) == 7
+
+ def test_a_personal_api_key_can_read_one_version(self):
+ # The scout reads this over MCP with a scoped token, so the action has to be a declared read
+ # action; an action missing from that list refuses the key rather than the scope.
+ self._seed("hog_flow_version", f"{self.flow.id}/1", succeeded=3)
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="scout", user=self.user, secure_value=hash_key_value(key), scopes=["hog_flow:read"]
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/metrics/version?version=1",
+ headers={"authorization": f"Bearer {key}"},
+ )
+
+ assert response.status_code == 200, response.json()
+ assert self._succeeded(response) == 3
+
+ def test_the_version_is_required(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/metrics/version")
+
+ assert response.status_code == 400, response.json()
+ assert "version" in str(response.json())
+
+ @parameterized.expand([("metrics/totals",), ("metrics",)])
+ def test_a_hog_function_still_reads_its_own_metrics(self, path: str):
+ function = HogFunction.objects.create(team=self.team, name="fn", type="destination", hog="return event")
+ create_app_metric2(
+ team_id=self.team.id,
+ app_source="hog_function",
+ app_source_id=str(function.id),
+ metric_kind="success",
+ metric_name="succeeded",
+ count=3,
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_functions/{function.id}/{path}")
+
+ assert response.status_code == 200, response.json()
+
+
class TestHogFlowGlobalStats(ClickhouseTestMixin, APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.py
index e464660a3895..5c5585e0dbb1 100644
--- a/products/workflows/backend/tests/api/test_workflow_proposals.py
+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py
@@ -1,5 +1,6 @@
import json
from types import SimpleNamespace
+from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -46,6 +47,14 @@ class TestWorkflowProposals(APIBaseTest):
def setUp(self):
super().setUp()
sync_template_to_db(webhook_template)
+ # Filing needs the scout's own scope, which no session carries.
+ self.producer_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="producer",
+ user=self.user,
+ secure_value=hash_key_value(self.producer_key),
+ scopes=["hog_flow:read", "hog_flow_proposal:write"],
+ )
def _optimize(self, flow_id: str) -> None:
response = self.client.post(
@@ -85,7 +94,10 @@ class TestWorkflowProposals(APIBaseTest):
live = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}")
payload["base_version"] = live.json()["version"]
response = self.client.post(
- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/", payload, format="json"
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ payload,
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert response.status_code == 201, response.json()
return response.json()
@@ -234,36 +246,32 @@ class TestWorkflowProposals(APIBaseTest):
assert response.json()["code"] == "proposal_out_of_date"
assert HogFlow.objects.get(id=flow_id).draft is None
- def test_a_step_sent_whole_leaves_the_fields_it_did_not_change(self, _mock_flag):
+ @parameterized.expand([("below the first version", 0), ("far below", -1000000000), ("beyond the live one", 99)])
+ def test_a_base_version_the_workflow_never_had_is_refused(self, _mock_flag, _name: str, base_version: int):
+ # The outcome card reads every version between the base and the live one, so an unreal base
+ # would make that span unbounded.
flow_id = self._create_active_flow()
- # The producer sends the step as it read it, changing only the name.
- whole_step = _webhook_action()
- whole_step["name"] = "renamed by the suggestion"
- proposal = self._propose(flow_id, content={"actions": [whole_step]})
- self.client.patch(
- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
{
- "operations": [
- {
- "op": "update_action",
- "id": "action_1",
- "patch": {"config": {"inputs": {"url": {"value": "https://moved.example.com"}}}},
- }
- ]
+ "title": "Shorten the subject",
+ "rationale": "Opens are low.",
+ "content": {"exit_condition": "exit_only_at_end"},
+ "base_version": base_version,
+ "evidence": {
+ "metric": "email open rate",
+ "current_value": 0.07,
+ "unit": "rate",
+ "n": 120,
+ "guardrails": [],
+ },
},
- HTTP_X_POSTHOG_CLIENT="mcp",
- )
- self._publish(flow_id)
-
- approve = self.client.post(
- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {"overwrite": True}
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
- assert approve.status_code == 200, approve.json()
- draft = HogFlow.objects.get(id=flow_id).draft
- assert draft is not None
- assert draft["actions"][1]["name"] == "renamed by the suggestion"
- assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://moved.example.com"
+ assert response.status_code == 400, response.json()
+ assert "base_version" in str(response.json())
def test_a_secret_input_in_a_patch_is_not_stored(self, _mock_flag):
# The patch carries no template_id, so the secret is only knowable from the step it patches.
@@ -303,6 +311,92 @@ class TestWorkflowProposals(APIBaseTest):
assert "api_key" not in stored.content["actions"][0]["config"]["inputs"]
assert "sk-live-not-a-real-key" not in json.dumps(proposal)
+ def test_a_secret_on_a_step_the_suggestion_adds_is_not_returned(self, _mock_flag):
+ secret_template = {
+ **webhook_template,
+ "id": "template-webhook-secret",
+ "inputs_schema": [
+ *(webhook_template.get("inputs_schema") or []),
+ {"key": "api_key", "type": "string", "secret": True},
+ ],
+ }
+ sync_template_to_db(secret_template)
+ flow_id = self._create_active_flow()
+ flow = HogFlow.objects.get(pk=flow_id)
+ draft_step = {
+ "id": "action_draft",
+ "name": "action_draft",
+ "type": "function",
+ "config": {
+ "template_id": "template-webhook-secret",
+ "inputs": {"url": {"value": "https://example.com"}},
+ },
+ }
+ flow.draft = {"actions": [_trigger_action(), _webhook_action(), draft_step]}
+ flow.draft_encrypted_inputs = {"action_draft": {"api_key": {"value": "sk-live-not-a-real-key"}}}
+ flow.save(update_fields=["draft", "draft_encrypted_inputs"])
+
+ live = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}").json()
+ edges = [*(live.get("edges") or []), {"from": "action_1", "to": "action_draft", "type": "continue"}]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Point the webhook somewhere that answers",
+ "rationale": "Every call to the current URL failed over the last week.",
+ "base_version": flow.version,
+ "content": {
+ "actions": [
+ {
+ **draft_step,
+ "config": {
+ "template_id": "template-webhook-secret",
+ "inputs": {
+ "url": {"value": "https://example.com"},
+ "api_key": {"secret": True},
+ },
+ },
+ }
+ ],
+ "edges": edges,
+ },
+ "evidence": {
+ "metric": "failure rate",
+ "current_value": 1.0,
+ "n": 240,
+ "unit": "rate",
+ "guardrails": [{"metric": "complaint rate", "value": 0.0, "n": 240, "unit": "rate"}],
+ },
+ },
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
+ )
+
+ assert response.status_code == 201, response.json()
+ assert "sk-live-not-a-real-key" not in json.dumps(response.json())
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=response.json()["id"])
+ assert "sk-live-not-a-real-key" not in json.dumps(stored.content)
+
+ def test_a_value_the_serializer_rewrites_is_stored_the_way_it_will_publish(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={"actions": [{"id": "action_1", "output_variable": "result"}]},
+ )
+
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert stored.content["actions"][0]["output_variable"] == {"key": "result"}
+
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ # The publish wrote the coerced shape, so the change has to read as still in its own version.
+ assert outcome["change_ended_at_version"] is None, outcome
+ assert [version["version"] for version in outcome["versions"] if version["applied"]] == [2], outcome
+
def test_a_field_the_merge_replaces_is_compared_whole(self, _mock_flag):
flow_id = self._create_active_flow()
proposal = self._propose(
@@ -381,6 +475,46 @@ class TestWorkflowProposals(APIBaseTest):
assert draft["exit_condition"] == "exit_only_at_end"
assert {action["name"] for action in draft["actions"]} >= {"renamed"}
+ def test_the_evidence_step_must_be_one_the_workflow_has(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "x",
+ "rationale": "y",
+ "content": {"exit_condition": "exit_only_at_end"},
+ "step_id": "ghost_step",
+ "base_version": 1,
+ },
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
+ )
+ assert response.status_code == 400, response.json()
+ assert "step_id" in str(response.json())
+ assert WorkflowProposal.objects.for_team(self.team.id).count() == 0
+
+ def test_a_workflow_that_is_not_live_cannot_be_opted_in_or_suggested_against(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ disabled = self.client.patch(f"/api/projects/{self.team.id}/hog_flows/{flow_id}", {"status": "draft"})
+ assert disabled.status_code == 200, disabled.json()
+
+ suggested = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {"title": "x", "rationale": "y", "content": {"exit_condition": "exit_only_at_end"}, "base_version": 1},
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
+ )
+ assert suggested.status_code == 409, suggested.json()
+ assert suggested.json()["code"] == "workflow_not_live"
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/?optimization_enabled=true").json()
+ assert flow_id not in {item["id"] for item in listed["results"]}
+
+ turned_on = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/optimization", {"enabled": True}, format="json"
+ )
+ assert turned_on.status_code == 409, turned_on.json()
+ assert turned_on.json()["code"] == "workflow_not_live"
+
def test_a_workflow_nobody_opted_in_is_not_suggested_against(self, _mock_flag):
flow_id = self._create_active_flow()
self.client.post(
@@ -403,6 +537,7 @@ class TestWorkflowProposals(APIBaseTest):
"base_version": 1,
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert refused.status_code == 409, refused.json()
assert refused.json()["code"] == "workflow_not_optimized"
@@ -435,6 +570,7 @@ class TestWorkflowProposals(APIBaseTest):
"source_id": "run-1",
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert again.status_code == 200, again.json()
assert again.json()["id"] == first["id"]
@@ -529,6 +665,7 @@ class TestWorkflowProposals(APIBaseTest):
"source_id": "run:1:finding:webhook-url",
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert again.status_code == 200, again.json()
assert again.json()["id"] == first["id"]
@@ -572,9 +709,11 @@ class TestWorkflowProposals(APIBaseTest):
},
"needs a `unit`",
),
+ ("a bare string", "0.07", "object"),
+ ("a bare number", 7, "object"),
]
)
- def test_a_rate_the_panel_cannot_read_back_is_refused(self, _mock_flag, _name: str, evidence: dict, expected: str):
+ def test_a_rate_the_panel_cannot_read_back_is_refused(self, _mock_flag, _name: str, evidence: Any, expected: str):
flow_id = self._create_active_flow()
response = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
@@ -585,6 +724,7 @@ class TestWorkflowProposals(APIBaseTest):
"evidence": evidence,
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert response.status_code == 400, response.json()
assert expected in str(response.json())
@@ -641,6 +781,167 @@ class TestWorkflowProposals(APIBaseTest):
]
assert body["unavailable_guardrails"] == ["unsubscribe rate"]
+ def test_the_after_side_runs_on_until_someone_changes_what_the_suggestion_changed(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "trigger_node", "patch": {"name": "renamed"}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ assert outcome["after"]["versions"] == [2, 3]
+ assert outcome["change_ended_at_version"] is None
+ assert outcome["before"]["versions"] == [1]
+ # v3 renamed the trigger on top of the suggestion, so its numbers hold both changes.
+ assert [version["version"] for version in outcome["versions"] if version["other_changes"]] == [3]
+ applied = next(version for version in outcome["versions"] if version["applied"])
+ assert [(change["field"], change["after"], change["from_suggestion"]) for change in applied["changes"]] == [
+ ("url", "https://proposed.example.com", True)
+ ]
+ assert applied["published_by"]["email"] == self.user.email
+
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "update_action",
+ "id": "action_1",
+ "patch": {"config": {"inputs": {"url": {"value": "https://someone-else.example.com"}}}},
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ assert outcome["after"]["versions"] == [2, 3]
+ assert outcome["change_ended_at_version"] == 4
+
+ @patch("products.workflows.backend.presentation.views.hog_flow.OUTCOME_VERSION_LIMIT", 2)
+ def test_the_after_side_charts_every_version_it_sums(self, _mock_flag):
+ # Enough publishes after the applied one that the recent range no longer reaches it.
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+ for name in ("renamed_once", "renamed_twice", "renamed_thrice"):
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "trigger_node", "patch": {"name": name}}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+
+ charted = {version["version"] for version in outcome["versions"]}
+ assert set(outcome["after"]["versions"]) <= charted, outcome
+ assert [version["version"] for version in outcome["versions"] if version["applied"]] == [2]
+ # v5 is past the versions the slice read, so the after side must not claim it.
+ assert outcome["after"]["versions"] == [2, 3], outcome
+
+ def test_a_version_that_removes_a_step_says_so(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "add_action",
+ "action": _webhook_action("action_2", "https://second.example.com"),
+ "edges": [{"from": "action_1", "to": "action_2", "type": "continue"}],
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "remove_action", "id": "action_2"}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ latest = max(outcome["versions"], key=lambda version: version["version"])
+ assert [change["field"] for change in latest["changes"] if change["field"] == "step removed"] == [
+ "step removed"
+ ], latest
+
+ def test_changing_the_trigger_is_not_also_counted_as_a_workflow_change(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(flow_id)
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {
+ "operations": [
+ {
+ "op": "update_action",
+ "id": "trigger_node",
+ "patch": {
+ "config": {
+ "filters": {
+ "events": [
+ {"id": "$autocapture", "name": "$autocapture", "type": "events", "order": 0}
+ ]
+ }
+ }
+ },
+ }
+ ]
+ },
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ latest = max(outcome["versions"], key=lambda version: version["version"])
+ # The trigger is derived from the trigger step, so the step change is the only one to report.
+ assert [change["field"] for change in latest["changes"] if change["step_name"] is None] == [], latest
+
+ def test_the_outcome_reads_the_metric_the_suggestion_aimed_at(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ evidence={"metric": "email_bounced", "current_value": 0.07, "n": 132, "unit": "rate", "guardrails": []},
+ )
+ self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
+ self._publish(flow_id)
+
+ outcome = self.client.get(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
+ ).json()
+ assert outcome["after"]["target"]["metric"] == "bounce rate"
+ # Opens sit beside it, since a bounce fix that costs opens is worth seeing.
+ assert outcome["after"]["secondary"]["metric"] == "email open rate"
+ assert [version["target"]["metric"] for version in outcome["versions"]] == ["bounce rate"] * len(
+ outcome["versions"]
+ )
+
def test_an_api_key_can_read_the_outcome_of_what_it_proposed(self, _mock_flag):
flow_id = self._create_active_flow()
proposal = self._propose(flow_id)
@@ -660,6 +961,39 @@ class TestWorkflowProposals(APIBaseTest):
assert response.status_code == 200, response.json()
assert response.json()["after"]["version"] == 2
+ def test_suggesting_takes_its_own_scope_not_workflow_write(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ payload = {
+ "title": "Point the webhook somewhere that answers",
+ "rationale": "Every call to the current URL failed over the last week.",
+ "content": {"actions": [_trigger_action(), _webhook_action(url="https://proposed.example.com")]},
+ "evidence": {"metric": "failure rate", "current_value": 1.0, "unit": "rate", "n": 240, "guardrails": []},
+ "base_version": 1,
+ }
+ suggest_only = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="producer",
+ user=self.user,
+ secure_value=hash_key_value(suggest_only),
+ scopes=["hog_flow:read", "hog_flow_proposal:write"],
+ )
+ self.client.logout()
+
+ created = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ payload,
+ format="json",
+ headers={"authorization": f"Bearer {suggest_only}"},
+ )
+ assert created.status_code == 201, created.json()
+
+ published = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
+ {},
+ headers={"authorization": f"Bearer {suggest_only}"},
+ )
+ assert published.status_code == 403, published.json()
+
def test_a_suggestion_carries_only_the_step_it_changes(self, _mock_flag):
flow_id = self._create_active_flow()
proposal = self._propose(
@@ -677,6 +1011,49 @@ class TestWorkflowProposals(APIBaseTest):
assert [action["id"] for action in draft["actions"]] == ["trigger_node", "action_1"]
assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+ def test_a_step_carries_only_the_fields_it_changes(self, _mock_flag):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id,
+ content={
+ "actions": [
+ {"id": "action_1", "config": {"inputs": {"url": {"value": "https://proposed.example.com"}}}}
+ ]
+ },
+ )
+
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ step = draft["actions"][1]
+ assert step["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+ assert step["name"] == "action_1"
+ assert step["type"] == "function"
+ assert step["config"]["template_id"] == "template-webhook"
+
+ def test_a_change_publish_would_refuse_is_refused_at_create(self, _mock_flag):
+ flow_id = self._create_active_flow()
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Drop the webhook's url",
+ "rationale": "A null field deletes it, and a webhook step without a url cannot be published.",
+ "content": {"actions": [{"id": "action_1", "config": {"inputs": {"url": None}}}]},
+ "base_version": 1,
+ },
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
+ )
+
+ assert response.status_code == 400, response.json()
+ assert "Publishing this change would be refused" in str(response.json())
+ assert WorkflowProposal.objects.for_team(self.team.id).filter(hog_flow_id=flow_id).count() == 0
+
def test_a_suggestion_survives_an_edit_to_a_different_step(self, _mock_flag):
flow_id = self._create_active_flow()
proposal = self._propose(
@@ -700,6 +1077,35 @@ class TestWorkflowProposals(APIBaseTest):
assert draft["actions"][0]["name"] == "renamed by a human"
assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+ @parameterized.expand([("another field of that step", "renamed"), ("the same change made by hand", None)])
+ def test_a_step_change_still_approves_after(self, _mock_flag, _label: str, new_name: str | None):
+ flow_id = self._create_active_flow()
+ proposal = self._propose(
+ flow_id, content={"actions": [_webhook_action(url="https://proposed.example.com")]}, source_id="one-field"
+ )
+ patch = (
+ {"name": new_name}
+ if new_name
+ else {"config": {"inputs": {"url": {"value": "https://proposed.example.com"}}}}
+ )
+ self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/graph",
+ {"operations": [{"op": "update_action", "id": "action_1", "patch": patch}]},
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ self._publish(flow_id)
+
+ listed = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/").json()["results"]
+ assert [item["is_stale"] for item in listed] == [False]
+ approve = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
+ )
+ assert approve.status_code == 200, approve.json()
+ draft = HogFlow.objects.get(id=flow_id).draft
+ assert draft is not None
+ assert draft["actions"][1]["name"] == (new_name or "action_1")
+ assert draft["actions"][1]["config"]["inputs"]["url"]["value"] == "https://proposed.example.com"
+
def test_a_suggestion_is_refused_once_the_step_it_changes_is_deleted(self, _mock_flag):
flow_id = self._create_active_flow()
proposal = self._propose(
@@ -735,6 +1141,7 @@ class TestWorkflowProposals(APIBaseTest):
"base_version": 1,
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert response.status_code == 400, response.json()
@@ -772,17 +1179,19 @@ class TestWorkflowProposals(APIBaseTest):
def test_a_whole_list_proposal_must_say_which_version_it_read(self, _mock_flag):
flow_id = self._create_active_flow()
- response = self.client.post(
- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
- {
- "title": "Point the webhook somewhere else",
- "rationale": "Testing the version contract.",
- "content": {"actions": [_trigger_action(), _webhook_action()]},
- },
- format="json",
- )
- assert response.status_code == 400, response.json()
- assert "base_version" in str(response.json())
+ for content in ({"actions": [_trigger_action(), _webhook_action()]}, {"exit_condition": "exit_only_at_end"}):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
+ {
+ "title": "Point the webhook somewhere else",
+ "rationale": "Testing the version contract.",
+ "content": content,
+ },
+ format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
+ )
+ assert response.status_code == 400, response.json()
+ assert "base_version" in str(response.json())
@parameterized.expand(
[
@@ -806,37 +1215,43 @@ class TestWorkflowProposals(APIBaseTest):
"base_version": 1,
},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert response.status_code == 400, response.json()
assert expected in str(response.json())
- def test_editing_the_draft_returns_the_approved_suggestion_to_the_queue(self, _mock_flag):
+ @parameterized.expand(
+ [
+ ("undoes the change", "https://edited.example.com", "action_1", "suggested", None),
+ ("touches another field of that step", "https://proposed.example.com", "renamed", "applied", 2),
+ ]
+ )
+ def test_editing_the_draft_hands_the_suggestion_back_only_if_the_edit(
+ self, _mock_flag, _label: str, url: str, name: str, status: str, applied_version: int | None
+ ):
flow_id = self._create_active_flow()
- proposal = self._propose(flow_id)
+ proposal = self._propose(flow_id, content={"actions": [_webhook_action(url="https://proposed.example.com")]})
approve = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {}
)
assert approve.status_code == 200, approve.json()
+ edited = _webhook_action(url=url)
+ edited["name"] = name
edit = self.client.patch(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
- {
- "actions": [_trigger_action(), _webhook_action(url="https://edited.example.com")],
- "stage_draft": True,
- },
+ {"actions": [_trigger_action(), edited], "stage_draft": True},
format="json",
)
assert edit.status_code == 200, edit.json()
-
- assert (
- WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status
- == WorkflowProposal.Status.SUGGESTED
+ assert WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"]).status == (
+ "approved" if status == "applied" else "suggested"
)
self._publish(flow_id)
- applied = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
- assert applied.status == WorkflowProposal.Status.SUGGESTED
- assert applied.applied_version is None
+ stored = WorkflowProposal.objects.for_team(self.team.id).get(id=proposal["id"])
+ assert stored.status == status
+ assert stored.applied_version == applied_version
def test_folding_the_draft_into_a_save_returns_the_suggestion_to_the_queue(self, _mock_flag):
flow_id = self._create_active_flow()
@@ -914,6 +1329,14 @@ class TestWorkflowProposalsFlagOff(APIBaseTest):
def setUp(self):
super().setUp()
sync_template_to_db(webhook_template)
+ # Filing needs the scout's own scope, which no session carries.
+ self.producer_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="producer",
+ user=self.user,
+ secure_value=hash_key_value(self.producer_key),
+ scopes=["hog_flow:read", "hog_flow_proposal:write"],
+ )
def test_the_surface_does_not_exist_without_the_flag(self, _mock_flag):
create = self.client.post(
@@ -928,6 +1351,7 @@ class TestWorkflowProposalsFlagOff(APIBaseTest):
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/",
{"title": "x", "rationale": "y", "content": {"actions": []}},
format="json",
+ headers={"authorization": f"Bearer {self.producer_key}"},
)
assert created.status_code == 404, created.json()
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
index b99733983fb7..9a759dabf227 100644
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
@@ -1,7 +1,60 @@
-import { LemonTag } from '@posthog/lemon-ui'
+import { LemonCollapse, LemonTag, Tooltip } from '@posthog/lemon-ui'
-import type { WorkflowProposalApi, WorkflowProposalOutcomeApi } from '../../generated/api.schemas'
-import { WorkflowMetricReading } from './WorkflowMetricReading'
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+
+import type {
+ WorkflowProposalApi,
+ WorkflowProposalMetricApi,
+ WorkflowProposalOutcomeApi,
+ WorkflowProposalVersionOutcomeApi,
+} from '../../generated/api.schemas'
+import { MIN_EVIDENCE_SAMPLE, formatValue } from './suggestionEvidence'
+
+const ROW_LABELS: Record<string, string> = {
+ 'email open rate': 'Opened',
+ 'click rate': 'Clicked',
+ 'complaint rate': 'Complaints',
+ 'bounce rate': 'Bounced',
+ 'unsubscribe rate': 'Unsubscribed',
+}
+
+// Roughly 6rem a bar, so a workflow with three versions does not get three bars the width of the card.
+function percent(reading: WorkflowProposalMetricApi | undefined): number {
+ return reading?.value ? Math.round(reading.value * 1000) / 10 : 0
+}
+
+function Reading({ label, reading }: { label: string; reading: WorkflowProposalMetricApi | undefined }): JSX.Element {
+ return (
+ <span className="flex items-baseline gap-1">
+ <span className="text-secondary">{label}</span>
+ <span className="font-semibold">
+ {reading ? (formatValue(reading.value, 'rate') ?? 'No data') : 'No data'}
+ </span>
+ {reading && <Denominator reading={reading} />}
+ </span>
+ )
+}
+
+// Opens and clicks read against tracked sends, not the Sends column, and each version has its own.
+function Denominator({ reading }: { reading: WorkflowProposalMetricApi }): JSX.Element | null {
+ // Nothing was sent, so there is no sample to warn about and "No data" already says it.
+ if (!reading.n) {
+ return null
+ }
+ if (reading.below_minimum_sample) {
+ return (
+ <Tooltip
+ title={`${reading.n} tracked sends, under ${MIN_EVIDENCE_SAMPLE}. Too few for the rate to mean anything.`}
+ >
+ <LemonTag type="warning" size="small">
+ n={reading.n}
+ </LemonTag>
+ </Tooltip>
+ )
+ }
+ return <span className="text-xs text-secondary">n={reading.n}</span>
+}
export function WorkflowAppliedOutcome({
proposal,
@@ -10,43 +63,255 @@ export function WorkflowAppliedOutcome({
proposal: WorkflowProposalApi
outcome: WorkflowProposalOutcomeApi
}): JSX.Element {
+ const published = outcome.versions ?? []
+ // Only versions that sent something can carry a rate, and a zero bar for one that never ran reads as a drop.
+ const charted = published.filter((version) => version.guardrails[0]?.n || version.target.n)
+ // The live version and what each version changed come from every published version, not only the
+ // ones with sends: a newer version that has not sent yet still shipped its edits.
+ const latest: WorkflowProposalVersionOutcomeApi | undefined = published[published.length - 1]
+
return (
- <div className="@container border rounded p-3 bg-surface-primary flex flex-col gap-2">
+ <div className="border rounded p-3 bg-surface-primary flex flex-col gap-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-semibold">{proposal.title}</span>
<LemonTag type="success">Applied as version {proposal.applied_version}</LemonTag>
+ {outcome.change_ended_at_version !== null && outcome.change_ended_at_version !== undefined && (
+ <Tooltip
+ title={`Version ${outcome.change_ended_at_version} changed this again, so later versions are measuring something else.`}
+ >
+ <LemonTag type="warning">Changed again in v{outcome.change_ended_at_version}</LemonTag>
+ </Tooltip>
+ )}
</div>
- <p className="mb-0 text-secondary text-sm">
- Measured over {outcome.window}, before and after. Different periods, so treat a difference as a signal
- to look closer, not as proof.
- </p>
- <div className="grid grid-cols-1 @md:grid-cols-2 gap-3 text-sm">
- {(['before', 'after'] as const).map((side) => {
- const reading = outcome[side]
- return (
- <div key={side} className="flex flex-col gap-1">
- <span className="font-semibold">
- {side === 'before' ? 'Before' : 'After'}
- {reading ? ` (v${reading.version})` : ''}
- </span>
- {reading ? (
- <>
- <WorkflowMetricReading reading={reading.target} />
- <WorkflowMetricReading reading={reading.click_through} />
- {reading.guardrails.map((guardrail) => (
- <WorkflowMetricReading key={guardrail.metric} reading={guardrail} />
+ {charted.length === 0 ? (
+ <p className="mb-0 text-secondary text-sm">
+ No sends recorded on this step yet, so there is nothing to compare.
+ </p>
+ ) : (
+ <>
+ <p className="mb-0 text-secondary text-sm">
+ The {charted[0].target.metric} of this step on each published version, over the time that
+ version was live. Other edits ship in these versions too, so read a move as a signal to look
+ closer, not as proof.
+ </p>
+ <LemonTable
+ size="small"
+ data-attr="workflow-suggestion-outcome"
+ columns={[
+ {
+ title: 'Version',
+ key: 'version',
+ width: '18%',
+ render: (_, version) => (
+ <span className="flex flex-col gap-0.5">
+ <span className={version.applied ? 'font-semibold' : undefined}>
+ v{version.version}
+ </span>
+ {version.published_at && (
+ <span className="text-xs text-secondary">
+ <TZLabel time={version.published_at} />
+ </span>
+ )}
+ </span>
+ ),
+ },
+ {
+ title: 'The change',
+ key: 'change',
+ width: '22%',
+ render: (_, version) =>
+ version.applied ? (
+ <LemonTag type="warning">applied here</LemonTag>
+ ) : version.carries_change ? (
+ <span className="flex items-center gap-2 flex-wrap">
+ <span>still in</span>
+ {version.other_changes && (
+ <span className="text-xs text-secondary">+ other edits</span>
+ )}
+ </span>
+ ) : (
+ <span className="text-secondary">
+ {version.version < (proposal.applied_version ?? 0)
+ ? 'before it'
+ : 'changed again'}
+ </span>
+ ),
+ },
+ {
+ title: ROW_LABELS[charted[0].target.metric] ?? charted[0].target.metric,
+ key: 'target',
+ width: '25%',
+ render: (_, version) => (
+ <span className="flex flex-col gap-1">
+ <span className="flex items-baseline gap-1">
+ {formatValue(version.target.value, 'rate') ?? 'No data'}
+ <Denominator reading={version.target} />
+ </span>
+ <span className="h-1 w-4/5 rounded bg-fill-primary overflow-hidden">
+ <span
+ className="block h-full rounded bg-accent"
+ // The width is the rate against the best version, so it cannot be a class.
+ style={{
+ width: `${Math.max(2, (percent(version.target) / Math.max(...charted.map((other) => percent(other.target)), 1)) * 100)}%`,
+ }}
+ />
+ </span>
+ </span>
+ ),
+ },
+ {
+ title: ROW_LABELS[charted[0].secondary?.metric ?? ''] ?? 'Clicked',
+ key: 'secondary',
+ width: '20%',
+ render: (_, version) => (
+ <span className="flex items-baseline gap-1 text-secondary">
+ {formatValue((version.secondary ?? version.click_through).value, 'rate') ??
+ 'No data'}
+ <Denominator reading={version.secondary ?? version.click_through} />
+ </span>
+ ),
+ },
+ {
+ title: 'Sends',
+ key: 'sends',
+ width: '15%',
+ render: (_, version) => (
+ <Tooltip title="Every send on this version. Open and click rates read against tracked sends only, shown as n beside each rate.">
+ <span className="text-secondary">
+ {version.guardrails[0]?.n ?? version.target.n}
+ </span>
+ </Tooltip>
+ ),
+ },
+ ]}
+ dataSource={charted}
+ rowKey={(version) => String(version.version)}
+ expandable={{
+ // A version that lifts opens and complaints together only shows on its own row.
+ rowExpandable: (version) => version.guardrails.length > 0,
+ expandedRowRender: (version) => (
+ <div className="flex items-center gap-4 flex-wrap text-sm py-2">
+ {version.guardrails.map((guardrail) => (
+ <Reading
+ key={guardrail.metric}
+ label={ROW_LABELS[guardrail.metric] ?? guardrail.metric}
+ reading={guardrail}
+ />
))}
- </>
- ) : (
- <span className="text-secondary">No data</span>
- )}
+ </div>
+ ),
+ }}
+ />
+ {latest && latest.guardrails.length > 0 && (
+ <div className="flex items-center gap-4 flex-wrap text-sm">
+ <span className="text-secondary">Live version:</span>
+ {latest.guardrails.map((guardrail) => (
+ <Reading
+ key={guardrail.metric}
+ label={ROW_LABELS[guardrail.metric] ?? guardrail.metric}
+ reading={guardrail}
+ />
+ ))}
</div>
- )
- })}
- </div>
+ )}
+ </>
+ )}
+ {published.some((version) => version.changes?.length) && (
+ <LemonCollapse
+ size="small"
+ panels={[
+ {
+ key: 'changes',
+ header: 'What changed in each version',
+ content: (
+ <div className="flex flex-col">
+ {[...published].reverse().map((version, index) => (
+ <div
+ key={version.version}
+ className={`flex flex-col gap-2 ${index > 0 ? 'pt-4' : ''}`}
+ >
+ <div className="flex flex-col gap-0.5">
+ <span className="flex items-center gap-2 flex-wrap">
+ <h4 className="mb-0">Version {version.version}</h4>
+ {version.applied && (
+ <LemonTag type="warning">the suggestion</LemonTag>
+ )}
+ </span>
+ <span className="flex items-center gap-1 flex-wrap text-xs text-secondary">
+ {version.published_by && (
+ <span>
+ Published by{' '}
+ {version.published_by.first_name ||
+ version.published_by.email}
+ </span>
+ )}
+ {version.published_at && <TZLabel time={version.published_at} />}
+ </span>
+ </div>
+ {version.changes?.length ? (
+ <LemonTable
+ size="small"
+ columns={[
+ {
+ title: 'Field',
+ key: 'field',
+ // Same split as the suggestion card's table, so the two read alike.
+ width: '20%',
+ render: (_, change) => (
+ <span className="flex items-center gap-1 flex-wrap">
+ {change.step_name && (
+ <span className="text-secondary">
+ {change.step_name} ›
+ </span>
+ )}
+ <span>{change.field}</span>
+ {change.from_suggestion && (
+ <LemonTag type="warning" size="small">
+ suggested
+ </LemonTag>
+ )}
+ </span>
+ ),
+ },
+ {
+ title: 'Was',
+ key: 'before',
+ width: '40%',
+ render: (_, change) => (
+ <span className="text-secondary">
+ {change.before ?? 'not set'}
+ </span>
+ ),
+ },
+ {
+ title: 'Became',
+ key: 'after',
+ width: '40%',
+ render: (_, change) => (
+ <span>{change.after ?? 'removed'}</span>
+ ),
+ },
+ ]}
+ dataSource={version.changes}
+ rowKey={(change) => `${change.step_name}:${change.field}`}
+ />
+ ) : (
+ <span className="text-xs text-secondary">
+ Nothing recorded for this version.
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ ),
+ },
+ ]}
+ />
+ )}
{outcome.unavailable_guardrails.length > 0 && (
<span className="text-xs text-secondary">
- Not measured: {outcome.unavailable_guardrails.join(', ')}
+ Not measured:{' '}
+ {outcome.unavailable_guardrails.map((metric) => ROW_LABELS[metric] ?? metric).join(', ')}
</span>
)}
</div>
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsx
deleted file mode 100644
index 08e1f862d467..000000000000
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowMetricReading.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-
-import type { WorkflowProposalMetricApi } from '../../generated/api.schemas'
-import { MIN_EVIDENCE_SAMPLE, formatValue } from './suggestionEvidence'
-
-export function WorkflowMetricReading({ reading }: { reading: WorkflowProposalMetricApi }): JSX.Element {
- return (
- <span className="flex items-center gap-1 flex-wrap">
- {reading.metric} {formatValue(reading.value, 'rate') ?? 'no data'}
- <span className="text-secondary">(n={reading.n})</span>
- {reading.below_minimum_sample && (
- <Tooltip title={`Under ${MIN_EVIDENCE_SAMPLE} observations. Not enough to call this a result.`}>
- <LemonTag type="warning">Too little data</LemonTag>
- </Tooltip>
- )}
- </span>
- )
-}
diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts
index 7a1c4677aedb..e1e3e4bf5ff7 100644
--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts
+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.test.ts
@@ -127,11 +127,15 @@ describe('workflowProposalsLogic', () => {
await expectLogic(flowLogic).toDispatchActions(['loadWorkflowSuccess'])
await expectLogic(logic).toDispatchActions(['loadProposalsSuccess'])
+ logic.actions.setOutcome(PROPOSAL_ID, { versions: [] } as any)
+ expect(logic.values.outcomes[PROPOSAL_ID]).not.toBeUndefined()
+
workflowVersion = 4
await expectLogic(logic, () => {
flowLogic.actions.loadWorkflow()
- }).toDispatchActions(['loadProposals', 'loadApplied'])
+ }).toDispatchActions(['clearOutcomes', 'loadProposals', 'loadApplied'])
expect(logic.values.lastSeenVersion).toBe(4)
+ expect(logic.values.outcomes).toEqual({})
})
it('reloads the queue when a discard rewrites the draft stamp without moving the version', async () => {
diff --git a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts
index 9ead1c6e7292..f5963014a926 100644
--- a/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts
+++ b/products/workflows/frontend/Workflows/suggestions/workflowProposalsLogic.ts
@@ -60,6 +60,7 @@ export interface workflowProposalsLogicActions {
approveProposal: (proposalId: string) => {
proposalId: string
}
+ clearOutcomes: () => {}
confirmApproveProposal: (
proposalId: string,
expectedDraftUpdatedAt: string | null
@@ -215,6 +216,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([
action,
}),
loadOutcome: (proposalId: string) => ({ proposalId }),
+ clearOutcomes: () => ({}),
setLastSeen: (version: number | null, draftStamp: string | null) => ({ version, draftStamp }),
setOptimizationUnreadable: (unreadable: boolean) => ({ unreadable }),
setOptimizationEnabled: (enabled: boolean) => ({ enabled }),
@@ -277,6 +279,7 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([
{} as Record<string, WorkflowProposalOutcomeApi>,
{
setOutcome: (state, { proposalId, outcome }) => ({ ...state, [proposalId]: outcome }),
+ clearOutcomes: () => ({}),
},
],
}),
@@ -501,6 +504,8 @@ export const workflowProposalsLogic = kea<workflowProposalsLogicType>([
return
}
actions.setLastSeen(version, draftStamp)
+ // The reload below skips a proposal that already has an outcome, so the stale one goes first.
+ actions.clearOutcomes()
actions.loadProposals()
actions.loadApplied()
},
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 7141759bedb5..f6c878806815 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1240,7 +1240,7 @@ export interface AppMetricsTotalsResponseApi {
}
export interface HogFlowOptimizationApi {
- /** Whether PostHog may read this workflow's metrics and suggest changes to it. */
+ /** Whether PostHog may suggest changes to this workflow. */
enabled: boolean
}
@@ -1287,7 +1287,7 @@ export interface WorkflowProposalApi {
readonly step_id: string | null
/** Live workflow version this was authored against. Approving compares the steps and fields this changes against that version to tell whether somebody else already changed them. */
readonly base_version: number
- /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges per step. */
+ /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges only what the proposal changes. */
readonly is_stale: boolean
readonly status: WorkflowProposalStatusEnumApi
/**
@@ -1337,8 +1337,11 @@ export interface WorkflowProposalCreateApi {
content: WorkflowProposalCreateApiContent
/** The metric numbers behind the proposal, so a human can judge it without re-deriving them. */
evidence?: WorkflowProposalCreateApiEvidence
- /** Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise. */
- base_version?: number
+ /**
+ * Workflow version this was authored against, as read from the workflow. It is the snapshot approve compares against to tell whether someone edited the same steps or fields since, and a defaulted version would read as current however long the producer took.
+ * @minimum 1
+ */
+ base_version: number
/**
* The step this is about. Send it for a change to one step: both the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Leave it out only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
* @maxLength 200
@@ -1363,6 +1366,28 @@ export interface WorkflowProposalApproveRequestApi {
expected_draft_updated_at?: string | null
}
+export interface WorkflowVersionChangeApi {
+ /**
+ * Step the field belongs to, or null for a workflow field.
+ * @nullable
+ */
+ step_name: string | null
+ /** What changed, as a person reads it, e.g. 'email > subject'. */
+ field: string
+ /**
+ * Value in the version before this one.
+ * @nullable
+ */
+ before: string | null
+ /**
+ * Value this version published.
+ * @nullable
+ */
+ after: string | null
+ /** Whether the suggestion is what changed this field. */
+ from_suggestion: boolean
+}
+
export interface WorkflowProposalMetricApi {
/** What was measured, e.g. 'email open rate'. */
metric: string
@@ -1380,8 +1405,29 @@ export interface WorkflowProposalMetricApi {
export interface WorkflowProposalVersionOutcomeApi {
/** Workflow version these numbers belong to. */
version: number
+ /** Whether the suggestion went live as this version. */
+ applied?: boolean
+ /** Whether the suggestion was written against this version. */
+ proposed_against?: boolean
+ /** Whether this version still holds what the suggestion changed. */
+ carries_change?: boolean
+ /** Whether this version also changed something the suggestion did not, which the numbers cannot separate. */
+ other_changes?: boolean
+ /** What this version changed against the version before it. */
+ changes?: WorkflowVersionChangeApi[]
+ /**
+ * When this version went live.
+ * @nullable
+ */
+ published_at?: string | null
+ /** Who published this version. */
+ published_by?: UserBasicApi | null
+ /** Every version summed into these numbers. The after side runs on while later versions keep the change. */
+ versions?: number[]
/** The metric the suggestion aimed at. */
target: WorkflowProposalMetricApi
+ /** The rate read beside the target, so a lift in one is visible against the other. */
+ secondary?: WorkflowProposalMetricApi
/** Click-through rate over the same window and denominator, since opens alone can move without clicks. */
click_through: WorkflowProposalMetricApi
/** Counter-metrics over the same window, so a harmful win is visible. */
@@ -1389,12 +1435,17 @@ export interface WorkflowProposalVersionOutcomeApi {
}
export interface WorkflowProposalOutcomeApi {
- /** Relative window both sides were measured over. */
- window: string
+ /** Every published version around the change, each read over its own time live, so a later edit shows up as its own point rather than ending the comparison. */
+ versions: WorkflowProposalVersionOutcomeApi[]
/** The version the change was proposed against. */
before: WorkflowProposalVersionOutcomeApi | null
- /** The version it went live as. Null until the proposal is applied. */
+ /** The versions that carried the change. Null until the proposal is applied. */
after: WorkflowProposalVersionOutcomeApi | null
+ /**
+ * The version that changed what the suggestion changed, which is where the after side stops. Null while the change is still live.
+ * @nullable
+ */
+ change_ended_at_version: number | null
/** Counter-metrics that cannot be read yet, named so their absence is not read as zero. */
unavailable_guardrails: string[]
}
@@ -2352,6 +2403,72 @@ export const HogFlowsMetricsTotalsRetrieveInterval = {
Week: 'week',
} as const
+export type HogFlowsMetricsVersionRetrieveParams = {
+ /**
+ * Start of the time range. Accepts relative formats like '-7d', '-24h' or ISO 8601 timestamps. Defaults to '-7d'.
+ * @minLength 1
+ */
+ after?: string
+ /**
+ * End of the time range. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string
+ /**
+ * Group the series by metric 'name' or 'kind'. Defaults to 'kind'.
+ *
+ * * `name` - name
+ * * `kind` - kind
+ * @minLength 1
+ */
+ breakdown_by?: HogFlowsMetricsVersionRetrieveBreakdownBy
+ /**
+ * Filter metrics to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string
+ /**
+ * Time bucket size for the series. One of: hour, day, week. Defaults to 'day'.
+ *
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * @minLength 1
+ */
+ interval?: HogFlowsMetricsVersionRetrieveInterval
+ /**
+ * Comma-separated metric kinds to filter by, e.g. 'success,failure'.
+ * @minLength 1
+ */
+ kind?: string
+ /**
+ * Comma-separated metric names to filter by.
+ * @minLength 1
+ */
+ name?: string
+ /**
+ * Read one workflow version's series: every run of that version, keyed on the workflow. The unversioned read keys batch and broadcast runs on the run instead, so it is not the sum of the versions; compare versions with each other, not with it.
+ */
+ version: number
+}
+
+export type HogFlowsMetricsVersionRetrieveBreakdownBy =
+ (typeof HogFlowsMetricsVersionRetrieveBreakdownBy)[keyof typeof HogFlowsMetricsVersionRetrieveBreakdownBy]
+
+export const HogFlowsMetricsVersionRetrieveBreakdownBy = {
+ Name: 'name',
+ Kind: 'kind',
+} as const
+
+export type HogFlowsMetricsVersionRetrieveInterval =
+ (typeof HogFlowsMetricsVersionRetrieveInterval)[keyof typeof HogFlowsMetricsVersionRetrieveInterval]
+
+export const HogFlowsMetricsVersionRetrieveInterval = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+} as const
+
export type HogFlowsProposalsListParams = {
/**
* Number of results to return per page.
@@ -2376,13 +2493,6 @@ export const HogFlowsProposalsListStatus = {
Suggested: 'suggested',
} as const
-export type HogFlowsProposalsOutcomeRetrieveParams = {
- /**
- * Relative window, e.g. -7d. Defaults to -7d.
- */
- window?: string
-}
-
export type HogFlowsRevisionsListParams = {
/**
* Number of results to return per page.
diff --git a/products/workflows/frontend/generated/api.ts b/products/workflows/frontend/generated/api.ts
index 1c205b8f0262..cc8e4811e8a2 100644
--- a/products/workflows/frontend/generated/api.ts
+++ b/products/workflows/frontend/generated/api.ts
@@ -39,8 +39,8 @@ import type {
HogFlowsMetricsGlobalRetrieveParams,
HogFlowsMetricsRetrieveParams,
HogFlowsMetricsTotalsRetrieveParams,
+ HogFlowsMetricsVersionRetrieveParams,
HogFlowsProposalsListParams,
- HogFlowsProposalsOutcomeRetrieveParams,
HogFlowsReputationRetrieveParams,
HogFlowsRevisionsListParams,
HogInvocationCancelRequestApi,
@@ -746,15 +746,53 @@ export const hogFlowsMetricsTotalsRetrieve = async (
})
}
+export const getHogFlowsMetricsVersionRetrieveUrl = (
+ projectId: string,
+ id: string,
+ params: HogFlowsMetricsVersionRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/hog_flows/${id}/metrics/version/?${stringifiedParams}`
+ : `/api/projects/${projectId}/hog_flows/${id}/metrics/version/`
+}
+
+/**
+ * One published version's series. Every hog flow metric is mirrored under
+ * `hog_flow_version` with the version appended to the id, which is what makes "before and
+ * after this change" answerable at all. The unversioned read keys batch and broadcast runs on
+ * the run instead, so it is not the sum of the versions.
+ */
+export const hogFlowsMetricsVersionRetrieve = async (
+ projectId: string,
+ id: string,
+ params: HogFlowsMetricsVersionRetrieveParams,
+ options?: RequestInit
+): Promise<AppMetricsResponseApi> => {
+ return apiMutator<AppMetricsResponseApi>(getHogFlowsMetricsVersionRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getHogFlowsOptimizationRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/hog_flows/${id}/optimization/`
}
/**
- * Whether PostHog may look at this workflow and suggest changes to it.
+ * Whether PostHog may suggest changes to this workflow.
*
- * Turning it off stops a producer reading the workflow. Suggestions already made are left
- * alone: someone still has them to resolve.
+ * Turning it off stops new suggestions. Suggestions already made are left alone: someone
+ * still has them to resolve.
*/
export const hogFlowsOptimizationRetrieve = async (
projectId: string,
@@ -772,10 +810,10 @@ export const getHogFlowsOptimizationCreateUrl = (projectId: string, id: string)
}
/**
- * Whether PostHog may look at this workflow and suggest changes to it.
+ * Whether PostHog may suggest changes to this workflow.
*
- * Turning it off stops a producer reading the workflow. Suggestions already made are left
- * alone: someone still has them to resolve.
+ * Turning it off stops new suggestions. Suggestions already made are left alone: someone
+ * still has them to resolve.
*/
export const hogFlowsOptimizationCreate = async (
projectId: string,
@@ -884,25 +922,8 @@ export const hogFlowsProposalsApproveCreate = async (
})
}
-export const getHogFlowsProposalsOutcomeRetrieveUrl = (
- projectId: string,
- id: string,
- proposalId: string,
- params?: HogFlowsProposalsOutcomeRetrieveParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/outcome/?${stringifiedParams}`
- : `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/outcome/`
+export const getHogFlowsProposalsOutcomeRetrieveUrl = (projectId: string, id: string, proposalId: string) => {
+ return `/api/projects/${projectId}/hog_flows/${id}/proposals/${proposalId}/outcome/`
}
/**
@@ -918,16 +939,12 @@ export const hogFlowsProposalsOutcomeRetrieve = async (
projectId: string,
id: string,
proposalId: string,
- params?: HogFlowsProposalsOutcomeRetrieveParams,
options?: RequestInit
): Promise<WorkflowProposalOutcomeApi> => {
- return apiMutator<WorkflowProposalOutcomeApi>(
- getHogFlowsProposalsOutcomeRetrieveUrl(projectId, id, proposalId, params),
- {
- ...options,
- method: 'GET',
- }
- )
+ return apiMutator<WorkflowProposalOutcomeApi>(getHogFlowsProposalsOutcomeRetrieveUrl(projectId, id, proposalId), {
+ ...options,
+ method: 'GET',
+ })
}
export const getHogFlowsProposalsRejectCreateUrl = (projectId: string, id: string, proposalId: string) => {
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index ee2ef66490d0..e05d8aead253 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2482,13 +2482,13 @@ export const HogFlowsInvocationsCancelCreateBody = /* @__PURE__ */ zod
.describe('Cancel in-flight invocations of a workflow. Provide exactly one selector.')
/**
- * Whether PostHog may look at this workflow and suggest changes to it.
+ * Whether PostHog may suggest changes to this workflow.
*
- * Turning it off stops a producer reading the workflow. Suggestions already made are left
- * alone: someone still has them to resolve.
+ * Turning it off stops new suggestions. Suggestions already made are left alone: someone
+ * still has them to resolve.
*/
export const HogFlowsOptimizationCreateBody = /* @__PURE__ */ zod.object({
- enabled: zod.boolean().describe("Whether PostHog may read this workflow's metrics and suggest changes to it."),
+ enabled: zod.boolean().describe('Whether PostHog may suggest changes to this workflow.'),
})
/**
@@ -2517,9 +2517,9 @@ export const HogFlowsProposalsCreateBody = /* @__PURE__ */ zod.object({
.describe('The metric numbers behind the proposal, so a human can judge it without re-deriving them.'),
base_version: zod
.number()
- .optional()
+ .min(1)
.describe(
- 'Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise.'
+ 'Workflow version this was authored against, as read from the workflow. It is the snapshot approve compares against to tell whether someone edited the same steps or fields since, and a defaulted version would read as current however long the producer took.'
),
step_id: zod
.string()
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 5c5b21e14584..3316d081476c 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -132,9 +132,6 @@ tools:
hog-flows-resume-email-sending:
operation: hog_flows_resume_email_sending
enabled: false
- hog-flows-revisions-list:
- operation: hog_flows_revisions_list
- enabled: false
hog-flows-revisions-restore-create:
operation: hog_flows_revisions_restore_create
enabled: false
@@ -505,7 +502,8 @@ tools:
at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports
breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read
email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends
- with open/click tracking off, which can never register an open or a click.
+ with open/click tracking off, which can never register an open or a click. This reads the workflow's whole
+ history; for one published version, call workflows-version-stats.
workflows-suggest:
operation: hog_flows_proposals_create
enabled: true
@@ -518,12 +516,14 @@ tools:
title: Suggest a workflow change
description: >
Suggest a change to a workflow for a human to review. Send only the content fields you want to change
- (usually actions), and in actions only the steps you change, each carrying its id. Send the evidence behind
- the suggestion, and a rationale a person can judge without re-deriving your numbers. This changes nothing on
- its own: a person approves the suggestion, which stages it as a draft, and publishes that draft to make it
- live. Pass a stable source_id for your run or finding so retrying returns the suggestion you already made
- instead of creating a second one. There is no tool to approve a suggestion, by design - only a person
- resolves one.
+ (usually actions), and in actions only the steps you change, each carrying its id and only the fields you
+ change; the rest of the step stays as it is. Pass the workflow version you read as base_version, so
+ approving can tell whether someone changed the same step or field since. Send the evidence behind the
+ suggestion, and a rationale a person can judge without re-deriving your numbers; PostHog reads the step's
+ own metrics at that version when you file and shows those next to yours. This changes nothing on its own: a
+ person approves the suggestion, which stages it as a draft, and publishes that draft to make it live. Pass a
+ stable source_id for your run or finding so retrying returns the suggestion you already made instead of
+ creating a second one. There is no tool to approve a suggestion, by design - only a person resolves one.
feature_flag: self-optimising-workflows
workflows-test-run:
operation: hog_flows_invocations_create
@@ -591,3 +591,20 @@ tools:
description: >
Update a recurring schedule's RRULE, start time, timezone, or variable overrides. Changing the cadence
reschedules the next run. Each firing re-broadcasts to the workflow's current trigger audience.
+ workflows-version-stats:
+ operation: hog_flows_metrics_version_retrieve
+ enabled: true
+ scopes:
+ - hog_flow:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get workflow stats for one version
+ description: >
+ Execution stats for a single published version of a workflow, in the same shape as workflows-stats. That is
+ how you tell whether a change helped: compare the version before it with the version after it. The
+ unversioned read in workflows-stats keys batch and broadcast runs on the run rather than the workflow, so it
+ is not the sum of the versions - compare versions with each other, not with it. Set instance_id to the step
+ you are reading, or several steps share one denominator.
+ feature_flag: self-optimising-workflows
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a909666dff33..76f19cc84d8c 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -14771,7 +14771,7 @@
}
},
"workflows-stats": {
- "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends with open/click tracking off, which can never register an open or a click.",
+ "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends with open/click tracking off, which can never register an open or a click. This reads the workflow's whole history; for one published version, call workflows-version-stats.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get workflow stats",
@@ -14785,7 +14785,7 @@
}
},
"workflows-suggest": {
- "description": "Suggest a change to a workflow for a human to review. Send only the content fields you want to change (usually actions), and in actions only the steps you change, each carrying its id. Send the evidence behind the suggestion, and a rationale a person can judge without re-deriving your numbers. This changes nothing on its own: a person approves the suggestion, which stages it as a draft, and publishes that draft to make it live. Pass a stable source_id for your run or finding so retrying returns the suggestion you already made instead of creating a second one. There is no tool to approve a suggestion, by design - only a person resolves one.",
+ "description": "Suggest a change to a workflow for a human to review. Send only the content fields you want to change (usually actions), and in actions only the steps you change, each carrying its id and only the fields you change; the rest of the step stays as it is. Pass the workflow version you read as base_version, so approving can tell whether someone changed the same step or field since. Send the evidence behind the suggestion, and a rationale a person can judge without re-deriving your numbers; PostHog reads the step's own metrics at that version when you file and shows those next to yours. This changes nothing on its own: a person approves the suggestion, which stages it as a draft, and publishes that draft to make it live. Pass a stable source_id for your run or finding so retrying returns the suggestion you already made instead of creating a second one. There is no tool to approve a suggestion, by design - only a person resolves one.",
"category": "Workflows",
"feature": "workflows",
"summary": "Suggest a workflow change",
@@ -14854,5 +14854,20 @@
"openWorldHint": true,
"readOnlyHint": false
}
+ },
+ "workflows-version-stats": {
+ "description": "Execution stats for a single published version of a workflow, in the same shape as workflows-stats. That is how you tell whether a change helped: compare the version before it with the version after it. The unversioned read in workflows-stats keys batch and broadcast runs on the run rather than the workflow, so it is not the sum of the versions - compare versions with each other, not with it. Set instance_id to the step you are reading, or several steps share one denominator.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow stats for one version",
+ "title": "Get workflow stats for one version",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "self-optimising-workflows"
}
}
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 18989909f8be..7aeb2e2dc974 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -15519,7 +15519,7 @@
}
},
"workflows-stats": {
- "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends with open/click tracking off, which can never register an open or a click.",
+ "description": "Execution stats for a single workflow by ID: time-series success/failure counts over a configurable interval (hour, day, or week). Use to inspect one workflow's health — failure spikes and reliability trends. For an at-a-glance view across ALL workflows, call workflows-global-stats first, then drill in here. Supports breakdown by metric kind (success/failure) or name, and time range filtering. For email engagement, read email_opened and email_link_clicked against (email_sent - email_untracked): email_untracked counts sends with open/click tracking off, which can never register an open or a click. This reads the workflow's whole history; for one published version, call workflows-version-stats.",
"category": "Workflows",
"feature": "workflows",
"summary": "Get workflow stats",
@@ -15533,7 +15533,7 @@
}
},
"workflows-suggest": {
- "description": "Suggest a change to a workflow for a human to review. Send only the content fields you want to change (usually actions), and in actions only the steps you change, each carrying its id. Send the evidence behind the suggestion, and a rationale a person can judge without re-deriving your numbers. This changes nothing on its own: a person approves the suggestion, which stages it as a draft, and publishes that draft to make it live. Pass a stable source_id for your run or finding so retrying returns the suggestion you already made instead of creating a second one. There is no tool to approve a suggestion, by design - only a person resolves one.",
+ "description": "Suggest a change to a workflow for a human to review. Send only the content fields you want to change (usually actions), and in actions only the steps you change, each carrying its id and only the fields you change; the rest of the step stays as it is. Pass the workflow version you read as base_version, so approving can tell whether someone changed the same step or field since. Send the evidence behind the suggestion, and a rationale a person can judge without re-deriving your numbers; PostHog reads the step's own metrics at that version when you file and shows those next to yours. This changes nothing on its own: a person approves the suggestion, which stages it as a draft, and publishes that draft to make it live. Pass a stable source_id for your run or finding so retrying returns the suggestion you already made instead of creating a second one. There is no tool to approve a suggestion, by design - only a person resolves one.",
"category": "Workflows",
"feature": "workflows",
"summary": "Suggest a workflow change",
@@ -15602,5 +15602,20 @@
"openWorldHint": true,
"readOnlyHint": false
}
+ },
+ "workflows-version-stats": {
+ "description": "Execution stats for a single published version of a workflow, in the same shape as workflows-stats. That is how you tell whether a change helped: compare the version before it with the version after it. The unversioned read in workflows-stats keys batch and broadcast runs on the run rather than the workflow, so it is not the sum of the versions - compare versions with each other, not with it. Set instance_id to the step you are reading, or several steps share one denominator.",
+ "category": "Workflows",
+ "feature": "workflows",
+ "summary": "Get workflow stats for one version",
+ "title": "Get workflow stats for one version",
+ "required_scopes": ["hog_flow:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "self-optimising-workflows"
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3d9cecbbbe42..e2eaf56d10f5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52425,7 +52425,7 @@ export namespace Schemas {
}
export interface HogFlowOptimization {
- /** Whether PostHog may read this workflow's metrics and suggest changes to it. */
+ /** Whether PostHog may suggest changes to this workflow. */
enabled: boolean;
}
@@ -73936,7 +73936,7 @@ export namespace Schemas {
readonly step_id: string | null;
/** Live workflow version this was authored against. Approving compares the steps and fields this changes against that version to tell whether somebody else already changed them. */
readonly base_version: number;
- /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges per step. */
+ /** Whether approving this would undo an edit made since it was proposed. False while the workflow only changed elsewhere, because approving merges only what the proposal changes. */
readonly is_stale: boolean;
readonly status: WorkflowProposalStatusEnum;
/**
@@ -107719,8 +107719,11 @@ export namespace Schemas {
content: WorkflowProposalCreateContent;
/** The metric numbers behind the proposal, so a human can judge it without re-deriving them. */
evidence?: WorkflowProposalCreateEvidence;
- /** Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise. */
- base_version?: number;
+ /**
+ * Workflow version this was authored against, as read from the workflow. It is the snapshot approve compares against to tell whether someone edited the same steps or fields since, and a defaulted version would read as current however long the producer took.
+ * @minimum 1
+ */
+ base_version: number;
/**
* The step this is about. Send it for a change to one step: both the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Leave it out only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
* @maxLength 200
@@ -107749,11 +107752,54 @@ export namespace Schemas {
below_minimum_sample: boolean;
}
+ export interface WorkflowVersionChange {
+ /**
+ * Step the field belongs to, or null for a workflow field.
+ * @nullable
+ */
+ step_name: string | null;
+ /** What changed, as a person reads it, e.g. 'email > subject'. */
+ field: string;
+ /**
+ * Value in the version before this one.
+ * @nullable
+ */
+ before: string | null;
+ /**
+ * Value this version published.
+ * @nullable
+ */
+ after: string | null;
+ /** Whether the suggestion is what changed this field. */
+ from_suggestion: boolean;
+ }
+
export interface WorkflowProposalVersionOutcome {
/** Workflow version these numbers belong to. */
version: number;
+ /** Whether the suggestion went live as this version. */
+ applied?: boolean;
+ /** Whether the suggestion was written against this version. */
+ proposed_against?: boolean;
+ /** Whether this version still holds what the suggestion changed. */
+ carries_change?: boolean;
+ /** Whether this version also changed something the suggestion did not, which the numbers cannot separate. */
+ other_changes?: boolean;
+ /** What this version changed against the version before it. */
+ changes?: WorkflowVersionChange[];
+ /**
+ * When this version went live.
+ * @nullable
+ */
+ published_at?: string | null;
+ /** Who published this version. */
+ published_by?: UserBasic | null;
+ /** Every version summed into these numbers. The after side runs on while later versions keep the change. */
+ versions?: number[];
/** The metric the suggestion aimed at. */
target: WorkflowProposalMetric;
+ /** The rate read beside the target, so a lift in one is visible against the other. */
+ secondary?: WorkflowProposalMetric;
/** Click-through rate over the same window and denominator, since opens alone can move without clicks. */
click_through: WorkflowProposalMetric;
/** Counter-metrics over the same window, so a harmful win is visible. */
@@ -107761,12 +107807,17 @@ export namespace Schemas {
}
export interface WorkflowProposalOutcome {
- /** Relative window both sides were measured over. */
- window: string;
+ /** Every published version around the change, each read over its own time live, so a later edit shows up as its own point rather than ending the comparison. */
+ versions: WorkflowProposalVersionOutcome[];
/** The version the change was proposed against. */
before: WorkflowProposalVersionOutcome | null;
- /** The version it went live as. Null until the proposal is applied. */
+ /** The versions that carried the change. Null until the proposal is applied. */
after: WorkflowProposalVersionOutcome | null;
+ /**
+ * The version that changed what the suggestion changed, which is where the after side stops. Null while the change is still live.
+ * @nullable
+ */
+ change_ended_at_version: number | null;
/** Counter-metrics that cannot be read yet, named so their absence is not read as zero. */
unavailable_guardrails: string[];
}
@@ -117991,6 +118042,72 @@ export namespace Schemas {
Week: 'week',
} as const;
+ export type HogFlowsMetricsVersionRetrieveParams = {
+ /**
+ * Start of the time range. Accepts relative formats like '-7d', '-24h' or ISO 8601 timestamps. Defaults to '-7d'.
+ * @minLength 1
+ */
+ after?: string;
+ /**
+ * End of the time range. Same format as 'after'. Defaults to now.
+ * @minLength 1
+ */
+ before?: string;
+ /**
+ * Group the series by metric 'name' or 'kind'. Defaults to 'kind'.
+ *
+ * * `name` - name
+ * * `kind` - kind
+ * @minLength 1
+ */
+ breakdown_by?: HogFlowsMetricsVersionRetrieveBreakdownBy;
+ /**
+ * Filter metrics to a specific execution instance.
+ * @minLength 1
+ */
+ instance_id?: string;
+ /**
+ * Time bucket size for the series. One of: hour, day, week. Defaults to 'day'.
+ *
+ * * `hour` - hour
+ * * `day` - day
+ * * `week` - week
+ * @minLength 1
+ */
+ interval?: HogFlowsMetricsVersionRetrieveInterval;
+ /**
+ * Comma-separated metric kinds to filter by, e.g. 'success,failure'.
+ * @minLength 1
+ */
+ kind?: string;
+ /**
+ * Comma-separated metric names to filter by.
+ * @minLength 1
+ */
+ name?: string;
+ /**
+ * Read one workflow version's series: every run of that version, keyed on the workflow. The unversioned read keys batch and broadcast runs on the run instead, so it is not the sum of the versions; compare versions with each other, not with it.
+ */
+ version: number;
+ };
+
+ export type HogFlowsMetricsVersionRetrieveBreakdownBy = typeof HogFlowsMetricsVersionRetrieveBreakdownBy[keyof typeof HogFlowsMetricsVersionRetrieveBreakdownBy];
+
+
+ export const HogFlowsMetricsVersionRetrieveBreakdownBy = {
+ Name: 'name',
+ Kind: 'kind',
+ } as const;
+
+ export type HogFlowsMetricsVersionRetrieveInterval = typeof HogFlowsMetricsVersionRetrieveInterval[keyof typeof HogFlowsMetricsVersionRetrieveInterval];
+
+
+ export const HogFlowsMetricsVersionRetrieveInterval = {
+ Hour: 'hour',
+ Day: 'day',
+ Week: 'week',
+ } as const;
+
export type HogFlowsProposalsListParams = {
/**
* Number of results to return per page.
@@ -118016,13 +118133,6 @@ export namespace Schemas {
Suggested: 'suggested',
} as const;
- export type HogFlowsProposalsOutcomeRetrieveParams = {
- /**
- * Relative window, e.g. -7d. Defaults to -7d.
- */
- window?: string;
- };
-
export type HogFlowsRevisionsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index 29781f888be7..79f7d0ed57a3 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 21 enabled ops
+ * PostHog API - MCP 22 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1036,6 +1036,57 @@ export const HogFlowsMetricsRetrieveQueryParams = () => zod.object({
name: zod.string().min(1).optional().describe('Comma-separated metric names to filter by.'),
})
+/**
+ * One published version's series. Every hog flow metric is mirrored under
+ * `hog_flow_version` with the version appended to the id, which is what makes "before and
+ * after this change" answerable at all. The unversioned read keys batch and broadcast runs on
+ * the run instead, so it is not the sum of the versions.
+ */
+export const HogFlowsMetricsVersionRetrieveParams = () => zod.object({
+ id: zod.string().describe('A UUID string identifying this hog flow.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const hogFlowsMetricsVersionRetrieveQueryAfterDefault = `-7d`
+
+export const hogFlowsMetricsVersionRetrieveQueryBreakdownByDefault = `kind`
+export const hogFlowsMetricsVersionRetrieveQueryIntervalDefault = `day`
+
+export const HogFlowsMetricsVersionRetrieveQueryParams = () => zod.object({
+ after: zod
+ .string()
+ .min(1)
+ .default(hogFlowsMetricsVersionRetrieveQueryAfterDefault)
+ .describe(
+ "Start of the time range. Accepts relative formats like '-7d', '-24h' or ISO 8601 timestamps. Defaults to '-7d'."
+ ),
+ before: zod.string().min(1).optional().describe("End of the time range. Same format as 'after'. Defaults to now."),
+ breakdown_by: zod
+ .enum(['name', 'kind'])
+ .default(hogFlowsMetricsVersionRetrieveQueryBreakdownByDefault)
+ .describe(
+ "Group the series by metric 'name' or 'kind'. Defaults to 'kind'.\n\n\* `name` - name\n\* `kind` - kind"
+ ),
+ instance_id: zod.string().min(1).optional().describe('Filter metrics to a specific execution instance.'),
+ interval: zod
+ .enum(['hour', 'day', 'week'])
+ .default(hogFlowsMetricsVersionRetrieveQueryIntervalDefault)
+ .describe(
+ "Time bucket size for the series. One of: hour, day, week. Defaults to 'day'.\n\n\* `hour` - hour\n\* `day` - day\n\* `week` - week"
+ ),
+ kind: zod.string().min(1).optional().describe("Comma-separated metric kinds to filter by, e.g. 'success,failure'."),
+ name: zod.string().min(1).optional().describe('Comma-separated metric names to filter by.'),
+ version: zod
+ .number()
+ .describe(
+ "Read one workflow version's series: every run of that version, keyed on the workflow. The unversioned read keys batch and broadcast runs on the run instead, so it is not the sum of the versions; compare versions with each other, not with it."
+ ),
+})
+
/**
* Agent-authored changes to this workflow, awaiting a human's decision.
*
@@ -1095,9 +1146,9 @@ export const HogFlowsProposalsCreateBody = () => zod.object({
.describe('The metric numbers behind the proposal, so a human can judge it without re-deriving them.'),
base_version: zod
.number()
- .optional()
+ .min(1)
.describe(
- 'Workflow version this was authored against. Required when the proposal changes actions, edges or variables: it is the snapshot approve compares against to tell whether someone edited the same steps since, and a defaulted version would read as current however long the producer took. Defaults to the current live version otherwise.'
+ 'Workflow version this was authored against, as read from the workflow. It is the snapshot approve compares against to tell whether someone edited the same steps or fields since, and a defaulted version would read as current however long the producer took.'
),
step_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 8aa5d2050adc..c6589f94f20f 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -694,6 +694,40 @@ const workflowsUpdateSchedule = (): ToolBase<
},
})
+const WorkflowsVersionStatsSchema = () => {
+ const HogFlowsMetricsVersionRetrieveParams = orvalSchemas.HogFlowsMetricsVersionRetrieveParams()
+ const HogFlowsMetricsVersionRetrieveQueryParams = orvalSchemas.HogFlowsMetricsVersionRetrieveQueryParams()
+ return HogFlowsMetricsVersionRetrieveParams.omit({ project_id: true }).extend(
+ HogFlowsMetricsVersionRetrieveQueryParams.shape
+ )
+}
+
+const workflowsVersionStats = (): ToolBase<
+ ReturnType<typeof WorkflowsVersionStatsSchema>,
+ Schemas.AppMetricsResponse
+> => ({
+ name: 'workflows-version-stats',
+ schema: WorkflowsVersionStatsSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof WorkflowsVersionStatsSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.AppMetricsResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_flows/${encodeURIComponent(String(params.id))}/metrics/version/`,
+ query: {
+ after: params.after,
+ before: params.before,
+ breakdown_by: params.breakdown_by,
+ instance_id: params.instance_id,
+ interval: params.interval,
+ kind: params.kind,
+ name: params.name,
+ version: params.version,
+ },
+ })
+ return result
+ },
+})
+
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'broadcasts-create': broadcastsCreate,
'workflows-create': workflowsCreate,
@@ -718,4 +752,5 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'workflows-test-run': workflowsTestRun,
'workflows-update': workflowsUpdate,
'workflows-update-schedule': workflowsUpdateSchedule,
+ 'workflows-version-stats': workflowsVersionStats,
}