Skip to content

test(api): bring the node runtime and dsl service tests under strict pyrefly - #46453

Open
MindOfqc wants to merge 14 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-node-runtime-and-dsl-service
Open

MindOfqc wants to merge 14 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-node-runtime-and-dsl-service

Conversation

@MindOfqc

Copy link
Copy Markdown
Contributor

core/workflow/test_node_runtime.py and services/agent/test_dsl_service.py leave api/tests/unit_tests/pyrefly.toml's project-excludes.

Node runtime

The tests reached workflow-private state through graphon's opaque ToolRuntimeHandle.raw, typed object. They now narrow the handle to the binding it actually carries:

def _tool_binding(handle: ToolRuntimeHandle) -> _WorkflowToolRuntimeBinding:
    binding = handle.raw
    assert isinstance(binding, _WorkflowToolRuntimeBinding)
    return binding

Model stubs now derive from the real ModelInstance base, so the calls under test keep their declared shapes instead of being erased by a stand-in. Assertions on values the mapped declarations allow to be unset (parent_trace_context, parse_file_reference(...)) first prove the value is present.

DSL service

Six tests replaced instance methods with plain assignments. They patch through the fixture now — same runtime effect, without asking the checker to ignore method types. The mock is held in a local variable where the test asserts on call counts, so the attribute access resolves on the mock rather than on the function it replaced.

Two tests were written by bypassing validation; they were replaced with tests of branches that are actually reachable, so the module keeps its coverage count.

Verification

errors=29 warnings=0 non_missing=0 target=0

The 29 are all missing-import for packages absent from a local virtualenv, matching the clean-tree baseline.

pytest on both modules → 118 passed, unchanged. ruff check / ruff format --check clean.

No # pyrefly: ignore, no typing.cast, no net-new mock constructors (the file's Mock(...) count goes 82 → 81).

project-excludes: 158 → 156.

…pyrefly

Both modules leave `api/tests/unit_tests/pyrefly.toml`'s `project-excludes`.

The node runtime tests reached the workflow-private state behind graphon's
opaque `ToolRuntimeHandle` through an untyped attribute, and asserted on
attributes that the mapped declarations do not allow to be unset. They now
narrow the handle to the binding it carries, assert the trace context and
file reference they expect, and build the model stubs from the real
`ModelInstance` base so the calls under test keep their declared shapes.

The dsl service tests replaced instance methods with plain assignments; they
now patch through the fixture, which is the same runtime effect without
teaching the checker to ignore the method types. Two tests that could only
be written by bypassing validation were replaced by tests of reachable
branches, so the module keeps its coverage.

Verification:
- `errors=29 warnings=0 non_missing=0 target=0`, the 29 all `missing-import`
  for packages absent from a local virtualenv, matching the clean baseline.
- `pytest` on both modules: 118 passed, unchanged from before the change.
- `ruff check` and `ruff format --check` clean.
- No `# pyrefly: ignore`, no `typing.cast`, no net-new mock constructors.

`project-excludes`: 158 -> 156.
@github-actions github-actions Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 15, 2026
@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-25 04:12:51.708858112 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-25 04:12:41.384742546 +0000
@@ -501,7 +501,7 @@
 ERROR Argument `Literal['workflow']` is not assignable to parameter `value` with type `AppMode | SQLCoreOperations[AppMode]` in function `sqlalchemy.orm.base.Mapped.__set__` [bad-argument-type]
     --> tests/e2e_tests/containers/services/test_app_dsl_service.py:1336:20
 ERROR Argument `list[SimpleNamespace]` is not assignable to parameter `dsl_dependencies` with type `list[PluginDependency]` in function `services.app_dsl_service.AppDslService.get_leaked_dependencies` [bad-argument-type]
-    --> tests/e2e_tests/containers/services/test_app_dsl_service.py:1618:73
+    --> tests/e2e_tests/containers/services/test_app_dsl_service.py:1625:73
 ERROR Object of class `NoneType` has no attribute `id` [missing-attribute]
    --> tests/e2e_tests/containers/services/test_app_generate_service.py:195:38
 ERROR Argument `str | None` is not assignable to parameter `created_by` with type `SQLCoreOperations[str] | str` in function `models.workflow.Workflow.__init__` [bad-argument-type]
