Skip to content

test(api): bring streaming utility tests under strict pyrefly - #46457

Open
MindOfqc wants to merge 16 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-streaming-plugin-daemon-service-api
Open

MindOfqc wants to merge 16 commits into
langgenius:mainfrom
MindOfqc:test/pyrefly-streaming-plugin-daemon-service-api

Conversation

@MindOfqc

@MindOfqc MindOfqc commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enable strict Pyrefly checking for test_streaming_utils.py. Type the streaming event iterators and test subscription doubles together so the existing stream retrieval and subscription coverage can run under the strict configuration.

This PR is now limited to streaming utilities. The plugin, service API/OpenAPI, and dataset retriever changes are not in the current diff.

Verification

  • pytest on test_streaming_utils.py and test_base_app_generator.py: 63 passed.
  • Ruff lint and formatting: passed for all five changed Python files.
  • Strict unit-test Pyrefly: same 25 missing-optional-dependency diagnostics as the local base, none in the changed streaming suite.

Graduate `test_streaming_utils`, `test_plugin_daemon`, the service-api
package `__init__` and `test_dataset_multi_retriever_tool` out of the
`project-excludes` list by dropping the type suppressions they relied on.

The fakes now extend the real classes they stand in for, `current_app` is
patched with the real `LocalProxy` instead of a hand-written stand-in, and
the assertions that inspected untyped mappings go through small narrowing
helpers. One assertion that only reached the unreachable `else` branch of
`CredentialType.get_name` was dropped together with the fabricated enum
value it needed: every caller passes a declared member, so the branch
cannot be observed from a real object.
@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-28 04:04:57.969318224 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-28 04:04:47.293279938 +0000
@@ -3254,50 +3254,6 @@
    --> tests/unit_tests/core/app/apps/test_base_app_runner.py:821:17
 ERROR Argument `TestAppRunner.test_handle_multimodal_image_content_fallback_return_branch._ToggleBool` is not assignable to parameter `base64_data` with type `str` in function `graphon.model_runtime.entities.message_entities.ImagePromptMessageContent.model_construct` [bad-argument-type]
    --> tests/unit_tests/core/app/apps/test_base_app_runner.py:822:25
-ERROR Class member `FakePreparedSubscriber.prepare_subscription` overrides parent class `SupportsPreparedSubscription` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:125:9
-ERROR Class member `FakePreparedSubscriber.subscribe` overrides parent class `SupportsPreparedSubscription` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:129:9
-ERROR Class member `FailingPreparedSubscriber.prepare_subscription` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:134:9
-ERROR Class member `FakePreparedTopic.as_subscriber` overrides parent class `FakeTopic` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:143:9
-ERROR Class member `FakePreparedTopic.as_subscriber` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:143:9
-ERROR Class member `FailingPreparedTopic.as_subscriber` overrides parent class `FakeTopic` in an inconsistent manner [bad-override]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:153:9
-ERROR Class member `FailingPreparedTopic.as_subscriber` overrides a member in a parent class but is missing an `@override` decorator [missing-override-decorator]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:153:9
-ERROR Cannot index into `str` [bad-index]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:183:12
-ERROR Cannot index into `str` [bad-index]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:209:12
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:250:22
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:267:22
-ERROR Cannot index into `str` [bad-index]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:273:12
-ERROR Cannot index into `str` [bad-index]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:274:12
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:289:52
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:305:26
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:360:56
-ERROR Argument `Literal['session']` is not assignable to parameter `type` with type `EndUserType | SQLCoreOperations[EndUserType]` in function `models.model.EndUser.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:383:48
-ERROR Argument `Literal[core.app.entities.app_invoke_entities.InvokeFrom.WEB_APP]` is not assignable to parameter `invoke_from` with type `models.enums.InvokeFrom | SQLCoreOperations[models.enums.InvokeFrom | None] | None` in function `models.model.Message.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:393:21
-ERROR Argument `str | None` is not assignable to parameter `workflow_run_id` with type `UUID | str` in function `tasks.app_generate.workflow_execute_task._publish_streaming_response` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:452:9
-ERROR Argument `FakeSubscription` is not assignable to parameter `subscription` with type `Subscription` in function `core.app.apps.streaming_utils.stream_topic_events` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:461:52
-ERROR Argument `Literal[graphon.enums.WorkflowType.CHAT]` is not assignable to parameter `workflow_type` with type `models.workflow.WorkflowType` in function `tests.helpers.unit.model_factories.make_workflow` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:518:23
-ERROR Argument `Literal['session']` is not assignable to parameter `type` with type `EndUserType | SQLCoreOperations[EndUserType]` in function `models.model.EndUser.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/app/apps/test_streaming_utils.py:533:67
 ERROR Argument `Mapping[str, Any] | None` is not assignable to parameter `graph_config` with type `Mapping[str, Any]` in function `core.workflow.workflow_entry.WorkflowEntry.__init__` [bad-argument-type]
    --> tests/unit_tests/core/app/apps/test_workflow_app_runner.py:145:39
 ERROR No matching overload found for function `dict.get` called with arguments: (dict[str, int | list[Unknown] | str] | dict[str, list[str] | str] | dict[str, list[Unknown] | str] | dict[str, str] | str, Literal['']) [no-matching-overload]

@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 88.05% 88.06% +0.01%
Strict coverage 87.69% 87.70% +0.01%
Typed symbols 98,721 98,734 +13
Untyped symbols 13,450 13,437 -13
Modules 4713 4713 0

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.47368% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.62%. Comparing base (b2cfc31) to head (4a711af).
⚠️ Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
api/core/app/apps/streaming_utils.py 77.77% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #46457   +/-   ##
=======================================
  Coverage   90.62%   90.62%           
=======================================
  Files        6665     6665           
  Lines      415303   415329   +26     
  Branches    83292    83291    -1     
=======================================
+ Hits       376363   376391   +28     
+ Misses      32556    32553    -3     
- Partials     6384     6385    +1     
Flag Coverage Δ
api 90.35% <89.47%> (+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.

}


def _mapping(value: object) -> dict[str, object]:

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.

type dict

Replace the four module-level helpers (_mapping, _listing, _path,
_branches) with explicit intermediates plus assert isinstance(...) at
each call site, matching the 21 assertions the module already used.

The helpers only existed because json.loads returns Any; nothing in the
production code was widened, so there is no origin annotation to
tighten. dict[str, Any] is not an option either: the unit-test lint
config bans typing.Any, which points callers at object plus narrowing.
@MindOfqc

Copy link
Copy Markdown
Contributor Author

Typed the payloads at each call site, and dropped the helpers.

_mapping, _listing, _path and _branches are gone. Every site now reads the key into a local and narrows it with assert isinstance(...) before indexing, which is what the rest of the module already did in 21 places:

components = payload["components"]
assert isinstance(components, dict)
schemas = components["schemas"]
assert isinstance(schemas, dict)
resolved = schemas[schema_name]

The helpers only existed to hide json.loads -> Any; the fixture reads a file into str, generate_specs(output_dir: Path) -> list[Path] is already precise, so there was no widened annotation in the production code to fix. dict[str, Any] is not available as the shortcut: api/tests/unit_tests/.ruff.toml bans typing.Any and points at object plus narrowing.

Assertions are unchanged — 42 tests still pass, pyrefly reports the same 29 pre-existing missing-import lines and nothing else.

schema_name = ref.removeprefix("#/components/schemas/")
resolved = payload["components"]["schemas"][schema_name]
components = payload["components"]
assert isinstance(components, dict)

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.

typeddict , put into origin code if possible.

@asukaminato0721 asukaminato0721 self-assigned this Nov 16, 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.

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

dify-codereview

@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 c4894df02c, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

The service API contract tests unloaded the rendered OpenAPI JSON into
dict[str, object] and re-checked every key and value type where they were
used, which is validation spread across the test bodies. This change moves
the document shape into libs/openapi_document.py: the raw payload is parsed
once at the boundary, and the tests then read paths, schemas, operations,
parameters, properties, required fields and anyOf variants through typed
accessors.

It also follows the review on the other two files: the parametrized cases
in test_plugin_daemon.py now declare the union of the case types instead of
object, the file-system retriever helper spells out its keyword parameters,
and the case that only re-checked a type error the type checker already
rejects is gone.
@github-actions github-actions Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Nov 16, 2026
@MindOfqc

Copy link
Copy Markdown
Contributor Author

All four parse-dont-validate notes are addressed by moving the shape into production code: api/libs/openapi_document.py now defines the OpenAPI document as TypedDicts (OpenAPIDocument/OpenAPIOperation/OpenAPISchema/…) and exposes parse_openapi_document(), which parses at the boundary once and returns the typed value. _is_openapi_document is a TypeGuard, so no cast is involved. In the test the 30 json.loads(...) calls became parse_openapi_document(...), the 47 assert isinstance(...) line-peels are gone, and the helpers now take/return the TypedDicts.

For precise-types in test_plugin_daemon.py: the nine object annotations became the actual payload unions (int | str | None, int | float | str, list[object] | dict[str, str], …) via two aliases, SelectorValue and ParsedCollection.

For no-test-for-type-errors: test_request_invoke_llm_prompt_messages_must_be_list is deleted — a str where a list is declared is what the type checker already rejects.

For the **kwargs note: fake_retriever now spells out its five parameters with types. One caveat worth stating plainly — the names have to match production (_ImmediateThread forwards by keyword), so the three unused ones would trip ARG001; I extended the existing per-file ignore for that file in tests/unit_tests/.ruff.toml from ["ARG002"] to ["ARG001", "ARG002"], matching the precedent already in this PR for test_streaming_utils.py.

Verification: pyrefly strict mode on tests/unit_tests/pyrefly.toml reports 29 diagnostics, all of them the local missing-import baseline, with zero hits in the touched files; 129 passed (the 130 baseline minus the one deleted test); ruff check and format clean; pure LF; no new ignore/cast/Mock/getattr/__new__.

@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 cb183fc35f, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

Comment thread api/libs/openapi_document.py Resolved
The typed accessors that replaced the per-test peeling were only exercised
indirectly, so the changed-line coverage gate failed on them.  Cover the
parsing boundary and each accessor, including the paths that reject a document
whose shape the format does not allow.

@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 a989843509, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 4 earlier suggestions are still open.

dify-codereview

Comment thread api/libs/openapi_document.py Resolved
asukaminato0721

This comment was marked as outdated.

@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
…-api

Both sides only moved lines in the pyrefly exclude list: this branch
graduates its own test files while upstream graduates different ones.
Keep both removals and upstream's new entry.

@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 9bc36dfbd4, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 10 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 16, 2026
Address the review notes on PR langgenius#46457 without suppressing types:
- openapi_document: validate document lookups through pydantic parsing instead
  of isinstance-then-assume paths, and expose precise return shapes so callers
  no longer re-check or cast
- streaming_utils / message_generator / task_entities / parameters: replace the
  loose dict[str, object] views with the real payload types
- tests assert returned and raised behaviour via real collaborators instead of
  pinned 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.

1 inline suggestion at 22fcc125a3, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 2 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 25, 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
Preserve both branches’ Pyrefly exclusion removals and remove the synchronous test-only Thread stand-in.

@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 67f13df7ec, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 2 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 25, 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 27, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up to the conflict review: merged current main into this branch at c34a4ac4 without rewriting history. The streaming test retains the import it uses, and all four intended strict-Pyrefly exclusion removals are preserved. GitHub reports the branch mergeable. Locally, 180 tests passed across the affected API, streaming, plugin, dataset-retriever, and OpenAPI modules. The four migrated modules passed scoped strict Pyrefly and Ruff passed for the conflict file. Hosted CI is being checked on the new 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 27, 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 27, 2026
@github-actions github-actions Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Nov 28, 2026
@MindOfqc MindOfqc changed the title test(api): bring streaming, plugin daemon and service-api tests under strict pyrefly test(api): bring streaming utility tests under strict pyrefly Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the scope review. 4a711afd limits this PR to the streaming utilities and their tests: 39 added non-test lines across six changed files. The plugin, service API/OpenAPI, and dataset retriever changes are out of the current diff. Locally, 63 focused tests and Ruff lint/format passed, and strict Pyrefly reported no diagnostics in the streaming suite (the same 25 optional-dependency errors as the base elsewhere).

Copy link
Copy Markdown
Contributor Author

Could a maintainer rerun just the API Integration Tests job for 4a711afd? Its only failed test was test_jinja2_with_code_template: the sandbox returned a timeout and killed the process (2,182 passed, 22 skipped). Both API unit shards, the controller tests, browser E2E and the Python style checks passed. I don’t have Actions write permission on this repository.

@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. Checked 4a711afd9e. 2 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 28, 2026
@asukaminato0721
asukaminato0721 dismissed their stale review November 28, 2026 04:16

Small enough to review: the split request no longer applies.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 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