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.

chore(workflows): route revisions, proposal outcomes and optimization through the facade (#109406)

Harley Alexander48aa84a4d604
diff --git a/products/workflows/backend/facade/content.py b/products/workflows/backend/facade/content.py
new file mode 100644
index 000000000000..81f84de383d5
--- /dev/null
+++ b/products/workflows/backend/facade/content.py
@@ -0,0 +1,9 @@
+"""A workflow's content: the fields the draft cycle stages and publish promotes, and how to read them."""
+
+from products.workflows.backend.services.hog_flow_content import DRAFT_CONTENT_FIELDS, deep_merge, snapshot_content
+
+__all__ = [
+ "DRAFT_CONTENT_FIELDS",
+ "deep_merge",
+ "snapshot_content",
+]
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 19ac37ccd353..bfa407b02509 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -324,3 +324,41 @@ class TwilioAccount(TypedDict, total=False):
"""Empty when the Twilio request fails."""
sid: str
+
+
+@frozen
+class WorkflowRevisionSummary:
+ """One entry of a workflow's version history, without the content snapshot."""
+
+ version: int
+ created_at: datetime
+ created_by: "User | None"
+
+
+@frozen
+class WorkflowRevision:
+ version: int
+ created_at: datetime
+ created_by: "User | None"
+ content: dict[str, Any]
+
+
+class WorkflowRevisionNotFound(Exception):
+ pass
+
+
+class WorkflowDraftExists(Exception):
+ """A draft is staged and the caller did not ask to overwrite it."""
+
+
+class WorkflowDraftChanged(Exception):
+ """The staged draft changed since the caller confirmed the overwrite."""
+
+
+@frozen
+class ProposalChanges:
+ """What approving a suggestion would stage. `conflicts` names the steps or fields someone else
+ changed since it was written; approval is refused while there are any."""
+
+ changes: dict
+ conflicts: list[str]
diff --git a/products/workflows/backend/facade/proposals.py b/products/workflows/backend/facade/proposals.py
new file mode 100644
index 000000000000..0a1d718e9a4e
--- /dev/null
+++ b/products/workflows/backend/facade/proposals.py
@@ -0,0 +1,31 @@
+"""Suggested changes to a workflow, the per-workflow opt-in that allows them, and what each change did."""
+
+from products.workflows.backend.metrics import HOG_FLOW_VERSION_APP_SOURCE
+from products.workflows.backend.services.workflow_proposals import (
+ PROPOSAL_MERGE_BY_ID_FIELDS,
+ as_the_serializer_stores_it,
+ is_optimization_enabled,
+ merge_proposal_content,
+ proposal_conflicts,
+ proposal_outcome,
+ set_optimization_enabled,
+ staged_proposal_changes,
+ target_metric_in,
+ unstage_workflow_proposals,
+ version_outcome,
+)
+
+__all__ = [
+ "HOG_FLOW_VERSION_APP_SOURCE",
+ "PROPOSAL_MERGE_BY_ID_FIELDS",
+ "as_the_serializer_stores_it",
+ "is_optimization_enabled",
+ "merge_proposal_content",
+ "proposal_conflicts",
+ "proposal_outcome",
+ "set_optimization_enabled",
+ "staged_proposal_changes",
+ "target_metric_in",
+ "unstage_workflow_proposals",
+ "version_outcome",
+]
diff --git a/products/workflows/backend/facade/revisions.py b/products/workflows/backend/facade/revisions.py
new file mode 100644
index 000000000000..59726b2a4683
--- /dev/null
+++ b/products/workflows/backend/facade/revisions.py
@@ -0,0 +1,15 @@
+"""A workflow's version history: one content snapshot per live change, and restoring one into the draft."""
+
+from products.workflows.backend.services.hog_flow_revisions import (
+ count_revisions,
+ get_revision,
+ list_revisions,
+ restore_revision,
+)
+
+__all__ = [
+ "count_revisions",
+ "get_revision",
+ "list_revisions",
+ "restore_revision",
+]
diff --git a/products/workflows/backend/presentation/views/graph_operations.py b/products/workflows/backend/presentation/views/graph_operations.py
index f5f5e78e996e..c65d9f0b27c2 100644
--- a/products/workflows/backend/presentation/views/graph_operations.py
+++ b/products/workflows/backend/presentation/views/graph_operations.py
@@ -3,6 +3,8 @@ from typing import NoReturn
from rest_framework import serializers
+from products.workflows.backend.facade.content import deep_merge
+
# Surgical, id-addressed edits to a workflow graph (actions + edges). The caller sends a small,
# ordered list of operations instead of re-transmitting the whole graph; these are applied to the
# stored actions/edges and the result is validated + saved by the serializer. Pure functions here —
@@ -10,20 +12,6 @@ from rest_framework import serializers
# (that's validate_graph) — so they're cheap to unit-test exhaustively.
-def _deep_merge(target: dict, patch: dict) -> dict:
- """Recursively merge `patch` into `target`. A null leaf deletes the key; a dict merges into a
- dict; anything else replaces. Lets a caller change config.inputs.subject without resending the
- rest of config."""
- for key, value in patch.items():
- if value is None:
- target.pop(key, None)
- elif isinstance(value, dict) and isinstance(target.get(key), dict):
- _deep_merge(target[key], value)
- else:
- target[key] = value
- return target
-
-
def _edges_match(a: dict, b: dict) -> bool:
return (
a.get("from") == b.get("from")
@@ -54,7 +42,7 @@ def apply_graph_operations(
action = actions_by_id.get(op["id"])
if action is None:
_fail(f"update_action: action '{op['id']}' not found")
- _deep_merge(action, op["patch"])
+ deep_merge(action, op["patch"])
elif kind == "add_action":
new_action = op["action"]
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 388fbe403fcf..c03f2f294810 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -1,10 +1,9 @@
import re
-import copy
import json
import uuid as uuid_mod
import hashlib
import dataclasses
-from collections.abc import Mapping, Sequence
+from collections.abc import Sequence
from copy import deepcopy
from datetime import timedelta
from time import monotonic
@@ -15,7 +14,7 @@ from django.conf import settings
from django.core.cache import cache
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import IntegrityError, models, transaction
-from django.db.models import Count, Exists, OuterRef, Q, QuerySet, Subquery
+from django.db.models import Count, F, OuterRef, Q, QuerySet, Subquery, Value
from django.db.models.expressions import RawSQL
from django.db.models.functions import Coalesce
from django.http import Http404, HttpResponse
@@ -53,7 +52,6 @@ from posthog.api.app_metrics2 import (
AppMetricsMixin,
AppMetricsRequestSerializer,
AppMetricsTotalsResponseSerializer,
- fetch_app_metric_totals,
fetch_app_metric_totals_by_source,
fetch_app_metrics_trends,
)
@@ -138,9 +136,14 @@ from products.workflows.backend.facade.blast_radius import (
is_account_audience,
parse_account_audience_filters,
)
+from products.workflows.backend.facade.content import DRAFT_CONTENT_FIELDS, deep_merge, snapshot_content
from products.workflows.backend.facade.contracts import (
StaffPausedError,
WorkflowBatchJobNotFound,
+ WorkflowDraftChanged,
+ WorkflowDraftExists,
+ WorkflowRevisionNotFound,
+ WorkflowRevisionSummary,
WorkflowScheduleNotFound,
)
from products.workflows.backend.facade.email_health import (
@@ -154,6 +157,21 @@ from products.workflows.backend.facade.email_health import (
team_email_sending_allowance,
)
from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus
+from products.workflows.backend.facade.proposals import (
+ HOG_FLOW_VERSION_APP_SOURCE,
+ PROPOSAL_MERGE_BY_ID_FIELDS,
+ as_the_serializer_stores_it,
+ is_optimization_enabled,
+ merge_proposal_content,
+ proposal_conflicts,
+ proposal_outcome,
+ set_optimization_enabled,
+ staged_proposal_changes,
+ target_metric_in,
+ unstage_workflow_proposals,
+ version_outcome,
+)
+from products.workflows.backend.facade.revisions import count_revisions, get_revision, list_revisions, restore_revision
from products.workflows.backend.facade.schedules import (
compute_next_occurrences,
create_schedule,
@@ -186,18 +204,6 @@ from products.workflows.backend.facade.validation import (
is_duration,
is_signed_duration,
)
-from products.workflows.backend.metrics import (
- GUARDRAIL_LABELS,
- GUARDRAIL_METRICS,
- HOG_FLOW_VERSION_APP_SOURCE,
- MIN_EVIDENCE_SAMPLE,
- TARGET_CLICK_METRIC,
- TARGET_METRICS,
- TARGET_OPEN_METRIC,
- TARGET_SEND_METRIC,
- TARGET_UNTRACKED_METRIC,
- UNAVAILABLE_GUARDRAILS,
-)
from products.workflows.backend.models.hog_flow.hog_flow import (
BILLABLE_ACTION_TYPES,
MESSAGING_ACTION_TYPES,
@@ -208,11 +214,10 @@ from products.workflows.backend.models.hog_flow.hog_flow import (
WORKFLOW_SAFE_INTERNAL_EVENTS,
HogFlow,
)
-from products.workflows.backend.models.hog_flow_optimization import HogFlowOptimization
from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
from products.workflows.backend.models.workflow_proposal import WorkflowProposal
from products.workflows.backend.presentation.views.action_redirects import compute_action_redirects
-from products.workflows.backend.presentation.views.graph_operations import _deep_merge, apply_graph_operations
+from products.workflows.backend.presentation.views.graph_operations import apply_graph_operations
from products.workflows.backend.presentation.views.graph_validation import validate_graph
from products.workflows.backend.presentation.views.hog_flow_batch_job import (
HogFlowBatchJobCancelResponseSerializer,
@@ -240,22 +245,6 @@ from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timin
logger = structlog.get_logger(__name__)
-# The content of a workflow: everything the draft cycle stages and publish promotes, and nothing
-# else. Metadata (name, description) and lifecycle (status) always apply to the live row. The draft
-# blob is a full snapshot of these fields so publish is a plain copy, not a merge.
-DRAFT_CONTENT_FIELDS = (
- "actions",
- "edges",
- "trigger",
- "trigger_masking",
- "conversion",
- "exit_condition",
- "email_sending_rate_limit",
- "abort_action",
- "variables",
-)
-
-
# Compiled from the author's filters rather than written by them, and only present once a condition has
# been through validation. Comparing them would make an unchanged condition look edited.
_DERIVED_FILTER_KEYS = ("bytecode", "bytecode_error", "bytecode_contract", "source")
@@ -371,22 +360,6 @@ def _reject_clock_based_wait(config: dict, team: Team) -> None:
)
-def snapshot_flow_content(flow: HogFlow) -> dict:
- snapshot = {field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS}
- # The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize
- # so re-validation of a snapshot (draft publish, revision restore) doesn't choke on a
- # never-edited column.
- for field in ("actions", "edges"):
- if not snapshot[field]:
- snapshot[field] = []
- # Defensively strip secrets: a legacy row written before encryption shipped still has plaintext
- # secret inputs in `actions`, and this snapshot feeds revision content — which must never carry
- # secrets. New rows are already stripped, so this is a no-op for them. Every create takes a
- # snapshot inside its transaction, so the cache resolves each template once instead of once per
- # action.
- return strip_content_secrets(snapshot, template_cache={})
-
-
def existing_secret_map(instance: "HogFlow", template_cache: Optional[TemplateCache] = None) -> dict[str, dict]:
# Every stored secret a masked re-save may need to recover, later sources winning: legacy
# plaintext (live, then draft), then the encrypted live map, then the encrypted draft map.
@@ -417,6 +390,14 @@ def mask_trigger_config(
return masked[0].get("config")
+def snapshot_flow_content(flow: HogFlow) -> dict:
+ return snapshot_content({field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS})
+
+
+def item_id(item: Any) -> Any:
+ return item.get("id") if isinstance(item, dict) else None
+
+
def strip_proposal_secrets(content: dict, live_content: dict, template_cache: Optional[TemplateCache] = None) -> dict:
"""Strip secret inputs from a proposal's content, classifying each step against the live step it
patches. A patch carries only the fields it changes, so it can set a secret input without the
@@ -426,13 +407,13 @@ def strip_proposal_secrets(content: dict, live_content: dict, template_cache: Op
actions = stripped.get("actions")
if not isinstance(actions, list):
return stripped
- live_by_id = {_item_id(item): item for item in live_content.get("actions") or []}
+ live_by_id = {item_id(item): item for item in live_content.get("actions") or []}
for item in actions:
- live_step = live_by_id.get(_item_id(item))
+ live_step = live_by_id.get(item_id(item))
inputs = (item.get("config") or {}).get("inputs") if isinstance(item, dict) else None
if live_step is None or not isinstance(inputs, dict):
continue
- for key in secret_keys_for_action(_deep_merge(deepcopy(live_step), item), template_cache):
+ for key in secret_keys_for_action(deep_merge(deepcopy(live_step), item), template_cache):
inputs.pop(key, None)
return stripped
@@ -3372,7 +3353,7 @@ def _apply_action_email_edit(
value["html"] = rendered.html
if email_patch:
- _deep_merge(value, email_patch)
+ deep_merge(value, email_patch)
return new_actions
@@ -3519,21 +3500,19 @@ class HogFlowPublishResponseSerializer(serializers.Serializer):
)
-class HogFlowRevisionBasicSerializer(serializers.ModelSerializer):
+class HogFlowRevisionBasicSerializer(serializers.Serializer):
+ version = serializers.IntegerField(read_only=True, help_text="Workflow version this snapshot was published as.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When this version was published.")
# allow_null: the first tracked write bootstraps a snapshot of the pre-existing live content,
# which has no author.
created_by = UserBasicSerializer(read_only=True, allow_null=True)
- class Meta:
- model = HogFlowRevision
- fields = ["version", "created_at", "created_by"]
- read_only_fields = fields
-
class HogFlowRevisionSerializer(HogFlowRevisionBasicSerializer):
- class Meta(HogFlowRevisionBasicSerializer.Meta):
- fields = [*HogFlowRevisionBasicSerializer.Meta.fields, "content"]
- read_only_fields = fields
+ content = serializers.JSONField(
+ read_only=True,
+ help_text="Full snapshot of the workflow's content fields (actions, edges, trigger, etc.) at this version.",
+ )
class HogFlowRevisionRestoreRequestSerializer(serializers.Serializer):
@@ -3561,12 +3540,6 @@ SELF_OPTIMISING_FEATURE_FLAG = "self-optimising-workflows"
PROPOSAL_CONTENT_FIELDS = tuple(field for field in DRAFT_CONTENT_FIELDS if field not in ("trigger", "abort_action"))
-# Fields a proposal replaces wholesale. `actions` merges per step instead, since steps carry stable
-# ids; edges have no id, and a variable list is short enough to carry whole.
-PROPOSAL_WHOLE_LIST_FIELDS = ("edges", "variables")
-
-PROPOSAL_MERGE_BY_ID_FIELDS = ("actions",)
-
# Their items reach helpers that read each item as a mapping, so anything else has to fail here as a 400.
PROPOSAL_LIST_OF_OBJECT_FIELDS = ("actions", "edges", "variables")
@@ -3657,7 +3630,9 @@ class WorkflowProposalSerializer(serializers.ModelSerializer):
cache = self.context.setdefault("proposal_conflicts", {})
key = (proposal.hog_flow_id, proposal.base_version, json.dumps(proposal.content, sort_keys=True))
if key not in cache:
- cache[key] = conflicting_parts(proposal.hog_flow, proposal)
+ cache[key] = proposal_conflicts(
+ team_id=proposal.team_id, hog_flow_id=proposal.hog_flow_id, proposal_id=proposal.id
+ )
return bool(cache[key])
@@ -3928,42 +3903,6 @@ 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
- that email and the rest of the graph exactly as they are now."""
- merged = {**live_content, **proposal_content}
- for field in PROPOSAL_MERGE_BY_ID_FIELDS:
- if field in proposal_content:
- merged[field] = _merge_by_id(live_content.get(field) or [], proposal_content[field] or [])
- return merged
-
-
-def _merge_by_id(live_items: list, changed_items: list) -> list:
- """Merge each changed step into the live step with the same id, field by field, the way the
- graph API's `update_action` does: a producer sends the fields it changes and nothing else, so a
- step can never lose its template inputs to a payload that only carried a subject line."""
- changed_by_id = {item["id"]: item for item in changed_items if isinstance(item, dict) and "id" in item}
- merged = []
- for item in live_items:
- patch = changed_by_id.pop(_item_id(item), None)
- merged.append(_deep_merge(copy.deepcopy(item), patch) if patch is not None else item)
- # Anything left names a step the workflow does not have yet, so the proposal is adding it whole.
- merged.extend(changed_by_id.values())
- return merged
-
-
-def _item_id(item: Any) -> Any:
- return item.get("id") if isinstance(item, dict) else None
-
-
def _validate_merge_keys(field: str, items: Any) -> None:
"""Merging is keyed on `id`, so a missing or repeated one has no defined meaning. Reject it here
rather than picking a winner and staging a draft the author did not write."""
@@ -3971,359 +3910,14 @@ def _validate_merge_keys(field: str, items: Any) -> None:
return
seen: set[str] = set()
for index, item in enumerate(items):
- item_id = _item_id(item)
- if not isinstance(item_id, str) or not item_id:
+ key = item_id(item)
+ if not isinstance(key, str) or not key:
raise exceptions.ValidationError(
f"`{field}[{index}]` needs the `id` of the step it changes. Send only the steps you change."
)
- if item_id in seen:
- raise exceptions.ValidationError(f"`{field}` names `{item_id}` twice.")
- seen.add(item_id)
-
-
-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,
- 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]
-
-
-def conflicting_parts(hog_flow: HogFlow, proposal: WorkflowProposal, content: Optional[dict] = None) -> list[str]:
- """Parts of the workflow the proposal changes that someone else already changed since it was
- written: step ids for `actions`, field names for everything else.
-
- The check follows merge semantics. A step merges per field, so only the fields the proposal sets
- on the steps it names are compared, as they were at `base_version` against as they are now. A
- whole-list field replaces the list, so any publish since counts. Every other field replaces one
- value, so that value is compared. An edit elsewhere merges cleanly, and an edit that already made
- the proposed change is nothing to undo, so neither is a reason to refuse."""
- if hog_flow.version == proposal.base_version:
- return []
- base_content = base_content_of(hog_flow, proposal)
- content = proposal_changes(proposal, base_content) if content is None else content
- touched_steps = {_item_id(item) for item in content.get("actions") or []} - {None}
- touched_lists = [field for field in PROPOSAL_WHOLE_LIST_FIELDS if field in content]
- touched_fields = [
- field
- for field in content
- if field not in PROPOSAL_MERGE_BY_ID_FIELDS and field not in PROPOSAL_WHOLE_LIST_FIELDS
- ]
- if touched_lists:
- # A whole-list field replaces the list, so any publish since counts.
- return sorted({*touched_steps, *touched_lists, *touched_fields})
- if base_content is None:
- # Without the snapshot the proposal read, "changed since" is unanswerable.
- return sorted({*touched_steps, *touched_fields})
- live_content = snapshot_flow_content(hog_flow)
- base_actions = {_item_id(item): item for item in base_content.get("actions") or []}
- live_actions = {_item_id(item): item for item in live_content.get("actions") or []}
- proposed_actions = {_item_id(item): item for item in content.get("actions") or []}
- moved_steps = [
- step_id
- for step_id in touched_steps
- # A step the proposal adds is only a conflict if that id now exists.
- if not (step_id not in base_actions and step_id not in live_actions)
- and _moved_since(base_actions.get(step_id), live_actions.get(step_id), proposed_actions[step_id])
- ]
- moved_fields = [
- field
- for field in touched_fields
- # These replace the whole value, so a key the proposal does not name still goes with it.
- if base_content.get(field) != live_content.get(field) and live_content.get(field) != content[field]
- ]
- return sorted({*moved_steps, *moved_fields})
-
-
-def base_content_of(hog_flow: HogFlow, proposal: WorkflowProposal) -> dict | None:
- """The workflow as the proposal read it. That is the live workflow while its version has not
- moved; after a publish it is the revision snapshot, which a workflow that has never been
- published under revision tracking may not have."""
- if hog_flow.version == proposal.base_version:
- return snapshot_flow_content(hog_flow)
- revision = HogFlowRevision.objects.filter(hog_flow=hog_flow, version=proposal.base_version).first()
- return dict(revision.content) if revision is not None else None
-
-
-def proposal_changes(proposal: WorkflowProposal, base_content: dict | None) -> dict:
- """The proposal's content reduced to what it changes against the workflow as it read it: a
- step keeps only the fields that read differently there, and a step that reads the same drops
- out. A producer that sends a whole step therefore still merges as the one-field change it made,
- and never writes the rest of that step back over a later edit. Without the snapshot the content
- stands as sent."""
- content = dict(proposal.content)
- if base_content is None or "actions" not in content:
- return content
- base_steps = {_item_id(item): item for item in base_content.get("actions") or []}
- changed_steps = []
- for item in content.get("actions") or []:
- base_step = base_steps.get(_item_id(item))
- if not isinstance(item, dict) or base_step is None:
- changed_steps.append(item)
- continue
- changed = _changed_leaves(base_step, {key: value for key, value in item.items() if key != "id"})
- if changed is not _ABSENT:
- changed_steps.append({"id": item["id"], **changed})
- content["actions"] = changed_steps
- return content
-
-
-_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_in(evidence: Any) -> str:
- """The metric the suggestion aimed at. Anything the surfaces cannot read is measured on opens."""
- named = evidence.get("metric") if isinstance(evidence, dict) else None
- return named if named in TARGET_METRICS else TARGET_OPEN_METRIC
-
-
-def target_metric_of(proposal: WorkflowProposal) -> str:
- return target_metric_in(proposal.evidence)
-
-
-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."""
- if isinstance(patch, dict) and isinstance(base, dict):
- kept = {}
- for key, value in patch.items():
- changed = _changed_leaves(base.get(key), value)
- if changed is not _ABSENT:
- kept[key] = changed
- return kept if kept else _ABSENT
- if patch is None:
- return _ABSENT if base is None else None
- return _ABSENT if patch == base else patch
-
-
-def _moved_since(base: Any, live: Any, proposed: Any) -> bool:
- """Whether someone changed, since `base`, something the proposal sets, and to a value other than
- the proposed one. Reads the patch the way `_deep_merge` writes it: a dict compares leaf by leaf,
- anything else as one value."""
- if not isinstance(proposed, dict) or base is None or live is None:
- return base != live and live != proposed
- return any(
- _leaf(live, path) != _leaf(base, path) and _leaf(live, path) != _leaf(proposed, path)
- for path in _patch_paths(proposed)
- )
-
-
-def _patch_paths(patch: Any, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]:
- if not isinstance(patch, dict) or not patch:
- return [prefix]
- return [path for key, value in patch.items() for path in _patch_paths(value, (*prefix, key))]
-
-
-def _leaf(item: Any, path: tuple[str, ...]) -> Any:
- for key in path:
- if not isinstance(item, dict) or key not in item:
- return _ABSENT
- item = item[key]
- # A null leaf in a patch deletes the key, so it reads as the key being absent.
- 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 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.
- """
- 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
- )
+ if key in seen:
+ raise exceptions.ValidationError(f"`{field}` names `{key}` twice.")
+ seen.add(key)
class CommaSeparatedListFilter(BaseInFilter, CharFilter):
@@ -4424,6 +4018,19 @@ class HogFlowFilterSet(FilterSet):
return queryset.filter(optimization__enabled=True, status=HogFlow.State.ACTIVE)
+class _RevisionPages:
+ """Lets LimitOffsetPagination page revisions in the database, as it did over a queryset."""
+
+ def __init__(self, hog_flow_id: uuid_mod.UUID) -> None:
+ self.hog_flow_id = hog_flow_id
+
+ def count(self) -> int:
+ return count_revisions(self.hog_flow_id)
+
+ def __getitem__(self, page: slice) -> list[WorkflowRevisionSummary]:
+ return list_revisions(self.hog_flow_id, offset=page.start or 0, limit=page.stop - (page.start or 0))
+
+
class HogFlowPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 500
@@ -4780,9 +4387,7 @@ class HogFlowViewSet(
)
queryset = queryset.annotate(
pending_suggestions=Coalesce(Subquery(pending), 0),
- suggestions_enabled=Exists(
- HogFlowOptimization.objects.filter(hog_flow=OuterRef("pk"), enabled=True).values("pk")
- ),
+ suggestions_enabled=Coalesce(F("optimization__enabled"), Value(False)),
)
# A suggestion waits on a person, so the page that shows them sorts it above recency. Every
# other reader of this list — the MCP tool, any other surface — keeps recency, or a stale
@@ -5182,7 +4787,7 @@ class HogFlowViewSet(
bump = self._stage_revision_bump(serializer.instance, before_update, serializer.validated_data)
if clears_staged_draft:
serializer.save(draft=None, draft_updated_at=None, draft_encrypted_inputs=None)
- unstage_workflow_proposals(serializer.instance)
+ unstage_workflow_proposals(team_id=serializer.instance.team_id, hog_flow_id=serializer.instance.pk)
else:
serializer.save()
if bump:
@@ -5299,7 +4904,7 @@ class HogFlowViewSet(
instance.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
# An edit over an approved draft may undo the suggestion, and publish reads approved as shipped.
- unstage_workflow_proposals(instance)
+ unstage_workflow_proposals(team_id=instance.team_id, hog_flow_id=instance.pk)
@extend_schema(request=HogFlowGraphUpdateSerializer, responses={200: HogFlowSerializer})
@action(detail=True, methods=["PATCH"])
@@ -5722,13 +5327,13 @@ class HogFlowViewSet(
locked.draft = None
locked.draft_updated_at = None
locked.draft_encrypted_inputs = None
- unstage_workflow_proposals(locked)
# updated_at (auto_now) is deliberately bumped: without a fresh live stamp the
# resource_edited broadcast carries the old updated_at — older than the draft stamp
# concurrent editors loaded, so they'd ignore the discard, and their next draft save
# would pass the staleness guard (which falls back to the live stamp once the draft is
# gone) and silently resurrect the discarded draft.
locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs", "updated_at"])
+ unstage_workflow_proposals(team_id=locked.team_id, hog_flow_id=locked.pk)
log_activity_from_viewset(self, locked, activity="draft_discarded", name=locked.name, previous=before_update)
self._emit_resource_edited(locked)
@@ -5744,8 +5349,7 @@ class HogFlowViewSet(
# Version history: one snapshot per live-content change, newest first. Content is fetched
# per-version via the detail endpoint — the list stays light.
instance = self.get_object()
- queryset = HogFlowRevision.objects.filter(hog_flow=instance).order_by("-version").select_related("created_by")
- page = self.paginate_queryset(queryset)
+ page = self.paginate_queryset(cast(Sequence[Any], _RevisionPages(instance.pk)))
return self.get_paginated_response(HogFlowRevisionBasicSerializer(page, many=True).data)
@extend_schema(
@@ -5755,9 +5359,8 @@ class HogFlowViewSet(
@action(detail=True, methods=["GET"], url_path=r"revisions/(?P<version>\d+)")
def revision_detail(self, request: Request, version: Optional[str] = None, *args, **kwargs):
instance = self.get_object()
- try:
- revision = HogFlowRevision.objects.get(hog_flow=instance, version=int(version or 0))
- except HogFlowRevision.DoesNotExist:
+ revision = get_revision(hog_flow_id=instance.pk, version=int(version or 0))
+ if revision is None:
raise exceptions.NotFound("No such revision for this workflow.")
return Response(HogFlowRevisionSerializer(revision).data)
@@ -5777,39 +5380,26 @@ class HogFlowViewSet(
param_serializer.is_valid(raise_exception=True)
instance = self.get_object()
- with transaction.atomic():
- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
- locked = HogFlow.objects.select_for_update().get(pk=instance.pk)
- try:
- revision = HogFlowRevision.objects.get(hog_flow_id=locked.pk, version=int(version or 0))
- except HogFlowRevision.DoesNotExist:
- raise exceptions.NotFound("No such revision for this workflow.")
- if locked.draft and not param_serializer.validated_data["overwrite"]:
- raise DraftExistsError()
- # Overwrite fencing: the client confirms against the draft stamp it saw. A draft staged
- # or edited between the confirmation dialog and this call carries a different stamp, and
- # overwriting it would lose unpublished content that no revision snapshots.
- expected_draft_updated_at = param_serializer.validated_data.get("expected_draft_updated_at")
- if (
- locked.draft
- and expected_draft_updated_at is not None
- and locked.draft_updated_at != expected_draft_updated_at
- ):
- raise StaleWorkflowUpdateError()
- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
- before_update = HogFlow.objects.get(pk=instance.pk)
- locked.draft = dict(revision.content)
- locked.draft_updated_at = timezone.now()
- unstage_workflow_proposals(locked)
- # Revision snapshots carry no secrets (they're stripped before snapshotting), so the
- # restored draft re-attaches from the live encrypted_inputs on the follow-up publish.
- # Clear any stale draft secrets from a prior draft so they can't bleed into this one.
- locked.draft_encrypted_inputs = None
- locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
+ restored_version = int(version or 0)
+ try:
+ restore_revision(
+ hog_flow_id=instance.pk,
+ version=restored_version,
+ overwrite=param_serializer.validated_data["overwrite"],
+ expected_draft_updated_at=param_serializer.validated_data.get("expected_draft_updated_at"),
+ )
+ except WorkflowRevisionNotFound:
+ raise exceptions.NotFound("No such revision for this workflow.")
+ except WorkflowDraftExists:
+ raise DraftExistsError()
+ except WorkflowDraftChanged:
+ raise StaleWorkflowUpdateError()
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance)
+ locked = HogFlow.objects.get(pk=instance.pk)
- log_activity_from_viewset(self, locked, activity="revision_restored", name=locked.name, previous=before_update)
+ log_activity_from_viewset(self, locked, activity="revision_restored", name=locked.name, previous=instance)
self._emit_resource_edited(locked)
- self._report_workflow_action("hog_flow_revision_restored", locked, {"version": revision.version})
+ self._report_workflow_action("hog_flow_revision_restored", locked, {"version": restored_version})
return Response(self.get_serializer(locked).data)
@@ -5893,7 +5483,7 @@ class HogFlowViewSet(
# 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():
+ if not is_optimization_enabled(instance.pk):
raise WorkflowNotOptimisedError()
live_content = snapshot_flow_content(instance)
@@ -5929,13 +5519,13 @@ class HogFlowViewSet(
]
}
)
- content = _as_the_serializer_stores_it(content, draft_serializer.validated_data)
+ 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 []}
+ 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."}
@@ -6033,10 +5623,11 @@ class HogFlowViewSet(
raise ProposalAlreadyResolvedError()
if locked.draft and not param_serializer.validated_data["overwrite"]:
raise DraftExistsError()
- changes = proposal_changes(locked_proposal, base_content_of(locked, locked_proposal))
- conflicts = conflicting_parts(locked, locked_proposal, changes)
- if conflicts:
- raise ProposalOutOfDateError(describe_steps(locked, conflicts))
+ staged = staged_proposal_changes(
+ team_id=locked.team_id, hog_flow_id=locked.pk, proposal_id=locked_proposal.pk
+ )
+ if staged.conflicts:
+ raise ProposalOutOfDateError(staged.conflicts)
expected_draft_updated_at = param_serializer.validated_data.get("expected_draft_updated_at")
if (
locked.draft
@@ -6049,7 +5640,7 @@ class HogFlowViewSet(
# The draft is a full snapshot (live plus what the suggestion changes), so publish stays
# a plain copy. A field the suggestion merely echoed is not staged, since writing it back
# would undo a later edit the conflict check let through.
- merged = merge_proposal_content(snapshot_flow_content(locked), changes)
+ merged = merge_proposal_content(snapshot_flow_content(locked), staged.changes)
try:
# Create validated the merge against the graph as it was then; it can have moved since.
validate_graph(merged.get("actions") or [], merged.get("edges") or [], merged.get("abort_action"))
@@ -6062,7 +5653,7 @@ class HogFlowViewSet(
locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
# The new draft replaces what was staged; an earlier approval stays only if the draft still carries it.
- unstage_workflow_proposals(locked)
+ unstage_workflow_proposals(team_id=locked.team_id, hog_flow_id=locked.pk)
locked_proposal.status = WorkflowProposal.Status.APPROVED
locked_proposal.resolved_at = timezone.now()
@@ -6102,157 +5693,12 @@ class HogFlowViewSet(
proposal = self._get_proposal_or_404(instance, proposal_id)
# 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(
- {
- "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),
- }
+ proposal_outcome(team_id=self.team_id, hog_flow_id=instance.pk, proposal_id=proposal.pk)
).data
)
- 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: 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 _measure_evidence(
self, hog_flow: HogFlow, base_version: int, step_id: Optional[str], evidence: dict
) -> Optional[dict]:
@@ -6267,7 +5713,14 @@ class HogFlowViewSet(
try:
after_date, _, _ = relative_date_parse_with_delta_mapping(window, self.team.timezone_info)
tag_queries(product=ProductKey.WORKFLOWS, feature=Feature.QUERY)
- reading = self._version_outcome(hog_flow, [base_version], after_date, step_id, target_metric_in(evidence))
+ reading = version_outcome(
+ team_id=self.team_id,
+ hog_flow_id=hog_flow.pk,
+ versions=[base_version],
+ after=after_date,
+ step_id=step_id,
+ target=target_metric_in(evidence),
+ )
except Exception:
logger.exception("workflow_proposal: could not measure evidence", extra={"hog_flow_id": str(hog_flow.id)})
return None
@@ -6275,39 +5728,6 @@ class HogFlowViewSet(
return None
return {**reading, "window": window}
- def _version_outcome(
- self,
- hog_flow: HogFlow,
- versions: Sequence[Optional[int]],
- after: Any,
- step_id: Optional[str] = None,
- target: str = TARGET_OPEN_METRIC,
- ) -> 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], target), "versions": read}
-
@extend_schema(
parameters=[
OpenApiParameter("proposal_id", OpenApiTypes.UUID, OpenApiParameter.PATH, description="Proposal to reject.")
@@ -6352,35 +5772,13 @@ class HogFlowViewSet(
self._require_self_optimising_enabled()
instance = self.get_object()
- row = HogFlowOptimization.objects.filter(hog_flow=instance).first()
-
if request.method == "POST":
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
- if enabled:
- # get_or_create rather than create: two first-time enables race, and the loser of
- # the one-to-one constraint would answer 500 for a workflow that is now on.
- # nosemgrep: idor-lookup-without-team - team scope is enforced by TeamScopedManager
- row, created = HogFlowOptimization.objects.get_or_create(
- hog_flow=instance, defaults={"enabled": True}
- )
- changed = created or not row.enabled
- if not created and not row.enabled:
- row.enabled = True
- row.save(update_fields=["enabled"])
- else:
- # Off keeps the row: how many tried this and stopped is a rollout question.
- changed = row.enabled != enabled
- if changed:
- row.enabled = enabled
- row.save(update_fields=["enabled"])
-
+ changed = set_optimization_enabled(hog_flow_id=instance.pk, enabled=enabled)
if changed:
log_activity_from_viewset(
self,
@@ -6391,8 +5789,10 @@ class HogFlowViewSet(
self._report_workflow_action(
"hog_flow_optimization_enabled" if enabled else "hog_flow_optimization_disabled", instance
)
+ else:
+ enabled = is_optimization_enabled(instance.pk)
- return Response(HogFlowOptimizationSerializer({"enabled": row is not None and row.enabled}).data)
+ return Response(HogFlowOptimizationSerializer({"enabled": enabled}).data)
@extend_schema(request=HogFlowInvocationSerializer, responses={200: _FallbackSerializer})
@action(detail=True, methods=["POST"])
diff --git a/products/workflows/backend/services/hog_flow_content.py b/products/workflows/backend/services/hog_flow_content.py
new file mode 100644
index 000000000000..374a61bfe5f9
--- /dev/null
+++ b/products/workflows/backend/services/hog_flow_content.py
@@ -0,0 +1,54 @@
+from collections.abc import Mapping
+
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.services.hog_flow_secrets import strip_content_secrets
+
+# The content of a workflow: everything the draft cycle stages and publish promotes, and nothing
+# else. Metadata (name, description) and lifecycle (status) always apply to the live row. The draft
+# blob is a full snapshot of these fields so publish is a plain copy, not a merge.
+DRAFT_CONTENT_FIELDS = (
+ "actions",
+ "edges",
+ "trigger",
+ "trigger_masking",
+ "conversion",
+ "exit_condition",
+ "email_sending_rate_limit",
+ "abort_action",
+ "variables",
+)
+
+
+def deep_merge(target: dict, patch: dict) -> dict:
+ """Recursively merge `patch` into `target`. A null leaf deletes the key; a dict merges into a
+ dict; anything else replaces. Lets a caller change config.inputs.subject without resending the
+ rest of config."""
+ for key, value in patch.items():
+ if value is None:
+ target.pop(key, None)
+ elif isinstance(value, dict) and isinstance(target.get(key), dict):
+ deep_merge(target[key], value)
+ else:
+ target[key] = value
+ return target
+
+
+def snapshot_content(values: Mapping[str, object]) -> dict:
+ """A workflow's content fields in the API shape, without secrets."""
+ snapshot = {field: values.get(field) for field in DRAFT_CONTENT_FIELDS}
+ # The model's legacy default for actions/edges is `{}`, but the API shape is a list — normalize
+ # so re-validation of a snapshot (draft publish, revision restore) doesn't choke on a
+ # never-edited column.
+ for field in ("actions", "edges"):
+ if not snapshot[field]:
+ snapshot[field] = []
+ # Defensively strip secrets: a legacy row written before encryption shipped still has plaintext
+ # secret inputs in `actions`, and this snapshot feeds revision content — which must never carry
+ # secrets. New rows are already stripped, so this is a no-op for them. Every create takes a
+ # snapshot inside its transaction, so the cache resolves each template once instead of once per
+ # action.
+ return strip_content_secrets(snapshot, template_cache={})
+
+
+def snapshot_flow_content(flow: HogFlow) -> dict:
+ return snapshot_content({field: getattr(flow, field) for field in DRAFT_CONTENT_FIELDS})
diff --git a/products/workflows/backend/services/hog_flow_revisions.py b/products/workflows/backend/services/hog_flow_revisions.py
new file mode 100644
index 000000000000..939875e81468
--- /dev/null
+++ b/products/workflows/backend/services/hog_flow_revisions.py
@@ -0,0 +1,76 @@
+from datetime import datetime
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from products.workflows.backend.facade.contracts import (
+ WorkflowDraftChanged,
+ WorkflowDraftExists,
+ WorkflowRevision,
+ WorkflowRevisionNotFound,
+ WorkflowRevisionSummary,
+)
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
+from products.workflows.backend.services.workflow_proposals import unstage_proposals_for_flow
+
+
+def count_revisions(hog_flow_id: UUID) -> int:
+ return HogFlowRevision.objects.filter(hog_flow_id=hog_flow_id).count()
+
+
+def list_revisions(hog_flow_id: UUID, *, offset: int, limit: int) -> list[WorkflowRevisionSummary]:
+ # Content is fetched per version via get_revision, so the list stays light.
+ revisions = (
+ HogFlowRevision.objects.filter(hog_flow_id=hog_flow_id)
+ .order_by("-version")
+ .select_related("created_by")
+ .defer("content")[offset : offset + limit]
+ )
+ return [
+ WorkflowRevisionSummary(version=r.version, created_at=r.created_at, created_by=r.created_by) for r in revisions
+ ]
+
+
+def get_revision(*, hog_flow_id: UUID, version: int) -> WorkflowRevision | None:
+ revision = HogFlowRevision.objects.filter(hog_flow_id=hog_flow_id, version=version).first()
+ if revision is None:
+ return None
+ return WorkflowRevision(
+ version=revision.version,
+ created_at=revision.created_at,
+ created_by=revision.created_by,
+ content=revision.content,
+ )
+
+
+def restore_revision(
+ *, hog_flow_id: UUID, version: int, overwrite: bool, expected_draft_updated_at: datetime | None
+) -> None:
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
+ locked = HogFlow.objects.select_for_update().get(pk=hog_flow_id)
+ try:
+ revision = HogFlowRevision.objects.get(hog_flow_id=locked.pk, version=version)
+ except HogFlowRevision.DoesNotExist:
+ raise WorkflowRevisionNotFound()
+ if locked.draft and not overwrite:
+ raise WorkflowDraftExists()
+ # Overwrite fencing: the client confirms against the draft stamp it saw. A draft staged
+ # or edited between the confirmation dialog and this call carries a different stamp, and
+ # overwriting it would lose unpublished content that no revision snapshots.
+ if (
+ locked.draft
+ and expected_draft_updated_at is not None
+ and locked.draft_updated_at != expected_draft_updated_at
+ ):
+ raise WorkflowDraftChanged()
+ locked.draft = dict(revision.content)
+ locked.draft_updated_at = timezone.now()
+ unstage_proposals_for_flow(locked)
+ # Revision snapshots carry no secrets (they're stripped before snapshotting), so the
+ # restored draft re-attaches from the live encrypted_inputs on the follow-up publish.
+ # Clear any stale draft secrets from a prior draft so they can't bleed into this one.
+ locked.draft_encrypted_inputs = None
+ locked.save(update_fields=["draft", "draft_updated_at", "draft_encrypted_inputs"])
diff --git a/products/workflows/backend/services/workflow_proposals.py b/products/workflows/backend/services/workflow_proposals.py
new file mode 100644
index 000000000000..7ad76b76046e
--- /dev/null
+++ b/products/workflows/backend/services/workflow_proposals.py
@@ -0,0 +1,653 @@
+import copy
+import json
+from collections.abc import Mapping, Sequence
+from copy import deepcopy
+from datetime import datetime
+from typing import Any, Optional
+from uuid import UUID
+
+from posthog.api.app_metrics2 import fetch_app_metric_totals
+
+from products.workflows.backend.facade.contracts import ProposalChanges
+from products.workflows.backend.metrics import (
+ GUARDRAIL_LABELS,
+ GUARDRAIL_METRICS,
+ HOG_FLOW_VERSION_APP_SOURCE,
+ MIN_EVIDENCE_SAMPLE,
+ TARGET_CLICK_METRIC,
+ TARGET_METRICS,
+ TARGET_OPEN_METRIC,
+ TARGET_SEND_METRIC,
+ TARGET_UNTRACKED_METRIC,
+ UNAVAILABLE_GUARDRAILS,
+)
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow_optimization import HogFlowOptimization
+from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
+from products.workflows.backend.models.workflow_proposal import WorkflowProposal
+from products.workflows.backend.services.hog_flow_content import deep_merge, snapshot_flow_content
+
+# Fields a proposal replaces wholesale. `actions` merges per step instead, since steps carry stable
+# ids; edges have no id, and a variable list is short enough to carry whole.
+PROPOSAL_WHOLE_LIST_FIELDS = ("edges", "variables")
+
+
+PROPOSAL_MERGE_BY_ID_FIELDS = ("actions",)
+
+
+# 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
+ that email and the rest of the graph exactly as they are now."""
+ merged = {**live_content, **proposal_content}
+ for field in PROPOSAL_MERGE_BY_ID_FIELDS:
+ if field in proposal_content:
+ merged[field] = _merge_by_id(live_content.get(field) or [], proposal_content[field] or [])
+ return merged
+
+
+def _merge_by_id(live_items: list, changed_items: list) -> list:
+ """Merge each changed step into the live step with the same id, field by field, the way the
+ graph API's `update_action` does: a producer sends the fields it changes and nothing else, so a
+ step can never lose its template inputs to a payload that only carried a subject line."""
+ changed_by_id = {item["id"]: item for item in changed_items if isinstance(item, dict) and "id" in item}
+ merged = []
+ for item in live_items:
+ patch = changed_by_id.pop(item_id(item), None)
+ merged.append(deep_merge(copy.deepcopy(item), patch) if patch is not None else item)
+ # Anything left names a step the workflow does not have yet, so the proposal is adding it whole.
+ merged.extend(changed_by_id.values())
+ return merged
+
+
+def item_id(item: Any) -> Any:
+ return item.get("id") if isinstance(item, dict) else 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,
+ 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]
+
+
+def conflicting_parts(hog_flow: HogFlow, proposal: WorkflowProposal, content: Optional[dict] = None) -> list[str]:
+ """Parts of the workflow the proposal changes that someone else already changed since it was
+ written: step ids for `actions`, field names for everything else.
+
+ The check follows merge semantics. A step merges per field, so only the fields the proposal sets
+ on the steps it names are compared, as they were at `base_version` against as they are now. A
+ whole-list field replaces the list, so any publish since counts. Every other field replaces one
+ value, so that value is compared. An edit elsewhere merges cleanly, and an edit that already made
+ the proposed change is nothing to undo, so neither is a reason to refuse."""
+ if hog_flow.version == proposal.base_version:
+ return []
+ base_content = base_content_of(hog_flow, proposal)
+ content = proposal_changes(proposal, base_content) if content is None else content
+ touched_steps = {item_id(item) for item in content.get("actions") or []} - {None}
+ touched_lists = [field for field in PROPOSAL_WHOLE_LIST_FIELDS if field in content]
+ touched_fields = [
+ field
+ for field in content
+ if field not in PROPOSAL_MERGE_BY_ID_FIELDS and field not in PROPOSAL_WHOLE_LIST_FIELDS
+ ]
+ if touched_lists:
+ # A whole-list field replaces the list, so any publish since counts.
+ return sorted({*touched_steps, *touched_lists, *touched_fields})
+ if base_content is None:
+ # Without the snapshot the proposal read, "changed since" is unanswerable.
+ return sorted({*touched_steps, *touched_fields})
+ live_content = snapshot_flow_content(hog_flow)
+ base_actions = {item_id(item): item for item in base_content.get("actions") or []}
+ live_actions = {item_id(item): item for item in live_content.get("actions") or []}
+ proposed_actions = {item_id(item): item for item in content.get("actions") or []}
+ moved_steps = [
+ step_id
+ for step_id in touched_steps
+ # A step the proposal adds is only a conflict if that id now exists.
+ if not (step_id not in base_actions and step_id not in live_actions)
+ and _moved_since(base_actions.get(step_id), live_actions.get(step_id), proposed_actions[step_id])
+ ]
+ moved_fields = [
+ field
+ for field in touched_fields
+ # These replace the whole value, so a key the proposal does not name still goes with it.
+ if base_content.get(field) != live_content.get(field) and live_content.get(field) != content[field]
+ ]
+ return sorted({*moved_steps, *moved_fields})
+
+
+def base_content_of(hog_flow: HogFlow, proposal: WorkflowProposal) -> dict | None:
+ """The workflow as the proposal read it. That is the live workflow while its version has not
+ moved; after a publish it is the revision snapshot, which a workflow that has never been
+ published under revision tracking may not have."""
+ if hog_flow.version == proposal.base_version:
+ return snapshot_flow_content(hog_flow)
+ revision = HogFlowRevision.objects.filter(hog_flow=hog_flow, version=proposal.base_version).first()
+ return dict(revision.content) if revision is not None else None
+
+
+def proposal_changes(proposal: WorkflowProposal, base_content: dict | None) -> dict:
+ """The proposal's content reduced to what it changes against the workflow as it read it: a
+ step keeps only the fields that read differently there, and a step that reads the same drops
+ out. A producer that sends a whole step therefore still merges as the one-field change it made,
+ and never writes the rest of that step back over a later edit. Without the snapshot the content
+ stands as sent."""
+ content = dict(proposal.content)
+ if base_content is None or "actions" not in content:
+ return content
+ base_steps = {item_id(item): item for item in base_content.get("actions") or []}
+ changed_steps = []
+ for item in content.get("actions") or []:
+ base_step = base_steps.get(item_id(item))
+ if not isinstance(item, dict) or base_step is None:
+ changed_steps.append(item)
+ continue
+ changed = _changed_leaves(base_step, {key: value for key, value in item.items() if key != "id"})
+ if changed is not _ABSENT:
+ changed_steps.append({"id": item["id"], **changed})
+ content["actions"] = changed_steps
+ return content
+
+
+_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_in(evidence: Any) -> str:
+ """The metric the suggestion aimed at. Anything the surfaces cannot read is measured on opens."""
+ named = evidence.get("metric") if isinstance(evidence, dict) else None
+ return named if named in TARGET_METRICS else TARGET_OPEN_METRIC
+
+
+def target_metric_of(proposal: WorkflowProposal) -> str:
+ return target_metric_in(proposal.evidence)
+
+
+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."""
+ if isinstance(patch, dict) and isinstance(base, dict):
+ kept = {}
+ for key, value in patch.items():
+ changed = _changed_leaves(base.get(key), value)
+ if changed is not _ABSENT:
+ kept[key] = changed
+ return kept if kept else _ABSENT
+ if patch is None:
+ return _ABSENT if base is None else None
+ return _ABSENT if patch == base else patch
+
+
+def _moved_since(base: Any, live: Any, proposed: Any) -> bool:
+ """Whether someone changed, since `base`, something the proposal sets, and to a value other than
+ the proposed one. Reads the patch the way `_deep_merge` writes it: a dict compares leaf by leaf,
+ anything else as one value."""
+ if not isinstance(proposed, dict) or base is None or live is None:
+ return base != live and live != proposed
+ return any(
+ _leaf(live, path) != _leaf(base, path) and _leaf(live, path) != _leaf(proposed, path)
+ for path in _patch_paths(proposed)
+ )
+
+
+def _patch_paths(patch: Any, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]:
+ if not isinstance(patch, dict) or not patch:
+ return [prefix]
+ return [path for key, value in patch.items() for path in _patch_paths(value, (*prefix, key))]
+
+
+def _leaf(item: Any, path: tuple[str, ...]) -> Any:
+ for key in path:
+ if not isinstance(item, dict) or key not in item:
+ return _ABSENT
+ item = item[key]
+ # A null leaf in a patch deletes the key, so it reads as the key being absent.
+ 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_proposals_for_flow(hog_flow: HogFlow) -> None:
+ """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.
+ """
+ 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
+ )
+
+
+def outcome_versions(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(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(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: fetch_app_metric_totals(
+ team_id=hog_flow.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(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(
+ *,
+ team_id: int,
+ hog_flow_id: UUID,
+ versions: Sequence[Optional[int]],
+ after: datetime,
+ step_id: Optional[str] = None,
+ target: str = TARGET_OPEN_METRIC,
+) -> 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.
+ per_version = fetch_app_metric_totals(
+ team_id=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 per_version.items():
+ totals[name] = totals.get(name, 0) + count
+ return {**outcome_from_totals(totals, read[0], target), "versions": read}
+
+
+def _proposal_outcome(hog_flow: HogFlow, proposal: WorkflowProposal) -> dict:
+ """What an applied suggestion did: per-version readings, and the before and after sides."""
+ carrying, ended_at = versions_carrying_change(hog_flow, proposal)
+ charted = outcome_versions(hog_flow, proposal, carrying)
+ totals = version_totals(hog_flow, charted, proposal.step_id)
+ history = version_history(hog_flow, 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 {
+ "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),
+ }
+
+
+def _load(team_id: int, hog_flow_id: UUID, proposal_id: UUID) -> tuple[HogFlow, WorkflowProposal]:
+ hog_flow = HogFlow.objects.get(team_id=team_id, pk=hog_flow_id)
+ proposal = WorkflowProposal.objects.get(team_id=team_id, hog_flow_id=hog_flow_id, pk=proposal_id)
+ return hog_flow, proposal
+
+
+def proposal_outcome(*, team_id: int, hog_flow_id: UUID, proposal_id: UUID) -> dict:
+ """What an applied suggestion did: per-version readings, and the before and after sides."""
+ return _proposal_outcome(*_load(team_id, hog_flow_id, proposal_id))
+
+
+def proposal_conflicts(*, team_id: int, hog_flow_id: UUID, proposal_id: UUID) -> list[str]:
+ """Parts of the workflow the suggestion changes that someone else changed since it was written."""
+ return conflicting_parts(*_load(team_id, hog_flow_id, proposal_id))
+
+
+def staged_proposal_changes(*, team_id: int, hog_flow_id: UUID, proposal_id: UUID) -> ProposalChanges:
+ """What approving the suggestion would stage, or the steps in the way when it no longer applies."""
+ hog_flow, proposal = _load(team_id, hog_flow_id, proposal_id)
+ changes = proposal_changes(proposal, base_content_of(hog_flow, proposal))
+ conflicts = conflicting_parts(hog_flow, proposal, changes)
+ return ProposalChanges(changes=changes, conflicts=describe_steps(hog_flow, conflicts))
+
+
+def unstage_workflow_proposals(*, team_id: int, hog_flow_id: UUID) -> None:
+ """Re-queues approved suggestions the saved draft no longer carries. Call it after the draft is saved."""
+ unstage_proposals_for_flow(HogFlow.objects.get(team_id=team_id, pk=hog_flow_id))
+
+
+def is_optimization_enabled(hog_flow_id: UUID) -> bool:
+ return HogFlowOptimization.objects.filter(hog_flow_id=hog_flow_id, enabled=True).exists()
+
+
+def set_optimization_enabled(*, hog_flow_id: UUID, enabled: bool) -> bool:
+ """Turn suggestions on or off for one workflow. Returns whether the setting changed."""
+ row = HogFlowOptimization.objects.filter(hog_flow_id=hog_flow_id).first()
+ if row is None:
+ # Turning it off for a workflow nobody turned on is a no-op, not a row saying "no".
+ if not enabled:
+ return False
+ # get_or_create rather than create: two first-time enables race, and the loser of
+ # the one-to-one constraint would answer 500 for a workflow that is now on.
+ # nosemgrep: idor-lookup-without-team - team scope is enforced by TeamScopedManager
+ row, created = HogFlowOptimization.objects.get_or_create(hog_flow_id=hog_flow_id, defaults={"enabled": True})
+ if not created and not row.enabled:
+ row.enabled = True
+ row.save(update_fields=["enabled"])
+ return True
+ return created
+ # Off keeps the row: how many tried this and stopped is a rollout question.
+ if row.enabled == enabled:
+ return False
+ row.enabled = enabled
+ row.save(update_fields=["enabled"])
+ return True
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 770039bc2311..b8482533d0ca 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -5471,7 +5471,7 @@ class TestHogFlowVersionedMetrics(ClickhouseTestMixin, APIBaseTest):
@patch("products.workflows.backend.presentation.views.hog_flow.posthoganalytics.feature_enabled", return_value=True)
@patch(
- "products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals",
+ "products.workflows.backend.services.workflow_proposals.fetch_app_metric_totals",
side_effect=Exception("clickhouse is down"),
)
def test_a_producer_cannot_pass_off_its_own_numbers_as_posthogs(self, _mock_totals, _mock_flag):
diff --git a/products/workflows/backend/tests/api/test_hog_flow_revisions.py b/products/workflows/backend/tests/api/test_hog_flow_revisions.py
index 14ac7e9dc1c6..dc010d46602e 100644
--- a/products/workflows/backend/tests/api/test_hog_flow_revisions.py
+++ b/products/workflows/backend/tests/api/test_hog_flow_revisions.py
@@ -368,6 +368,9 @@ class TestHogFlowRevisions(APIBaseTest):
assert flow.action_redirects is None, "re-adding the deleted step must prune its redirect entry"
assert flow.draft is None
assert [r["version"] for r in self._list_revisions(flow_id)] == [3, 2, 1]
+ page = self.client.get(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/revisions?limit=1&offset=1").json()
+ assert page["count"] == 3
+ assert [r["version"] for r in page["results"]] == [2]
def _stage_draft_delete_action_1(self, flow_id: str) -> None:
response = self.client.patch(
diff --git a/products/workflows/backend/tests/api/test_workflow_proposals.py b/products/workflows/backend/tests/api/test_workflow_proposals.py
index 3cd2bc107717..ec372af753bd 100644
--- a/products/workflows/backend/tests/api/test_workflow_proposals.py
+++ b/products/workflows/backend/tests/api/test_workflow_proposals.py
@@ -773,7 +773,7 @@ class TestWorkflowProposals(APIBaseTest):
self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/approve/", {})
self._publish(flow_id)
- with patch("products.workflows.backend.presentation.views.hog_flow.fetch_app_metric_totals") as mock_totals:
+ with patch("products.workflows.backend.services.workflow_proposals.fetch_app_metric_totals") as mock_totals:
mock_totals.return_value = SimpleNamespace(totals={})
response = self.client.get(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/proposals/{proposal['id']}/outcome"
@@ -853,7 +853,7 @@ class TestWorkflowProposals(APIBaseTest):
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)
+ @patch("products.workflows.backend.services.workflow_proposals.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()
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index bc483e15ee4c..938975ebfb25 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1645,6 +1645,7 @@ export interface WorkflowEmailPauseStatusApi {
export interface HogFlowRevisionBasicApi {
/** Workflow version this snapshot was published as. */
readonly version: number
+ /** When this version was published. */
readonly created_at: string
readonly created_by: UserBasicApi | null
}
@@ -1661,6 +1662,7 @@ export interface PaginatedHogFlowRevisionBasicListApi {
export interface HogFlowRevisionApi {
/** Workflow version this snapshot was published as. */
readonly version: number
+ /** When this version was published. */
readonly created_at: string
readonly created_by: UserBasicApi | null
/** Full snapshot of the workflow's content fields (actions, edges, trigger, etc.) at this version. */
diff --git a/pyproject.toml b/pyproject.toml
index 09d210a2869d..0dffb1dc3874 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -722,9 +722,7 @@ ignore_imports = [
"products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.api.message_templates",
"products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.models",
"products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.unlayer",
- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.metrics",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow.hog_flow",
- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_optimization",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.workflow_proposal",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 04206983f7f0..abbe616b9301 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -52872,6 +52872,7 @@ export namespace Schemas {
export interface HogFlowRevision {
/** Workflow version this snapshot was published as. */
readonly version: number;
+ /** When this version was published. */
readonly created_at: string;
readonly created_by: UserBasic | null;
/** Full snapshot of the workflow's content fields (actions, edges, trigger, etc.) at this version. */
@@ -52881,6 +52882,7 @@ export namespace Schemas {
export interface HogFlowRevisionBasic {
/** Workflow version this snapshot was published as. */
readonly version: number;
+ /** When this version was published. */
readonly created_at: string;
readonly created_by: UserBasic | null;
}