@@ -4745,68 +4745,6 @@
     --> tests/unit_tests/core/workflow/test_node_factory.py:1521:37
 ERROR `SimpleNamespace` is not assignable to attribute `runtime_state` with type `RuntimeState` [bad-assignment]
     --> tests/unit_tests/core/workflow/test_node_factory.py:1522:37
-ERROR Object of class `object` has no attribute `parent_trace_context` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1184:16
-ERROR Object of class `object` has no attribute `trace_session_id` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1225:16
-ERROR Argument `object` is not assignable to parameter `message` with type `ToolInvokeMessage.BlobChunkMessage | ToolInvokeMessage.BlobMessage | ToolInvokeMessage.FileMessage | ToolInvokeMessage.JsonMessage | ToolInvokeMessage.LogMessage | ToolInvokeMessage.RetrieverResourceMessage | ToolInvokeMessage.TextMessage | ToolInvokeMessage.VariableMessage | None` in function `core.workflow.node_runtime.DifyToolNodeRuntime._convert_message_payload` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1318:52
-ERROR Argument `object` is not assignable to parameter `message` with type `ToolInvokeMessage.BlobChunkMessage | ToolInvokeMessage.BlobMessage | ToolInvokeMessage.FileMessage | ToolInvokeMessage.JsonMessage | ToolInvokeMessage.LogMessage | ToolInvokeMessage.RetrieverResourceMessage | ToolInvokeMessage.TextMessage | ToolInvokeMessage.VariableMessage | None` in function `core.workflow.node_runtime.DifyToolNodeRuntime._convert_message_payload` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1325:46
-ERROR `object | None` is not assignable to attribute `model_runtime` with type `LLMModelRuntime` [bad-assignment]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1444:30
-ERROR Argument `list[FromClause]` is not assignable to parameter `tables` with type `Sequence[Table] | None` in function `sqlalchemy.sql.schema.MetaData.create_all` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1508:60
-ERROR Object of class `ExternalRecipient` has no attribute `reference_id` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1533:16
-ERROR Argument `object` is not assignable to parameter `method` with type `EmailDeliveryMethod | InstantMessageDeliveryMethod | InteractiveSurfaceDeliveryMethod` in function `core.workflow.node_runtime.apply_dify_debug_email_recipient` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1548:49
-ERROR Argument `_ModelInstanceStub` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1571:36
-ERROR Object of class `FunctionType` has no attribute `assert_called_once_with` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1590:9
-ERROR Argument `_ModelInstanceStub` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1604:36
-ERROR Argument `_ModelInstanceStub` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1612:36
-ERROR Argument `SimpleNamespace` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1639:36
-ERROR Argument `_ModelInstanceStub` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedPollingLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1664:43
-ERROR Object of class `FunctionType` has no attribute `return_value` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1729:9
-ERROR Object of class `FunctionType` has no attribute `return_value` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1767:9
-ERROR Object of class `FunctionType` has no attribute `side_effect` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1804:9
-ERROR Object of class `FunctionType` has no attribute `call_count` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1818:16
-ERROR Object of class `FunctionType` has no attribute `return_value` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1835:9
-ERROR Object of class `FunctionType` has no attribute `return_value` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1865:9
-ERROR Argument `_ModelInstanceStub` is not assignable to parameter `model_instance` with type `ModelInstance` in function `core.workflow.node_runtime.DifyPreparedPollingLLM.__init__` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1902:43
-ERROR Argument `Literal['chat']` is not assignable to parameter `model_mode` with type `LLMMode` in function `core.workflow.node_runtime.DifyPromptMessageSerializer.serialize` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1919:24
-ERROR Object of class `NoneType` has no attribute `storage_key` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:1948:16
-ERROR Argument `object` is not assignable to parameter `variable_pool` with type `VariablePool | None` in function `core.workflow.node_runtime.DifyToolNodeRuntime.get_runtime` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2182:27
-ERROR Object of class `object` has no attribute `tool` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2186:16
-ERROR Object of class `object` has no attribute `parent_trace_context` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2187:16
-ERROR Object of class `object` has no attribute `trace_session_id` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2210:9
-ERROR Argument `object` is not assignable to parameter `variable_pool` with type `VariablePool | None` in function `core.workflow.node_runtime.DifyToolNodeRuntime.get_runtime` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2227:27
-ERROR Object of class `object` has no attribute `trace_session_id` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2231:16
-ERROR Argument `object` is not assignable to parameter `variable_pool` with type `VariablePool | None` in function `core.workflow.node_runtime.DifyToolNodeRuntime.get_runtime` [bad-argument-type]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2259:27
-ERROR Object of class `object` has no attribute `tool` [missing-attribute]
-    --> tests/unit_tests/core/workflow/test_node_runtime.py:2262:16
 WARN Cannot instantiate `BaseNodeData` because it directly extends `ABC` or uses `ABCMeta` [direct-abstract-base-instantiation]
     --> tests/unit_tests/core/workflow/test_workflow_entry.py:1010:50
 ERROR `in` is not supported between `Literal['Maximum execution steps exceeded: 3 > 2']` and `None` [not-iterable]
@@ -4895,10 +4833,6 @@
     --> tests/unit_tests/libs/broadcast_channel/redis/test_pubsub_channel.py:1012:20
 ERROR Argument `FakeRedisClient` is not assignable to parameter `client` with type `Redis[Unknown] | RedisCluster[Unknown]` in function `libs.broadcast_channel.redis._subscription.RedisSubscriptionBase.__init__` [bad-argument-type]
     --> tests/unit_tests/libs/broadcast_channel/redis/test_pubsub_channel.py:1109:24
-ERROR Argument `dict[str, list[@_]]` is not assignable to parameter `graph` with type `SQLCoreOperations[str] | str` in function `models.workflow.Workflow.__init__` [bad-argument-type]
-   --> tests/unit_tests/services/agent/test_dsl_service.py:120:15
-ERROR `object` is not assignable to dict key `agent_binding` with type `str` [bad-assignment]
-   --> tests/unit_tests/services/agent/test_dsl_service.py:131:33
 ERROR Argument `Literal['emoji']` is not assignable to parameter `icon_type` with type `AgentIconType | SQLCoreOperations[AgentIconType | None] | None` in function `models.agent.Agent.__init__` [bad-argument-type]
     --> tests/unit_tests/services/agent/test_roster_service.py:1386:19
 ERROR Argument `Literal['emoji']` is not assignable to parameter `icon_type` with type `AgentIconType | SQLCoreOperations[AgentIconType | None] | None` in function `models.agent.Agent.__init__` [bad-argument-type]

@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 87.84% 87.84% +0.00%
Strict coverage 87.50% 87.50% +0.00%
Typed symbols 96,950 96,958 +8
Untyped symbols 13,477 13,477 0
Modules 4666 4666 0

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.46%. Comparing base (d27e28d) to head (393dd25).
⚠️ Report is 15 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #46453   +/-   ##
=======================================
  Coverage   90.46%   90.46%           
=======================================
  Files        6567     6567           
  Lines      409787   409818   +31     
  Branches    82100    82100           
=======================================
+ Hits       370694   370723   +29     
- Misses      32703    32706    +3     
+ Partials     6390     6389    -1     
Flag Coverage Δ
api 90.16% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@@ -1152,7 +1156,7 @@ def test_get_runtime_stores_parent_trace_context_for_workflow_tools(
)
)
workflow_runtime = MagicMock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

real class ?

@@ -1192,7 +1198,7 @@ def test_get_runtime_stores_trace_session_id_for_workflow_tools(
)
)
workflow_runtime = MagicMock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

@@ -1230,7 +1237,7 @@ def test_get_runtime_leaves_non_workflow_tool_runtime_parameters_unchanged(
)
)
builtin_runtime = MagicMock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

@asukaminato0721 asukaminato0721 self-assigned this Nov 15, 2026
get_workflow_tool_runtime is annotated to return Tool, so the three get_runtime
tests now give it a concrete _StubTool with a real ToolRuntime instead of a
MagicMock whose .runtime chain the assertions happened to read.
@MindOfqc

Copy link
Copy Markdown
Contributor Author

Done. ToolManager.get_workflow_tool_runtime is annotated to return Tool, so the three get_runtime tests now hand it a real _StubTool (a concrete Tool subclass implementing the two abstract members) backed by a real ToolRuntime, instead of a MagicMock whose .runtime.runtime_parameters chain the assertions happened to read.

