Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): store posthog's own reading beside a suggestion's claim (#107795)

Daniel Marchuk5fb4e7cd4b7d
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 665338cff401..6039306f979e 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -3720,6 +3720,8 @@ WORKFLOW_PROPOSAL_EVIDENCE_SCHEMA = {
"string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; "
"`n`, the denominator that value was computed over; and `guardrails`, a list of "
"{metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. "
+ "PostHog then reads the step's own metrics at `base_version` when the suggestion is filed and stores "
+ "them under `measured`; the page shows that reading and flags a disagreement with yours. "
"Also conventional: target_value, window, query, app_source_id. A rate with no denominator "
"lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change "
"that lifts one number by harming another, and a number under a key of your own reads to a "
@@ -4291,12 +4293,16 @@ def describe_version_changes(previous: dict, current: dict, proposed: Mapping) -
return changes
-def target_metric_of(proposal: WorkflowProposal) -> str:
+def target_metric_in(evidence: Any) -> str:
"""The metric the suggestion aimed at. Anything the surfaces cannot read is measured on opens."""
- named = (proposal.evidence or {}).get("metric") if isinstance(proposal.evidence, dict) else None
+ 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.
@@ -6022,11 +6028,9 @@ class HogFlowViewSet(
return Response(WorkflowProposalSerializer(retry_of).data, status=status.HTTP_200_OK)
# A version the workflow has not reached names nothing, and the outcome read spans versions.
- if params["base_version"] > (instance.version or 1):
+ if params["base_version"] > instance.version:
raise exceptions.ValidationError(
- {
- "base_version": f"This workflow is on version {instance.version or 1}, so there is nothing later to read."
- }
+ {"base_version": f"This workflow is on version {instance.version}, so there is nothing later to read."}
)
# Reading the queue stays open while the flag is on; the workflow's opt-in only gates producing a new one.
@@ -6080,7 +6084,13 @@ class HogFlowViewSet(
{"step_id": "Name a step this workflow has, or one the suggestion adds."}
)
+ # The producer's numbers are its own claim; PostHog's reading of the same step and version sits beside them.
+ # `measured` is the server's word, so a producer's own copy of that key never survives a failed read.
evidence = dict(params.get("evidence") or {})
+ evidence.pop("measured", None)
+ measured = self._measure_evidence(instance, params["base_version"], step_id, evidence)
+ if measured is not None:
+ evidence["measured"] = measured
proposal = WorkflowProposal(
hog_flow=instance,
@@ -6386,8 +6396,35 @@ class HogFlowViewSet(
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]:
+ """PostHog's own reading of the metrics a suggestion is about, taken when it is filed.
+
+ Same read as the outcome's "before" side, over the producer's window when it names a
+ relative one. A read that fails leaves the suggestion filed with the producer's numbers
+ only, which the page labels as unverified."""
+ window = evidence.get("window") if isinstance(evidence.get("window"), str) else None
+ if not window or not re.fullmatch(r"-\d+[dh]", window):
+ window = "-7d"
+ 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))
+ except Exception:
+ logger.exception("workflow_proposal: could not measure evidence", extra={"hog_flow_id": str(hog_flow.id)})
+ return None
+ if reading is None:
+ return None
+ return {**reading, "window": window}
+
def _version_outcome(
- self, hog_flow: HogFlow, versions: Sequence[Optional[int]], after: Any, step_id: Optional[str] = None
+ 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:
@@ -6412,7 +6449,7 @@ class HogFlowViewSet(
).totals
for name, count in version_totals.items():
totals[name] = totals.get(name, 0) + count
- return {**_outcome_from_totals(totals, read[0]), "versions": read}
+ return {**_outcome_from_totals(totals, read[0], target), "versions": read}
@extend_schema(
parameters=[
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index 2b70347e158a..770039bc2311 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -5402,6 +5402,119 @@ class TestHogFlowVersionedMetrics(ClickhouseTestMixin, APIBaseTest):
assert response.status_code == 400, response.json()
assert "version" in str(response.json())
+ @parameterized.expand(
+ [
+ ("opens", "email_opened", "email open rate", 0.1),
+ ("clicks", "email_link_clicked", "click rate", 0.25),
+ ]
+ )
+ @patch("products.workflows.backend.presentation.views.hog_flow.posthoganalytics.feature_enabled", return_value=True)
+ def test_a_suggestion_carries_what_posthog_measured_next_to_what_it_claimed(
+ self, _name, named_metric, expected_label, expected_value, _mock_flag
+ ):
+ HogFlow.objects.filter(id=self.flow.id).update(
+ actions=[{"id": "email_1", "type": "function_email", "name": "Email", "config": {}}], status="active"
+ )
+ opted_in = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/optimization", {"enabled": True}, format="json"
+ )
+ assert opted_in.status_code == 200, opted_in.json()
+ for name, count in (
+ ("email_sent", 100),
+ ("email_opened", 10),
+ ("email_link_clicked", 25),
+ ("email_bounced", 2),
+ ):
+ create_app_metric2(
+ team_id=self.team.id,
+ app_source="hog_flow_version",
+ app_source_id=f"{self.flow.id}/1",
+ instance_id="email_1",
+ metric_kind="email",
+ metric_name=name,
+ count=count,
+ )
+
+ producer_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="producer",
+ user=self.user,
+ secure_value=hash_key_value(producer_key),
+ scopes=["hog_flow:read", "hog_flow_proposal:write"],
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/proposals/",
+ {
+ "title": "Shorten the subject",
+ "rationale": "Opens are low.",
+ "content": {"exit_condition": "exit_only_at_end"},
+ "step_id": "email_1",
+ "base_version": 1,
+ "evidence": {"metric": named_metric, "current_value": 0.5, "unit": "rate", "n": 9, "guardrails": []},
+ },
+ format="json",
+ headers={"authorization": f"Bearer {producer_key}"},
+ )
+
+ assert response.status_code == 201, response.json()
+ evidence = response.json()["evidence"]
+ assert evidence["current_value"] == 0.5
+ measured = evidence["measured"]
+ assert measured["version"] == 1
+ assert measured["target"] == {
+ "metric": expected_label,
+ "value": expected_value,
+ "n": 100,
+ "below_minimum_sample": False,
+ }
+ assert {g["metric"]: g["value"] for g in measured["guardrails"]}["bounce rate"] == 0.02
+
+ @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",
+ side_effect=Exception("clickhouse is down"),
+ )
+ def test_a_producer_cannot_pass_off_its_own_numbers_as_posthogs(self, _mock_totals, _mock_flag):
+ HogFlow.objects.filter(id=self.flow.id).update(
+ actions=[{"id": "email_1", "type": "function_email", "name": "Email", "config": {}}], status="active"
+ )
+ self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/optimization", {"enabled": True}, format="json"
+ )
+
+ # `hog_flow_proposal` is an internal scope object, so only a token carrying it can file.
+ producer_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="producer",
+ user=self.user,
+ secure_value=hash_key_value(producer_key),
+ scopes=["hog_flow:read", "hog_flow_proposal:write"],
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{self.flow.id}/proposals/",
+ {
+ "title": "Shorten the subject",
+ "rationale": "Opens are low.",
+ "content": {"exit_condition": "exit_only_at_end"},
+ "step_id": "email_1",
+ "base_version": 1,
+ "evidence": {
+ "metric": "email_opened",
+ "current_value": 0.5,
+ "unit": "rate",
+ "n": 9,
+ "guardrails": [],
+ "measured": {"version": 1, "target": {"metric": "email open rate", "value": 0.9, "n": 5000}},
+ },
+ },
+ format="json",
+ headers={"authorization": f"Bearer {producer_key}"},
+ )
+
+ assert response.status_code == 201, response.json()
+ # The read failed, so the suggestion reads as unverified rather than carrying the producer's own copy.
+ assert "measured" not in response.json()["evidence"]
+
@parameterized.expand([("metrics/totals",), ("metrics",)])
def test_a_hog_function_still_reads_its_own_metrics(self, path: str):
function = HogFunction.objects.create(team=self.team, name="fn", type="destination", hog="return event")
diff --git a/products/workflows/frontend/Workflows/hogflows/types.ts b/products/workflows/frontend/Workflows/hogflows/types.ts
index 601ff314e582..c6dd1b4864f5 100644
--- a/products/workflows/frontend/Workflows/hogflows/types.ts
+++ b/products/workflows/frontend/Workflows/hogflows/types.ts
@@ -109,6 +109,9 @@ export interface HogFlow extends z.infer<typeof HogFlowSchema> {
// True when only PostHog can lift the pause: staff placed it, or it re-tripped soon after a resume.
email_sending_pause_requires_support?: boolean
email_sending_resumed_at?: string | null
+ // Suggested changes waiting for a person. Only the list endpoint counts it.
+ pending_suggestions?: number | null
+ suggestions_enabled?: boolean | null
}
export interface HogFlowEdge extends z.infer<typeof HogFlowEdgeSchema> {}
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
index 9a759dabf227..1fde84d84c5b 100644
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowAppliedOutcome.tsx
@@ -63,7 +63,7 @@ export function WorkflowAppliedOutcome({
proposal: WorkflowProposalApi
outcome: WorkflowProposalOutcomeApi
}): JSX.Element {
- const published = outcome.versions ?? []
+ const published = outcome.versions
// Only versions that sent something can carry a rate, and a zero bar for one that never ran reads as a drop.
const charted = published.filter((version) => version.guardrails[0]?.n || version.target.n)
// The live version and what each version changed come from every published version, not only the
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx
index 3a70b90f4f92..0876dd81403a 100644
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx
+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionCard.tsx
@@ -33,7 +33,7 @@ export function WorkflowSuggestionCard({ id, proposal }: { id: string; proposal:
<LemonTag type="highlight">Suggested by PostHog</LemonTag>
</Tooltip>
{proposal.is_stale && (
- <Tooltip title="Someone changed the same step since this was suggested. Approving it would undo their edit, so ask for a fresh suggestion.">
+ <Tooltip title="Someone changed the same step since this was suggested. Approving it would undo their edit. Reject it, and the scout can suggest again from the current version.">
<LemonTag type="warning">Out of date</LemonTag>
</Tooltip>
)}
@@ -83,11 +83,12 @@ export function WorkflowSuggestionCard({ id, proposal }: { id: string; proposal:
</div>
<LemonCollapse
size="small"
+ defaultActiveKey="details"
panels={[
{
key: 'details',
- header: 'What it changes and why',
- content: <WorkflowSuggestionDetails proposal={proposal} />,
+ header: 'What changes',
+ content: <WorkflowSuggestionDetails id={id} proposal={proposal} />,
},
]}
/>
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx
index 710c4c1a38de..721fbf04b8eb 100644
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx
+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionDetails.tsx
@@ -1,26 +1,95 @@
+import { useValues } from 'kea'
+
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
import type { WorkflowProposalApi } from '../../generated/api.schemas'
+import { workflowLogic } from '../workflowLogic'
+import { SuggestedFieldChange, describeSuggestedChanges } from './suggestionChanges'
+
+function ChangedValue({ value }: { value: unknown }): JSX.Element {
+ if (value === undefined) {
+ return <span className="text-secondary italic">Not set</span>
+ }
+ if (value === null) {
+ return <span className="text-secondary italic">Removed</span>
+ }
+ if (typeof value === 'string') {
+ return <span className="whitespace-pre-wrap break-words line-clamp-4">{value}</span>
+ }
+ return (
+ <pre className="text-xs bg-surface-secondary rounded p-2 overflow-x-auto mb-0 max-h-40">
+ {JSON.stringify(value, null, 2)}
+ </pre>
+ )
+}
-export function WorkflowSuggestionDetails({ proposal }: { proposal: WorkflowProposalApi }): JSX.Element {
- const changedFields = Object.keys(proposal.content)
+const COLUMNS: LemonTableColumns<SuggestedFieldChange> = [
+ {
+ title: 'Field',
+ key: 'field',
+ width: '20%',
+ render: (_, change) => (
+ <Tooltip title={change.path}>
+ <span className="font-medium">{change.label}</span>
+ </Tooltip>
+ ),
+ },
+ { title: 'Now', key: 'before', width: '40%', render: (_, change) => <ChangedValue value={change.before} /> },
+ { title: 'Suggested', key: 'after', width: '40%', render: (_, change) => <ChangedValue value={change.after} /> },
+]
+
+export function WorkflowSuggestionDetails({
+ id,
+ proposal,
+}: {
+ id: string
+ proposal: WorkflowProposalApi
+}): JSX.Element {
+ const { originalWorkflow } = useValues(workflowLogic({ id }))
+ const changes = describeSuggestedChanges(proposal.content, originalWorkflow)
+ const nothingToShow = changes.steps.length === 0 && changes.workflow.length === 0
return (
- <div className="flex flex-col gap-2 text-sm">
- <div>
- <span className="font-semibold">Workflow fields it changes: </span>
- {changedFields.length ? changedFields.join(', ') : 'none'}
- </div>
- <div className="flex flex-col gap-1">
- <span className="font-semibold">Evidence</span>
- <pre className="text-xs bg-surface-secondary rounded p-2 overflow-x-auto mb-0">
- {JSON.stringify(proposal.evidence, null, 2)}
- </pre>
- </div>
- {proposal.source_id && (
- <div>
- <span className="font-semibold">Source: </span>
- {proposal.source_id}
+ <div className="flex flex-col gap-3 text-sm">
+ {nothingToShow && <span className="text-secondary">This suggestion changes nothing on the workflow.</span>}
+ {changes.steps.map((step) => (
+ <div key={step.stepId} className="flex flex-col gap-1">
+ <span className="font-semibold">
+ {step.stepName ? `Step: ${step.stepName}` : `New step: ${step.stepId}`}
+ </span>
+ <LemonTable size="small" columns={COLUMNS} dataSource={step.fields} rowKey="path" />
+ </div>
+ ))}
+ {changes.workflow.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <span className="font-semibold">Workflow</span>
+ <LemonTable size="small" columns={COLUMNS} dataSource={changes.workflow} rowKey="path" />
</div>
)}
+ <LemonCollapse
+ size="xsmall"
+ panels={[
+ {
+ key: 'raw',
+ header: 'Raw details',
+ content: (
+ <div className="flex flex-col gap-2">
+ <pre className="text-xs bg-surface-secondary rounded p-2 overflow-x-auto mb-0">
+ {JSON.stringify(proposal.evidence, null, 2)}
+ </pre>
+ {proposal.source_id && (
+ <div>
+ <span className="font-semibold">Scout run: </span>
+ {proposal.source_id}
+ </div>
+ )}
+ </div>
+ ),
+ },
+ ]}
+ />
</div>
)
}
diff --git a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx
index 33a3948e885f..9fab1b7f6c04 100644
--- a/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx
+++ b/products/workflows/frontend/Workflows/suggestions/WorkflowSuggestionEvidence.tsx
@@ -1,6 +1,14 @@
import { LemonTag, Tooltip } from '@posthog/lemon-ui'
-import { MIN_EVIDENCE_SAMPLE, formatValue, readGuardrails, readUnit } from './suggestionEvidence'
+import {
+ MIN_EVIDENCE_SAMPLE,
+ describeWindow,
+ evidenceDisagrees,
+ formatValue,
+ readGuardrails,
+ readMeasured,
+ readUnit,
+} from './suggestionEvidence'
export function WorkflowSuggestionEvidence({ evidence }: { evidence: Record<string, unknown> }): JSX.Element | null {
const metric = typeof evidence.metric === 'string' ? evidence.metric : null
@@ -12,10 +20,51 @@ export function WorkflowSuggestionEvidence({ evidence }: { evidence: Record<stri
const target = formatValue(evidence.target_value, unit)
const window = typeof evidence.window === 'string' ? evidence.window : null
const sample = typeof evidence.n === 'number' ? evidence.n : null
+ const measured = readMeasured(evidence)
+
+ if (measured) {
+ const measuredValue = formatValue(measured.target.value, 'rate')
+ return (
+ <div className="flex flex-col gap-1 text-sm">
+ <span className="flex items-center gap-2 flex-wrap">
+ <span>
+ {measured.target.metric} {measuredValue ?? 'no data'} on {measured.target.n} tracked sends (v
+ {measured.version}, {describeWindow(measured.window)}){target ? `, target ${target}` : ''}
+ </span>
+ <Tooltip title="PostHog read this step's metrics itself when the suggestion was filed.">
+ <LemonTag type="success">Measured by PostHog</LemonTag>
+ </Tooltip>
+ {measured.target.below_minimum_sample && (
+ <Tooltip
+ title={`Under ${MIN_EVIDENCE_SAMPLE} sends. Treat this as a hunch to check, not a finding.`}
+ >
+ <LemonTag type="warning">Too little data</LemonTag>
+ </Tooltip>
+ )}
+ </span>
+ {measured.guardrails.length > 0 && (
+ <span className="text-secondary">
+ Alongside:{' '}
+ {measured.guardrails
+ .map(
+ (guardrail) =>
+ `${guardrail.metric} ${formatValue(guardrail.value, 'rate') ?? 'no data'}`
+ )
+ .join(', ')}
+ </span>
+ )}
+ {evidenceDisagrees(evidence, measured) && (
+ <span className="text-warning">
+ This suggestion claimed {current ?? 'no value'}
+ {sample !== null ? ` on ${sample}` : ''}, which is not what PostHog measured. Read its reasoning
+ with that in mind.
+ </span>
+ )}
+ </div>
+ )
+ }
+
const guardrails = readGuardrails(evidence)
- const unavailable = Array.isArray(evidence.guardrails_unavailable)
- ? evidence.guardrails_unavailable.filter((name): name is string => typeof name === 'string')
- : []
const lowSample = sample !== null && sample < MIN_EVIDENCE_SAMPLE
return (
@@ -27,6 +76,9 @@ export function WorkflowSuggestionEvidence({ evidence }: { evidence: Record<stri
{window ? ` over ${window}` : ''}
{sample !== null ? ` (${sample} observations)` : ''}
</span>
+ <Tooltip title="These numbers came from the producer. PostHog could not read the step's metrics when this was filed, so check them on the Metrics tab before deciding.">
+ <LemonTag type="warning">Unverified</LemonTag>
+ </Tooltip>
{sample === null && (
<Tooltip title="This suggestion did not say how many observations its number came from, so there is no way to tell a result from noise.">
<LemonTag type="warning">No sample size</LemonTag>
@@ -49,14 +101,8 @@ export function WorkflowSuggestionEvidence({ evidence }: { evidence: Record<stri
`${guardrail.metric} ${formatValue(guardrail.value, readUnit(guardrail.unit)) ?? 'no data'}`
)
.join(', ')}
- {unavailable.length > 0 ? `. Not measured: ${unavailable.join(', ')}` : ''}
</span>
)}
- {guardrails.length === 0 && (
- <Tooltip title="No counter-metrics were sent with this suggestion, so a change that lifts the target by harming something else would not show here.">
- <LemonTag type="warning">No counter-metrics</LemonTag>
- </Tooltip>
- )}
</div>
)
}
diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts
new file mode 100644
index 000000000000..d8cba7ab0811
--- /dev/null
+++ b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.test.ts
@@ -0,0 +1,74 @@
+import type { HogFlow } from '../hogflows/types'
+import { describeSuggestedChanges } from './suggestionChanges'
+
+const live = {
+ name: 'Onboarding welcome',
+ actions: [
+ {
+ id: 'email_1',
+ name: 'Welcome email',
+ config: { inputs: { email: { value: { subject: 'Old subject', html: '<p>hi</p>' } } } },
+ },
+ ],
+} as unknown as HogFlow
+
+describe('describeSuggestedChanges', () => {
+ it('pairs each changed field with the live value at the same path and names the step', () => {
+ const changes = describeSuggestedChanges(
+ {
+ actions: [
+ { id: 'email_1', config: { inputs: { email: { value: { subject: 'New subject', html: null } } } } },
+ ],
+ },
+ live
+ )
+
+ expect(changes.workflow).toEqual([])
+ expect(changes.steps).toEqual([
+ {
+ stepId: 'email_1',
+ stepName: 'Welcome email',
+ fields: [
+ {
+ path: 'config.inputs.email.value.subject',
+ label: 'email › subject',
+ before: 'Old subject',
+ after: 'New subject',
+ },
+ { path: 'config.inputs.email.value.html', label: 'email › html', before: '<p>hi</p>', after: null },
+ ],
+ },
+ ])
+ })
+
+ it.each([
+ ['a step the live workflow does not have', { actions: [{ id: 'new_1', name: 'Added' }] }, null],
+ ['no live workflow yet', { actions: [{ id: 'email_1', name: 'Added' }] }, null],
+ ])('reads nothing as before for %s', (_name, content, expectedName) => {
+ const changes = describeSuggestedChanges(content, _name.startsWith('no') ? null : live)
+ expect(changes.steps[0].stepName).toBe(expectedName)
+ expect(changes.steps[0].fields).toEqual([{ path: 'name', label: 'name', before: undefined, after: 'Added' }])
+ })
+
+ it('lists changes outside the steps against the live workflow', () => {
+ const changes = describeSuggestedChanges({ name: 'Renamed' }, live)
+ expect(changes.steps).toEqual([])
+ expect(changes.workflow).toEqual([
+ { path: 'name', label: 'name', before: 'Onboarding welcome', after: 'Renamed' },
+ ])
+ })
+
+ it('leaves out fields a whole-step patch resent unchanged', () => {
+ const live = {
+ actions: [{ id: 'email_1', name: 'Email', config: { subject: 'Old', from: '[email protected]' } }],
+ } as unknown as HogFlow
+
+ const { steps } = describeSuggestedChanges(
+ { actions: [{ id: 'email_1', name: 'Email', config: { subject: 'New', from: '[email protected]' } }] },
+ live
+ )
+
+ // Approving reduces the patch the same way, so the table must not read as a four-field edit.
+ expect(steps[0].fields.map((field) => field.path)).toEqual(['config.subject'])
+ })
+})
diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts
new file mode 100644
index 000000000000..4d6165c8a9b2
--- /dev/null
+++ b/products/workflows/frontend/Workflows/suggestions/suggestionChanges.ts
@@ -0,0 +1,99 @@
+import type { HogFlow } from '../hogflows/types'
+
+export interface SuggestedFieldChange {
+ path: string
+ label: string
+ before: unknown
+ after: unknown
+}
+
+export interface SuggestedStepChange {
+ stepId: string
+ stepName: string | null
+ fields: SuggestedFieldChange[]
+}
+
+export interface SuggestedChanges {
+ steps: SuggestedStepChange[]
+ workflow: SuggestedFieldChange[]
+}
+
+// Every step input sits at `config.inputs.<name>.value`, so those segments say nothing to a reader.
+const SILENT_SEGMENTS = new Set(['config', 'inputs', 'value'])
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+function readPath(source: unknown, segments: string[]): unknown {
+ let current = source
+ for (const segment of segments) {
+ if (!isPlainObject(current)) {
+ return undefined
+ }
+ current = current[segment]
+ }
+ return current
+}
+
+function labelFor(segments: string[]): string {
+ const spoken = segments.filter((segment) => !SILENT_SEGMENTS.has(segment))
+ return (spoken.length ? spoken : segments).join(' › ')
+}
+
+function leafChanges(patch: Record<string, unknown>, live: unknown, prefix: string[] = []): SuggestedFieldChange[] {
+ const changes: SuggestedFieldChange[] = []
+ for (const [key, value] of Object.entries(patch)) {
+ const segments = [...prefix, key]
+ if (isPlainObject(value) && Object.keys(value).length > 0) {
+ changes.push(...leafChanges(value, live, segments))
+ continue
+ }
+ const before = readPath(live, segments)
+ // Approving reduces the patch to what differs, so a step sent whole must not read here as if
+ // every field were an edit. A null leaf removes the key, which is nothing when it is absent.
+ if (sameLeaf(before, value)) {
+ continue
+ }
+ changes.push({
+ path: segments.join('.'),
+ label: labelFor(segments),
+ before,
+ after: value,
+ })
+ }
+ return changes
+}
+
+function sameLeaf(before: unknown, after: unknown): boolean {
+ if (after === null) {
+ return before === undefined || before === null
+ }
+ if (before === undefined) {
+ return false
+ }
+ return JSON.stringify(before) === JSON.stringify(after)
+}
+
+export function describeSuggestedChanges(content: Record<string, unknown>, live: HogFlow | null): SuggestedChanges {
+ const { actions, ...rest } = content
+ const liveSteps = new Map((live?.actions ?? []).map((action) => [action.id, action]))
+
+ const steps: SuggestedStepChange[] = []
+ if (Array.isArray(actions)) {
+ for (const step of actions) {
+ if (!isPlainObject(step) || typeof step.id !== 'string') {
+ continue
+ }
+ const { id, ...patch } = step
+ const liveStep = liveSteps.get(id)
+ steps.push({
+ stepId: id,
+ stepName: liveStep?.name ?? null,
+ fields: leafChanges(patch, liveStep),
+ })
+ }
+ }
+
+ return { steps, workflow: leafChanges(rest, live) }
+}
diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts
index 3620eb98978b..51ff8ed6183f 100644
--- a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts
+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.test.ts
@@ -1,4 +1,4 @@
-import { formatValue, readUnit } from './suggestionEvidence'
+import { evidenceDisagrees, formatValue, readUnit } from './suggestionEvidence'
describe('suggestionEvidence', () => {
it.each([
@@ -25,4 +25,21 @@ describe('suggestionEvidence', () => {
])('reads the unit %s', (raw, expected) => {
expect(readUnit(raw)).toBe(expected)
})
+
+ const measured = {
+ version: 1,
+ window: '-7d',
+ target: { metric: 'email open rate', value: 0.076, n: 132, below_minimum_sample: false },
+ click_through: { metric: 'click rate', value: 0.008, n: 132, below_minimum_sample: false },
+ guardrails: [],
+ }
+
+ it.each([
+ ['the same number', { unit: 'rate', current_value: 0.0758, n: 132 }, false],
+ ['a number a whole point off', { unit: 'rate', current_value: 0.09, n: 132 }, true],
+ ['a different denominator', { unit: 'rate', current_value: 0.076, n: 500 }, true],
+ ['a count, which is not compared', { unit: 'count', current_value: 10, n: 132 }, false],
+ ])('flags %s against what PostHog measured', (_name, evidence, expected) => {
+ expect(evidenceDisagrees(evidence, measured)).toBe(expected)
+ })
})
diff --git a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts
index 30e1d43a838c..1ed054d2ecb6 100644
--- a/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts
+++ b/products/workflows/frontend/Workflows/suggestions/suggestionEvidence.ts
@@ -29,3 +29,53 @@ export function formatValue(value: unknown, unit: EvidenceUnit | null): string |
}
return unit === 'rate' ? `${(value * 100).toFixed(1)}%` : String(value)
}
+
+export interface MeasuredReading {
+ metric: string
+ value: number | null
+ n: number
+ below_minimum_sample: boolean
+}
+
+/** PostHog's own read of the step at `base_version`, stored by the server when the suggestion was filed. */
+export interface MeasuredEvidence {
+ version: number
+ window: string
+ target: MeasuredReading
+ click_through: MeasuredReading
+ guardrails: MeasuredReading[]
+}
+
+export function readMeasured(evidence: Record<string, unknown>): MeasuredEvidence | null {
+ const measured = evidence.measured
+ if (!measured || typeof measured !== 'object' || !('target' in measured)) {
+ return null
+ }
+ return measured as MeasuredEvidence
+}
+
+export function describeWindow(window: string): string {
+ const match = /^-(\d+)([dh])$/.exec(window)
+ if (!match) {
+ return window
+ }
+ const unit = match[2] === 'd' ? 'day' : 'hour'
+ return `the last ${match[1]} ${unit}${match[1] === '1' ? '' : 's'}`
+}
+
+// Half a point: the producer reads the same series moments earlier.
+const RATE_TOLERANCE = 0.005
+
+export function evidenceDisagrees(evidence: Record<string, unknown>, measured: MeasuredEvidence): boolean {
+ if (
+ readUnit(evidence.unit) !== 'rate' ||
+ typeof evidence.current_value !== 'number' ||
+ measured.target.value === null
+ ) {
+ return false
+ }
+ if (typeof evidence.n === 'number' && evidence.n !== measured.target.n) {
+ return true
+ }
+ return Math.abs(evidence.current_value - measured.target.value) > RATE_TOLERANCE
+}
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index f6c878806815..8c26d8bf0c31 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -1266,7 +1266,7 @@ export const WorkflowProposalStatusEnumApi = {
export type WorkflowProposalApiContent = { [key: string]: unknown }
/**
- * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
+ * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. PostHog then reads the step's own metrics at `base_version` when the suggestion is filed and stores them under `measured`; the page shows that reading and flags a disagreement with yours. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
*/
export type WorkflowProposalApiEvidence = { [key: string]: unknown }
@@ -1278,7 +1278,7 @@ export interface WorkflowProposalApi {
readonly rationale: string
/** Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself. */
readonly content: WorkflowProposalApiContent
- /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
+ /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. PostHog then reads the step's own metrics at `base_version` when the suggestion is filed and stores them under `measured`; the page shows that reading and flags a disagreement with yours. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
readonly evidence: WorkflowProposalApiEvidence
/**
* The workflow step this is about. Set for a change to one step: the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Null only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e2eaf56d10f5..2ef01e9430da 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -73915,7 +73915,7 @@ export namespace Schemas {
export type WorkflowProposalContent = { [key: string]: unknown };
/**
- * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
+ * The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. PostHog then reads the step's own metrics at `base_version` when the suggestion is filed and stores them under `measured`; the page shows that reading and flags a disagreement with yours. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all.
*/
export type WorkflowProposalEvidence = { [key: string]: unknown };
@@ -73927,7 +73927,7 @@ export namespace Schemas {
readonly rationale: string;
/** Only the content fields the proposal changes. Valid keys: actions, edges, trigger_masking, conversion, exit_condition, email_sending_rate_limit, variables. Each value has the same shape as on the workflow itself. */
readonly content: WorkflowProposalContent;
- /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
+ /** The numbers behind the proposal, read back by name. Five keys are required: `metric`, the metric name; `current_value`, its value as a number (a rate as a fraction, 0.0865, never a string); `unit`, either `rate` or `count`, since 1.0 is either every message or one of them; `n`, the denominator that value was computed over; and `guardrails`, a list of {metric, value, n, unit} counter-metrics read over the same window, empty only if none apply. PostHog then reads the step's own metrics at `base_version` when the suggestion is filed and stores them under `measured`; the page shows that reading and flags a disagreement with yours. Also conventional: target_value, window, query, app_source_id. A rate with no denominator lets a reviewer mistake noise for a result, a target with no counter-metrics hides a change that lifts one number by harming another, and a number under a key of your own reads to a person as no evidence at all. */
readonly evidence: WorkflowProposalEvidence;
/**
* The workflow step this is about. Set for a change to one step: the evidence and the outcome then read that step's metrics, so a change to one email in a sequence is not measured against the rest. Null only for a change that spans the workflow, such as its exit condition or a step being taken out, which is measured on the workflow's own numbers.