← Back to Pull requests

test(api): bring the knowledge fs contract and workflow mock factory under strict pyrefly #46418

Open
MindOfqc opened this pull request with 227 lines diff across 3 files
View on GitHub
MindOfqc MindOfqc commented on Nov 14, 2026 15:13 UTC
Author

Why


api/tests/unit_tests/pyrefly.toml still lists dev/test_generate_knowledge_fs_contract.py and the shared ../helpers/workflow/mock_factory.py as strict-mode debt. Neither needs a type suppression, so they should not stay on the list.

What changed


mock_factory.py builds the node and variable fixtures the workflow contract tests are written against, so the annotations follow the production entities instead of widening with object:
  • node factories return Node and accept NodeData subclasses, which is what the call sites already pass

  • variable factories return VariableBase, matching factories/variable_factory.py

  • the mapping helpers reuse the dict[str, object] convention from the other strict-clean helpers under tests/helpers/
  • test_generate_knowledge_fs_contract.py:

  • CLI runner helpers gained return annotations

  • parsed JSON payloads are narrowed through a small _mapping helper before indexing, instead of relying on implicit Any
  • api/tests/unit_tests/pyrefly.toml drops the two entries (199 -> 197).

    How to test


    cd api
    uv run --project . --dev pyrefly check
    uv run --project . --dev pytest tests/unit_tests/dev/test_generate_knowledge_fs_contract.py \
      tests/unit_tests/core/workflow/test_workflow_entry.py
    

    Locally, with both entries removed from project-excludes:
  • whole-project pyrefly: the same 29 baseline missing-import errors, zero warnings, zero non-missing-import errors, zero remaining diagnostics for either file

  • pytest: 37 passed / 1 pre-existing failure before and after (test_contract_cli_updates_checks_and_detects_openapi_drift also fails on the unmodified checkout)

  • test_workflow_entry.py, the other consumer of the shared helper: 77 passed

  • ruff check and format: clean
  • No new pyrefly: ignore, type: ignore, cast or typing.Any.

    Diff: 227 lines (+138 / -89) across 3 files Reviewer: asukaminato0721 Review duration: 24905m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.38) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.38 · 227 lines diff across 3 files
    0.38
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.95 · 5 substantive comment(s)
    0.95
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    93%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.325
    Real PR Conversation Timeline
    18 items
    github-actions[bot] github-actions[bot] commented on Nov 14, 2026 15:16 UTC
    Bot

    Pyrefly Diff


    <details>
    <summary>base → PR</summary>

    --- /tmp/pyrefly_base.txt	2026-11-30 12:53:07.163846374 +0000
    +++ /tmp/pyrefly_pr.txt	2026-11-30 12:52:55.483783718 +0000
    @@ -1574,12 +1574,6 @@
        --> tests/helpers/legacy_model_type_migration.py:139:23
     ERROR Object of class `FromClause` has no attribute `insert` [missing-attribute]
        --> tests/helpers/legacy_model_type_migration.py:183:13
    -ERROR Cannot extend final class `DifyNodeFactory` [invalid-inheritance]
    -  --> tests/helpers/workflow/mock_factory.py:38:23
    -ERROR Class member `MockNodeFactory.create_node` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
    -   --> tests/helpers/workflow/mock_factory.py:113:9
    -ERROR Cannot set item in `dict[str, type[MockAgentNode] | type[MockCodeNode] | type[MockDocumentExtractorNode] | type[MockHttpRequestNode] | type[MockIterationNode] | type[MockKnowledgeRetrievalNode] | type[MockLLMNode] | type[MockLoopNode] | type[MockParameterExtractorNode] | type[MockQuestionClassifierNode] | type[MockTemplateTransformNode] | type[MockToolNode]]` [unsupported-operation]
    -   --> tests/helpers/workflow/mock_factory.py:205:44
     ERROR Unexpected keyword argument `node_id` in function `object.__init__` [unexpected-keyword]
        --> tests/helpers/workflow/mock_nodes.py:118:13
     ERROR Unexpected keyword argument `data` in function `object.__init__` [unexpected-keyword]
    @@ -4117,18 +4111,6 @@
         --> tests/unit_tests/core/workflow/test_workflow_entry.py:1795:24
     ERROR Object of class `FunctionType` has no attribute `call_args` [missing-attribute]
         --> tests/unit_tests/core/workflow/test_workflow_entry.py:1796:35
    -ERROR Object of class `object` has no attribute `append` [missing-attribute]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:121:13
    -ERROR Cannot set item in `object` [unsupported-operation]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:130:13
    -ERROR Object of class `object` has no attribute `pop` [missing-attribute]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:130:32
    -ERROR Cannot index into `object` [bad-index]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:224:30
    -ERROR Cannot index into `object` [bad-index]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:232:5
    -ERROR `object` is not assignable to dict key `security` with type `dict[str, dict[str, dict[str, object]]]` [bad-assignment]
    -   --> tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:660:32
     ERROR Object of class `NoneType` has no attribute `partition` [missing-attribute]
       --> tests/unit_tests/extensions/logstore/repositories/test_logstore_api_workflow_node_execution_repository.py:58:34
     ERROR `<=` is not supported between `None` and `int` [unsupported-operation]
    
    

    </details>

    github-actions[bot] github-actions[bot] commented on Nov 14, 2026 15:16 UTC
    Bot

    Pyrefly Type Coverage

    | Metric | Base | PR | Delta |
    | --- | ---: | ---: | ---: |
    | Type coverage | 90.82% | 90.82% | +0.00% |
    | Strict coverage | 90.47% | 90.47% | +0.00% |
    | Typed symbols | 106,067 | 106,073 | +6 |
    | Untyped symbols | 10,764 | 10,764 | 0 |
    | Modules | 4974 | 4974 | 0 |

    codecov[bot] codecov[bot] commented on Nov 14, 2026 15:20 UTC
    Bot

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 90.54%. Comparing base (5d50d5f) to head (912d042).
    :warning: Report is 1 commits behind head on main.

    <details><summary>Additional details and impacted files</summary>

    @@           Coverage Diff           @@
    ##             main   #46418   +/-   ##
    =======================================
      Coverage   90.54%   90.54%           
    =======================================
      Files        6897     6897           
      Lines      432401   432432   +31     
      Branches    86698    86699    +1     
    =======================================
    + Hits       391507   391537   +30     
    - Misses      34069    34070    +1     
      Partials     6825     6825           
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | api | 90.08% <ø> (+<0.01%) | :arrow_up: |

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

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -118,15 +118,18 @@ def disallow_subprocess(*_args: object, **_kwargs: object) -> None:
             if change == "schema":
                 document["components"] = {"schemas": {"KnowledgeSpace": {"type": "object"}}}
             elif change == "query":
    -            openapi_operation(document, "get")["parameters"].append(
    -                {"in": "query", "name": "limit", "schema": {"maximum": 200, "type": "integer"}}
    -            )
    +            get_operation = openapi_operation(document, "get")
    +            parameters = get_operation["parameters"]
    +            assert isinstance(parameters, list)
    +            parameters.append({"in": "query", "name": "limit", "schema": {"maximum": 200, "type": "integer"}})
             elif change == "body":
                 openapi_operation(document, "post")["requestBody"] = {
                     "content": {"application/json": {"schema": {"required": ["name"], "type": "object"}}}
                 }
             elif change == "response":
    -            responses = openapi_operation(document, "post")["responses"]
    +            post_operation = openapi_operation(document, "post")
    +            responses = post_operation["responses"]
    +            assert isinstance(responses, dict)

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=3445c77111533754 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -221,23 +224,29 @@ def test_contract_update_requires_explicit_source_and_check_rejects_source(monke
     
     def test_product_operation_manifest_must_cover_ready_and_gap_runtime_registry() -> None:
         manifest = fixture_product_manifest()
    -    manifest["operations"] = manifest["operations"][:-1]
    +    operations = manifest["operations"]
    +    assert isinstance(operations, list)
    +    manifest["operations"] = operations[:-1]
     
         with pytest.raises(ValueError, match="completeness drifted.*createUploadSession"):
             validate_fixture_product_contracts(manifest=manifest)
     
     
     def test_product_operation_manifest_must_match_capability_and_openapi_fields() -> None:
         manifest = fixture_product_manifest()
    -    manifest["operations"][0]["method"] = "POST"
    +    operations = manifest["operations"]
    +    assert isinstance(operations, list)
    +    first_operation = operations[0]
    +    assert isinstance(first_operation, dict)

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=db1d702898c3369c -->

    asukaminato0721 asukaminato0721 commented on Nov 16, 2026 09:45 UTC
    Reviewer

    2 inline suggestions at 1c51058b58, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=1c51058b58ae05f99e5a1a0c84865f384232d734 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:46 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -617,7 +626,7 @@ def test_validate_declarations_ignores_undeclared_operations() -> None:
                     "get": operation("knowledge-spaces:read", "listKnowledgeSpaces"),
                 },
                 "/internal-maintenance": {
    -                "head": {"responses": {"200": {}}},
    +                "head": {"responses": {"200": dict[str, object]()}},

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=77fec5c90ef0a413 -->

    asukaminato0721 asukaminato0721 commented on Nov 16, 2026 09:46 UTC
    Reviewer

    2 inline suggestions at 1c51058b58, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=1c51058b58ae05f99e5a1a0c84865f384232d734 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:46 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -283,8 +292,8 @@ def test_validate_declarations_accepts_matching_contract() -> None:
         route["parameters"] = [{"in": "header", "name": "X-Trace-Id"}]
         route["responses"] = {
             "200": {
    -            "content": {"application/json": {}},
    -            "headers": {"X-Trace-Id": {}},
    +            "content": {"application/json": dict[str, object]()},

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=81c6a19f34654e6d -->

    MindOfqc MindOfqc commented on code on Nov 26, 2026 23:58 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -221,23 +224,29 @@ def test_contract_update_requires_explicit_source_and_check_rejects_source(monke
     
     def test_product_operation_manifest_must_cover_ready_and_gap_runtime_registry() -> None:
         manifest = fixture_product_manifest()
    -    manifest["operations"] = manifest["operations"][:-1]
    +    operations = manifest["operations"]
    +    assert isinstance(operations, list)
    +    manifest["operations"] = operations[:-1]
     
         with pytest.raises(ValueError, match="completeness drifted.*createUploadSession"):
             validate_fixture_product_contracts(manifest=manifest)
     
     
     def test_product_operation_manifest_must_match_capability_and_openapi_fields() -> None:
         manifest = fixture_product_manifest()
    -    manifest["operations"][0]["method"] = "POST"
    +    operations = manifest["operations"]
    +    assert isinstance(operations, list)
    +    first_operation = operations[0]
    +    assert isinstance(first_operation, dict)

    Updated in fb9b084f. The ready-manifest fixture and its helper now use the production ProductOperationManifest TypedDict, with typed operation entries. The tests can remove an operation and change a method without narrowing dictionaries by hand. The fixture still goes through the production parser, and the two cases still assert the specific completeness and method-drift errors. All 38 generator tests passed and scoped strict Pyrefly reported zero diagnostics.

    asukaminato0721 asukaminato0721 commented on code on Nov 27, 2026 00:17 UTC
    Code Review
    api/tests/helpers/workflow/mock_factory.py:1
    @@ -83,23 +134,20 @@ def with_runtime_state(self, runtime_state: "RuntimeState") -> "MockNodeFactory"
             )
     
         @override
    -    def _resolve_node_class_for_factory(
    -        self,
    -        *,
    -        node_type: NodeType,
    -        node_version: str,
    -        node_data: BaseNodeData,
    -    ) -> type[Node]:
    -        mock_class = self._mock_node_types.get(node_type)
    -        if mock_class is not None:
    -            return mock_class
    -        return super()._resolve_node_class_for_factory(
    -            node_type=node_type,
    -            node_version=node_version,
    -            node_data=node_data,
    -        )
    +    def with_graph_config(self, graph_config: Mapping[str, Any]) -> "MockNodeFactory":

    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.

    <sub>dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=parse-dont-validate;key=e164b0c440531745 -->

    asukaminato0721 asukaminato0721 requested changes on Nov 27, 2026 00:17 UTC
    Changes Requested Reviewer

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

    <sub>dify-codereview</sub>
    <!-- dify-review:head=fb9b084face1f83dadb3a41540c07e9992fe425a -->

    MindOfqc MindOfqc commented on code on Nov 27, 2026 01:02 UTC
    Code Review
    api/tests/helpers/workflow/mock_factory.py:1
    @@ -83,23 +134,20 @@ def with_runtime_state(self, runtime_state: "RuntimeState") -> "MockNodeFactory"
             )
     
         @override
    -    def _resolve_node_class_for_factory(
    -        self,
    -        *,
    -        node_type: NodeType,
    -        node_version: str,
    -        node_data: BaseNodeData,
    -    ) -> type[Node]:
    -        mock_class = self._mock_node_types.get(node_type)
    -        if mock_class is not None:
    -            return mock_class
    -        return super()._resolve_node_class_for_factory(
    -            node_type=node_type,
    -            node_version=node_version,
    -            node_data=node_data,
    -        )
    +    def with_graph_config(self, graph_config: Mapping[str, Any]) -> "MockNodeFactory":

    This is a false positive: MockNodeFactory.with_graph_config is an @override matching the production DifyNodeFactory.with_graph_config(self, graph_config: Mapping[str, Any]) signature (api/core/workflow/node_factory.py:456). It does not construct an ad-hoc dict or inspect keys here—it forwards graph_config directly to self._delegate.with_graph_config(graph_config). Changing the parameter type in the test override would violate Liskov substitution against the production NodeFactory protocol.

    MindOfqc MindOfqc commented on code on Nov 27, 2026 05:55 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -118,15 +118,18 @@ def disallow_subprocess(*_args: object, **_kwargs: object) -> None:
             if change == "schema":
                 document["components"] = {"schemas": {"KnowledgeSpace": {"type": "object"}}}
             elif change == "query":
    -            openapi_operation(document, "get")["parameters"].append(
    -                {"in": "query", "name": "limit", "schema": {"maximum": 200, "type": "integer"}}
    -            )
    +            get_operation = openapi_operation(document, "get")
    +            parameters = get_operation["parameters"]
    +            assert isinstance(parameters, list)
    +            parameters.append({"in": "query", "name": "limit", "schema": {"maximum": 200, "type": "integer"}})
             elif change == "body":
                 openapi_operation(document, "post")["requestBody"] = {
                     "content": {"application/json": {"schema": {"required": ["name"], "type": "object"}}}
                 }
             elif change == "response":
    -            responses = openapi_operation(document, "post")["responses"]
    +            post_operation = openapi_operation(document, "post")
    +            responses = post_operation["responses"]
    +            assert isinstance(responses, dict)

    I kept this fixture at the raw JSON boundary. The response mutation changes only the exported POST status from 200 to 201, writes the JSON to disk, and checks that the real CLI reports openapiSha256 drift. Production loads that same artifact with load_json_object; this case is about the lock detecting a file change, not about whether the response matches a separate OpenAPI model.

    MindOfqc MindOfqc commented on code on Nov 27, 2026 05:55 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -617,7 +626,7 @@ def test_validate_declarations_ignores_undeclared_operations() -> None:
                     "get": operation("knowledge-spaces:read", "listKnowledgeSpaces"),
                 },
                 "/internal-maintenance": {
    -                "head": {"responses": {"200": {}}},
    +                "head": {"responses": {"200": dict[str, object]()}},

    I kept this input deliberately minimal. The extra HEAD /internal-maintenance has no operationId and its 200 response is empty, so it does not meet the full OpenAPI Response Object requirements. The test checks that validate_declarations ignores the unrelated operation instead of walking its response. Pre-validating the whole fixture would reject that input before the declaration checker gets to exercise this behavior.

    MindOfqc MindOfqc commented on code on Nov 27, 2026 05:55 UTC
    Code Review
    api/tests/unit_tests/dev/test_generate_knowledge_fs_contract.py:1
    @@ -283,8 +292,8 @@ def test_validate_declarations_accepts_matching_contract() -> None:
         route["parameters"] = [{"in": "header", "name": "X-Trace-Id"}]
         route["responses"] = {
             "200": {
    -            "content": {"application/json": {}},
    -            "headers": {"X-Trace-Id": {}},
    +            "content": {"application/json": dict[str, object]()},

    I kept the media and header descriptor values empty here so the assertion is about the fields the real declaration checker reads: the application/json content key and the X-Trace-Id response header, alongside the request header. validate_declarations consumes the raw parsed document; a full descriptor model would add constraints unrelated to this matching test. The separate product manifest fixture now uses its production TypedDict.

    asukaminato0721 asukaminato0721 requested changes on Nov 30, 2026 11:18 UTC
    Changes Requested Reviewer

    This branch has conflicts with main: please rebase onto the latest main. Checked fb9b084fac.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=fb9b084face1f83dadb3a41540c07e9992fe425a;conflict=fb9b084face1f83dadb3a41540c07e9992fe425a -->

    Assignees
    MindOfqc MindOfqc
    Labels
    risk: low confidence: 93% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 38.4% (MEDIUM) · Higher = larger blast radius
    38.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 93% · Lower = rushed or shallow review
    93%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.7% · Safe to merge
    2.7%