MagicMock usage in this file goes from 46 to 43 (only removed, none added).

Verified: 0 diagnostics for the file under the strict tests project, 79 tests pass (same as the base commit), ruff clean.

@asukaminato0721 asukaminato0721 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

6 inline suggestions at 716ae10e09, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

…time tests

Replace the hand-rolled `_StubTool` with the real `CurrentTimeTool`, annotate
`invoke_llm_result` as `LLMResult`, and drop the unused `runtime_parameters`
parameter. Define `AgentNodeBindingDict` / `AgentNodeGraphNodeDict` /
`AgentNodeGraphDict` in the production DTO module and use them instead of
`dict[str, object]`. Let the two dsl service tests run the real import path so
they assert persisted agents, bindings and revisions instead of patched calls.

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 inline suggestions at 5e82b9716e, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

@asukaminato0721 asukaminato0721 added the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 16, 2026
落实评审四条:
- :424/:574 inject-dependency:去掉对 resolve_package_soul/unique_roster_name/AgentRosterService/_create_workflow_only_agent 的 patch,两条导入/克隆测试改走 sqlite_session 上的真实协作者,断言持久化后的 Agent/AgentConfigSnapshot/AgentConfigRevision 与返回元组。
- :127 parse-dont-validate:在生产 dsl_entities 定义 AgentNodeDataDict(type/version/agent_node_kind/agent_binding/agent_job),测试 import 使用,_agent_node 不再手拼 dict[str, object]。
- :492 parse-dont-validate:非法 package_ref 形态改为经 json 往返构造原始文档形状(边界不信任数据本来就是 untyped),不再 cast 进 TypedDict。
@MindOfqc

Copy link
Copy Markdown
Contributor Author

已在 e76c80d 落实四条评审:

  • :424 / :574(inject-dependency):test_import_agent_app_package_creates_config_and_unpublished_draft 与 test_clone_inline_binding_copies_soul 不再 patch resolve_package_soul / unique_roster_name / AgentRosterService / _create_workflow_only_agent,两条测试改在 sqlite_session 上跑全部真实协作者,断言改为持久化后的 Agent / AgentConfigSnapshot / AgentConfigRevision(含 operation == IMPORT_PACKAGE / CREATE_VERSION)与返回元组本身。
  • :127(parse-dont-validate):节点 data 的形状现在由生产侧 services/agent/dsl_entities.py::AgentNodeDataDict(TypedDict,镜像 domain.workflow.agent_node.is_dify_agent_node_data 的识别契约)定义,测试 import 使用;_agent_node 不再手拼 dict[str, object]。
  • :492(parse-dont-validate):非法 package_ref 用例改为经 json 往返构造——未信任文档在边界本来就是 untyped 原始数据,这正是 parse-dont-validate 的输入形态;不再需要 cast。

验证:该文件 39 passed;tests/unit_tests pyrefly 整项目 29 条全 missing-import 与基线一致、零新增;diff 无新增 cast/SimpleNamespace/Mock;ruff check+format 通过。

@github-actions github-actions Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Nov 17, 2026

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 inline suggestions at e76c80d93b, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 3 review threads are still unresolved.

dify-codereview

"""Provide real attachment and upload-file persistence to node runtime tests."""

TypeBase.metadata.create_all(sqlite_engine, tables=[SegmentAttachmentBinding.__table__, UploadFile.__table__])
attachment_table = SegmentAttachmentBinding.__table__

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we import and use the real class here instead of a stand-in? Then the test checks the real behaviour, not the mock.

dify-codereview · tests-real-dependencies (import-real-class) Learned from an earlier review. Reply here if this is wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line already uses the real production class — SegmentAttachmentBinding.__table__ (imported from models.dataset), created in a real in-memory SQLite database via TypeBase.metadata.create_all in the fixture. There is no test double here: the isinstance check only narrows the static type of the bound table. Verified with the node-runtime suite (79 passed), so no change is needed at this site.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is a false positive: the fixture needs the real table object to create the schema, which is exactly what it uses — SegmentAttachmentBinding is imported and __table__ is passed to create_all, so no fake class is involved. I have kept the assertion that spells out the type so the intent stays visible; happy to drop it if the extra line is unwelcome.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 17, 2026
The parametrize cases for test_agent_package_rejects_null_file_id_for_available_assets
constructed ad hoc dict[str, object] payloads. Build them from the production
AgentConfigSkillRefConfig / AgentConfigFileRefConfig models instead, dump to JSON,
and inject the malformed null file_id on the serialized payload before the single
AgentPackage.model_validate boundary check. The after-validator still rejects an
available asset whose file_id is null, so the tested behavior is unchanged.

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 inline suggestion at fcc9923373, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 4 review threads are still unresolved.

