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): publish impact preview with confirm token (#72506)

Harley Alexandera3f96f959d71
diff --git a/nodejs/src/cdp/cdp-api.test.ts b/nodejs/src/cdp/cdp-api.test.ts
index acae19b8fc2c..5d99a0353ff8 100644
--- a/nodejs/src/cdp/cdp-api.test.ts
+++ b/nodejs/src/cdp/cdp-api.test.ts
@@ -915,7 +915,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
- countInFlightJobs: jest.fn().mockResolvedValue(0),
+ countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1003,7 +1003,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
- countInFlightJobs: jest.fn().mockResolvedValue(0),
+ countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1065,7 +1065,7 @@ describe('CDP API', () => {
const createJobMock = jest.fn().mockResolvedValue('resolver-job-id')
api['batchResolverProducer'] = {
createJob: createJobMock,
- countInFlightJobs: jest.fn().mockResolvedValue(0),
+ countInFlightJobs: jest.fn().mockResolvedValue({ count: 0, byAction: {}, positionUnknown: 0 }),
rescheduleParkedJobs: jest.fn(),
disconnect: jest.fn().mockResolvedValue(undefined),
}
@@ -1180,7 +1180,9 @@ describe('CDP API', () => {
let mockCountInFlightJobs: jest.Mock
beforeEach(async () => {
- mockCountInFlightJobs = jest.fn().mockResolvedValue(3)
+ mockCountInFlightJobs = jest
+ .fn()
+ .mockResolvedValue({ count: 3, byAction: { delay_1: 2 }, positionUnknown: 1 })
api['batchResolverProducer'] = {
createJob: jest.fn(),
disconnect: jest.fn(),
@@ -1213,7 +1215,7 @@ describe('CDP API', () => {
)
expect(res.status).toEqual(200)
- expect(res.body).toEqual({ count: 3 })
+ expect(res.body).toEqual({ count: 3, by_action: { delay_1: 2 }, position_unknown: 1 })
expect(mockCountInFlightJobs).toHaveBeenCalledWith(countHogFlow.team_id, countHogFlow.id)
})
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index d48b6f6a566a..3707f3517c74 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -843,8 +843,12 @@ export class CdpApi {
return res.status(404).json({ error: 'Workflow not found' })
}
- const count = await this.batchResolverProducer.countInFlightJobs(team.id, id)
- return res.json({ count })
+ const counts = await this.batchResolverProducer.countInFlightJobs(team.id, id)
+ return res.json({
+ count: counts.count,
+ by_action: counts.byAction,
+ position_unknown: counts.positionUnknown,
+ })
} catch (e) {
logger.error('Error counting in-flight hog flow jobs', {
error: e instanceof Error ? e.message : String(e),
diff --git a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
index 5d7f4f670d63..7305ebbd61ac 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/cyclotron-v2.test.ts
@@ -288,19 +288,25 @@ describe('Cyclotron V2', () => {
}
)
- it('countInFlightJobs counts available and running jobs for one team and function', async () => {
+ it('countInFlightJobs counts available and running jobs grouped by action', async () => {
const functionId = uuidv7()
const otherFunctionId = uuidv7()
- await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
- const runningId = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
+ await manager.createJob({ teamId: 1, queueName: QUEUE, functionId, actionId: 'delay_1' })
+ const runningId = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId, actionId: 'delay_1' })
await assertPool.query(`UPDATE cyclotron_jobs SET status = 'running' WHERE id = $1`, [runningId])
+ // No actionId: a job written before the lookup column existed → position unknown
+ await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
// Not counted: terminal status, other function, other team
const completedId = await manager.createJob({ teamId: 1, queueName: QUEUE, functionId })
await assertPool.query(`UPDATE cyclotron_jobs SET status = 'completed' WHERE id = $1`, [completedId])
- await manager.createJob({ teamId: 1, queueName: QUEUE, functionId: otherFunctionId })
- await manager.createJob({ teamId: 2, queueName: QUEUE, functionId })
+ await manager.createJob({ teamId: 1, queueName: QUEUE, functionId: otherFunctionId, actionId: 'delay_1' })
+ await manager.createJob({ teamId: 2, queueName: QUEUE, functionId, actionId: 'delay_1' })
- expect(await manager.countInFlightJobs(1, functionId)).toBe(2)
+ expect(await manager.countInFlightJobs(1, functionId)).toEqual({
+ count: 3,
+ byAction: { delay_1: 2 },
+ positionUnknown: 1,
+ })
})
describe('rescheduleParkedJobs', () => {
diff --git a/nodejs/src/cdp/services/cyclotron-v2/manager.ts b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
index ebfc201ec568..1d3ccd15ae9f 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/manager.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/manager.ts
@@ -7,6 +7,7 @@ import { logger } from '~/common/utils/logger'
import { sleep } from '~/common/utils/utils'
import {
+ CyclotronV2InFlightCounts,
CyclotronV2JobInit,
CyclotronV2JobInitSchema,
CyclotronV2ManagerConfig,
@@ -435,13 +436,28 @@ export class CyclotronV2Manager {
// "In flight" = jobs still owned by the queue: parked waits/delays ('available' with a future
// scheduled time) and jobs a worker currently holds ('running'). Terminal rows don't count.
- async countInFlightJobs(teamId: number, functionId: string): Promise<number> {
- const result = await this.pool.query<{ count: number }>(
- `SELECT COUNT(*)::int AS count FROM cyclotron_jobs
- WHERE team_id = $1 AND function_id = $2 AND status IN ('available', 'running')`,
+ // Grouped by action_id so publish impact can say "N runs are parked on step X"; rows without
+ // one (freshly enqueued and not yet executed, or predating the lookup column) land in
+ // positionUnknown, never silently dropped.
+ async countInFlightJobs(teamId: number, functionId: string): Promise<CyclotronV2InFlightCounts> {
+ const result = await this.pool.query<{ action_id: string | null; count: number }>(
+ `SELECT action_id, COUNT(*)::int AS count FROM cyclotron_jobs
+ WHERE team_id = $1 AND function_id = $2 AND status IN ('available', 'running')
+ GROUP BY action_id`,
[teamId, functionId]
)
- return result.rows[0].count
+ let count = 0
+ let positionUnknown = 0
+ const byAction: Record<string, number> = {}
+ for (const row of result.rows) {
+ count += row.count
+ if (row.action_id) {
+ byAction[row.action_id] = row.count
+ } else {
+ positionUnknown = row.count
+ }
+ }
+ return { count, byAction, positionUnknown }
}
/**
diff --git a/nodejs/src/cdp/services/cyclotron-v2/types.ts b/nodejs/src/cdp/services/cyclotron-v2/types.ts
index d3ca08517eed..b806fdbe9771 100644
--- a/nodejs/src/cdp/services/cyclotron-v2/types.ts
+++ b/nodejs/src/cdp/services/cyclotron-v2/types.ts
@@ -130,9 +130,19 @@ export type CyclotronV2RescheduleParkedResult = {
* on the interface (testable, mockable) without pulling the full manager
* implementation. Add methods here as new producers need them.
*/
+export interface CyclotronV2InFlightCounts {
+ count: number
+ /** Parked/running jobs per current action id. Point-in-time — jobs transition during the read. */
+ byAction: Record<string, number>
+ /** Jobs with no action_id: freshly enqueued and not yet executed (currentAction is set on the
+ * first executor pass), or written before the lookup column existed. A steady-state category
+ * that grows under worker lag, not a shrinking migration artifact. */
+ positionUnknown: number
+}
+
export interface CyclotronV2JobProducer {
createJob(input: CyclotronV2JobInit): Promise<string>
- countInFlightJobs(teamId: number, functionId: string): Promise<number>
+ countInFlightJobs(teamId: number, functionId: string): Promise<CyclotronV2InFlightCounts>
rescheduleParkedJobs(options: CyclotronV2RescheduleParkedOptions): Promise<CyclotronV2RescheduleParkedResult>
disconnect(): Promise<void>
}
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.py
index 1161dfa1a936..9f5297d43399 100644
--- a/posthog/plugins/plugin_server_api.py
+++ b/posthog/plugins/plugin_server_api.py
@@ -112,9 +112,13 @@ def create_hog_flow_scheduled_invocation(
def get_hog_flow_in_flight_count(team_id: int, hog_flow_id: str) -> requests.Response:
+ # The count scans every in-flight row for the flow, which can be slow on a very large flow with
+ # a cold visibility map. The timeout keeps a slow scan from pinning the calling request thread —
+ # callers already treat any failure as "count unavailable" and render the impact without it.
return internal_requests.get(
CDP_API_URL + f"/api/projects/{team_id}/hog_flows/{hog_flow_id}/in_flight_count",
headers=get_internal_api_headers(),
+ timeout=10,
)
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index 14dc5726f0b6..8043591602c7 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -6,6 +6,7 @@ from datetime import timedelta
from typing import Any, Optional, cast
from django.core.exceptions import ValidationError as DjangoValidationError
+from django.core.signing import BadSignature, SignatureExpired, TimestampSigner
from django.db import transaction
from django.db.models import QuerySet
from django.http import Http404, HttpResponse
@@ -83,6 +84,7 @@ from products.workflows.backend.api.message_assets import (
fetch_message_asset_html,
fetch_message_assets,
)
+from products.workflows.backend.api.publish_impact import build_publish_impact
from products.workflows.backend.models.email_reputation import EmailReputationSnapshot
from products.workflows.backend.models.hog_flow.hog_flow import (
BILLABLE_ACTION_TYPES,
@@ -1386,19 +1388,79 @@ class HogFlowPublishRequestSerializer(serializers.Serializer):
confirm = serializers.BooleanField(
default=False,
help_text=(
- "False (default) previews the publish: returns how many runs are in flight without changing "
+ "False (default) previews the publish: returns the impact on people in-flight without changing "
"anything. True applies the staged draft to the live workflow."
),
)
- draft_updated_at = serializers.DateTimeField(
+ confirm_token = serializers.CharField(
required=False,
help_text=(
- "The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you "
- "never publish a draft someone else has changed since you read it."
+ "From the preview response — required when confirm=true. Expires after 15 minutes, and any "
+ "draft edit invalidates it (409), so you always publish the exact draft you previewed."
),
)
+class HogFlowPublishImpactMoveTargetSerializer(serializers.Serializer):
+ action_id = serializers.CharField(help_text="Id of the surviving step runs will continue at.")
+ name = serializers.CharField(help_text="Name of the surviving step.")
+
+
+class HogFlowPublishImpactDeletedStepSerializer(serializers.Serializer):
+ action_id = serializers.CharField(help_text="Id of the step this publish deletes.")
+ name = serializers.CharField(help_text="Name of the deleted step.")
+ runs = serializers.IntegerField(
+ allow_null=True,
+ help_text="About how many in-flight runs are parked on this step. Null when the count is unavailable.",
+ )
+ moves_to = HogFlowPublishImpactMoveTargetSerializer(
+ allow_null=True,
+ help_text="Where those runs continue (skip-forward). Null when nothing downstream survives.",
+ )
+ exits = serializers.BooleanField(
+ help_text="True when runs parked here exit the workflow instead of moving forward."
+ )
+
+
+class HogFlowPublishImpactEmptyVariableSerializer(serializers.Serializer):
+ variable = serializers.CharField(help_text="Variable that renders empty for runs already past its producer.")
+ set_by = serializers.CharField(
+ allow_null=True,
+ help_text="Id of the new action that sets it; null when the draft newly declares it as a workflow variable.",
+ )
+ referenced_by = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Ids of steps whose content references the variable.",
+ )
+
+
+class HogFlowPublishImpactScheduleConflictSerializer(serializers.Serializer):
+ schedule_id = serializers.CharField(help_text="Schedule whose variable overrides reference removed variables.")
+ variables = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Override keys the draft no longer declares as workflow variables.",
+ )
+
+
+class HogFlowPublishImpactSerializer(serializers.Serializer):
+ deleted_steps = HogFlowPublishImpactDeletedStepSerializer(
+ many=True,
+ help_text="Per deleted step: how many runs are parked there and where they go. Empty for content-only edits.",
+ )
+ position_unknown = serializers.IntegerField(
+ allow_null=True,
+ help_text="In-flight runs whose current step is unknown. Null when the count is unavailable.",
+ )
+ empty_variables = HogFlowPublishImpactEmptyVariableSerializer(
+ many=True,
+ help_text="Variables that render empty for runs predating their producer.",
+ )
+ schedule_conflicts = HogFlowPublishImpactScheduleConflictSerializer(
+ many=True,
+ help_text="Schedules overriding variables the draft removes.",
+ )
+
+
class HogFlowPublishResponseSerializer(serializers.Serializer):
published = serializers.BooleanField(help_text="Whether the draft was applied to the live workflow.")
in_flight_runs = serializers.IntegerField(
@@ -1410,7 +1472,15 @@ class HogFlowPublishResponseSerializer(serializers.Serializer):
)
draft_updated_at = serializers.DateTimeField(
allow_null=True,
- help_text="Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.",
+ help_text="The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.",
+ )
+ confirm_token = serializers.CharField(
+ allow_null=True,
+ help_text="Echo this back with confirm=true to publish the previewed draft. Only set on previews.",
+ )
+ impact = HogFlowPublishImpactSerializer(
+ allow_null=True,
+ help_text="What publishing does to people in-flight. Only set on previews; counts are approximate.",
)
workflow = HogFlowSerializer(
required=False,
@@ -1444,6 +1514,22 @@ class StaleWorkflowUpdateError(exceptions.APIException):
default_code = "stale_update"
+# The confirm token makes the publish preview structurally unskippable: only the preview mints it,
+# and it signs the exact draft it previewed — so a valid token proves the caller saw the impact
+# summary for the draft being published. Short max-age keeps the previewed counts fresh.
+PUBLISH_CONFIRM_TOKEN_MAX_AGE = timedelta(minutes=15)
+_PUBLISH_CONFIRM_SALT = "hogflow-publish"
+
+
+def _publish_confirm_value(hog_flow: HogFlow) -> str:
+ draft_updated_at = hog_flow.draft_updated_at.isoformat() if hog_flow.draft_updated_at else ""
+ return f"{hog_flow.id}:{draft_updated_at}"
+
+
+def mint_publish_confirm_token(hog_flow: HogFlow) -> str:
+ return TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).sign(_publish_confirm_value(hog_flow))
+
+
@extend_schema(extensions={"x-product": "workflows"})
class HogFlowViewSet(
TeamAndOrgViewSetMixin, AccessControlViewSetMixin, LogEntryMixin, AppMetricsMixin, viewsets.ModelViewSet
@@ -1878,13 +1964,19 @@ class HogFlowViewSet(
lambda: reschedule_hog_flow_timing.delay(team_id=team_id, hog_flow_id=hog_flow_id, action_ids=action_ids)
)
- def _get_in_flight_run_count(self, hog_flow: HogFlow) -> Optional[int]:
- # Best-effort: publish must not fail because the counting service is unreachable — the count
- # is advisory ("N runs in flight will follow the new config"), not a gate.
+ def _get_in_flight_counts(self, hog_flow: HogFlow) -> Optional[dict]:
+ # Best-effort: publish must not fail because the counting service is unreachable — the counts
+ # are advisory ("N runs in flight will follow the new config"), not a gate. by_action and
+ # position_unknown are None when the plugin server predates the per-action breakdown.
try:
res = get_hog_flow_in_flight_count(team_id=self.team_id, hog_flow_id=str(hog_flow.id))
if res.status_code == 200:
- return res.json().get("count")
+ body = res.json()
+ return {
+ "count": body.get("count"),
+ "by_action": body.get("by_action"),
+ "position_unknown": body.get("position_unknown"),
+ }
logger.warning(
"Failed to fetch in-flight run count for workflow",
hog_flow_id=str(hog_flow.id),
@@ -1896,6 +1988,26 @@ class HogFlowViewSet(
)
return None
+ def _build_publish_impact(self, hog_flow: HogFlow, counts: Optional[dict]) -> dict:
+ draft = hog_flow.draft or {}
+ schedule_overrides = {
+ str(schedule_id): variables or {}
+ for schedule_id, variables in hog_flow.schedules.exclude(
+ status=HogFlowSchedule.Status.COMPLETED
+ ).values_list("id", "variables")
+ }
+ return build_publish_impact(
+ live_actions=hog_flow.actions or [],
+ live_edges=hog_flow.edges or [],
+ live_variables=hog_flow.variables or [],
+ draft_actions=draft.get("actions") or [],
+ draft_variables=draft.get("variables") or [],
+ existing_redirects=hog_flow.action_redirects,
+ by_action_counts=counts.get("by_action") if counts else None,
+ position_unknown=counts.get("position_unknown") if counts else None,
+ schedule_overrides=schedule_overrides,
+ )
+
@extend_schema(request=HogFlowPublishRequestSerializer, responses={200: HogFlowPublishResponseSerializer})
@action(detail=True, methods=["POST"])
def publish(self, request: Request, *args, **kwargs):
@@ -1913,18 +2025,42 @@ class HogFlowViewSet(
raise exceptions.ValidationError("This workflow has no staged draft to publish.")
if not confirm:
+ counts = self._get_in_flight_counts(instance)
return Response(
{
"published": False,
- "in_flight_runs": self._get_in_flight_run_count(instance),
+ "in_flight_runs": counts.get("count") if counts else None,
"draft_updated_at": instance.draft_updated_at,
+ "confirm_token": mint_publish_confirm_token(instance),
+ "impact": self._build_publish_impact(instance, counts),
}
)
- expected_draft_updated_at = param_serializer.validated_data.get("draft_updated_at")
- if not expected_draft_updated_at:
+ confirm_token = param_serializer.validated_data.get("confirm_token")
+ if not confirm_token:
+ raise exceptions.ValidationError(
+ {
+ "confirm_token": (
+ "Required when confirming a publish — call publish without confirm first to preview "
+ "the impact and get a token."
+ )
+ }
+ )
+ try:
+ previewed_value = TimestampSigner(salt=_PUBLISH_CONFIRM_SALT).unsign(
+ confirm_token, max_age=PUBLISH_CONFIRM_TOKEN_MAX_AGE
+ )
+ except SignatureExpired:
+ raise exceptions.ValidationError(
+ {"confirm_token": "Expired — preview the publish again to get a fresh token."}
+ )
+ except BadSignature:
raise exceptions.ValidationError(
- {"draft_updated_at": "Required when confirming a publish — pass the draft_updated_at you loaded."}
+ {
+ "confirm_token": (
+ "Invalid — call publish without confirm first to preview the impact and get a token."
+ )
+ }
)
with transaction.atomic():
@@ -1932,7 +2068,7 @@ class HogFlowViewSet(
locked = HogFlow.objects.select_for_update().get(pk=instance.pk)
if not locked.draft:
raise exceptions.ValidationError("This workflow has no staged draft to publish.")
- if locked.draft_updated_at != expected_draft_updated_at:
+ if previewed_value != _publish_confirm_value(locked):
raise StaleWorkflowUpdateError()
# nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance for activity logging)
@@ -1956,6 +2092,8 @@ class HogFlowViewSet(
"published": True,
"in_flight_runs": None,
"draft_updated_at": None,
+ "confirm_token": None,
+ "impact": None,
"workflow": self.get_serializer(locked).data,
}
)
diff --git a/products/workflows/backend/api/publish_impact.py b/products/workflows/backend/api/publish_impact.py
new file mode 100644
index 000000000000..0b5f2f7b8863
--- /dev/null
+++ b/products/workflows/backend/api/publish_impact.py
@@ -0,0 +1,143 @@
+import re
+from typing import Any, Optional
+
+from products.workflows.backend.api.action_redirects import compute_action_redirects
+
+# Publish-time impact summary: what applying a staged draft will do to people already in the flow.
+# Pure functions over the two graphs plus externally-fetched counts, so the matrix is unit-testable
+# without a DB — mirrors the worker's runtime variable scan (hogflow-variable-usage.ts), which
+# observes the same misses per-run at execution time.
+
+# Both templating modes reference workflow variables textually: `{variables.foo}` (hog) and
+# `{{ variables.foo }}` (liquid), plus the bracket form `variables['my-var']`.
+_DOT_REFERENCE_REGEX = re.compile(r"\bvariables\.([A-Za-z_$][A-Za-z0-9_$]*)")
+_BRACKET_REFERENCE_REGEX = re.compile(r"\bvariables\s*\[\s*['\"]([^'\"\]]+)['\"]\s*\]")
+
+# Compiled hog output carried alongside the template strings — never scanned, matching the worker:
+# references there are separate string constants, and a template embedded verbatim as a bytecode
+# constant would be a false positive.
+_SKIPPED_KEYS = {"bytecode", "transpiled"}
+
+# Draft configs are user-controlled JSON: a ~6 KB payload nested ~1000 deep parses fine at write
+# time but would RecursionError this scan. Legitimate configs nest a handful of levels; anything
+# deeper is ignored rather than crashing the preview (same posture as integration_usage.py).
+_MAX_CONFIG_DEPTH = 20
+
+
+def find_variable_references(value: Any) -> set[str]:
+ """Names of workflow variables referenced anywhere in a config blob's template strings."""
+ found: set[str] = set()
+ _collect_references(value, found, _MAX_CONFIG_DEPTH)
+ return found
+
+
+def _collect_references(value: Any, into: set[str], depth_left: int) -> None:
+ if depth_left <= 0:
+ return
+ if isinstance(value, str):
+ for regex in (_DOT_REFERENCE_REGEX, _BRACKET_REFERENCE_REGEX):
+ into.update(regex.findall(value))
+ return
+ if isinstance(value, list):
+ for item in value:
+ _collect_references(item, into, depth_left - 1)
+ return
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if key not in _SKIPPED_KEYS:
+ _collect_references(item, into, depth_left - 1)
+
+
+def _output_variable_keys(action: dict) -> list[str]:
+ output_variable = action.get("output_variable")
+ if not output_variable:
+ return []
+ entries = output_variable if isinstance(output_variable, list) else [output_variable]
+ return [entry["key"] for entry in entries if isinstance(entry, dict) and entry.get("key")]
+
+
+def build_publish_impact(
+ *,
+ live_actions: list[dict],
+ live_edges: list[dict],
+ live_variables: list[dict],
+ draft_actions: list[dict],
+ draft_variables: list[dict],
+ existing_redirects: Optional[dict[str, str]],
+ by_action_counts: Optional[dict[str, int]],
+ position_unknown: Optional[int],
+ schedule_overrides: dict[str, dict],
+) -> dict:
+ """What publishing the draft does to people in-flight. Counts are point-in-time approximations
+ (jobs transition during the read); None means the counting service was unavailable, never 0."""
+ draft_ids = {action["id"] for action in draft_actions if action.get("id")}
+ draft_names = {action["id"]: action.get("name") or action["id"] for action in draft_actions if action.get("id")}
+
+ redirects = compute_action_redirects(live_actions, live_edges, draft_actions, existing_redirects) or {}
+ deleted_steps = []
+ for action in live_actions:
+ action_id = action.get("id")
+ if not action_id or action_id in draft_ids:
+ continue
+ target = redirects.get(action_id)
+ deleted_steps.append(
+ {
+ "action_id": action_id,
+ "name": action.get("name") or action_id,
+ "runs": by_action_counts.get(action_id, 0) if by_action_counts is not None else None,
+ "moves_to": {"action_id": target, "name": draft_names[target]} if target else None,
+ "exits": target is None,
+ }
+ )
+
+ # A variable produced only by something new in the draft may render empty for runs already past
+ # its producer: an output_variable key this draft adds (on a new action, or newly added to a
+ # surviving one), or a workflow variable declared by this draft (declared variables are seeded
+ # at run start, so pre-existing runs never had it).
+ producers: dict[str, Optional[str]] = {}
+ live_variable_keys = {variable.get("key") for variable in live_variables}
+ for variable in draft_variables:
+ key = variable.get("key")
+ if key and key not in live_variable_keys:
+ producers[key] = None
+ live_output_keys = {action["id"]: set(_output_variable_keys(action)) for action in live_actions if action.get("id")}
+ for action in draft_actions:
+ action_id = action.get("id")
+ if not action_id:
+ continue
+ for key in _output_variable_keys(action):
+ if key not in live_output_keys.get(action_id, set()):
+ producers[key] = action_id
+
+ empty_variables = []
+ if producers:
+ references: dict[str, list[str]] = {key: [] for key in producers}
+ for action in draft_actions:
+ action_id = action.get("id")
+ if not action_id:
+ continue
+ config = action.get("config") or {}
+ # Only inputs/mappings — the worker renders templates from those two fields alone, so a
+ # variables-shaped string anywhere else in the config never renders and must not warn.
+ for key in find_variable_references([config.get("inputs"), config.get("mappings")]):
+ if key in references and action_id != producers[key]:
+ references[key].append(action_id)
+ empty_variables = [
+ {"variable": key, "set_by": producers[key], "referenced_by": referenced_by}
+ for key, referenced_by in sorted(references.items())
+ if referenced_by
+ ]
+
+ declared_keys = {variable.get("key") for variable in draft_variables}
+ schedule_conflicts = [
+ {"schedule_id": schedule_id, "variables": orphaned}
+ for schedule_id, overrides in schedule_overrides.items()
+ if (orphaned := sorted(set(overrides) - declared_keys))
+ ]
+
+ return {
+ "deleted_steps": deleted_steps,
+ "position_unknown": position_unknown,
+ "empty_variables": empty_variables,
+ "schedule_conflicts": schedule_conflicts,
+ }
diff --git a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
index f80e48dd9c9b..10cc4aa66392 100644
--- a/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
+++ b/products/workflows/backend/api/test/test_hog_flow_draft_publish.py
@@ -1,3 +1,4 @@
+from freezegun import freeze_time
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -232,10 +233,22 @@ class TestHogFlowDraftPublish(APIBaseTest):
assert response.status_code == 200, response.json()
return HogFlow.objects.get(pk=flow_id)
+ def _publish_preview(self, flow_id: str, counts: dict | None = None):
+ with patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count") as mock_count:
+ if counts is None:
+ mock_count.side_effect = Exception("count service down")
+ else:
+ mock_count.return_value = MagicMock(status_code=200, json=lambda: counts)
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})
+ assert response.status_code == 200, response.json()
+ return response
+
@patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")
@patch(FLAG_PATH, return_value=True)
def test_publish_without_confirm_returns_impact_only(self, _flag, mock_count):
- mock_count.return_value = MagicMock(status_code=200, json=lambda: {"count": 42})
+ mock_count.return_value = MagicMock(
+ status_code=200, json=lambda: {"count": 42, "by_action": {"action_1": 42}, "position_unknown": 0}
+ )
flow_id = self._create_active_flow()
flow = self._stage_draft(flow_id)
live_actions_before = flow.actions
@@ -244,6 +257,14 @@ class TestHogFlowDraftPublish(APIBaseTest):
assert response.status_code == 200, response.json()
assert response.json()["in_flight_runs"] == 42
assert response.json()["draft_updated_at"] is not None
+ assert response.json()["confirm_token"]
+ # Content-only edit: impact present but empty — nothing to warn about
+ assert response.json()["impact"] == {
+ "deleted_steps": [],
+ "position_unknown": 0,
+ "empty_variables": [],
+ "schedule_conflicts": [],
+ }
flow.refresh_from_db()
assert flow.actions == live_actions_before
@@ -251,7 +272,7 @@ class TestHogFlowDraftPublish(APIBaseTest):
@patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")
@patch(FLAG_PATH, return_value=True)
- def test_publish_impact_degrades_to_null_when_count_unavailable(self, _flag, mock_count):
+ def test_publish_impact_degrades_to_null_counts_when_unavailable(self, _flag, mock_count):
mock_count.side_effect = Exception("node service down")
flow_id = self._create_active_flow()
self._stage_draft(flow_id)
@@ -259,19 +280,46 @@ class TestHogFlowDraftPublish(APIBaseTest):
response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})
assert response.status_code == 200, response.json()
assert response.json()["in_flight_runs"] is None
+ # Graph-derived impact still renders; only the counts degrade
+ assert response.json()["impact"]["position_unknown"] is None
+
+ @patch("products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count")
+ @patch(FLAG_PATH, return_value=True)
+ def test_publish_preview_reports_deleted_step_moves(self, _flag, mock_count):
+ mock_count.return_value = MagicMock(
+ status_code=200, json=lambda: {"count": 7, "by_action": {"action_1": 5}, "position_unknown": 2}
+ )
+ flow_id = self._create_active_three_step_flow()
+ stage = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}",
+ self._DELETE_ACTION_1_PAYLOAD,
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ )
+ assert stage.status_code == 200, stage.json()
+
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})
+ assert response.status_code == 200, response.json()
+ impact = response.json()["impact"]
+ assert impact["deleted_steps"] == [
+ {
+ "action_id": "action_1",
+ "name": "action_1",
+ "runs": 5,
+ "moves_to": {"action_id": "action_2", "name": "action_2"},
+ "exits": False,
+ }
+ ]
+ assert impact["position_unknown"] == 2
@patch(FLAG_PATH, return_value=True)
def test_publish_with_confirm_promotes_draft_and_clears_it(self, _flag):
flow_id = self._create_active_flow()
flow = self._stage_draft(flow_id)
- # Narrow a local, not the attribute — narrowing flow.draft_updated_at here would make the
- # post-publish `is None` assertion unreachable in mypy's eyes (it can't see refresh_from_db)
- staged_at = flow.draft_updated_at
- assert staged_at is not None
+ confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
response = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": staged_at.isoformat()},
+ {"confirm": True, "confirm_token": confirm_token},
)
assert response.status_code == 200, response.json()
@@ -285,31 +333,50 @@ class TestHogFlowDraftPublish(APIBaseTest):
assert trigger["config"]["filters"].get("bytecode"), "publish must compile trigger filter bytecode"
@patch(FLAG_PATH, return_value=True)
- def test_publish_with_stale_draft_pointer_is_rejected_with_409(self, _flag):
+ def test_publish_with_stale_token_after_draft_reedit_is_rejected_with_409(self, _flag):
flow_id = self._create_active_flow()
self._stage_draft(flow_id)
+ confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
+ # The draft changes between preview and confirm — the token no longer matches what's staged
+ reedit = self._patch_actions_via_mcp(flow_id, url="https://reedited.example.com")
+ assert reedit.status_code == 200, reedit.json()
response = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": "2020-01-01T00:00:00Z"},
+ {"confirm": True, "confirm_token": confirm_token},
)
assert response.status_code == 409, response.json()
@parameterized.expand(
[
- ("flag_off", False, True),
- ("no_draft", True, False),
+ ("flag_off", False, True, "garbage"),
+ ("no_draft", True, False, "garbage"),
+ ("no_token", True, True, None),
+ ("forged_token", True, True, "not-a-signed-value:1a2b3c:forged"),
]
)
- def test_publish_rejected(self, _name, flag_on, stage_draft):
+ def test_publish_rejected(self, _name, flag_on, stage_draft, confirm_token):
flow_id = self._create_active_flow()
if stage_draft:
self._stage_draft(flow_id)
+ payload: dict = {"confirm": True}
+ if confirm_token is not None:
+ payload["confirm_token"] = confirm_token
with patch(FLAG_PATH, return_value=flag_on):
- response = self.client.post(
- f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": "2026-01-01T00:00:00Z"},
- )
+ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", payload)
+ assert response.status_code == 400, response.json()
+
+ @patch(FLAG_PATH, return_value=True)
+ def test_publish_with_expired_token_is_rejected(self, _flag):
+ flow_id = self._create_active_flow()
+ with freeze_time("2026-01-01T00:00:00Z"):
+ self._stage_draft(flow_id)
+ confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
+ {"confirm": True, "confirm_token": confirm_token},
+ )
assert response.status_code == 400, response.json()
@patch(FLAG_PATH, return_value=True)
@@ -319,13 +386,15 @@ class TestHogFlowDraftPublish(APIBaseTest):
flow_id = self._create_active_flow()
flow = self._stage_draft(flow_id)
assert flow.draft is not None
- assert flow.draft_updated_at is not None
+ confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
+ # Tampering via the ORM leaves draft_updated_at untouched, so the token stays valid —
+ # strict revalidation is what must catch the bad blob
flow.draft = {**flow.draft, "actions": [{"id": "bad", "type": "function", "config": {}}]}
flow.save(update_fields=["draft"])
response = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": flow.draft_updated_at.isoformat()},
+ {"confirm": True, "confirm_token": confirm_token},
)
assert response.status_code == 400, response.json()
@@ -427,11 +496,11 @@ class TestHogFlowDraftPublish(APIBaseTest):
assert response.status_code == 200, response.json()
flow = HogFlow.objects.get(pk=flow_id)
assert flow.action_redirects is None, "staging a draft must not touch the live redirect map"
- assert flow.draft_updated_at is not None
+ confirm_token = self._publish_preview(flow_id).json()["confirm_token"]
response = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": flow.draft_updated_at.isoformat()},
+ {"confirm": True, "confirm_token": confirm_token},
)
assert response.status_code == 200, response.json()
# Re-fetch rather than refresh_from_db: the is-None assert above narrows the attribute
diff --git a/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py b/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py
index 8e03a7dee4df..b0720da27512 100644
--- a/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py
+++ b/products/workflows/backend/api/test/test_hog_flow_timing_reschedule.py
@@ -130,14 +130,20 @@ class TestHogFlowTimingRescheduleTrigger(APIBaseTest):
flow_id = self._create_flow()
response = self._patch_actions(flow_id, delay_duration="1d", HTTP_X_POSTHOG_CLIENT="mcp")
assert response.status_code == 200, response.json()
- staged_at = HogFlow.objects.get(pk=flow_id).draft_updated_at
- assert staged_at is not None
+ assert HogFlow.objects.get(pk=flow_id).draft_updated_at is not None
mock_task.delay.assert_not_called()
+ with patch(
+ "products.workflows.backend.api.hog_flow.get_hog_flow_in_flight_count",
+ side_effect=Exception("count service down"),
+ ):
+ preview = self.client.post(f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish", {})
+ assert preview.status_code == 200, preview.json()
+
with self.captureOnCommitCallbacks(execute=True):
publish = self.client.post(
f"/api/projects/{self.team.id}/hog_flows/{flow_id}/publish",
- {"confirm": True, "draft_updated_at": staged_at.isoformat()},
+ {"confirm": True, "confirm_token": preview.json()["confirm_token"]},
)
assert publish.status_code == 200, publish.json()
diff --git a/products/workflows/backend/api/test/test_publish_impact.py b/products/workflows/backend/api/test/test_publish_impact.py
new file mode 100644
index 000000000000..854f02a0bf86
--- /dev/null
+++ b/products/workflows/backend/api/test/test_publish_impact.py
@@ -0,0 +1,180 @@
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.workflows.backend.api.publish_impact import build_publish_impact, find_variable_references
+
+
+def _action(action_id: str, name: str | None = None, output_variable: dict | list | None = None, **config) -> dict:
+ return {
+ "id": action_id,
+ "name": name or action_id,
+ "type": "function",
+ "output_variable": output_variable,
+ "config": config or {"inputs": {}},
+ }
+
+
+def _continue_edge(source: str, target: str) -> dict:
+ return {"from": source, "to": target, "type": "continue"}
+
+
+class TestFindVariableReferences(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("hog_dot", {"inputs": {"url": {"value": "{variables.foo}"}}}, {"foo"}),
+ ("liquid_dot", {"inputs": {"body": {"value": "Hi {{ variables.name }}!"}}}, {"name"}),
+ ("bracket", {"inputs": {"body": {"value": "{{ variables['my-var'] }}"}}}, {"my-var"}),
+ ("bracket_spaced", {"inputs": {"x": {"value": "variables[ 'y' ]"}}}, {"y"}),
+ ("nested_and_lists", {"mappings": [{"v": ["{variables.a}", {"w": "{variables.b}"}]}]}, {"a", "b"}),
+ ("bytecode_skipped", {"inputs": {"url": {"bytecode": ["{variables.foo}"], "value": "plain"}}}, set()),
+ ("transpiled_skipped", {"inputs": {"url": {"transpiled": "{variables.foo}"}}}, set()),
+ ("no_references", {"inputs": {"url": {"value": "https://example.com"}}}, set()),
+ ]
+ )
+ def test_reference_extraction(self, _name, config, expected):
+ assert find_variable_references(config) == expected
+
+ def test_pathological_nesting_is_ignored_not_crashed(self):
+ deep: dict = {"value": "{variables.too_deep}"}
+ for _ in range(2000):
+ deep = {"nested": deep}
+ assert find_variable_references({"inputs": {"shallow": "{variables.ok}", "deep": deep}}) == {"ok"}
+
+
+class TestBuildPublishImpact(SimpleTestCase):
+ def _base(self, **overrides: Any) -> dict:
+ kwargs: dict[str, Any] = {
+ "live_actions": [_action("trigger"), _action("a"), _action("b"), _action("c")],
+ "live_edges": [_continue_edge("trigger", "a"), _continue_edge("a", "b"), _continue_edge("b", "c")],
+ "live_variables": [],
+ "draft_actions": [_action("trigger"), _action("a"), _action("b"), _action("c")],
+ "draft_variables": [],
+ "existing_redirects": None,
+ "by_action_counts": {},
+ "position_unknown": 0,
+ "schedule_overrides": {},
+ }
+ kwargs.update(overrides)
+ return build_publish_impact(**kwargs)
+
+ def test_content_only_edit_produces_empty_impact(self):
+ impact = self._base()
+ assert impact == {
+ "deleted_steps": [],
+ "position_unknown": 0,
+ "empty_variables": [],
+ "schedule_conflicts": [],
+ }
+
+ def test_deleted_step_with_survivor_reports_move(self):
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a"), _action("c", name="Step C")],
+ by_action_counts={"b": 312, "a": 5},
+ )
+ assert impact["deleted_steps"] == [
+ {
+ "action_id": "b",
+ "name": "b",
+ "runs": 312,
+ "moves_to": {"action_id": "c", "name": "Step C"},
+ "exits": False,
+ }
+ ]
+
+ def test_deleted_dead_end_reports_exit(self):
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a"), _action("b")],
+ by_action_counts={"c": 45},
+ )
+ assert impact["deleted_steps"] == [{"action_id": "c", "name": "c", "runs": 45, "moves_to": None, "exits": True}]
+
+ def test_counts_unavailable_reports_unknown_runs_not_zero(self):
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a"), _action("c")],
+ by_action_counts=None,
+ position_unknown=None,
+ )
+ assert impact["deleted_steps"][0]["runs"] is None
+ assert impact["deleted_steps"][0]["moves_to"] == {"action_id": "c", "name": "c"}
+ assert impact["position_unknown"] is None
+
+ def test_prior_edit_redirect_entries_are_not_reported_again(self):
+ # `old_deleted` was removed by an earlier edit; only this edit's deletions ("b") are impact.
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a"), _action("c")],
+ existing_redirects={"old_deleted": "a"},
+ by_action_counts={"b": 1},
+ )
+ assert [step["action_id"] for step in impact["deleted_steps"]] == ["b"]
+
+ @parameterized.expand(
+ [
+ ("single", {"key": "discount_code"}),
+ ("list", [{"key": "discount_code"}, {"key": "unreferenced"}]),
+ ]
+ )
+ def test_new_action_output_variable_referenced_downstream_is_flagged(self, _name, output_variable):
+ impact = self._base(
+ draft_actions=[
+ _action("trigger"),
+ _action("assign", output_variable=output_variable),
+ _action("email", inputs={"body": {"value": "Use {{ variables.discount_code }}"}}),
+ ],
+ )
+ assert impact["empty_variables"] == [
+ {"variable": "discount_code", "set_by": "assign", "referenced_by": ["email"]}
+ ]
+
+ def test_existing_action_output_variable_is_not_flagged(self):
+ actions = [
+ _action("trigger"),
+ _action("a", output_variable={"key": "score"}),
+ _action("b", inputs={"body": {"value": "{variables.score}"}}),
+ ]
+ impact = self._base(live_actions=actions, draft_actions=actions)
+ assert impact["empty_variables"] == []
+
+ def test_output_variable_added_to_existing_action_is_flagged(self):
+ # Runs already past "a" never executed the version that stores its output
+ impact = self._base(
+ draft_actions=[
+ _action("trigger"),
+ _action("a", output_variable={"key": "score"}),
+ _action("b", inputs={"body": {"value": "{variables.score}"}}),
+ _action("c"),
+ ],
+ )
+ assert impact["empty_variables"] == [{"variable": "score", "set_by": "a", "referenced_by": ["b"]}]
+
+ def test_reference_outside_inputs_and_mappings_is_not_flagged(self):
+ # The worker renders templates only from config.inputs/config.mappings — a variables-shaped
+ # string elsewhere in the config never renders, so it must not warn
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a", metadata={"note": "{variables.plan}"})],
+ draft_variables=[{"key": "plan", "type": "string", "default": ""}],
+ )
+ assert impact["empty_variables"] == []
+
+ def test_newly_declared_variable_referenced_in_draft_is_flagged(self):
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("a", inputs={"body": {"value": "{variables.plan}"}})],
+ draft_variables=[{"key": "plan", "type": "string", "default": ""}],
+ )
+ assert impact["empty_variables"] == [{"variable": "plan", "set_by": None, "referenced_by": ["a"]}]
+
+ def test_produced_but_unreferenced_variable_is_not_flagged(self):
+ impact = self._base(
+ draft_actions=[_action("trigger"), _action("assign", output_variable={"key": "orphan"})],
+ )
+ assert impact["empty_variables"] == []
+
+ def test_schedule_override_of_deleted_variable_is_flagged(self):
+ impact = self._base(
+ live_variables=[{"key": "kept"}, {"key": "removed"}],
+ draft_variables=[{"key": "kept"}],
+ schedule_overrides={"sched-1": {"kept": "x", "removed": "y"}, "sched-2": {"kept": "z"}},
+ )
+ assert impact["schedule_conflicts"] == [{"schedule_id": "sched-1", "variables": ["removed"]}]
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 9d57045572a4..2ce1a3d603c8 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -819,10 +819,66 @@ export interface AppMetricsTotalsResponseApi {
}
export interface HogFlowPublishRequestApi {
- /** False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow. */
+ /** False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow. */
confirm?: boolean
- /** The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it. */
- draft_updated_at?: string
+ /** From the preview response — required when confirm=true. Expires after 15 minutes, and any draft edit invalidates it (409), so you always publish the exact draft you previewed. */
+ confirm_token?: string
+}
+
+export interface HogFlowPublishImpactMoveTargetApi {
+ /** Id of the surviving step runs will continue at. */
+ action_id: string
+ /** Name of the surviving step. */
+ name: string
+}
+
+export interface HogFlowPublishImpactDeletedStepApi {
+ /** Id of the step this publish deletes. */
+ action_id: string
+ /** Name of the deleted step. */
+ name: string
+ /**
+ * About how many in-flight runs are parked on this step. Null when the count is unavailable.
+ * @nullable
+ */
+ runs: number | null
+ /** Where those runs continue (skip-forward). Null when nothing downstream survives. */
+ moves_to: HogFlowPublishImpactMoveTargetApi | null
+ /** True when runs parked here exit the workflow instead of moving forward. */
+ exits: boolean
+}
+
+export interface HogFlowPublishImpactEmptyVariableApi {
+ /** Variable that renders empty for runs already past its producer. */
+ variable: string
+ /**
+ * Id of the new action that sets it; null when the draft newly declares it as a workflow variable.
+ * @nullable
+ */
+ set_by: string | null
+ /** Ids of steps whose content references the variable. */
+ referenced_by: string[]
+}
+
+export interface HogFlowPublishImpactScheduleConflictApi {
+ /** Schedule whose variable overrides reference removed variables. */
+ schedule_id: string
+ /** Override keys the draft no longer declares as workflow variables. */
+ variables: string[]
+}
+
+export interface HogFlowPublishImpactApi {
+ /** Per deleted step: how many runs are parked there and where they go. Empty for content-only edits. */
+ deleted_steps: HogFlowPublishImpactDeletedStepApi[]
+ /**
+ * In-flight runs whose current step is unknown. Null when the count is unavailable.
+ * @nullable
+ */
+ position_unknown: number | null
+ /** Variables that render empty for runs predating their producer. */
+ empty_variables: HogFlowPublishImpactEmptyVariableApi[]
+ /** Schedules overriding variables the draft removes. */
+ schedule_conflicts: HogFlowPublishImpactScheduleConflictApi[]
}
export interface HogFlowPublishResponseApi {
@@ -834,10 +890,17 @@ export interface HogFlowPublishResponseApi {
*/
in_flight_runs: number | null
/**
- * Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.
+ * The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.
* @nullable
*/
draft_updated_at: string | null
+ /**
+ * Echo this back with confirm=true to publish the previewed draft. Only set on previews.
+ * @nullable
+ */
+ confirm_token: string | null
+ /** What publishing does to people in-flight. Only set on previews; counts are approximate. */
+ impact: HogFlowPublishImpactApi | null
/** The workflow after publishing (only set when published=true). */
workflow?: HogFlowApi | null
}
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index 55c95726e73d..b6f9468983d1 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -1981,13 +1981,13 @@ export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(hogFlowsPublishCreateBodyConfirmDefault)
.describe(
- 'False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.'
+ 'False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow.'
),
- draft_updated_at: zod.iso
- .datetime({ offset: true })
+ confirm_token: zod
+ .string()
.optional()
.describe(
- 'The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.'
+ 'From the preview response — required when confirm=true. Expires after 15 minutes, and any draft edit invalidates it (409), so you always publish the exact draft you previewed.'
),
})
diff --git a/products/workflows/mcp/tools.yaml b/products/workflows/mcp/tools.yaml
index 42db81d5189d..44265f0a298d 100644
--- a/products/workflows/mcp/tools.yaml
+++ b/products/workflows/mcp/tools.yaml
@@ -293,9 +293,11 @@ tools:
title: Publish workflow draft
description: >
Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns
- in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at,
- changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and
- that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm.
+ in_flight_runs, a confirm_token, and an impact summary (per deleted step: about how many people are parked
+ there and whether they move to a surviving step or exit; variables that may render empty for runs that never
+ executed their new producer; schedules overriding removed variables), changing nothing. Echo the impact to
+ the user and get their go-ahead, then call again with confirm=true and that confirm_token. A 409 means the
+ draft changed since the preview and a 400 means the token expired — preview again and re-confirm either way.
Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and
the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).
workflows-stats:
diff --git a/products/workflows/skills/building-workflows/SKILL.md b/products/workflows/skills/building-workflows/SKILL.md
index c63ab11722b0..71eb327e1715 100644
--- a/products/workflows/skills/building-workflows/SKILL.md
+++ b/products/workflows/skills/building-workflows/SKILL.md
@@ -40,10 +40,10 @@ Editing an active workflow stages a **draft** instead of changing what's running
1. **Edit.** `workflows-patch-graph` (or `workflows-update` for content fields) on the active workflow writes to its draft — the first edit copies the live graph into the draft, later edits compose onto it. `workflows-get` shows the staged draft in `draft`; the live config stays in `actions`/`edges`. Metadata (name, description) applies live immediately.
2. **Test the draft.** `workflows-test-run` with `use_draft=true` executes the staged draft instead of the live config. Re-test every path you changed.
-3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs` — people currently mid-flow (parked on waits/delays) who will follow the new config — plus `draft_updated_at`. **Echo that impact to the user and get their go-ahead**, then call again with `confirm=true` and that exact `draft_updated_at`. A 409 means the draft changed since you read it: re-read, re-confirm. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.
+3. **Publish deliberately.** `workflows-publish` without `confirm` returns `in_flight_runs`, a `confirm_token`, and an `impact` summary: per deleted step, about how many people are parked there and whether they move to a surviving step (`moves_to`) or exit; `empty_variables` that may render empty for people already past their new producer when they reach a reference (a structural warning — it can fire even when everyone in-flight is still upstream of the producer); `schedule_conflicts` where a schedule overrides a variable the draft removes. **Echo the impact to the user and get their go-ahead**, then call again with `confirm=true` and that `confirm_token`. A 409 means the draft changed since the preview and a 400 means the token expired (15 minutes) — preview again and re-confirm either way. Publish revalidates everything, so an invalid draft is rejected and live config stays untouched.
4. **Or bail.** `workflows-discard-draft` throws the staged draft away.
-In-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don't re-run.
+In-flight runs follow the live config: once published, people mid-flow continue from their current step on the new version. Steps they already passed don't re-run; people parked on a step the publish deletes skip forward to its next surviving step (or exit at a dead end), exactly as the impact preview reported.
If an edit is rejected with "editing an active workflow isn't supported", draft editing isn't enabled for this project yet — then a live change means recreating the workflow as a new draft (`workflows-create`), testing it, and enabling it as a replacement.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ad0583316e2c..2f3beff90ecb 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10266,7 +10266,7 @@
}
},
"workflows-publish": {
- "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at, changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",
+ "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs, a confirm_token, and an impact summary (per deleted step: about how many people are parked there and whether they move to a surviving step or exit; variables that may render empty for runs that never executed their new producer; schedules overriding removed variables), changing nothing. Echo the impact to the user and get their go-ahead, then call again with confirm=true and that confirm_token. A 409 means the draft changed since the preview and a 400 means the token expired — preview again and re-confirm either way. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",
"category": "Workflows",
"feature": "workflows",
"summary": "Publish workflow draft",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 1daec37b235a..3e3aba627f45 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -10887,7 +10887,7 @@
}
},
"workflows-publish": {
- "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs (people mid-flow who will follow the new config once published) and draft_updated_at, changing nothing. Echo that impact to the user and get their go-ahead, then call again with confirm=true and that exact draft_updated_at; a 409 means the draft changed since you read it, so re-read and re-confirm. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",
+ "description": "Apply a workflow's staged draft to its live config. Two-step: call without confirm first — it returns in_flight_runs, a confirm_token, and an impact summary (per deleted step: about how many people are parked there and whether they move to a surviving step or exit; variables that may render empty for runs that never executed their new producer; schedules overriding removed variables), changing nothing. Echo the impact to the user and get their go-ahead, then call again with confirm=true and that confirm_token. A 409 means the draft changed since the preview and a 400 means the token expired — preview again and re-confirm either way. Publish revalidates the draft fully and recompiles it, so an invalid draft is rejected with the reason and the live config stays untouched. Test the draft first with workflows-test-run (use_draft=true).",
"category": "Workflows",
"feature": "workflows",
"summary": "Publish workflow draft",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f2a1de383e95..b6f5e4d787f6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -32602,11 +32602,67 @@ export namespace Schemas {
readonly user_access_level: string | null;
}
+ export interface HogFlowPublishImpactMoveTarget {
+ /** Id of the surviving step runs will continue at. */
+ action_id: string;
+ /** Name of the surviving step. */
+ name: string;
+ }
+
+ export interface HogFlowPublishImpactDeletedStep {
+ /** Id of the step this publish deletes. */
+ action_id: string;
+ /** Name of the deleted step. */
+ name: string;
+ /**
+ * About how many in-flight runs are parked on this step. Null when the count is unavailable.
+ * @nullable
+ */
+ runs: number | null;
+ /** Where those runs continue (skip-forward). Null when nothing downstream survives. */
+ moves_to: HogFlowPublishImpactMoveTarget | null;
+ /** True when runs parked here exit the workflow instead of moving forward. */
+ exits: boolean;
+ }
+
+ export interface HogFlowPublishImpactEmptyVariable {
+ /** Variable that renders empty for runs already past its producer. */
+ variable: string;
+ /**
+ * Id of the new action that sets it; null when the draft newly declares it as a workflow variable.
+ * @nullable
+ */
+ set_by: string | null;
+ /** Ids of steps whose content references the variable. */
+ referenced_by: string[];
+ }
+
+ export interface HogFlowPublishImpactScheduleConflict {
+ /** Schedule whose variable overrides reference removed variables. */
+ schedule_id: string;
+ /** Override keys the draft no longer declares as workflow variables. */
+ variables: string[];
+ }
+
+ export interface HogFlowPublishImpact {
+ /** Per deleted step: how many runs are parked there and where they go. Empty for content-only edits. */
+ deleted_steps: HogFlowPublishImpactDeletedStep[];
+ /**
+ * In-flight runs whose current step is unknown. Null when the count is unavailable.
+ * @nullable
+ */
+ position_unknown: number | null;
+ /** Variables that render empty for runs predating their producer. */
+ empty_variables: HogFlowPublishImpactEmptyVariable[];
+ /** Schedules overriding variables the draft removes. */
+ schedule_conflicts: HogFlowPublishImpactScheduleConflict[];
+ }
+
export interface HogFlowPublishRequest {
- /** False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow. */
+ /** False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow. */
confirm?: boolean;
- /** The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it. */
- draft_updated_at?: string;
+ /** From the preview response — required when confirm=true. Expires after 15 minutes, and any draft edit invalidates it (409), so you always publish the exact draft you previewed. */
+ confirm_token?: string;
}
export interface HogFlowPublishResponse {
@@ -32618,10 +32674,17 @@ export namespace Schemas {
*/
in_flight_runs: number | null;
/**
- * Echo of the staged draft's timestamp — pass it back with confirm=true to publish exactly this draft.
+ * The staged draft's timestamp, for reference; publishing is confirmed via confirm_token.
* @nullable
*/
draft_updated_at: string | null;
+ /**
+ * Echo this back with confirm=true to publish the previewed draft. Only set on previews.
+ * @nullable
+ */
+ confirm_token: string | null;
+ /** What publishing does to people in-flight. Only set on previews; counts are approximate. */
+ impact: HogFlowPublishImpact | null;
/** The workflow after publishing (only set when published=true). */
workflow?: HogFlow | null;
}
diff --git a/services/mcp/src/generated/workflows/api.ts b/services/mcp/src/generated/workflows/api.ts
index e43ec93434d1..f56da1026818 100644
--- a/services/mcp/src/generated/workflows/api.ts
+++ b/services/mcp/src/generated/workflows/api.ts
@@ -1003,13 +1003,13 @@ export const HogFlowsPublishCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(hogFlowsPublishCreateBodyConfirmDefault)
.describe(
- 'False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.'
+ 'False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow.'
),
- draft_updated_at: zod.iso
- .datetime({ offset: true })
+ confirm_token: zod
+ .string()
.optional()
.describe(
- 'The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.'
+ 'From the preview response — required when confirm=true. Expires after 15 minutes, and any draft edit invalidates it (409), so you always publish the exact draft you previewed.'
),
})
diff --git a/services/mcp/src/tools/generated/workflows.ts b/services/mcp/src/tools/generated/workflows.ts
index 573e2d7df381..e064627115df 100644
--- a/services/mcp/src/tools/generated/workflows.ts
+++ b/services/mcp/src/tools/generated/workflows.ts
@@ -273,8 +273,8 @@ const workflowsPublish = (): ToolBase<typeof WorkflowsPublishSchema, Schemas.Hog
if (params.confirm !== undefined) {
body['confirm'] = params.confirm
}
- if (params.draft_updated_at !== undefined) {
- body['draft_updated_at'] = params.draft_updated_at
+ if (params.confirm_token !== undefined) {
+ body['confirm_token'] = params.confirm_token
}
const result = await context.api.request<Schemas.HogFlowPublishResponse>({
method: 'POST',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json
index f3ef60141a3f..a4ef9b2dd732 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/workflows-publish.json
@@ -3,13 +3,11 @@
"properties": {
"confirm": {
"default": false,
- "description": "False (default) previews the publish: returns how many runs are in flight without changing anything. True applies the staged draft to the live workflow.",
+ "description": "False (default) previews the publish: returns the impact on people in-flight without changing anything. True applies the staged draft to the live workflow.",
"type": "boolean"
},
- "draft_updated_at": {
- "description": "The draft_updated_at you loaded — required when confirm=true. A mismatch returns 409, so you never publish a draft someone else has changed since you read it.",
- "format": "date-time",
- "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",
+ "confirm_token": {
+ "description": "From the preview response — required when confirm=true. Expires after 15 minutes, and any draft edit invalidates it (409), so you always publish the exact draft you previewed.",
"type": "string"
},
"id": {