Files

425 lines
16 KiB
Python

import logging
import time
from collections.abc import Callable, Mapping, Sequence
from typing import Any
from pydantic import BaseModel, ConfigDict
from core.app.apps.draft_variable_saver import DraftVariableSaverFactory
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, build_dify_run_context
from core.credit_usage import CreditUsageAppType
from core.workflow.system_variables import (
build_bootstrap_variables,
default_system_variables,
get_node_creation_preload_selectors,
inject_default_system_variable_mappings,
preload_node_creation_variables,
)
from core.workflow.variable_pool_initializer import add_variables_to_pool
from graphon.entities.base_node_data import BaseNodeData
from graphon.entities.graph_config import NodeConfigDict, NodeConfigDictAdapter
from graphon.graph import Graph
from graphon.graph.scoping import resolve_container_id
from graphon.runtime import RuntimeState, VariablePool
from graphon.variable_loader import DUMMY_VARIABLE_LOADER, VariableLoader, load_into_variable_pool
from models import Account
from models.agent_runtime_contracts import WorkflowAgentRuntimeBindings
from services.workflow.contracts import WorkflowSnapshot
from services.workflow.execution.adapters.node_factory import (
DifyGraphInitContext,
DifyNodeFactory,
get_default_root_node_id,
resolve_workflow_node_class,
)
from services.workflow.execution.adapters.workflow_entry import WorkflowEntry
from services.workflow.execution.ports import WorkflowRuntime
from services.workflow.variable_contracts import environment_variable_values
from services.workflow_node_variables import load_additional_node_variables
logger = logging.getLogger(__name__)
class _WorkflowGraphNodeData(BaseNodeData):
"""Node data fields the runner needs before concrete node validation."""
start_node_id: str | None = None
iteration_id: str | None = None
loop_id: str | None = None
class _WorkflowGraphNodeConfig(BaseModel):
"""Top-level node wrapper used for runner graph filtering."""
id: str
data: _WorkflowGraphNodeData
model_config = ConfigDict(extra="allow", strict=True)
def to_graph_node_config(self) -> dict[str, Any]:
return {
**self.model_dump(mode="python", exclude={"data"}, exclude_unset=True),
"data": self.data.model_dump(mode="python", exclude_unset=True),
}
def to_typed_node_config(self) -> NodeConfigDict:
return NodeConfigDictAdapter.validate_python(
{**self.model_dump(mode="python", exclude={"data"}), "data": self.data}
)
class _WorkflowGraphEdgeConfig(BaseModel):
"""Top-level edge wrapper used for selecting a single-node subgraph."""
source: str | None = None
target: str | None = None
model_config = ConfigDict(extra="allow", strict=True)
class _WorkflowGraphConfig(BaseModel):
"""Validated graph config boundary for runner methods.
Workflow graph payloads are persisted JSON mappings with extra metadata used
by graphon, so validation is intentionally limited to the top-level graph
shape this runner needs before passing the mapping onward.
"""
nodes: list[_WorkflowGraphNodeConfig]
edges: list[_WorkflowGraphEdgeConfig]
model_config = ConfigDict(extra="allow", strict=True)
def to_graph_config(self) -> dict[str, Any]:
return self.model_dump(mode="python", exclude_unset=True)
class WorkflowGraphBuilder:
"""Build a complete workflow or an isolated iteration/loop graph."""
def __init__(
self,
*,
app_id: str,
variable_loader: VariableLoader = DUMMY_VARIABLE_LOADER,
draft_variable_saver: Callable[[str, Account], DraftVariableSaverFactory] | None = None,
agent_binding_resolver: WorkflowAgentRuntimeBindings | None = None,
workflow_runtime: WorkflowRuntime | None = None,
) -> None:
self._app_id = app_id
self._variable_loader = variable_loader
self._draft_variable_saver = draft_variable_saver
self._agent_binding_resolver = agent_binding_resolver
self._workflow_runtime = workflow_runtime
@staticmethod
def resolve_user_from(invoke_from: InvokeFrom) -> UserFrom:
if invoke_from.runs_as_account():
return UserFrom.ACCOUNT
return UserFrom.END_USER
def build(
self,
graph_config: Mapping[str, Any],
graph_runtime_state: RuntimeState,
user_from: UserFrom,
invoke_from: InvokeFrom,
call_depth: int,
workflow_id: str = "",
tenant_id: str = "",
user_id: str = "",
root_node_id: str | None = None,
app_type: CreditUsageAppType | None = None,
trace_session_id: str | None = None,
) -> Graph:
"""
Init graph
"""
graph_config = _WorkflowGraphConfig.model_validate(graph_config).to_graph_config()
# Create explicit graph init context for Graph.init.
run_context = build_dify_run_context(
tenant_id=tenant_id or "",
app_id=self._app_id,
user_id=user_id,
user_from=user_from,
invoke_from=invoke_from,
app_type=app_type,
trace_session_id=trace_session_id,
)
graph_init_context = DifyGraphInitContext(
workflow_id=workflow_id,
graph_config=graph_config,
run_context=run_context,
call_depth=call_depth,
)
# Use the provided graph_runtime_state for consistent state management
node_factory = DifyNodeFactory.from_graph_init_context(
graph_init_context=graph_init_context,
runtime_state=graph_runtime_state,
draft_variable_saver=self._draft_variable_saver,
agent_binding_resolver=self._agent_binding_resolver,
workflow_runtime=self._workflow_runtime,
)
if root_node_id is None:
root_node_id = get_default_root_node_id(graph_config)
# init graph
graph = Graph.init(graph_config=graph_config, node_factory=node_factory, root_node_id=root_node_id)
if not graph:
raise ValueError("graph not found in workflow")
return graph
def build_single_node(
self,
workflow: WorkflowSnapshot,
single_iteration_run: Any | None = None,
single_loop_run: Any | None = None,
*,
user_id: str,
app_type: CreditUsageAppType | None = None,
trace_session_id: str | None = None,
) -> tuple[Graph, VariablePool, RuntimeState]:
"""
Prepare graph, variable pool, and runtime state for single node execution
(either single iteration or single loop).
Args:
workflow: The workflow instance
single_iteration_run: SingleIterationRunEntity if running single iteration, None otherwise
single_loop_run: SingleLoopRunEntity if running single loop, None otherwise
Returns:
A tuple containing (graph, variable_pool, graph_runtime_state)
Raises:
ValueError: If neither single_iteration_run nor single_loop_run is specified
"""
# Create initial runtime state with variable pool containing environment variables
variable_pool = VariablePool()
add_variables_to_pool(
variable_pool,
build_bootstrap_variables(
system_variables=default_system_variables(),
environment_variables=environment_variable_values(workflow),
),
)
graph_runtime_state = RuntimeState(
workflow_id=workflow.id,
variable_pool=variable_pool,
start_at=time.time(),
)
# Determine which type of single node execution and get graph/variable_pool
if single_iteration_run:
graph, variable_pool = self._get_graph_and_variable_pool_for_single_node_run(
workflow=workflow,
node_id=single_iteration_run.node_id,
user_inputs=dict(single_iteration_run.inputs),
graph_runtime_state=graph_runtime_state,
node_type_label="iteration",
user_id=user_id,
app_type=app_type,
trace_session_id=trace_session_id,
)
elif single_loop_run:
graph, variable_pool = self._get_graph_and_variable_pool_for_single_node_run(
workflow=workflow,
node_id=single_loop_run.node_id,
user_inputs=dict(single_loop_run.inputs),
graph_runtime_state=graph_runtime_state,
node_type_label="loop",
user_id=user_id,
app_type=app_type,
trace_session_id=trace_session_id,
)
else:
raise ValueError("Neither single_iteration_run nor single_loop_run is specified")
# Return the graph, variable_pool, and the same graph_runtime_state used during graph creation
# This ensures all nodes in the graph reference the same RuntimeState instance
return graph, variable_pool, graph_runtime_state
def _get_graph_and_variable_pool_for_single_node_run(
self,
workflow: WorkflowSnapshot,
node_id: str,
user_inputs: dict[str, Any],
graph_runtime_state: RuntimeState,
node_type_label: str = "node", # 'iteration' or 'loop' for error messages
*,
user_id: str = "",
app_type: CreditUsageAppType | None = None,
trace_session_id: str | None = None,
) -> tuple[Graph, VariablePool]:
"""
Get graph and variable pool for single node execution (iteration or loop).
The workflow graph and user inputs are treated as caller-owned data; the
narrowed graph config used for execution is built locally.
Args:
workflow: The workflow instance
node_id: The node ID to execute
user_inputs: User inputs for the node
graph_runtime_state: The graph runtime state
node_type_label: Label for error messages ('iteration' or 'loop')
Returns:
A tuple containing (graph, variable_pool)
"""
# fetch workflow graph
source_graph_config = _WorkflowGraphConfig.model_validate(workflow.graph_dict)
node_user_inputs = dict(user_inputs)
graph_config = source_graph_config.to_graph_config()
# Resolve ownership against the complete graph, then retain every nested
# descendant of the selected container for isolated execution.
all_node_configs = graph_config["nodes"]
nodes_by_id = {node["id"]: node for node in all_node_configs}
container_ids = {node["id"]: resolve_container_id(node, nodes_by_id=nodes_by_id) for node in all_node_configs}
node_ids = {node_id}
while True:
child_node_ids = {node["id"] for node in all_node_configs if container_ids[node["id"]] in node_ids}
child_node_ids -= node_ids
if not child_node_ids:
break
node_ids.update(child_node_ids)
# Preserve ownership resolved with the complete ancestry before removing
# nodes outside the debug subtree. Nested legacy IDs can otherwise become ambiguous.
selected_node_configs = []
for node in all_node_configs:
if node["id"] not in node_ids:
continue
selected_node = dict(node)
selected_node["data"] = dict(node["data"])
selected_node["data"]["container_id"] = container_ids[node["id"]]
selected_node_configs.append(_WorkflowGraphNodeConfig.model_validate(selected_node))
# filter edges only in the specified node type
selected_edge_configs = [
edge
for edge in source_graph_config.edges
if (edge.source is None or edge.source in node_ids) and (edge.target is None or edge.target in node_ids)
]
node_configs = [node.to_graph_node_config() for node in selected_node_configs]
edge_configs = [edge.model_dump(mode="python", exclude_unset=True) for edge in selected_edge_configs]
graph_config = {
**graph_config,
"nodes": node_configs,
"edges": edge_configs,
}
typed_node_configs = selected_node_configs
# Create explicit graph init context for Graph.init.
run_context = build_dify_run_context(
tenant_id=workflow.tenant_id,
app_id=self._app_id,
user_id=user_id,
user_from=UserFrom.ACCOUNT,
invoke_from=InvokeFrom.DEBUGGER,
app_type=app_type,
trace_session_id=trace_session_id,
)
graph_init_context = DifyGraphInitContext(
workflow_id=workflow.id,
graph_config=graph_config,
run_context=run_context,
call_depth=0,
)
node_factory = DifyNodeFactory.from_graph_init_context(
graph_init_context=graph_init_context,
runtime_state=graph_runtime_state,
draft_variable_saver=self._draft_variable_saver,
agent_binding_resolver=self._agent_binding_resolver,
workflow_runtime=self._workflow_runtime,
)
target_node_config = None
for node in typed_node_configs:
if node.id == node_id:
target_node_config = node
break
if not target_node_config:
raise ValueError(f"{node_type_label} node id not found in workflow graph")
# Get node class
node_type = target_node_config.data.type
node_version = str(target_node_config.data.version)
node_cls = resolve_workflow_node_class(node_type=node_type, node_version=node_version)
# Use the variable pool from graph_runtime_state instead of creating a new one
variable_pool = graph_runtime_state.variable_pool
preload_node_creation_variables(
variable_loader=self._variable_loader,
variable_pool=variable_pool,
selectors=[
selector
for node_config in typed_node_configs
for selector in get_node_creation_preload_selectors(
node_type=node_config.data.type,
node_data=node_config.data,
)
],
)
try:
variable_mapping = node_cls.extract_variable_selector_to_variable_mapping(
graph_config=graph_config, config=target_node_config.to_typed_node_config()
)
except NotImplementedError:
variable_mapping = dict[str, Sequence[str]]()
variable_mapping = inject_default_system_variable_mappings(
node_id=target_node_config.id,
node_type=node_type,
node_data=target_node_config.data,
variable_mapping=variable_mapping,
)
load_into_variable_pool(
variable_loader=self._variable_loader,
variable_pool=variable_pool,
variable_mapping=variable_mapping,
user_inputs=node_user_inputs,
)
variable_mapping = load_additional_node_variables(
node_config=target_node_config.to_typed_node_config(),
graph_config=graph_config,
variable_mapping=variable_mapping,
variable_loader=self._variable_loader,
variable_pool=variable_pool,
user_inputs=node_user_inputs,
)
WorkflowEntry.mapping_user_inputs_to_variable_pool(
variable_mapping=variable_mapping,
user_inputs=node_user_inputs,
variable_pool=variable_pool,
tenant_id=workflow.tenant_id,
)
# init graph after constructor-time context has been loaded
graph = Graph.init(
graph_config=graph_config,
node_factory=node_factory,
root_node_id=node_id,
container_id=container_ids[node_id],
skip_validation=True,
)
if not graph:
raise ValueError("graph not found in workflow")
return graph, variable_pool