dify-codereview

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 17, 2026
asukaminato0721

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 removed the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 18, 2026
asukaminato0721

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 22, 2026

@asukaminato0721 asukaminato0721 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI is failing: API Tests, Run API Tests / API Integration Tests (3.13). Please fix it. 3 inline suggestions at 5cc2981fbf, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 4 review threads are still unresolved.

dify-codereview

_AGENT_NODE_GRAPH_ADAPTER = TypeAdapter(AgentNodeGraphDict)


def parse_agent_node_graph(value: object) -> AgentNodeGraphDict:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use the precise type here, not object / Any: e.g. -> str, -> Session, Callable[...]; for a parametrized test, the union of the case types (or a type alias for it); for __exit__, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None.

dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a25e469: added AgentNodeGraphEdgeDict (source/target) and declared AgentNodeGraphDict.edges: list[AgentNodeGraphEdgeDict] instead of list[dict[str, object]]. edges keeps extra="allow" like the rest of the envelope so edges carrying extra keys still validate.

assert result["nodes"][1]["data"]["agent_binding"]["agent_id"] == "agent-1"
assert all(AGENT_NODE_JOB_DSL_KEY not in node["data"] for node in result["nodes"])
assert AGENT_NODE_JOB_DSL_KEY in graph["nodes"][0]["data"]
assert AGENT_NODE_JOB_DSL_KEY in graph_nodes[0]["data"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a25e469: the remaining graph literal is now typed as AgentNodeGraphDict with "edges": [], and test_graph_without_package_bindings_removes_portable_fields builds its nodes as list[AgentNodeGraphNodeDict]. No ad hoc dict[str, object] is constructed in this file any more — the values come from the production AgentNodeGraphDict shape.

graph, agent_packages = AgentDslService(self._session).export_workflow_packages(
workflow=workflow,
graph=workflow_dict.get("graph", {}),
graph=parse_agent_node_graph(workflow_dict.get("graph", {})),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.

dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a25e469: _append_workflow_export_data now reads the graph that parse_agent_node_graph produced (graph["nodes"], node["data"]) instead of walking the raw dict with .get(...) fallbacks, so the data is validated once at the boundary and the typed value is passed on.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 22, 2026
MindOfqc and others added 2 commits November 23, 2026 15:24
AgentNodeGraphDict boundary validation requires every node to carry an id; the hand-built fixtures in the e2e workflow export test omitted it.
asukaminato0721

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 23, 2026
@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 23, 2026
asukaminato0721

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 24, 2026
# Conflicts:
#	api/services/agent/dsl_service.py
Review asked for the precise edge type instead of list[dict[str, object]],
and for the export helper to use the graph it already parsed instead of
re-reading the raw dict with .get() fallbacks.

- add AgentNodeGraphEdgeDict and use it for AgentNodeGraphDict.edges
- read graph["nodes"] / node["data"] in _append_workflow_export_data
- annotate the remaining test graph literal as AgentNodeGraphDict

Verified: 82 passed in the agent/snippet unit tests, ruff check and
ruff format clean, pyrefly reports 0 diagnostics.
@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 24, 2026
asukaminato0721

This comment was marked as outdated.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 25, 2026
Resolve the Pyrefly exclusion list using main plus the two originally scoped removals; do not restore stale exclusions.

Copy link
Copy Markdown
Contributor Author

Synced this branch with main in 393dd25f using a merge commit to keep the existing history. The Pyrefly config now differs from main only by removing the two exclusions this PR targets; the other eight changed files are unchanged by the sync. All 310 focused tests passed, along with the targeted production type checks, strict Pyrefly on the affected test files, and Ruff. GitHub reports the PR is mergeable; the full hosted checks will run on this head.

@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XL This PR changes 500-999 lines, ignoring generated files. waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants