Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(workflow): never mint a node id that another node keeps
trohitg0e3742a54cdf
diff --git a/server/services/workflow_naming.py b/server/services/workflow_naming.pyindex 5fe47273..0487f733 100644--- a/server/services/workflow_naming.py+++ b/server/services/workflow_naming.py@@ -140,27 +140,60 @@ def canonicalize_node_ids(Plugin ``type`` is the fixed identity while the per-type ordinal permitsrepeatable plugins such as ``aiAgent``. List order is the stable migrationorder used for legacy graphs. The function is pure and idempotent.++ Ids are unique in the result. The first node holding a canonical id keeps+ it, and its ordinal is reserved before any other node gets one, so a node+ that needs a new id never receives an id a canonical node later in the+ list keeps. Every other node takes the next free ordinal of its type in+ list order."""prefix = f"{workflow_id}:"++ def plugin_type_of(node: dict) -> str:+ plugin_type = str(node.get("type") or (node.get("data") or {}).get("type") or "node")+ return re.sub(r"[^A-Za-z0-9_-]+", "-", plugin_type).strip("-") or "node"++ def canonical_ordinal(node_id: str, plugin_type: str) -> int | None:+ match = re.fullmatch(re.escape(prefix + plugin_type) + r":([1-9]\d*)", node_id)+ return int(match.group(1)) if match else None++ keeps: set[int] = set()+ kept_ids: set[str] = set()+ reserved: dict[str, set[int]] = {}+ for index, node in enumerate(nodes):+ plugin_type = plugin_type_of(node)+ old_id = str(node.get("id") or "")+ ordinal = canonical_ordinal(old_id, plugin_type)+ if ordinal is None or old_id in kept_ids:+ continue+ keeps.add(index)+ kept_ids.add(old_id)+ reserved.setdefault(plugin_type, set()).add(ordinal)+counts: dict[str, int] = {}mapping: dict[str, str] = {}normalized_nodes: list[dict] = []- for node in nodes:+ for index, node in enumerate(nodes):item = dict(node)- plugin_type = str(item.get("type") or (item.get("data") or {}).get("type") or "node")- plugin_type = re.sub(r"[^A-Za-z0-9_-]+", "-", plugin_type).strip("-") or "node"+ plugin_type = plugin_type_of(item)counts[plugin_type] = counts.get(plugin_type, 0) + 1old_id = str(item.get("id") or "")- expected = f"{prefix}{plugin_type}:{counts[plugin_type]}"- # Already canonical graphs retain their ordinals even if nodes were- # reordered by a later layout/save operation.- match = re.fullmatch(re.escape(prefix + plugin_type) + r":([1-9]\d*)", old_id)- if match:- counts[plugin_type] = max(counts[plugin_type], int(match.group(1)))- expected = old_id- if old_id and old_id != expected:- mapping[old_id] = expected- item["id"] = expected+ if index in keeps:+ # Already canonical graphs retain their ordinals even if nodes were+ # reordered by a later layout/save operation.+ counts[plugin_type] = max(counts[plugin_type], canonical_ordinal(old_id, plugin_type) or 0)+ new_id = old_id+ else:+ taken = reserved.get(plugin_type, set())+ while counts[plugin_type] in taken:+ counts[plugin_type] += 1+ new_id = f"{prefix}{plugin_type}:{counts[plugin_type]}"+ # Edges and parameter rows name a node by its id. An id that a+ # kept node holds, or that an earlier node already claimed, stays+ # with that node: a duplicate cannot be told apart from it.+ if old_id and old_id not in kept_ids and old_id not in mapping:+ mapping[old_id] = new_id+ item["id"] = new_idnormalized_nodes.append(item)normalized_edges: list[dict] = []diff --git a/server/tests/services/test_identity_allocation.py b/server/tests/services/test_identity_allocation.pyindex a675d25c..0c3f2362 100644--- a/server/tests/services/test_identity_allocation.py+++ b/server/tests/services/test_identity_allocation.py@@ -42,6 +42,57 @@ def test_node_ids_are_plugin_derived_repeatable_and_idempotent():assert aliases["old-b"] == "7:aiAgent:2"+def test_a_legacy_node_never_takes_an_id_a_later_canonical_node_keeps():+ """A legacy node listed before a canonical node of the same type used to+ be given ordinal 1 while the canonical node kept ``7:aiAgent:1``, so the+ saved graph held two nodes with one id."""+ nodes = [+ {"id": "legacy-x", "type": "aiAgent"},+ {"id": "7:aiAgent:1", "type": "aiAgent"},+ ]+ edges = [+ {"id": "e1", "source": "legacy-x", "target": "7:aiAgent:1"},+ ]+ migrated_nodes, migrated_edges, aliases = canonicalize_node_ids("7", nodes, edges)++ ids = [node["id"] for node in migrated_nodes]+ assert len(set(ids)) == len(ids)+ assert ids == ["7:aiAgent:2", "7:aiAgent:1"]+ assert aliases == {"legacy-x": "7:aiAgent:2"}+ assert (migrated_edges[0]["source"], migrated_edges[0]["target"]) == ("7:aiAgent:2", "7:aiAgent:1")+ assert canonicalize_node_ids("7", migrated_nodes, migrated_edges)[2] == {}+++def test_a_duplicated_canonical_id_is_split_and_edges_stay_with_the_first_node():+ """A graph saved while the bug was live holds one id twice. The second+ node gets a fresh id; edges naming the id stay with the first node,+ because nothing tells the two apart."""+ nodes = [+ {"id": "7:aiAgent:1", "type": "aiAgent"},+ {"id": "7:aiAgent:1", "type": "aiAgent"},+ {"id": "7:start:1", "type": "start"},+ ]+ edges = [{"id": "e1", "source": "7:start:1", "target": "7:aiAgent:1"}]+ migrated_nodes, migrated_edges, aliases = canonicalize_node_ids("7", nodes, edges)++ assert [node["id"] for node in migrated_nodes] == ["7:aiAgent:1", "7:aiAgent:2", "7:start:1"]+ assert aliases == {}+ assert migrated_edges[0]["target"] == "7:aiAgent:1"+++def test_a_mixed_graph_without_a_collision_keeps_its_ids():+ """Only a collision changes an assignment: a legacy node listed before+ ``7:aiAgent:3`` still gets ordinal 1, as before the fix."""+ nodes = [+ {"id": "legacy-x", "type": "aiAgent"},+ {"id": "7:aiAgent:3", "type": "aiAgent"},+ {"id": "legacy-y", "type": "aiAgent"},+ ]+ migrated_nodes, _edges, _aliases = canonicalize_node_ids("7", nodes, [])++ assert [node["id"] for node in migrated_nodes] == ["7:aiAgent:1", "7:aiAgent:3", "7:aiAgent:4"]++@pytest.mark.asyncioasync def test_allocators_are_atomic_and_execution_ids_are_workflow_scoped(tmp_path: Path):path = tmp_path / f"identity-{uuid.uuid4().hex}.db"