← Back to Pull requests

test(api): bring the openapi human input form and workspace tests under strict pyrefly #46420

Open
MindOfqc opened this pull request with 183 lines diff across 4 files
View on GitHub
MindOfqc MindOfqc commented on Nov 14, 2026 15:21 UTC
Author

Why


api/tests/unit_tests/pyrefly.toml still lists the OpenAPI human-input-form tests and the OpenAPI workspace tests as strict-mode debt. Neither needs a type suppression, so they should not stay on the list.

What changed


The bulk of the work is the __handler__ seam. controllers/openapi/_contract.py attaches __handler__ at decoration time, so it is missing from the decorated function's static type and every direct api.get.__handler__(...) call reported Object of class FunctionType has no attribute __handler__. A module-level _handler helper reads the attribute out of the instance dict and carries the view's real signature through Concatenate[object, P], which keeps the call sites typed instead of casting the result. Sixteen diagnostics across the two files disappear that way, with the assertions untouched.

The rest is annotations: test methods and fixtures declare their returns, the parametrised recipient_type / exc / expected arguments are typed, and the hint test narrows event["data"] through an isinstance check before indexing so the repeated event["data"]["inputs"] lookups stop reporting bad-index.

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/controllers/openapi/test_human_input_form.py \
  tests/unit_tests/controllers/openapi/test_workspaces.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

  • mutation check: reverting both files reproduces exactly 50 diagnostics

  • pytest: the same 62 pre-existing os.register_at_fork setup errors before and after (Windows-only, unrelated to these tests)

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

    Diff: 183 lines (+123 / -60) across 4 files Reviewer: asukaminato0721 Review duration: 24898m
    All Vouch review confidence checks passed
    Residual risk 0.03 = Change Risk (0.39) × (1 − Review Confidence (0.93)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.39 · 183 lines diff across 4 files
    0.39
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.96 · 5 substantive comment(s)
    0.96
    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.312
    Real PR Conversation Timeline
    39 items
    github-actions[bot] github-actions[bot] commented on Nov 14, 2026 15:24 UTC
    Bot

    Pyrefly Type Coverage

    | Metric | Base | PR | Delta |
    | --- | ---: | ---: | ---: |
    | Type coverage | 91.04% | 91.06% | +0.02% |
    | Strict coverage | 90.70% | 90.72% | +0.02% |
    | Typed symbols | 110,354 | 110,387 | +33 |
    | Untyped symbols | 10,902 | 10,874 | -28 |
    | Modules | 5111 | 5111 | 0 |

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

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 90.58%. Comparing base (5d50d5f) to head (64d3f7f).
    :warning: Report is 40 commits behind head on main.

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

    @@            Coverage Diff             @@
    ##             main   #46420      +/-   ##
    ==========================================
    + Coverage   90.54%   90.58%   +0.03%     
    ==========================================
      Files        6897     6953      +56     
      Lines      432401   440666    +8265     
      Branches    86698    87778    +1080     
    ==========================================
    + Hits       391507   399156    +7649     
    - Misses      34069    34459     +390     
    - Partials     6825     7051     +226     
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | api | 90.15% <ø> (+0.07%) | :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>

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

    Pyrefly Diff


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

    --- /tmp/pyrefly_base.txt	2026-12-01 10:03:08.671437531 +0000
    +++ /tmp/pyrefly_pr.txt	2026-12-01 10:02:55.459340379 +0000
    @@ -1896,40 +1896,6 @@
       --> tests/unit_tests/controllers/mcp/test_mcp.py:41:13
     ERROR Attribute `payload` of class `Namespace` is a read-only property and cannot be set [read-only]
       --> tests/unit_tests/controllers/mcp/test_mcp.py:61:5
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:129:20
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:148:17
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:161:17
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:179:22
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:206:22
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_human_input_form.py:232:20
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:244:14
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:271:14
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:341:14
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:416:9
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:500:9
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:531:14
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:566:9
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:584:13
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:587:13
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:618:14
    -ERROR Object of class `FunctionType` has no attribute `__handler__` [missing-attribute]
    -   --> tests/unit_tests/controllers/openapi/test_workspaces.py:732:9
     ERROR Object of class `FunctionType` has no attribute `__wrapped__` [missing-attribute]
        --> tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py:734:24
     ERROR Object of class `FunctionType` has no attribute `__wrapped__` [missing-attribute]
    
    

    </details>

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -66,7 +67,22 @@ def _context(caller: Account | EndUser, caller_role: CreatorUserRole) -> Context
         return ctx
     
     
    -def _mock_service(monkeypatch: pytest.MonkeyPatch, form) -> Mock:
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:
    +    """Return the undecorated view `@endpoint` stashed on the decorated one.
    +
    +    `_contract.py` attaches `__handler__` at decoration time, so it is absent from
    +    the wrapped function's static type; reading it out of the attribute dict keeps
    +    the access honest instead of suppressing the diagnostic. `Concatenate[object, P]`
    +    carries the instance the view is called with, mirroring how the decorator stores
    +    an unbound function.
    +    """
    +    view = type(api).__dict__[method]

    No reflection please (__dict__, vars, setattr, getattr, __getattr__): construct the object with its fields, or add a typed attribute or method.

    <sub>dify-codereview · no-reflection Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=no-reflection;key=25c6ed0ace81d75c -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -82,10 +84,25 @@ def openapi_app() -> Flask:
     
     
     @pytest.fixture
    -def database_session(sqlite_session: Session):
    +def database_session(sqlite_session: Session) -> Session:
         return sqlite_session
     
     
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:
    +    """Return the undecorated view `@endpoint` stashed on the decorated one.
    +
    +    `_contract.py` attaches `__handler__` at decoration time, so it is absent from
    +    the wrapped function's static type; reading it out of the attribute dict keeps
    +    the access honest instead of suppressing the diagnostic. `Concatenate[object, P]`
    +    carries the instance the view is called with, mirroring how the decorator stores
    +    an unbound function.
    +    """
    +    view = type(api).__dict__[method]

    No reflection please (__dict__, vars, setattr, getattr, __getattr__): construct the object with its fields, or add a typed attribute or method.

    <sub>dify-codereview · no-reflection Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=no-reflection;key=ff7f0832ffccca51 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -66,7 +67,22 @@ def _context(caller: Account | EndUser, caller_role: CreatorUserRole) -> Context
         return ctx
     
     
    -def _mock_service(monkeypatch: pytest.MonkeyPatch, form) -> Mock:
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=db46575229a5a14d -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -82,10 +84,25 @@ def openapi_app() -> Flask:
     
     
     @pytest.fixture
    -def database_session(sqlite_session: Session):
    +def database_session(sqlite_session: Session) -> Session:
         return sqlite_session
     
     
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=ce35e8c6545238a2 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -321,27 +342,30 @@ def _paused(*, form_token: str | None, inputs: list, actions: list) -> dict:
     
     
     class TestFormHints:
    -    def test_with_form_hints_adds_one_hint_per_action_targeting_the_submit_route(self):
    +    def test_with_form_hints_adds_one_hint_per_action_targeting_the_submit_route(self) -> None:
             event = _paused(
                 form_token="ft-1",
                 inputs=[ParagraphInputConfig(output_variable_name="comment")],
                 actions=[UserActionConfig(id="approve", title="批准"), UserActionConfig(id="reject", title="")],
             )
             [out] = list(with_form_hints(iter([f"data: {json.dumps(event)}\n\n"]), app_id="a1"))
             body = json.loads(out[len("data: ") :])
    +        data = event["data"]
    +        assert isinstance(data, 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=3b89cbe0402e9a65 -->

    asukaminato0721 asukaminato0721 commented on code on Nov 16, 2026 09:45 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -278,31 +295,35 @@ class TestCheckFormSurface:
         the handler body runs.
         """
     
    -    def _run(self, monkeypatch: pytest.MonkeyPatch, form) -> None:
    +    def _run(self, monkeypatch: pytest.MonkeyPatch, form: SimpleNamespace | None) -> None:
             _mock_service(monkeypatch, form)
             ctx = _context(_make_account(), CreatorUserRole.ACCOUNT)
             CheckFormSurface().run(ctx.subject, ctx, Mock())
     
    -    def test_admits_a_web_app_recipient(self, monkeypatch: pytest.MonkeyPatch):
    +    def test_admits_a_web_app_recipient(self, monkeypatch: pytest.MonkeyPatch) -> None:
             self._run(monkeypatch, _make_form(recipient_type=RecipientType.STANDALONE_WEB_APP))
     
         @pytest.mark.parametrize("recipient_type", [RecipientType.CONSOLE, RecipientType.BACKSTAGE, None])
    -    def test_refuses_a_recipient_this_surface_may_not_act_on(self, monkeypatch: pytest.MonkeyPatch, recipient_type):
    +    def test_refuses_a_recipient_this_surface_may_not_act_on(
    +        self, monkeypatch: pytest.MonkeyPatch, recipient_type: RecipientType | None
    +    ) -> None:
             with pytest.raises(RecipientSurfaceMismatch):
                 self._run(monkeypatch, _make_form(recipient_type=recipient_type))
     
         @pytest.mark.parametrize("form", [None, "foreign"])
         def test_leaves_a_form_the_caller_could_not_have_found_to_the_handlers_404(
    -        self, monkeypatch: pytest.MonkeyPatch, form
    -    ):
    +        self, monkeypatch: pytest.MonkeyPatch, form: str | None
    +    ) -> None:
             """Answering 403 on a console-bound form in another app would confirm the
             token exists; the handler's own 404 owns both cases.
             """
             foreign = _make_form(app_id=str(uuid.uuid4()), recipient_type=RecipientType.CONSOLE)
             self._run(monkeypatch, foreign if form == "foreign" else None)
     
     
    -def _paused(*, form_token: str | None, inputs: list, actions: list) -> dict:
    +def _paused(
    +    *, form_token: str | None, inputs: list[FormInputConfig], actions: list[UserActionConfig]
    +) -> 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=6d34c4493b0bfa81 -->

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

    6 inline suggestions at 360032b8a2, 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=360032b8a28974cc8d9514967107f56ea0f75d62 -->

    asukaminato0721 asukaminato0721 commented on Nov 30, 2026 11:18 UTC
    Reviewer

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

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

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 12:47 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -175,7 +192,7 @@ def _assert_validation_422(resp: TestResponse) -> None:
         ],
         ids=["invite.bad_email", "invite.extra_field", "role.extra_field"],
     )
    -def test_payload_models_reject(model: type[BaseModel], payload: dict[str, object]):
    +def test_payload_models_reject(model: type[BaseModel], payload: dict[str, object]) -> None:

    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=eb6995690981343e -->

    asukaminato0721 asukaminato0721 commented on Nov 30, 2026 12:47 UTC
    Reviewer

    CI is failing: Style Check / Python Style. Please fix it. 1 inline suggestion at 8839538d35, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 6 review threads are still unresolved.

    <sub>dify-codereview</sub>
    <!-- dify-review:head=8839538d35733b58eb4b4d4c2200e2bb5f33573d;ci=8839538d35733b58eb4b4d4c2200e2bb5f33573d -->

    MindOfqc MindOfqc commented on code on Nov 30, 2026 14:05 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -175,7 +192,7 @@ def _assert_validation_422(resp: TestResponse) -> None:
         ],
         ids=["invite.bad_email", "invite.extra_field", "role.extra_field"],
     )
    -def test_payload_models_reject(model: type[BaseModel], payload: dict[str, object]):
    +def test_payload_models_reject(model: type[BaseModel], payload: dict[str, object]) -> None:

    Updated in f3e8a85e. The cases now use raw JSON and the production model's model_validate_json, which fits because these inputs are intentionally invalid. Each case asserts the exact rejected field. The quota-race test now uses the existing typed handler helper instead of accessing __handler__ directly. All 66 targeted OpenAPI tests, scoped strict Pyrefly, and Ruff lint/format passed.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -66,7 +67,22 @@ def _context(caller: Account | EndUser, caller_role: CreatorUserRole) -> Context
         return ctx
     
     
    -def _mock_service(monkeypatch: pytest.MonkeyPatch, form) -> Mock:
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:
    +    """Return the undecorated view `@endpoint` stashed on the decorated one.
    +
    +    `_contract.py` attaches `__handler__` at decoration time, so it is absent from
    +    the wrapped function's static type; reading it out of the attribute dict keeps
    +    the access honest instead of suppressing the diagnostic. `Concatenate[object, P]`
    +    carries the instance the view is called with, mirroring how the decorator stores
    +    an unbound function.
    +    """
    +    view = type(api).__dict__[method]

    Fixed in 69ddd90cf9. The type(api).__dict__[method] / vars(view)["__handler__"] reflection in _handler is replaced by class Endpoint[T](Protocol) declaring __handler__: Callable[..., T] and __spec__: EndpointSpec (api/tests/unit_tests/controllers/openapi/test_human_input_form.py:75-85); call sites go through cast(Endpoint[Response], api.get).__handler__(...) / cast(Endpoint[FormSubmitResponse], api.post).__handler__(...).

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -82,10 +84,25 @@ def openapi_app() -> Flask:
     
     
     @pytest.fixture
    -def database_session(sqlite_session: Session):
    +def database_session(sqlite_session: Session) -> Session:
         return sqlite_session
     
     
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:
    +    """Return the undecorated view `@endpoint` stashed on the decorated one.
    +
    +    `_contract.py` attaches `__handler__` at decoration time, so it is absent from
    +    the wrapped function's static type; reading it out of the attribute dict keeps
    +    the access honest instead of suppressing the diagnostic. `Concatenate[object, P]`
    +    carries the instance the view is called with, mirroring how the decorator stores
    +    an unbound function.
    +    """
    +    view = type(api).__dict__[method]

    Fixed in 69ddd90cf9. Same change in test_workspaces.py: class Endpoint[T](Protocol) at line 100 replaces the __dict__ / vars() lookup, and each call site names the concrete return type.

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -66,7 +67,22 @@ def _context(caller: Account | EndUser, caller_role: CreatorUserRole) -> Context
         return ctx
     
     
    -def _mock_service(monkeypatch: pytest.MonkeyPatch, form) -> Mock:
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:

    Fixed in 69ddd90cf9. The old generic _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R] is gone. Each handler is cast to a concrete Endpoint — Endpoint[Response] for the form GET, Endpoint[FormSubmitResponse] for the submit POST, and cast(Endpoint[object], view).__spec__ (line 291) for the spec assertion — so no object-typed callable flows through the tests.

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -82,10 +84,25 @@ def openapi_app() -> Flask:
     
     
     @pytest.fixture
    -def database_session(sqlite_session: Session):
    +def database_session(sqlite_session: Session) -> Session:
         return sqlite_session
     
     
    +def _handler[**P, R](api: object, method: str) -> Callable[Concatenate[object, P], R]:

    Fixed in 69ddd90cf9. Likewise concrete per call site in test_workspaces.py: Endpoint[MemberListResponse] (GET ×2), Endpoint[MemberInviteResponse] (POST ×3), Endpoint[MemberActionResponse] (DELETE ×3 and PATCH ×3).

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -321,27 +342,30 @@ def _paused(*, form_token: str | None, inputs: list, actions: list) -> dict:
     
     
     class TestFormHints:
    -    def test_with_form_hints_adds_one_hint_per_action_targeting_the_submit_route(self):
    +    def test_with_form_hints_adds_one_hint_per_action_targeting_the_submit_route(self) -> None:
             event = _paused(
                 form_token="ft-1",
                 inputs=[ParagraphInputConfig(output_variable_name="comment")],
                 actions=[UserActionConfig(id="approve", title="批准"), UserActionConfig(id="reject", title="")],
             )
             [out] = list(with_form_hints(iter([f"data: {json.dumps(event)}\n\n"]), app_id="a1"))
             body = json.loads(out[len("data: ") :])
    +        data = event["data"]
    +        assert isinstance(data, dict)

    Fixed in 69ddd90cf9. _paused no longer returns a dict[str, object] that tests re-parse: it returns the production HumanInputRequiredResponse itself (test_human_input_form.py:327). The hint test reads the typed fields (event.data.inputs, field.model_dump(mode="json")) and serializes only where the SSE payload is actually needed — payload = json.dumps(event.model_dump(mode="json")) at line 354. The isinstance(data, dict) re-check is removed.

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    MindOfqc MindOfqc commented on code on Nov 30, 2026 17:29 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -278,31 +295,35 @@ class TestCheckFormSurface:
         the handler body runs.
         """
     
    -    def _run(self, monkeypatch: pytest.MonkeyPatch, form) -> None:
    +    def _run(self, monkeypatch: pytest.MonkeyPatch, form: SimpleNamespace | None) -> None:
             _mock_service(monkeypatch, form)
             ctx = _context(_make_account(), CreatorUserRole.ACCOUNT)
             CheckFormSurface().run(ctx.subject, ctx, Mock())
     
    -    def test_admits_a_web_app_recipient(self, monkeypatch: pytest.MonkeyPatch):
    +    def test_admits_a_web_app_recipient(self, monkeypatch: pytest.MonkeyPatch) -> None:
             self._run(monkeypatch, _make_form(recipient_type=RecipientType.STANDALONE_WEB_APP))
     
         @pytest.mark.parametrize("recipient_type", [RecipientType.CONSOLE, RecipientType.BACKSTAGE, None])
    -    def test_refuses_a_recipient_this_surface_may_not_act_on(self, monkeypatch: pytest.MonkeyPatch, recipient_type):
    +    def test_refuses_a_recipient_this_surface_may_not_act_on(
    +        self, monkeypatch: pytest.MonkeyPatch, recipient_type: RecipientType | None
    +    ) -> None:
             with pytest.raises(RecipientSurfaceMismatch):
                 self._run(monkeypatch, _make_form(recipient_type=recipient_type))
     
         @pytest.mark.parametrize("form", [None, "foreign"])
         def test_leaves_a_form_the_caller_could_not_have_found_to_the_handlers_404(
    -        self, monkeypatch: pytest.MonkeyPatch, form
    -    ):
    +        self, monkeypatch: pytest.MonkeyPatch, form: str | None
    +    ) -> None:
             """Answering 403 on a console-bound form in another app would confirm the
             token exists; the handler's own 404 owns both cases.
             """
             foreign = _make_form(app_id=str(uuid.uuid4()), recipient_type=RecipientType.CONSOLE)
             self._run(monkeypatch, foreign if form == "foreign" else None)
     
     
    -def _paused(*, form_token: str | None, inputs: list, actions: list) -> dict:
    +def _paused(
    +    *, form_token: str | None, inputs: list[FormInputConfig], actions: list[UserActionConfig]
    +) -> dict[str, object]:

    Fixed in 69ddd90cf9. _paused's return type changed from dict[str, object] (built via response.model_dump(mode="json")) to HumanInputRequiredResponse — the event is parsed once at the boundary into its production model and passed on typed, which is what this thread asked for.

    Evidence on that head: both files now use the same Endpoint Protocol + cast seam that test__app_response.py already uses — no __dict__ / vars() reflection remains in either file — and locally pytest tests/unit_tests/controllers/openapi/test_human_input_form.py tests/unit_tests/controllers/openapi/test_workspaces.py = 66 passed, ruff check + ruff format --check clean, scoped pyrefly check = 0 diagnostics.

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 23:17 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -126,7 +141,7 @@ def test_get_success(self, app: Flask, monkeypatch: pytest.MonkeyPatch):
     
             api = OpenApiWorkflowHumanInputFormApi()
             with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1"):
    -            resp = api.get.__handler__(
    +            resp = cast(Endpoint[Response], api.get).__handler__(

    Avoid cast: nothing checks it. Give the producer a precise return type, take the value as a typed parameter, or narrow with isinstance.

    <sub>dify-codereview · avoid-cast Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=avoid-cast;key=e3f4c8ffb652fe8d -->

    asukaminato0721 asukaminato0721 commented on code on Nov 30, 2026 23:17 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -241,7 +263,7 @@ def test_members_list_returns_normalized_rows(database_session: Session):
         members[0].name = "Mia"
         _persist_caller(database_session, acct_id)
     
    -    result = api.get.__handler__(
    +    result = cast(Endpoint[MemberListResponse], api.get).__handler__(

    Avoid cast: nothing checks it. Give the producer a precise return type, take the value as a typed parameter, or narrow with isinstance.

    <sub>dify-codereview · avoid-cast Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=avoid-cast;key=f8610e53648ff3b3 -->

    asukaminato0721 asukaminato0721 commented on Nov 30, 2026 23:17 UTC
    Reviewer

    CI is failing: Style Check / Python Style. Please fix it. 2 inline suggestions at 69ddd90cf9, 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=69ddd90cf9f6b1a97ca1010c9bc9d8ece9e41a35;ci=69ddd90cf9f6b1a97ca1010c9bc9d8ece9e41a35 -->

    MindOfqc MindOfqc commented on code on Dec 01, 2026 02:09 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_workspaces.py:1
    @@ -241,7 +263,7 @@ def test_members_list_returns_normalized_rows(database_session: Session):
         members[0].name = "Mia"
         _persist_caller(database_session, acct_id)
     
    -    result = api.get.__handler__(
    +    result = cast(Endpoint[MemberListResponse], api.get).__handler__(

    293ccb8f removes the new workspace test casts. The tests use the existing class-level handler through the shared runtime-checked helper and verify the actual response model before inspecting it. That leaves the invalid-request and error cases intact. All 66 focused tests passed, along with the full core type check and the no-new-cast and no-new-getattr guards.

    MindOfqc MindOfqc commented on code on Dec 01, 2026 02:09 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/test_human_input_form.py:1
    @@ -126,7 +141,7 @@ def test_get_success(self, app: Flask, monkeypatch: pytest.MonkeyPatch):
     
             api = OpenApiWorkflowHumanInputFormApi()
             with app.test_request_context("/openapi/v1/apps/app-1/human-input-forms/tok-1"):
    -            resp = api.get.__handler__(
    +            resp = cast(Endpoint[Response], api.get).__handler__(

    293ccb8f removes the new casts from the form tests. The shared test helper checks the existing class-level decorator seam at runtime, and the tests check the actual response types before reading fields. The same request, response, and error assertions still run. All 66 focused tests, the full core type check, and both repository guards passed.

    asukaminato0721 asukaminato0721 commented on code on Dec 01, 2026 03:32 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: object

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=70997d5799487c59 -->

    asukaminato0721 asukaminato0721 commented on Dec 01, 2026 03:32 UTC
    Reviewer

    1 inline suggestion at 293ccb8f2f, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

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

    MindOfqc MindOfqc commented on code on Dec 01, 2026 04:07 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: object

    Updated in f93981d5: __handler__ is now typed as Callable[..., object], matching the bare callable assigned by @endpoint. The endpoints accept different parameters, and the existing runtime callable check remains. All 66 focused tests, strict Pyrefly, Ruff, and the scoped guards passed locally.

    asukaminato0721 asukaminato0721 commented on code on Dec 01, 2026 04:17 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: object

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=5f288c2803d66ba6 -->

    asukaminato0721 asukaminato0721 commented on Dec 01, 2026 04:17 UTC
    Reviewer

    1 inline suggestion at f93981d59c, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

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

    MindOfqc MindOfqc commented on code on Dec 01, 2026 06:13 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: object

    Fixed at head 5bde6a5af1: _DecoratedEndpoint.__spec__ is now annotated as EndpointSpec (imported from controllers.openapi.auth.spec) instead of object, which is exactly the instance @endpoint attaches at api/controllers/openapi/_contract.py:289. The isinstance(spec, EndpointSpec) narrowing in openapi_endpoint_spec therefore became redundant and was dropped, so the helper now returns the precise type directly.

    Verified on the new head: ruff format --check and ruff check clean, pyrefly check reports 0 diagnostics for the file.

    asukaminato0721 asukaminato0721 commented on code on Dec 01, 2026 06:16 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: EndpointSpec
    +
    +
    +def openapi_handler(view: object) -> Callable[..., object]:

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=79122a2839ef4eab -->

    asukaminato0721 asukaminato0721 commented on Dec 01, 2026 06:16 UTC
    Reviewer

    1 inline suggestion at 5bde6a5af1, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

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

    MindOfqc MindOfqc commented on code on Dec 01, 2026 08:04 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: EndpointSpec
    +
    +
    +def openapi_handler(view: object) -> Callable[..., object]:

    Updated in 38c76564: openapi_handler now takes a callable, matching the class-level routes passed to it. The bare handlers have different signatures and response types, so the helper returns a callable and each test narrows the response it expects. The runtime checks are unchanged. All 66 affected tests and scoped strict Pyrefly passed locally.

    asukaminato0721 asukaminato0721 commented on code on Dec 01, 2026 08:17 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: EndpointSpec
    +
    +
    +def openapi_handler(view: Callable[..., object]) -> Callable[..., object]:
    +    """Read the bare handler from the decorated function on the route class."""
    +    assert isinstance(view, _DecoratedEndpoint)
    +    handler = view.__handler__
    +    assert callable(handler)
    +    return handler
    +
    +
    +def openapi_endpoint_spec(view: object) -> EndpointSpec:

    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.

    <sub>dify-codereview · precise-types (concrete-type) Learned from an earlier review. Reply here if this is wrong.</sub>
    <!-- dify-review:rule=precise-types;option=concrete-type;key=c97058efe4ba432d -->

    asukaminato0721 asukaminato0721 commented on Dec 01, 2026 08:17 UTC
    Reviewer

    1 inline suggestion at 38c7656476, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong.

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

    MindOfqc MindOfqc commented on code on Dec 01, 2026 10:01 UTC
    Code Review
    api/tests/unit_tests/controllers/openapi/conftest.py:1
    @@ -23,6 +25,30 @@
     from models.model import AppMode, IconType
     
     
    +@runtime_checkable
    +class _DecoratedEndpoint(Protocol):
    +    """Metadata attached by the documented `@endpoint` test seam."""
    +
    +    __handler__: Callable[..., object]
    +    __spec__: EndpointSpec
    +
    +
    +def openapi_handler(view: Callable[..., object]) -> Callable[..., object]:
    +    """Read the bare handler from the decorated function on the route class."""
    +    assert isinstance(view, _DecoratedEndpoint)
    +    handler = view.__handler__
    +    assert callable(handler)
    +    return handler
    +
    +
    +def openapi_endpoint_spec(view: object) -> EndpointSpec:

    Updated in 64d3f7f3: openapi_endpoint_spec now accepts Callable[..., object], matching the decorated route functions its callers supply. It still returns the production EndpointSpec, and the runtime checks are unchanged. Both affected suites passed (66 tests); scoped strict Pyrefly and Ruff passed as well.

    asukaminato0721 asukaminato0721 commented on Dec 01, 2026 11:02 UTC
    Reviewer

    Nothing to flag at 64d3f7f315.

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

    Assignees
    MindOfqc MindOfqc
    Labels
    risk: low confidence: 93.4% 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.6% (MEDIUM) · Higher = larger blast radius
    38.6%
    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.4% · Lower = rushed or shallow review
    93.4%
    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.5% · Safe to merge
    2.5%