Skip to content

Self-improving AI Employees for everyone

fix(deployment): a running generation keeps the slug it started with

trohitg3c4cf815a0f0
diff --git a/CLAUDE.md b/CLAUDE.md
index 568d395a..3c4f7592 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1092,7 +1092,7 @@ Single source of truth: [`server/services/workflow_naming.py`](./server/services
`node_label` is `node.data.label` (the F2-renamed canvas label) when set, falling back to `node.type` (`chatTrigger` / `telegramReceive` / `aiAgent` / etc.). Computed once at deploy time via `node_label_slug(node)` and passed into Temporal workflows as `trigger_label` in `listener_data`; agent child ids use the node id, not the label. Stable `TriggerNodeId` / `EventWorkflowId` Search Attributes still use the immutable node_id / UUID so admin queries don't break across rename.
-**Rename path** — there is NO dedicated rename endpoint. The frontend's auto-save chain (`TopToolbar` inline edit → `updateWorkflow({name})` → debounced save → REST `POST /api/database/workflows` → `services.workflow_storage.handlers.handle_save_workflow`) IS the rename path. When `name` changes between saves, the handler (1) allocates a fresh slug via `next_available_slug`, (2) `database.rename_workflow` updates name + slug atomically (id UUID stays put), (3) renames the on-disk workspace dir via `Path.rename()`, (4) broadcasts a CloudEvents `workflow.renamed` envelope (`broadcaster.broadcast_workflow_lifecycle("renamed", workflow_id=..., name=..., slug=..., old_slug=...)`) so other tabs invalidate their workflows query.
+**Rename path** — the editor has NO dedicated rename endpoint: its auto-save chain (`TopToolbar` inline edit → `updateWorkflow({name})` → debounced save → REST `POST /api/database/workflows` → `services.workflow_storage.handlers.handle_save_workflow`) IS its rename path. Home's `rename_employee` renames through `rename_saved_workflow` in the same module, without touching the graph. When `name` changes, either path (1) allocates a fresh slug via `next_available_slug`, (2) `database.rename_workflow` updates name + slug atomically (id UUID stays put), (3) renames the on-disk workspace dir via `Path.rename()`, (4) broadcasts a CloudEvents `workflow.renamed` envelope (`broadcaster.broadcast_workflow_lifecycle("renamed", workflow_id=..., name=..., slug=..., old_slug=...)`) so other tabs invalidate their workflows query. A rename leaves a running generation's Temporal ids alone: its listeners and cron Schedules keep the slug its Start recorded in the control row's `graph_snapshot` (`workflow_slug`, read by `DeploymentManager._generation_slug`), so the re-arm after a restart registers the same ids instead of a second set beside them, which made every event start two runs. The next Start names them by the new slug.
**Invariants** (locked by `tests/services/test_workflow_naming.py` + `test_workflow_rename.py` — 39 tests):
- First creation always gets `_1` suffix (no bare-base slugs).
diff --git a/docs-internal/temporal-workflow-control.md b/docs-internal/temporal-workflow-control.md
index 435debc4..dd3b2ca5 100644
--- a/docs-internal/temporal-workflow-control.md
+++ b/docs-internal/temporal-workflow-control.md
@@ -199,7 +199,9 @@ the control plane is hardened against Temporal's per-run event-history ceiling
(admission, trigger pause flags, cron schedule pause). Re-arm is idempotent:
controller `register_trigger` is keyed by listener id, legacy listener
starts use `USE_EXISTING`, and cron schedule creation preserves server-owned
- pause state.
+ pause state. Listener and Schedule ids use the slug the generation's Start
+ recorded in its snapshot (`workflow_slug`), not the saved one, so a rename
+ while it runs cannot give the re-arm a second set of ids.
- **No lifetime caps.** Spawned graph runs, agent children, and delegated-task
runners no longer carry 1-2h execution/run timeouts (Temporal's timers keep
ticking through a pause, so the caps silently terminated paused work).
diff --git a/docs-internal/workflow-schema.md b/docs-internal/workflow-schema.md
index c64eaad5..af7a77ba 100644
--- a/docs-internal/workflow-schema.md
+++ b/docs-internal/workflow-schema.md
@@ -39,7 +39,7 @@ A workflow JSON document contains:
},
"slug": {
"type": "string",
- "description": "Human-readable identifier (e.g. AI_Assistant_1). Derived from name via services.workflow_naming.next_available_slug. Mutable on rename — recomputed + propagated to workspace dir + Temporal Web UI prefix + cron Schedule IDs. UNIQUE across active workflows.",
+ "description": "Human-readable identifier (e.g. AI_Assistant_1). Derived from name via services.workflow_naming.next_available_slug. Mutable on rename — recomputed + propagated to the workspace dir; Temporal ids and cron Schedule IDs follow at the next Start (a running generation keeps the slug it started with). UNIQUE across active workflows.",
"pattern": "^[A-Za-z0-9]+(_[0-9]+)?$"
},
"nodes": {
diff --git a/server/services/deployment/control.py b/server/services/deployment/control.py
index bffc4eac..d763a8d9 100644
--- a/server/services/deployment/control.py
+++ b/server/services/deployment/control.py
@@ -130,6 +130,8 @@ class WorkflowControlService:
raise ValueError("workflow_already_started")
generation = (latest.generation + 1) if latest else 1
execution_id = await self.database.allocate_execution_id(workflow_id)
+ saved = await self.database.get_workflow(workflow_id)
+ slug = getattr(saved, "slug", None)
control = WorkflowControlExecution(
id=f"workflow-control:{workflow_id}:{generation}", workflow_id=workflow_id,
generation=generation, execution_id=execution_id, root_execution_id=execution_id,
@@ -141,6 +143,9 @@ class WorkflowControlService:
"owner_id": safe_graph["owner_id"],
"nodes": nodes,
"edges": edges,
+ # What this generation's Temporal ids (listeners, Schedules)
+ # are named by, fixed at Start: see DeploymentManager.deploy.
+ "workflow_slug": slug if isinstance(slug, str) and slug else None,
},
idempotency_key=idempotency_key,
# Revisions are monotonic across generations so a delayed request
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 3ade1a95..e33da6ad 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -196,11 +196,12 @@ class DeploymentManager:
"deployment_id": self._deployments[workflow_id].deployment_id,
}
- # Human-readable slug for Temporal Web UI prefixing. Falls back
- # to workflow_id when the DB row is missing OR slug is empty
+ # Human-readable slug for Temporal Web UI prefixing. A generation
+ # keeps the slug it started with; otherwise the saved one, falling
+ # back to workflow_id when the DB row is missing OR slug is empty
# (one-off deploys / tests without a saved record).
wf = await self.database.get_workflow(workflow_id)
- workflow_slug = (wf and wf.slug) or workflow_id
+ workflow_slug = await self._generation_slug(workflow_id, generation) or (wf and wf.slug) or workflow_id
# Setup
deployment_id = f"deploy_{workflow_id}_{int(time.time() * 1000)}"
@@ -668,6 +669,23 @@ class DeploymentManager:
"""
return f"{workflow_slug}-{trigger_label}"
+ async def _generation_slug(self, workflow_id: str, generation: int) -> Optional[str]:
+ """The slug a generation's listeners and Schedules were named by at Start.
+
+ A rename moves the saved slug while those keep their ids. Re-armed
+ after a restart under the new slug, the generation would register a
+ second listener (and Schedule) beside the first, and every event
+ would start two runs. ``None`` for a generation that recorded none.
+ """
+ if generation <= 0:
+ return None
+ lookup = self.database.get_latest_workflow_control(workflow_id)
+ control = await lookup if inspect.isawaitable(lookup) else None
+ if control is None or control.generation != generation:
+ return None
+ slug = (control.graph_snapshot or {}).get("workflow_slug")
+ return slug if isinstance(slug, str) and slug else None
+
@staticmethod
def _trigger_kind_for(node_type: str) -> str:
"""Coarse-grained classification for the ``EventTriggerKind``
diff --git a/server/tests/services/test_workflow_control.py b/server/tests/services/test_workflow_control.py
index 86e01986..461ecc94 100644
--- a/server/tests/services/test_workflow_control.py
+++ b/server/tests/services/test_workflow_control.py
@@ -58,6 +58,28 @@ async def test_begin_generation_is_idempotent():
assert serialize_control(control)["can_pause"] is False
+async def test_generation_records_the_slug_its_temporal_ids_are_named_by():
+ db = AsyncMock()
+ db.get_workflow_control_by_idempotency_key.return_value = None
+ db.get_latest_workflow_control.return_value = None
+ db.get_workflow.return_value = SimpleNamespace(slug="Ana_1")
+ db.create_workflow_control.side_effect = lambda control: control
+ service = WorkflowControlService(db)
+
+ control, _ = await service.begin_generation(
+ workflow_id="wf", nodes=[], edges=[], session_id="s", idempotency_key="start-1"
+ )
+ assert control.graph_snapshot["workflow_slug"] == "Ana_1"
+
+ # A workflow that was never saved names its ids by its id instead.
+ db.get_workflow.return_value = None
+ control, _ = await service.begin_generation(
+ workflow_id="wf", nodes=[], edges=[], session_id="s", idempotency_key="start-2"
+ )
+ assert control.graph_snapshot["workflow_slug"] is None
+
+
@pytest.mark.asyncio
async def test_generation_atomically_creates_and_archives_isolated_data_scope(control_database):
service = WorkflowControlService(control_database)
diff --git a/server/tests/test_deployment_canary_listener.py b/server/tests/test_deployment_canary_listener.py
index d4c8a13e..c6ec6a44 100644
--- a/server/tests/test_deployment_canary_listener.py
+++ b/server/tests/test_deployment_canary_listener.py
@@ -135,6 +135,68 @@ class TestDeterministicListenerId:
assert a != b
+class TestGenerationSlug:
+ """A generation keeps the slug its Start recorded. Re-armed after a
+ rename under the new slug, it registered a second listener beside the
+ first with its controller, and every event started two runs."""
+
+ @staticmethod
+ def _manager(saved_slug: str, control):
+ from types import SimpleNamespace
+
+ from services.deployment.manager import DeploymentManager
+
+ database = MagicMock()
+ database.get_workflow = AsyncMock(return_value=SimpleNamespace(slug=saved_slug))
+ database.get_latest_workflow_control = AsyncMock(return_value=control)
+ broadcaster = MagicMock()
+ broadcaster.update_node_status = AsyncMock()
+ mgr = DeploymentManager(
+ database=database,
+ execute_workflow_fn=AsyncMock(),
+ store_output_fn=AsyncMock(),
+ broadcaster=broadcaster,
+ )
+ mgr._load_settings = AsyncMock()
+ mgr._notify = AsyncMock()
+ return mgr
+
+ @staticmethod
+ def _control(generation: int, slug=None):
+ from types import SimpleNamespace
+
+ snapshot: Dict[str, Any] = {"nodes": [], "edges": []}
+ if slug is not None:
+ snapshot["workflow_slug"] = slug
+ return SimpleNamespace(generation=generation, graph_snapshot=snapshot)
+
+ @pytest.mark.asyncio
+ async def test_rearm_after_a_rename_keeps_the_generation_slug(self):
+ mgr = self._manager("Ana_Ortiz_1", self._control(2, "Ana_1"))
+
+ result = await mgr.deploy(nodes=[], edges=[], workflow_id="wf", graph_version=2, generation=2)
+
+ assert result["success"] is True
+ assert mgr._deployments["wf"].workflow_slug == "Ana_1"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "generation, control",
+ [
+ (0, None), # not a durable generation
+ (2, None), # no control row
+ (2, (3, "Ana_1")), # the latest row is another generation
+ (2, (2, None)), # a snapshot from before the slug was recorded
+ ],
+ )
+ async def test_otherwise_the_saved_slug(self, generation, control):
+ mgr = self._manager("Ana_Ortiz_1", self._control(*control) if control else None)
+
+ await mgr.deploy(nodes=[], edges=[], workflow_id="wf", graph_version=2, generation=generation)
+
+ assert mgr._deployments["wf"].workflow_slug == "Ana_Ortiz_1"
+
+
# ---------------------------------------------------------------------------
# C1d.2 — canary scope: flag + type
# ---------------------------------------------------------------------------