Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(agent): pin chatflow participant versions across config updates (#42105)

zyssyz123c3f603c4dcb5
diff --git a/api/core/workflow/nodes/agent_v2/agent_node.py b/api/core/workflow/nodes/agent_v2/agent_node.py
index 86c6f993221..702c235345e 100644
--- a/api/core/workflow/nodes/agent_v2/agent_node.py
+++ b/api/core/workflow/nodes/agent_v2/agent_node.py
@@ -187,6 +187,7 @@ class DifyAgentNode(Node[DifyAgentNodeData]):
node_id=self._node_id,
binding_id=existing_scope.workflow_agent_binding_id if existing_scope is not None else None,
snapshot_id=existing_scope.agent_config_snapshot_id if existing_scope is not None else None,
+ conversation_id=conversation_id,
)
except WorkflowAgentBindingError as error:
yield self._failure_event(
diff --git a/api/core/workflow/nodes/agent_v2/binding_resolver.py b/api/core/workflow/nodes/agent_v2/binding_resolver.py
index 3710af100b0..4ea47adc5f8 100644
--- a/api/core/workflow/nodes/agent_v2/binding_resolver.py
+++ b/api/core/workflow/nodes/agent_v2/binding_resolver.py
@@ -6,9 +6,14 @@ from sqlalchemy import select
from core.agent.publish_visibility import workflow_callable_active_snapshot_filter
from core.db.session_factory import session_factory
+from core.workflow.nodes.agent_v2.session_store import (
+ WorkflowAgentWorkspaceStore,
+ resolve_workflow_agent_workspace_owner_scope,
+)
from models.agent import (
Agent,
AgentConfigSnapshot,
+ AgentConfigVersionKind,
AgentScope,
AgentStatus,
WorkflowAgentBindingType,
@@ -43,8 +48,9 @@ class WorkflowAgentBindingResolver:
node_id: str,
binding_id: str | None = None,
snapshot_id: str | None = None,
+ conversation_id: str | None = None,
) -> WorkflowAgentBindingBundle:
- """Resolve the current binding, optionally at a generation pinned by an existing execution."""
+ """Resolve the generation pinned by an execution or a Chatflow conversation participant."""
if (binding_id is None) != (snapshot_id is None):
raise WorkflowAgentBindingError(
@@ -86,6 +92,29 @@ class WorkflowAgentBindingResolver:
f"Agent {binding.agent_id} is not available or has not been published.",
)
+ # A new node execution in the same conversation must keep its participant's
+ # config/Home generation even after the roster Agent publishes a new version.
+ if snapshot_id is None and conversation_id:
+ participant = WorkflowAgentWorkspaceStore.load_active_participant(
+ session=session,
+ scope=resolve_workflow_agent_workspace_owner_scope(
+ tenant_id=tenant_id,
+ app_id=app_id,
+ conversation_id=conversation_id,
+ workflow_run_id=None,
+ node_id=node_id,
+ workflow_agent_binding_id=binding.id,
+ ),
+ agent_id=agent.id,
+ )
+ if participant is not None:
+ if participant.agent_config_version_kind != AgentConfigVersionKind.SNAPSHOT:
+ raise WorkflowAgentBindingError(
+ "agent_binding_generation_invalid",
+ "Chatflow Agent participant must reference a config snapshot.",
+ )
+ snapshot_id = participant.agent_config_version_id
+
effective_snapshot_id = (
(
agent.active_config_snapshot_id
diff --git a/api/core/workflow/nodes/agent_v2/session_store.py b/api/core/workflow/nodes/agent_v2/session_store.py
index 7ea3450deb5..dd5f5117efe 100644
--- a/api/core/workflow/nodes/agent_v2/session_store.py
+++ b/api/core/workflow/nodes/agent_v2/session_store.py
@@ -104,6 +104,21 @@ class StoredWorkflowAgentSession:
class WorkflowAgentWorkspaceStore:
"""Load or create the participant named by a node execution caller row."""
+ @staticmethod
+ def load_active_participant(
+ *,
+ session: Session,
+ scope: WorkspaceOwnerScope,
+ agent_id: str,
+ ) -> AgentWorkspaceBinding | None:
+ """Look up the participant that pins a Chatflow node's generation."""
+
+ return AgentWorkspaceService.resolve_active_binding_for_scope(
+ session=session,
+ scope=scope,
+ agent_id=agent_id,
+ )
+
def load_existing_node_execution_scope(
self,
*,
@@ -315,7 +330,7 @@ class WorkflowAgentWorkspaceStore:
"""Reuse a conversation-scoped participant or allocate a new one."""
if scope.conversation_id is not None:
- existing_binding = AgentWorkspaceService.resolve_active_binding_for_scope(
+ existing_binding = WorkflowAgentWorkspaceStore.load_active_participant(
session=session,
scope=scope.workspace_owner,
agent_id=scope.agent_id,
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
index 4847e6af397..4a12122bcce 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
@@ -581,6 +581,7 @@ def test_agent_node_resume_resolves_the_generation_from_the_persisted_execution(
assert store.existing_scope_lookups[0]["node_execution_id"] == node.execution_id
assert binding_resolver.calls[0]["binding_id"] == "binding-1"
assert binding_resolver.calls[0]["snapshot_id"] == "snapshot-pinned"
+ assert binding_resolver.calls[0]["conversation_id"] == "conversation-1"
def test_agent_node_maps_persisted_participant_lookup_error_to_node_failure() -> None:
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_binding_resolver.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_binding_resolver.py
index 14e0f99c699..f4dd2b3b4c1 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_binding_resolver.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_binding_resolver.py
@@ -1,26 +1,252 @@
from collections.abc import Iterator
+from unittest.mock import MagicMock
from uuid import uuid4
import pytest
+from agenton.compositor import CompositorSessionSnapshot
from sqlalchemy import event, inspect
from sqlalchemy.orm import ORMExecuteState, Session, sessionmaker
from sqlalchemy.sql import Executable
from core.workflow.nodes.agent_v2.binding_resolver import WorkflowAgentBindingError, WorkflowAgentBindingResolver
+from core.workflow.nodes.agent_v2.session_store import WorkflowAgentSessionScope, WorkflowAgentWorkspaceStore
+from graphon.enums import WorkflowNodeExecutionStatus
from models.agent import (
Agent,
AgentConfigRevision,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
+ AgentConfigVersionKind,
+ AgentHomeSnapshot,
AgentScope,
AgentSource,
AgentStatus,
+ AgentWorkingResourceStatus,
+ AgentWorkspace,
+ AgentWorkspaceBinding,
+ AgentWorkspaceOwnerType,
WorkflowAgentBindingType,
WorkflowAgentNodeBinding,
)
from models.agent_config_entities import AgentSoulConfig, AgentSoulModelConfig, WorkflowNodeJobConfig
+from models.enums import CreatorUserRole
+from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
+from services.agent.workspace_service import AgentWorkspaceService
RESOLVER_MODELS = (WorkflowAgentNodeBinding, Agent, AgentConfigSnapshot, AgentConfigRevision)
+CHATFLOW_MODELS = (
+ *RESOLVER_MODELS,
+ AgentWorkspace,
+ AgentWorkspaceBinding,
+ AgentHomeSnapshot,
+ WorkflowNodeExecutionModel,
+)
+
+
+def _conversation_participant(
+ session: Session,
+ *,
+ ids: dict[str, str],
+ binding: WorkflowAgentNodeBinding,
+ snapshot: AgentConfigSnapshot,
+) -> AgentWorkspaceBinding:
+ workspace = AgentWorkspace(
+ tenant_id=ids["tenant_id"],
+ app_id=ids["app_id"],
+ owner_type=AgentWorkspaceOwnerType.CONVERSATION,
+ owner_id=ids["conversation_id"],
+ owner_scope_key=f"{ids['node_id']}:{binding.id}",
+ backend_workspace_ref="workspace-ref",
+ status=AgentWorkingResourceStatus.ACTIVE,
+ active_guard=1,
+ )
+ session.add(workspace)
+ session.flush()
+ participant = AgentWorkspaceBinding(
+ tenant_id=ids["tenant_id"],
+ app_id=ids["app_id"],
+ workspace_id=workspace.id,
+ agent_id=snapshot.agent_id,
+ agent_config_version_id=snapshot.id,
+ agent_config_version_kind=AgentConfigVersionKind.SNAPSHOT,
+ base_home_snapshot_id=snapshot.home_snapshot_id,
+ backend_binding_ref="participant-ref",
+ status=AgentWorkingResourceStatus.ACTIVE,
+ session_snapshot=CompositorSessionSnapshot(layers=[]).model_dump_json(),
+ )
+ session.add(participant)
+ session.flush()
+ return participant
+
+
[email protected]("sqlite_session", [CHATFLOW_MODELS], indirect=True)
[email protected]("binding_type", [WorkflowAgentBindingType.ROSTER_AGENT, WorkflowAgentBindingType.INLINE_AGENT])
+def test_chatflow_keeps_participant_config_and_home_after_agent_update(
+ sqlite_session: Session,
+ monkeypatch: pytest.MonkeyPatch,
+ binding_type: WorkflowAgentBindingType,
+) -> None:
+ ids = {**_resolve_ids(), "conversation_id": str(uuid4())}
+ is_roster = binding_type == WorkflowAgentBindingType.ROSTER_AGENT
+ agent = _agent(
+ tenant_id=ids["tenant_id"],
+ scope=AgentScope.ROSTER if is_roster else AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.ROSTER if is_roster else AgentSource.WORKFLOW,
+ )
+ sqlite_session.add(agent)
+ sqlite_session.flush()
+ original = _snapshot(tenant_id=ids["tenant_id"], agent_id=agent.id)
+ original.home_snapshot_id = str(uuid4())
+ sqlite_session.add(original)
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = original.id
+ binding = _binding(ids=ids, agent_id=agent.id, snapshot_id=original.id, binding_type=binding_type)
+ sqlite_session.add(binding)
+ sqlite_session.flush()
+ participant = _conversation_participant(sqlite_session, ids=ids, binding=binding, snapshot=original)
+ sqlite_session.commit()
+ resolver = WorkflowAgentBindingResolver()
+ assert resolver.resolve(**ids).snapshot.id == original.id
+
+ published = _snapshot(tenant_id=ids["tenant_id"], agent_id=agent.id)
+ published.version = 2
+ published.home_snapshot_id = str(uuid4())
+ sqlite_session.add(published)
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = published.id
+ if not is_roster:
+ binding.current_snapshot_id = published.id
+ sqlite_session.commit()
+
+ continuing = resolver.resolve(**ids)
+ assert continuing.snapshot.id == original.id
+ assert continuing.snapshot.home_snapshot_id == original.home_snapshot_id
+ assert resolver.resolve(**{**ids, "conversation_id": str(uuid4())}).snapshot.id == published.id
+ assert (
+ resolver.resolve(
+ tenant_id=ids["tenant_id"],
+ app_id=ids["app_id"],
+ workflow_id=ids["workflow_id"],
+ node_id=ids["node_id"],
+ ).snapshot.id
+ == published.id
+ )
+
+ execution = WorkflowNodeExecutionModel(
+ tenant_id=ids["tenant_id"],
+ app_id=ids["app_id"],
+ workflow_id=ids["workflow_id"],
+ triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
+ workflow_run_id=str(uuid4()),
+ index=1,
+ node_execution_id=str(uuid4()),
+ node_id=ids["node_id"],
+ node_type="agent",
+ title="Agent",
+ status=WorkflowNodeExecutionStatus.RUNNING,
+ created_by_role=CreatorUserRole.ACCOUNT,
+ created_by=str(uuid4()),
+ )
+ sqlite_session.add(execution)
+ sqlite_session.commit()
+ create_binding = MagicMock(side_effect=AssertionError("must reuse the existing participant"))
+ monkeypatch.setattr(AgentWorkspaceService, "create_binding", create_binding)
+ scope = WorkflowAgentSessionScope(
+ **ids,
+ workflow_run_id=execution.workflow_run_id,
+ node_execution_id=execution.id,
+ workflow_agent_binding_id=binding.id,
+ agent_id=agent.id,
+ agent_config_snapshot_id=continuing.snapshot.id,
+ )
+ stored = WorkflowAgentWorkspaceStore().load_or_create_node_execution_session(
+ scope,
+ home_snapshot_id=continuing.snapshot.home_snapshot_id,
+ )
+ assert stored.binding_id == participant.id
+ assert stored.backend_binding_ref == participant.backend_binding_ref
+ assert stored.session_snapshot == CompositorSessionSnapshot(layers=[])
+ create_binding.assert_not_called()
+
+ agent.status = AgentStatus.ARCHIVED
+ sqlite_session.commit()
+ with pytest.raises(WorkflowAgentBindingError, match="not available"):
+ resolver.resolve(**ids)
+
+
[email protected]("mismatch", ["tenant", "app", "conversation", "node", "agent", "retired"])
[email protected]("sqlite_session", [CHATFLOW_MODELS], indirect=True)
+def test_chatflow_pin_is_scoped_to_active_conversation_node_participant(
+ sqlite_session: Session,
+ mismatch: str,
+) -> None:
+ ids = {**_resolve_ids(), "conversation_id": str(uuid4())}
+ agent = _agent(tenant_id=ids["tenant_id"], scope=AgentScope.ROSTER, source=AgentSource.ROSTER)
+ sqlite_session.add(agent)
+ sqlite_session.flush()
+ current = _snapshot(tenant_id=ids["tenant_id"], agent_id=agent.id)
+ sqlite_session.add(current)
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = current.id
+ binding = _binding(
+ ids=ids, agent_id=agent.id, snapshot_id=current.id, binding_type=WorkflowAgentBindingType.ROSTER_AGENT
+ )
+ sqlite_session.add(binding)
+ sqlite_session.flush()
+ participant = _conversation_participant(sqlite_session, ids=ids, binding=binding, snapshot=current)
+ participant.agent_config_version_id = str(uuid4())
+ workspace = sqlite_session.get(AgentWorkspace, participant.workspace_id)
+ assert workspace is not None
+ match mismatch:
+ case "tenant":
+ workspace.tenant_id = str(uuid4())
+ case "app":
+ workspace.app_id = str(uuid4())
+ case "conversation":
+ workspace.owner_id = str(uuid4())
+ case "node":
+ workspace.owner_scope_key = "another-node:another-binding"
+ case "agent":
+ participant.agent_id = str(uuid4())
+ case "retired":
+ participant.status = AgentWorkingResourceStatus.RETIRED
+ sqlite_session.commit()
+
+ assert WorkflowAgentBindingResolver().resolve(**ids).snapshot.id == current.id
+
+
[email protected]("version_kind", [AgentConfigVersionKind.DRAFT, AgentConfigVersionKind.SNAPSHOT])
[email protected]("sqlite_session", [CHATFLOW_MODELS], indirect=True)
+def test_chatflow_never_falls_back_from_invalid_pinned_generation(
+ sqlite_session: Session,
+ version_kind: AgentConfigVersionKind,
+) -> None:
+ ids = {**_resolve_ids(), "conversation_id": str(uuid4())}
+ agent = _agent(tenant_id=ids["tenant_id"], scope=AgentScope.ROSTER, source=AgentSource.ROSTER)
+ sqlite_session.add(agent)
+ sqlite_session.flush()
+ current = _snapshot(tenant_id=ids["tenant_id"], agent_id=agent.id)
+ sqlite_session.add(current)
+ sqlite_session.flush()
+ agent.active_config_snapshot_id = current.id
+ binding = _binding(
+ ids=ids, agent_id=agent.id, snapshot_id=current.id, binding_type=WorkflowAgentBindingType.ROSTER_AGENT
+ )
+ sqlite_session.add(binding)
+ sqlite_session.flush()
+ participant = _conversation_participant(sqlite_session, ids=ids, binding=binding, snapshot=current)
+ participant.agent_config_version_kind = version_kind
+ participant.agent_config_version_id = str(uuid4())
+ sqlite_session.commit()
+
+ with pytest.raises(WorkflowAgentBindingError) as exc_info:
+ WorkflowAgentBindingResolver().resolve(**ids)
+ expected = (
+ "agent_binding_generation_invalid"
+ if version_kind == AgentConfigVersionKind.DRAFT
+ else "agent_config_snapshot_not_found"
+ )
+ assert exc_info.value.error_code == expected
def _resolve_ids() -> dict[str, str]: