From 2fb51857ce20eaffdf443c799d6bca8fe707dd76 Mon Sep 17 00:00:00 2001 From: Charles Yao Date: Mon, 21 Sep 2026 21:06:50 -0700 Subject: [PATCH] fix(workflow): name the node in every node-config error A graph-init failure surfaced as "2 validation errors for HttpRequestNodeData ..." -- pydantic names the model class, never the node. graphon logs the node id and re-raises the raw error, so the error frame the Builder received (ESQ1-302) could not say which node was wrong, and its repair agent had to guess. DifyNodeFactory.create_node now re-raises every ValueError from the validation stage (shared-shape validation, class resolution, concrete NodeData re-validation) prefixed "node '' (): ". This runs for EVERY workflow start, so the error text of every graph-init failure changes, not only the Builder's. The wrapped error is a plain ValueError, so app_generator's handling takes its ValueError branch (log only under DEBUG) instead of the ValidationError branch; the published error is the same. validate_node_config runs the same three validation steps with no factory instance and no runtime state -- the dry Graph.init a draft can be put through before it is written or run. Co-Authored-By: Claude Opus 5 (1M context) --- api/core/workflow/node_factory.py | 65 +++++++++-- .../core/workflow/test_node_factory.py | 110 ++++++++++++++++++ 2 files changed, 163 insertions(+), 12 deletions(-) diff --git a/api/core/workflow/node_factory.py b/api/core/workflow/node_factory.py index 1d868c58f9c..5d5ef20c5f5 100644 --- a/api/core/workflow/node_factory.py +++ b/api/core/workflow/node_factory.py @@ -414,18 +414,26 @@ class DifyNodeFactory(NodeFactory): if node type is unknown, or if no implementation exists for the resolved version """ adapted_node_config = adapt_node_config_for_graph(node_config) - typed_node_config = NodeConfigDictAdapter.validate_python(adapted_node_config) - node_id = typed_node_config["id"] - node_data = typed_node_config["data"] - node_class = self._resolve_node_class( - node_type=node_data.type, - node_version=str(node_data.version), - node_data=node_data, - ) - # Graph configs are initially validated against permissive shared node data. - # Re-validate using the resolved node class so workflow-local node schemas - # stay explicit and constructors receive the concrete typed payload. - resolved_node_data = self._validate_resolved_node_data(node_class, node_data) + try: + typed_node_config = NodeConfigDictAdapter.validate_python(adapted_node_config) + node_id = typed_node_config["id"] + node_data = typed_node_config["data"] + node_class = self._resolve_node_class( + node_type=node_data.type, + node_version=str(node_data.version), + node_data=node_data, + ) + # Graph configs are initially validated against permissive shared node data. + # Re-validate using the resolved node class so workflow-local node schemas + # stay explicit and constructors receive the concrete typed payload. + resolved_node_data = self._validate_resolved_node_data(node_class, node_data) + except ValueError as exc: + # pydantic's ValidationError subclasses ValueError. Its message names + # only the model class ("... for HttpRequestNodeData"), so a run that + # dies at Graph.init could not say WHICH node was wrong (ESQ1-302). + # Every workflow start goes through here, so this changes the error + # text of every graph-init failure, not only the Builder's. + raise _node_config_error(adapted_node_config, exc) from exc node_type = node_data.type if node_type == BuiltinNodeTypes.LLM: resolved_node_data = self._resolve_llm_model_reference(cast(LLMNodeData, resolved_node_data)) @@ -739,3 +747,36 @@ class DifyNodeFactory(NodeFactory): node_data_memory=node_data.memory, model_instance=model_instance, ) + + +def _node_config_error(node_config: Mapping[str, Any], exc: Exception) -> ValueError: + """``exc`` re-raised as a ``ValueError`` whose message starts with the + offending node's id and type, e.g. ``node 'node4' (http-request): ...``.""" + data = node_config.get("data") + node_type = str(data.get("type") or "") if isinstance(data, Mapping) else "" + node_id = str(node_config.get("id") or "") + return ValueError(f"node {node_id!r} ({node_type or 'unknown type'}): {exc}") + + +def validate_node_config(node_config: Mapping[str, Any] | NodeConfigDict) -> BaseNodeData: + """Validate ONE raw node config exactly as ``DifyNodeFactory.create_node`` + does before constructing the node -- adapt, shared-shape validation, + node-class resolution, concrete NodeData re-validation -- with no factory + instance and no runtime state. + + This is the dry check a draft can be put through BEFORE it is run: whatever + raises here would raise at ``Graph.init`` and kill the run before its first + node. Raises ``ValueError`` prefixed ``node ():``. + """ + adapted_node_config = adapt_node_config_for_graph(node_config) + try: + typed_node_config = NodeConfigDictAdapter.validate_python(adapted_node_config) + node_data = typed_node_config["data"] + node_class = DifyNodeFactory._resolve_node_class( + node_type=node_data.type, + node_version=str(node_data.version), + node_data=node_data, + ) + return DifyNodeFactory._validate_resolved_node_data(node_class, node_data) + except ValueError as exc: + raise _node_config_error(adapted_node_config, exc) from exc diff --git a/api/tests/unit_tests/core/workflow/test_node_factory.py b/api/tests/unit_tests/core/workflow/test_node_factory.py index c92c6a0e588..c18af7503d7 100644 --- a/api/tests/unit_tests/core/workflow/test_node_factory.py +++ b/api/tests/unit_tests/core/workflow/test_node_factory.py @@ -1,3 +1,4 @@ +import copy from collections.abc import Mapping from types import SimpleNamespace from unittest.mock import MagicMock, Mock, patch, sentinel @@ -1323,3 +1324,112 @@ class TestDifyNodeFactoryMemory: node_data_memory=memory_config, model_instance=sentinel.model_instance, ) + + +class TestNodeConfigErrorsNameTheNode: + """ESQ1-302: a graph-init failure surfaced as "2 validation errors for + HttpRequestNodeData ..." -- the model class, never the node. The Builder (and + anyone reading the run's error) had to guess which node it was. Every + node-config error now starts with ``node ():``. This wrapping is + in ``DifyNodeFactory.create_node``, so it changes the error text of EVERY + workflow run that fails at graph init, not only the Builder's.""" + + # The http-request node exactly as the ESQ1-302 draft stored it (dev app + # a26c8d2b, node4): a json body whose items lack ``type``. + ESQ1_302_HTTP_NODE = { + "id": "node4", + "type": "custom", + "data": { + "type": "http-request", + "title": "Call PPT API", + "desc": "Call external PPT generation API with the validated slide content.", + "method": "post", + "url": "https://api.example.com/ppt/generate", + "authorization": {"config": None, "type": "no-auth"}, + "headers": "", + "params": "", + "ssl_verify": True, + "timeout": {"max_connect_timeout": 0, "max_write_timeout": 0, "max_read_timeout": 0}, + "retry_config": {"max_retries": 3, "retry_interval": 100, "retry_enabled": True}, + "variables": [ + {"variable": "slide_content", "value_selector": ["node3", "text"]}, + {"variable": "output_filename", "value_selector": ["node1", "output_filename"]}, + ], + "body": { + "type": "json", + "data": [ + {"value": "{{#node3.text#}}", "key": "slides"}, + {"value": "{{#node1.output_filename#}}", "key": "filename"}, + ], + }, + }, + } + + # The if-else node exactly as the ESQ1-303 draft stored it (dev app + # 0f11bedc, node2): ``value`` is the JSON number 60. + ESQ1_303_IF_ELSE_NODE = { + "id": "node2", + "type": "custom", + "data": { + "type": "if-else", + "title": "判断分数", + "_targetBranches": [{"id": "true", "name": "IF"}, {"id": "false", "name": "ELSE"}], + "logical_operator": "and", + "cases": [ + { + "case_id": "true", + "logical_operator": "and", + "conditions": [ + { + "id": "c1", + "variable_selector": ["node1", "score"], + "comparison_operator": "=", + "value": 60, + } + ], + } + ], + }, + } + + @pytest.fixture + def factory(self): + factory = object.__new__(node_factory.DifyNodeFactory) + factory.graph_init_params = sentinel.graph_init_params + factory.graph_runtime_state = SimpleNamespace(variable_pool=MagicMock()) + return factory + + def test_create_node_names_the_node_that_failed_validation(self, factory): + with pytest.raises(ValueError, match=r"^node 'node4' \(http-request\): ") as excinfo: + factory.create_node(self.ESQ1_302_HTTP_NODE) + + assert "body.data.0.type" in str(excinfo.value) + assert "body.data.1.type" in str(excinfo.value) + + def test_create_node_still_names_the_node_for_an_unknown_type(self, factory): + with pytest.raises( + ValueError, match=r"^node 'node-id' \(missing\): No class mapping found for node type: missing" + ): + factory.create_node({"id": "node-id", "data": {"type": "missing"}}) + + def test_validate_node_config_rejects_the_esq1_303_numeric_value_with_the_node_id(self): + with pytest.raises(ValueError, match=r"^node 'node2' \(if-else\): ") as excinfo: + node_factory.validate_node_config(self.ESQ1_303_IF_ELSE_NODE) + + assert "Input should be a valid string" in str(excinfo.value) + + def test_validate_node_config_accepts_the_same_node_once_the_value_is_a_string(self): + healed = copy.deepcopy(self.ESQ1_303_IF_ELSE_NODE) + healed["data"]["cases"][0]["conditions"][0]["value"] = "60" + + data = node_factory.validate_node_config(healed) + + assert data.type == BuiltinNodeTypes.IF_ELSE + + def test_validate_node_config_needs_no_factory_instance(self): + # No graph_init_params / runtime state anywhere: a pure, dry check. + data = node_factory.validate_node_config( + {"id": "s", "data": {"type": BuiltinNodeTypes.START, "title": "Start"}} + ) + + assert data.type == BuiltinNodeTypes.START