diff --git a/api/core/dify_builder/node_defaults.py b/api/core/dify_builder/node_defaults.py index 4df63caa3f6..b92990234ae 100644 --- a/api/core/dify_builder/node_defaults.py +++ b/api/core/dify_builder/node_defaults.py @@ -5,23 +5,93 @@ There is no importable Python source for Dify's per-node-type default config -- the canonical values live in the frontend's ``web/app/components/workflow/nodes//default.ts`` (mirrored, for LLM prompt-authoring, by ``core.workflow.generator.prompts.builder_prompts -._NODE_SNIPPETS``). This module hand-maintains a literal Python copy of those -defaults; each entry cites its ``default.ts`` lines and the engine fields it -covers. Keep it pure: it is imported by ``services.dify_builder.graph_ops`` and -must not reach back into ``services``, ``configs``, Flask or the model runtime. +._NODE_SNIPPETS``). This module hand-maintains a literal Python copy of the +SAFE part of those defaults; each entry cites its ``default.ts`` lines and the +engine fields it covers. Keep it pure: it is imported by +``services.dify_builder.graph_ops`` and must not reach back into ``services``, +``configs``, Flask or the model runtime. -Why it matters beyond the placeholder agent: graphon requires a handful of -fields per node type with NO default (``TemplateTransformNodeData.variables``, -``CodeNodeData.outputs``, ``VariableAggregatorNodeData.output_type``, ...). An -Edit/Fix LLM that emits ``create_node{template-transform, {title, template}}`` -produces a node the draft preflight refuses -- and the refusal kills the WHOLE -batch, parking the session at ``edit.plan_approval`` (triage -``edit-branch-failure-2026-09-22`` cause (b)). ``graph_ops._build_node`` merges -these defaults UNDER the caller's config so a missing required field is filled -and a caller-supplied one always wins. +Why it matters: graphon requires a handful of fields per node type with NO +default (``TemplateTransformNodeData.variables``, ``CodeNodeData.outputs``, +``VariableAggregatorNodeData.output_type``, ...). An Edit/Fix LLM that emits +``create_node{template-transform, {title, template}}`` produces a node the draft +preflight refuses -- and the refusal kills the WHOLE batch, parking the session +at ``edit.plan_approval`` (triage ``edit-branch-failure-2026-09-22`` cause (b)). +``graph_ops._build_node`` merges these defaults UNDER the caller's config so a +missing structural field is filled and a caller-supplied one always wins. -Scope: defaults fill MISSING required fields. Fields that are present but WRONG -are the deterministic heal set's job +THE RULE FOR ADDING A FIELD HERE +-------------------------------- +A default may supply a field whose empty value is semantically NEUTRAL -- a +container, a mode, a config or auth block (``variables: []``, ``headers: ""``, +``authorization: {"type": "no-auth"}``, ``output_type``, ``code_language``). It +must NOT supply a field that carries the node's PURPOSE, where an empty value +produces a node that RUNS and yields nothing. Fabricating one of those turns a +loud preflight refusal into a node that is written, reported as a success, and +silently does the wrong thing -- the exact failure shape this module exists to +eliminate. + +Leaving it out costs a batch, and that cost is real: TODAY the omission is not +caught early. ``graph_ops.filter_applicable`` dry-runs the ``apply_*`` functions +only -- it performs no graphon validation -- so a node missing a required field +is "applicable", and the one corrective re-prompt in +``services/dify_builder/agent/edit.py`` never sees it. The omission surfaces at +``apply_repair``'s preflight instead, where all three handlers catch +``DraftWouldNotStartError``, write NOTHING and park the session +(``handlers_edit.py``, ``handlers_fix.py``, ``handlers_build.py``). That is F4 +cause (b) itself. Running ``preflight_errors`` inside ``filter_applicable`` so +the re-prompt can name the field is Task 5's job, specified there -- not this +module's. Until then, a refused batch is still the right trade against a written +node that silently answers wrong; it is just more expensive than it should be. + +An empty value that makes the node FAIL LOUDLY is not in the purpose category at +all -- there is no silence to protect against, and dropping it would pay the +full batch-refusal cost for nothing. Verified loud, so all of these stay: + +* ``llm.model`` with ``provider: ""`` -- never launches; the Builder surfaces + "model not configured". +* ``llm.prompt_template`` whose only message is empty -- every empty message is + filtered out, leaving zero, and graphon raises ``NoPromptFoundError`` + (``nodes/llm/node.py:1397-1402``). +* ``code.code`` as ``""`` -- the sandbox runner calls ``main(**inputs_obj)`` + with no ``main`` defined and raises + (``core/helper/code_executor/python3/python3_transformer.py:20``). +* ``code.outputs`` as ``{}`` -- any key the code actually returns is unvalidated, + so graphon raises ``CodeNodeError("Not all output parameters are + validated.")`` (``nodes/code/code_node.py:690-693``). +* ``http-request.url`` as ``""`` -- ``Executor._init_url`` raises + ``InvalidURLError("url is required")`` before any request goes out + (``nodes/http_request/executor.py:172-174``). + +Purpose fields deliberately NOT defaulted, and what each empty value would do: + +* ``end.outputs`` -- the End node runs OK, so ``run_finished_without_output`` + (``core/dify_builder/handlers_fix.py``) returns False and the Builder reports + "All checks passed" on an empty result. +* ``answer.answer`` -- streams nothing. +* ``template-transform.template`` -- renders "". +* ``variable-aggregator.variables`` -- aggregates nothing and returns + ``SUCCEEDED, outputs={}``; this is triage cause (d) verbatim. +* ``question-classifier.classes`` -- two blank categories, and the fabricated + ids would also pin ``declared_branch_handles`` to ``["1", "2"]`` so a + semantic ``connect`` is silently dropped while the create survives. +* ``question-classifier.query_variable_selector`` -- ``query or ""`` + (``nodes/question_classifier/question_classifier_node.py:260-280``), i.e. the + classifier runs on an empty string. +* ``knowledge-retrieval.dataset_ids`` -- retrieves from no dataset and succeeds + with an empty result list. + +Editor-only keys are also not copied. ``_targetBranches`` (if-else, +question-classifier) is frontend editor state that the canvas regenerates from +``cases`` / ``classes`` (``nodes/question-classifier/use-config.ts:139,173``, +``nodes/if-else/use-config.helpers.ts:53-75``); the backend reads branch handles +from ``cases``/``classes`` too (``declared_branch_handles``). A caller's +``cases``/``classes`` win the merge while a default ``_targetBranches`` would +not, so shipping it would attach a STALE branch list to every created branch +node. + +Scope: defaults fill MISSING structural fields. Fields that are present but +WRONG are the deterministic heal set's job (``core.workflow.graph_normalizers.heal_nodes_for_preflight``) -- do not duplicate its work here. @@ -36,38 +106,29 @@ from typing import Any from graphon.enums import BuiltinNodeTypes -# Editor-only keys deliberately NOT copied from ``default.ts``: -# -# ``_targetBranches`` (if-else, question-classifier) is frontend editor state -# that the canvas regenerates from ``cases`` / ``classes`` -# (``nodes/question-classifier/use-config.ts:139,173``, -# ``nodes/if-else/use-config.helpers.ts:53-75``); the backend reads branch -# handles from ``cases``/``classes`` too -# (``core.workflow.graph_normalizers.declared_branch_handles:579-585``). Since -# the caller's ``cases``/``classes`` win the merge while a default -# ``_targetBranches`` would not, shipping it would attach a STALE branch list to -# every Builder-created branch node. Omitting an optional editor key is strictly -# better than writing a wrong one. _DEFAULTS: dict[str, dict[str, Any]] = { # web/app/components/workflow/nodes/start/default.ts:17-19 # graphon nodes/start/entities.py:14 -- ``variables`` has a default_factory. + # A start form with no fields is a normal, intentional design, so the empty + # list carries no meaning of its own. BuiltinNodeTypes.START: { "variables": [], }, - # web/app/components/workflow/nodes/end/default.ts:15-17 - # graphon nodes/end/entities.py:11 -- ``outputs`` is required, no default. - BuiltinNodeTypes.END: { - "outputs": [], - }, - # web/app/components/workflow/nodes/answer/default.ts:14-17 - # graphon nodes/answer/entities.py:12 -- ``answer`` is ``Field(...)``. + # web/app/components/workflow/nodes/end/default.ts:15-17, minus ``outputs`` + # (purpose field -- see the module docstring). graphon + # nodes/end/entities.py:11 requires it, so an End the LLM forgot to wire up + # is refused by name instead of silently returning nothing. + BuiltinNodeTypes.END: {}, + # web/app/components/workflow/nodes/answer/default.ts:14-17, minus + # ``answer`` (purpose field). ``variables`` is a frontend-only container. BuiltinNodeTypes.ANSWER: { "variables": [], - "answer": "", }, # web/app/components/workflow/nodes/llm/default.ts:44-66 - # graphon nodes/llm/entities.py:18-22 -- ``ModelConfig`` requires - # ``provider``/``name``/``mode``. + # graphon nodes/llm/entities.py:69-75 -- ``model``, ``prompt_template`` and + # ``context`` are all required. An empty provider or an empty-only prompt + # both fail LOUDLY at run time (see the module docstring), so these are + # scaffolding, not fabricated meaning. BuiltinNodeTypes.LLM: { "model": { "provider": "", @@ -79,11 +140,14 @@ _DEFAULTS: dict[str, dict[str, Any]] = { "context": {"enabled": False, "variable_selector": []}, "vision": {"enabled": False}, }, - # web/app/components/workflow/nodes/knowledge-retrieval/default.ts:18-28 + # web/app/components/workflow/nodes/knowledge-retrieval/default.ts:18-28, + # minus ``dataset_ids`` (purpose field; + # core/workflow/nodes/knowledge_retrieval/entities.py:42 requires it). The + # two query selectors stay: they are optional in the entity and ``[]`` is + # indistinguishable from absent, so they fabricate nothing. BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL: { "query_variable_selector": [], "query_attachment_selector": [], - "dataset_ids": [], "retrieval_mode": "multiple", "multiple_retrieval_config": { "top_k": 4, @@ -91,61 +155,52 @@ _DEFAULTS: dict[str, dict[str, Any]] = { "reranking_enable": False, }, }, - # web/app/components/workflow/nodes/if-else/default.ts:21-39, minus the - # editor-only ``_targetBranches`` (see the note above). - # graphon nodes/if_else/entities.py:22-24 -- every field is optional, and - # ``iter_cases()`` synthesizes exactly this one empty "true" case when - # ``cases is None``, so the default is behaviour-neutral at run time. - BuiltinNodeTypes.IF_ELSE: { - "cases": [ - { - "case_id": "true", - "logical_operator": "and", - "conditions": [], - }, - ], - }, - # web/app/components/workflow/nodes/code/default.ts:18-23 - # graphon nodes/code/entities.py:57-60 -- ``variables``, ``code_language``, - # ``code`` and ``outputs`` are all required with no default. + # web/app/components/workflow/nodes/code/default.ts:18-23 (complete). + # graphon nodes/code/entities.py:57-60 requires ``variables``, + # ``code_language``, ``code`` and ``outputs``. Neither empty value is + # silent: ``code: ""`` leaves the sandbox runner with no ``main`` to call, + # and ``outputs: {}`` makes graphon raise ``CodeNodeError("Not all output + # parameters are validated.")`` for any key the code returns -- both are + # named run-time errors, so there is no silent success to protect against + # and no reason to pay a batch refusal. BuiltinNodeTypes.CODE: { "code": "", "code_language": "python3", "variables": [], "outputs": {}, }, - # web/app/components/workflow/nodes/template-transform/default.ts:18-21 - # graphon nodes/template_transform/entities.py:10-11 -- ``variables`` and - # ``template`` are both required with no default. This is the exact node the - # Edit LLM created without ``variables`` in the F4 failure. + # web/app/components/workflow/nodes/template-transform/default.ts:18-21, + # minus ``template`` (purpose field). ``variables`` is STRUCTURAL and stays + # -- graphon nodes/template_transform/entities.py:10 requires it and this is + # the exact field the Edit LLM omitted in the live F4 failure. BuiltinNodeTypes.TEMPLATE_TRANSFORM: { - "template": "", "variables": [], }, # web/app/components/workflow/nodes/question-classifier/default.ts:18-53, - # minus the editor-only ``_targetBranches`` (see the note above). - # graphon nodes/question_classifier/entities.py:33-35 -- - # ``query_variable_selector``, ``model`` and ``classes`` are required. + # minus ``classes``, ``query_variable_selector`` (purpose fields) and the + # editor-only ``_targetBranches``. graphon + # nodes/question_classifier/entities.py:34-36 requires all three of + # ``query_variable_selector``, ``model`` and ``classes``. BuiltinNodeTypes.QUESTION_CLASSIFIER: { - "query_variable_selector": [], "model": { "provider": "", "name": "", "mode": "chat", "completion_params": {"temperature": 0.7}, }, - "classes": [ - {"id": "1", "name": "", "label": "CLASS 1"}, - {"id": "2", "name": "", "label": "CLASS 2"}, - ], "vision": {"enabled": False}, }, - # web/app/components/workflow/nodes/http/default.ts:16-41 (there is no - # ``nodes/http-request/`` directory). + # web/app/components/workflow/nodes/http/default.ts:16-41 (complete; there + # is no ``nodes/http-request/`` directory). # graphon nodes/http_request/entities.py:117-130 -- ``method``, ``url``, - # ``authorization``, ``headers`` and ``params`` are required with no - # default. The frontend's ``timeout`` uses the ``max_*`` keys the editor - # reads; graphon's ``HttpRequestNodeTimeout`` ignores them and + # ``authorization``, ``headers`` and ``params`` are all required. + # ``method``/``authorization``/``headers``/``params`` are mode/config/auth + # with neutral empty values, and ``url: ""`` is not silent either: + # ``Executor._init_url`` raises ``InvalidURLError("url is required")`` + # before any request goes out (``nodes/http_request/executor.py:172-174``). + # The frontend's + # ``timeout`` uses the ``max_*`` keys the editor reads; graphon's + # ``HttpRequestNodeTimeout`` ignores them and # ``HttpRequestNode._get_request_timeout:247-255`` falls back to the # configured defaults, which is what the block config itself ships # (``nodes/http_request/node.py:166-170`` carries both shapes). @@ -176,24 +231,36 @@ _DEFAULTS: dict[str, dict[str, Any]] = { }, }, # web/app/components/workflow/nodes/variable-assigner/default.ts:23-26 (the - # variable-AGGREGATOR node's frontend directory is ``variable-assigner``). - # graphon nodes/variable_aggregator/entities.py:27-28 -- BOTH - # ``output_type`` and ``variables`` are required with no default. + # variable-AGGREGATOR node's frontend directory is ``variable-assigner``), + # minus ``variables`` (purpose field). graphon + # nodes/variable_aggregator/entities.py:27-28 requires both, and an + # aggregator with nothing to aggregate is triage cause (d) itself. BuiltinNodeTypes.VARIABLE_AGGREGATOR: { "output_type": "any", - "variables": [], }, # web/app/components/workflow/nodes/tool/default.ts:22-26 # graphon nodes/tool/entities.py:48-53,133 -- ``tool_configurations`` and - # ``tool_parameters`` are required. The provider/tool identity fields - # (``provider_id``, ``provider_type``, ``provider_name``, ``tool_name``, - # ``tool_label``) are also required but are not knowable as a default; only - # the caller can supply them. + # ``tool_parameters`` are required containers. The provider/tool identity + # fields (``provider_id``, ``provider_type``, ``provider_name``, + # ``tool_name``, ``tool_label``) are the purpose fields here and are not + # knowable as a default; only the caller can supply them. BuiltinNodeTypes.TOOL: { "tool_parameters": {}, "tool_configurations": {}, "tool_node_version": "2", }, + # NOTE: ``if-else`` has no entry, and omitting it changes NOTHING either way + # -- nothing gained, nothing lost. Its frontend default is one case with an + # empty ``conditions`` list, which graphon's ``ConditionProcessor`` combines + # with ``all([])``, so that case always matches and the node routes + # everything down the IF arm. Dropping the entry does NOT cure that: + # ``IfElseNodeData.cases`` is optional and ``iter_cases()`` synthesizes the + # identical empty "true" case when it is absent, so an unconfigured if-else + # behaves the same with or without us writing it down. ``_if_else_case_ids`` + # likewise already reports ``["true"]`` for a node without ``cases``, so + # declared handles are unchanged. The entry is simply noise: it would write + # a fabricated always-true condition into the draft, making the node look + # configured in the canvas and in ``diff_graphs`` when it is not. } diff --git a/api/core/dify_builder/placeholder_agent.py b/api/core/dify_builder/placeholder_agent.py index 8866fe5ef49..af342c877ce 100644 --- a/api/core/dify_builder/placeholder_agent.py +++ b/api/core/dify_builder/placeholder_agent.py @@ -145,6 +145,12 @@ class PlaceholderAgent: # Start -> Knowledge-Retrieval -> LLM -> End. Creates and connects are # interleaved so each connect's endpoints already exist when # apply_connect validates them. + # + # ``node_defaults`` deliberately refuses to fabricate a node's PURPOSE + # fields, so this agent -- which builds a blank skeleton for the user to + # fill in on the canvas, and genuinely means "no dataset, no output" -- + # spells those two blanks out itself. A default that said them for every + # caller would let an LLM's forgotten field through as a silent success. return BuildNodesResult( intents=[ MutationIntent( @@ -159,7 +165,10 @@ class PlaceholderAgent: op="create_node", args={ "node_type": BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL, - "config": node_defaults.default_config(BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL), + "config": { + **node_defaults.default_config(BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL), + "dataset_ids": [], + }, "node_id": BUILD_KNOWLEDGE_ID, }, ), @@ -177,7 +186,7 @@ class PlaceholderAgent: op="create_node", args={ "node_type": BuiltinNodeTypes.END, - "config": node_defaults.default_config(BuiltinNodeTypes.END), + "config": {**node_defaults.default_config(BuiltinNodeTypes.END), "outputs": []}, "node_id": BUILD_END_ID, }, ), diff --git a/api/core/workflow/graph_normalizers.py b/api/core/workflow/graph_normalizers.py index 324112bb4a3..4111947cd85 100644 --- a/api/core/workflow/graph_normalizers.py +++ b/api/core/workflow/graph_normalizers.py @@ -47,8 +47,11 @@ _LIST_OPERATORS = frozenset({"in", "not in", "all of"}) # be either and ``!=`` / ``<>`` likewise -- the same ambiguity that keeps the # word forms (``equals``, ``gte``) rejected. The ordering forms carry none of # it: graphon has no string ordering operator at all -# (``_assert_greater_than`` and its three siblings raise "Invalid actual -# value type: number" for anything but a number), so ``>=`` can only mean ``≥``. +# (``_assert_greater_than`` and its three siblings reject anything that is not a +# number), so ``>=`` can only mean ``≥``. Do not quote that rejection's wording +# here -- it contains a bare ``type`` marker that mypy reads as a type comment +# whenever a reflow leaves it leading a line, which silently kills the whole +# type check from this module outward. # Guessing an equality would silently change which comparison the draft runs; # a loud refusal is the right outcome there. _ASCII_COMPARISON_OPERATORS: Mapping[str, str] = { diff --git a/api/tests/unit_tests/core/dify_builder/fakes.py b/api/tests/unit_tests/core/dify_builder/fakes.py index 21922c0bc44..59e83fb4de7 100644 --- a/api/tests/unit_tests/core/dify_builder/fakes.py +++ b/api/tests/unit_tests/core/dify_builder/fakes.py @@ -620,7 +620,7 @@ _EDIT_SEED_INTENTS = [ op="create_node", args={ "node_type": BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL, - "config": node_defaults.default_config(BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL), + "config": {**node_defaults.default_config(BuiltinNodeTypes.KNOWLEDGE_RETRIEVAL), "dataset_ids": []}, "node_id": "knowledge_retrieval", }, ), @@ -638,7 +638,7 @@ _EDIT_SEED_INTENTS = [ op="create_node", args={ "node_type": BuiltinNodeTypes.END, - "config": node_defaults.default_config(BuiltinNodeTypes.END), + "config": {**node_defaults.default_config(BuiltinNodeTypes.END), "outputs": []}, "node_id": "end", }, ), diff --git a/api/tests/unit_tests/core/dify_builder/test_node_defaults.py b/api/tests/unit_tests/core/dify_builder/test_node_defaults.py index bb2435e45a6..1f1ea2ea1f4 100644 --- a/api/tests/unit_tests/core/dify_builder/test_node_defaults.py +++ b/api/tests/unit_tests/core/dify_builder/test_node_defaults.py @@ -2,12 +2,15 @@ Values are pinned against the FE registry they mirror (``web/app/components /workflow/nodes//default.ts``) -- see the per-entry comments in -``node_defaults.py`` for the exact source lines -- and each entry is validated -against the engine node data class that consumes it, so a graphon field that -gains or loses a default fails here rather than in a live Edit. +``node_defaults.py`` for the exact source lines -- and every entry is run +through the engine node data class that consumes it, pinned in BOTH directions: +no structural field is missing, and no PURPOSE field is fabricated. """ +import importlib + import pytest +from pydantic import ValidationError from core.dify_builder.node_defaults import default_config, default_config_or_empty @@ -16,10 +19,6 @@ def test_default_config_start_matches_fe_default(): assert default_config("start") == {"variables": []} -def test_default_config_end_matches_fe_default(): - assert default_config("end") == {"outputs": []} - - def test_default_config_llm_matches_fe_default(): assert default_config("llm") == { "model": { @@ -34,11 +33,10 @@ def test_default_config_llm_matches_fe_default(): } -def test_default_config_knowledge_retrieval_matches_fe_default(): +def test_default_config_knowledge_retrieval_matches_fe_default_without_dataset_ids(): assert default_config("knowledge-retrieval") == { "query_variable_selector": [], "query_attachment_selector": [], - "dataset_ids": [], "retrieval_mode": "multiple", "multiple_retrieval_config": { "top_k": 4, @@ -48,15 +46,15 @@ def test_default_config_knowledge_retrieval_matches_fe_default(): } -def test_default_config_answer_matches_fe_default(): - assert default_config("answer") == {"variables": [], "answer": ""} - - -def test_default_config_template_transform_matches_fe_default(): - assert default_config("template-transform") == {"template": "", "variables": []} +def test_default_config_template_transform_keeps_variables_and_drops_template(): + """The F4 fix is ``variables`` -- structural, engine-required, and the exact + field the live Edit omitted. ``template`` is the node's purpose.""" + assert default_config("template-transform") == {"variables": []} def test_default_config_code_matches_fe_default(): + """Both empty values fail loudly (no ``main`` to call; ``CodeNodeError("Not + all output parameters are validated.")``), so neither is a purpose field.""" assert default_config("code") == { "code": "", "code_language": "python3", @@ -65,14 +63,16 @@ def test_default_config_code_matches_fe_default(): } -def test_default_config_variable_aggregator_matches_fe_default(): +def test_default_config_variable_aggregator_keeps_only_output_type(): """``nodes/variable-assigner/default.ts`` is the variable-AGGREGATOR's frontend directory; there is no ``nodes/variable-aggregator/``.""" - assert default_config("variable-aggregator") == {"output_type": "any", "variables": []} + assert default_config("variable-aggregator") == {"output_type": "any"} def test_default_config_http_request_matches_fe_default(): - """``nodes/http/default.ts``; there is no ``nodes/http-request/``.""" + """``nodes/http/default.ts``; there is no ``nodes/http-request/``. ``url`` + is kept: an empty one raises ``InvalidURLError("url is required")`` before + any request goes out, so it is loud, not silent.""" assert default_config("http-request") == { "variables": [], "method": "get", @@ -87,32 +87,16 @@ def test_default_config_http_request_matches_fe_default(): } -def test_default_config_if_else_matches_fe_default_without_target_branches(): - """``_targetBranches`` is editor-only state the canvas regenerates from - ``cases``. A caller-supplied ``cases`` wins the merge while a default - ``_targetBranches`` would not, so shipping one would attach a stale branch - list to every Builder-created if-else.""" - default = default_config("if-else") - - assert default == {"cases": [{"case_id": "true", "logical_operator": "and", "conditions": []}]} - assert "_targetBranches" not in default - - -def test_default_config_question_classifier_matches_fe_default_without_target_branches(): +def test_default_config_question_classifier_keeps_only_model_and_vision(): default = default_config("question-classifier") assert default == { - "query_variable_selector": [], "model": { "provider": "", "name": "", "mode": "chat", "completion_params": {"temperature": 0.7}, }, - "classes": [ - {"id": "1", "name": "", "label": "CLASS 1"}, - {"id": "2", "name": "", "label": "CLASS 2"}, - ], "vision": {"enabled": False}, } assert "_targetBranches" not in default @@ -140,6 +124,57 @@ def test_default_config_returns_a_fresh_copy_each_call(): assert second == {"variables": []} +# ---- a default must never fabricate a node's purpose ------------------------ + + +@pytest.mark.parametrize( + ("node_type", "forbidden"), + [ + ("end", "outputs"), # End runs OK -> "All checks passed" on an empty result + ("answer", "answer"), # streams nothing + ("template-transform", "template"), # renders "" + ("variable-aggregator", "variables"), # SUCCEEDED, outputs={} -- triage cause (d) + ("question-classifier", "classes"), # two blank categories + fabricated handle ids + ("question-classifier", "query_variable_selector"), # classifies "" + ("knowledge-retrieval", "dataset_ids"), # retrieves from no dataset, succeeds empty + ], +) +def test_no_entry_fabricates_a_purpose_field(node_type: str, forbidden: str): + """A field whose empty value produces a node that RUNS and yields nothing + must be left to the caller. Supplying it turns a loud preflight refusal into + a silent wrong answer -- the failure shape this module exists to prevent.""" + assert forbidden not in default_config(node_type) + + +def test_if_else_has_no_entry_at_all(): + """The frontend default is one case with an empty ``conditions`` list, and + graphon combines zero conditions with ``all([])`` -- so it always matches + and the node silently routes everything down the IF arm. Omitting it costs + nothing: ``cases`` is optional and ``iter_cases()`` synthesizes the same + empty case, so the engine behaves identically.""" + assert default_config_or_empty("if-else") == {} + with pytest.raises(ValueError, match="if-else"): + default_config("if-else") + + +def test_an_if_else_without_cases_still_declares_both_branch_handles(): + """Proof that dropping the entry did not weaken handle validation.""" + from core.workflow.graph_normalizers import declared_branch_handles + + bare = {"id": "n1", "data": {"type": "if-else", "title": "Check", **default_config_or_empty("if-else")}} + + assert declared_branch_handles(bare) == ["true", "false"] + + +def test_an_empty_condition_group_always_matches_so_it_is_not_safe_to_default(): + """The engine evidence behind the if-else decision.""" + from graphon.utils.condition.processor import ConditionProcessor + + result = ConditionProcessor().process_conditions(variable_pool=None, conditions=[], operator="and") + + assert result[2] is True + + # ---- default_config_or_empty ------------------------------------------------ @@ -160,65 +195,81 @@ def test_default_config_or_empty_returns_a_fresh_copy_each_call(): assert default_config_or_empty("code")["outputs"] == {} -# ---- the engine accepts every default -------------------------------------- +# ---- what the engine says about each default ------------------------------- # -# The point of the registry is that a node built from it alone is a node the -# draft preflight will not refuse. Each case names the graphon data class that -# consumes the type and the fields that class requires with NO default. +# Pinned in both directions: the fields the engine still reports missing from a +# node built from the default ALONE must be exactly the purpose fields the +# registry deliberately refuses to fabricate -- no more (a structural field +# would be a regression of the F4 fix) and no fewer (a purpose field creeping +# back in would be a silent-success regression). -_ENGINE_DATA_CLASSES: list[tuple[str, str, str]] = [ - ("start", "graphon.nodes.start.entities", "StartNodeData"), - ("end", "graphon.nodes.end.entities", "EndNodeData"), - ("answer", "graphon.nodes.answer.entities", "AnswerNodeData"), - ("if-else", "graphon.nodes.if_else.entities", "IfElseNodeData"), - ("code", "graphon.nodes.code.entities", "CodeNodeData"), - ("template-transform", "graphon.nodes.template_transform.entities", "TemplateTransformNodeData"), - ("http-request", "graphon.nodes.http_request.entities", "HttpRequestNodeData"), - ("variable-aggregator", "graphon.nodes.variable_aggregator.entities", "VariableAggregatorNodeData"), - ("question-classifier", "graphon.nodes.question_classifier.entities", "QuestionClassifierNodeData"), +_ENGINE_EXPECTATIONS: list[tuple[str, str, str, set[str]]] = [ + ("start", "graphon.nodes.start.entities", "StartNodeData", set()), + ("llm", "graphon.nodes.llm.entities", "LLMNodeData", set()), + ("code", "graphon.nodes.code.entities", "CodeNodeData", set()), + ("http-request", "graphon.nodes.http_request.entities", "HttpRequestNodeData", set()), + ("end", "graphon.nodes.end.entities", "EndNodeData", {"outputs"}), + ("answer", "graphon.nodes.answer.entities", "AnswerNodeData", {"answer"}), + ( + "knowledge-retrieval", + "core.workflow.nodes.knowledge_retrieval.entities", + "KnowledgeRetrievalNodeData", + {"dataset_ids"}, + ), + ( + "template-transform", + "graphon.nodes.template_transform.entities", + "TemplateTransformNodeData", + {"template"}, + ), + ( + "variable-aggregator", + "graphon.nodes.variable_aggregator.entities", + "VariableAggregatorNodeData", + {"variables"}, + ), + ( + "question-classifier", + "graphon.nodes.question_classifier.entities", + "QuestionClassifierNodeData", + {"query_variable_selector", "classes"}, + ), + ( + "tool", + "graphon.nodes.tool.entities", + "ToolNodeData", + {"provider_id", "provider_type", "provider_name", "tool_name", "tool_label"}, + ), ] -@pytest.mark.parametrize(("node_type", "module_name", "class_name"), _ENGINE_DATA_CLASSES) -def test_the_engine_validates_a_node_built_from_the_default_alone(node_type: str, module_name: str, class_name: str): - import importlib - +@pytest.mark.parametrize(("node_type", "module_name", "class_name", "expected_missing"), _ENGINE_EXPECTATIONS) +def test_the_engine_reports_exactly_the_purpose_fields_as_missing( + node_type: str, module_name: str, class_name: str, expected_missing: set[str] +): data_class = getattr(importlib.import_module(module_name), class_name) + payload = {"type": node_type, "title": "T", **default_config(node_type)} - data_class.model_validate({"type": node_type, "title": "T", **default_config(node_type)}) - - -def test_the_engine_still_rejects_a_template_transform_without_the_default(): - """The registry entry is load-bearing, not decoration: this is the exact - shape the Edit LLM emitted in the F4 failure.""" - from pydantic import ValidationError - - from graphon.nodes.template_transform.entities import TemplateTransformNodeData - - with pytest.raises(ValidationError, match="variables"): - TemplateTransformNodeData.model_validate({"type": "template-transform", "template": "excellent"}) - - -def test_the_engine_still_rejects_a_variable_aggregator_without_an_output_type(): - """``VariableAggregatorNodeData`` requires ``output_type`` as well as - ``variables``; the frontend default supplies both.""" - from pydantic import ValidationError - - from graphon.nodes.variable_aggregator.entities import VariableAggregatorNodeData - - with pytest.raises(ValidationError, match="output_type"): - VariableAggregatorNodeData.model_validate({"type": "variable-aggregator", "variables": []}) - - -def test_the_engine_rejects_a_tool_built_from_the_default_alone_for_identity_only(): - """The tool default cannot invent a provider/tool identity -- only the - caller knows it. Everything the default DOES cover validates.""" - from pydantic import ValidationError - - from graphon.nodes.tool.entities import ToolNodeData + if not expected_missing: + data_class.model_validate(payload) # must not raise + return with pytest.raises(ValidationError) as excinfo: - ToolNodeData.model_validate({"type": "tool", "title": "T", **default_config("tool")}) + data_class.model_validate(payload) + missing = {str(error["loc"][0]) for error in excinfo.value.errors() if error["type"] == "missing"} + assert missing == expected_missing - missing = {error["loc"][0] for error in excinfo.value.errors()} - assert missing == {"provider_id", "provider_type", "provider_name", "tool_name", "tool_label"} + +def test_an_if_else_needs_nothing_the_registry_would_have_to_supply(): + from graphon.nodes.if_else.entities import IfElseNodeData + + IfElseNodeData.model_validate({"type": "if-else", "title": "T"}) # must not raise + + +def test_the_llm_defaults_fail_loudly_rather_than_silently(): + """Why ``model`` and ``prompt_template`` are kept while other purpose fields + are dropped: neither empty value lets the node run and yield nothing.""" + from graphon.nodes.llm.exc import NoPromptFoundError + + assert issubclass(NoPromptFoundError, Exception) + assert default_config("llm")["model"]["provider"] == "" # -> "model not configured" at launch diff --git a/api/tests/unit_tests/services/dify_builder/test_graph_ops.py b/api/tests/unit_tests/services/dify_builder/test_graph_ops.py index ff521d89bf6..7dea1b26568 100644 --- a/api/tests/unit_tests/services/dify_builder/test_graph_ops.py +++ b/api/tests/unit_tests/services/dify_builder/test_graph_ops.py @@ -346,9 +346,12 @@ def test_insert_between_fills_required_fields_too(): assert data["code"] == "print(1)" -def test_filter_applicable_dry_run_sees_the_same_defaults_the_port_will_write(): - """The dry run and the live apply must agree, or a create the dry run - accepts is a create the preflight refuses.""" +def test_filter_applicable_routes_a_create_through_the_apply_fn_that_fills_defaults(): + """``filter_applicable`` does not return its working graph, so this cannot + assert on the node the dry run built. What it CAN pin is the link that makes + the dry run and the live apply agree: the dry run dispatches through + ``APPLY_FNS``, whose ``create_node`` entry is the very function that merges + the defaults in -- and it accepts a config that omits one.""" intents = [ MutationIntent( op="create_node", @@ -360,8 +363,9 @@ def test_filter_applicable_dry_run_sees_the_same_defaults_the_port_will_write(): assert rejected == [] assert applicable == intents - dry_run, _ = graph_ops.apply_create_node({"nodes": [], "edges": []}, **intents[0].args) - assert dry_run["nodes"][0]["data"]["variables"] == [] + assert graph_ops.APPLY_FNS["create_node"] is graph_ops.apply_create_node + built, _ = graph_ops.apply_create_node({"nodes": [], "edges": []}, **intents[0].args) + assert built["nodes"][0]["data"]["variables"] == [] # ---- apply_delete_node ------------------------------------------------------