refactor(api): read API tool providers through Session(db.engine) in ToolManager #47419
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,080 | +13 |
| Untyped symbols | 10,764 | 10,767 | +3 |
| Modules | 4974 | 4974 | 0 |
Codecov Report
:x: Patch coverage is
92.75362% with 5 lines in your changes missing coverage. Please review.:white_check_mark: Project coverage is 90.54%. Comparing base (
5d50d5f) to head (b89154a).:warning: Report is 1 commits behind head on main.
| Files with missing lines | Patch % | Lines |
|---|---|---|
| ...core/workflow/nodes/agent\_v2/dify\_tools\_builder.py | 0.00% | 2 Missing :warning: |
| api/services/data\_migration/export\_service.py | 60.00% | 1 Missing and 1 partial :warning: |
| api/services/tools/api\_tools\_manage\_service.py | 66.66% | 1 Missing :warning: |
<details><summary>Additional details and impacted files</summary>
@@ Coverage Diff @@
## main #47419 +/- ##
=======================================
Coverage 90.54% 90.54%
=======================================
Files 6897 6897
Lines 432401 432477 +76
Branches 86698 86702 +4
=======================================
+ Hits 391507 391591 +84
+ Misses 34069 34067 -2
+ Partials 6825 6819 -6
| Flag | Coverage Δ | |
|---|---|---|
| api | 90.09% <92.75%> (+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>
</details>
why do you change the permission? 100644 -> 100755
Please split this into smaller pull requests: it adds 1164 lines of non-test code, more than 300. Split it by feature: each pull request carries one functional change together with its tests, so each feature stands on its own and can be reviewed, merged and reverted independently. It will be reviewed once it is under 300. Size counts added non-test lines; tests, lock files and snapshots do not count.
<sub>dify-codereview</sub>
<!-- dify-review:head=f27bb149148e1a1f17caa90c03ae77de7de66f02;split=f27bb149148e1a1f17caa90c03ae77de7de66f02 -->
Good catch — that was an accident in my upload tooling, not an intentional change. The script I use to push commits inferred the executable bit from the local filesystem, and on Windows every file reports as executable, so the blob got mode 100755.
Fixed in 3a7d654: the file is back to 100644 and the diff no longer contains a mode change. Thanks for spotting it!
Pyrefly Diff
<details>
<summary>base → PR</summary>
--- /tmp/pyrefly_base.txt 2026-11-30 13:47:15.172819117 +0000
+++ /tmp/pyrefly_pr.txt 2026-11-30 13:46:55.487790864 +0000
@@ -1727,7 +1727,7 @@
ERROR Missing argument `endpoint_id` in function `controllers.console.workspace.endpoint.EndpointIdPayload.__init__` [missing-argument]
--> tests/unit_tests/controllers/console/workspace/test_endpoint.py:561:46
ERROR Argument `list[object]` is not assignable to parameter `parameters` with type `Iterable[Mapping[str, Any] | WorkflowToolParameterConfiguration]` in function `controllers.console.workspace.tool_providers.WorkflowToolCreatePayload.__init__` [bad-argument-type]
- --> tests/unit_tests/controllers/console/workspace/test_tool_providers.py:620:62
+ --> tests/unit_tests/controllers/console/workspace/test_tool_providers.py:621:62
ERROR Argument `Literal['file-id']` is not assignable to parameter `file_id` with type `UUID` in function `controllers.files.upload_file_delivery.ImagePreviewApi.get` [bad-argument-type]
--> tests/unit_tests/controllers/files/test_upload_file_delivery.py:101:53
ERROR Argument `Literal['file-id']` is not assignable to parameter `file_id` with type `UUID` in function `controllers.files.upload_file_delivery.ImagePreviewApi.get` [bad-argument-type]
@@ -3329,12 +3329,18 @@
--> tests/unit_tests/core/tools/test_tool_manager.py:1115:32
ERROR Argument `Literal['']` is not assignable to parameter `typ` with type `Literal['api', 'builtin', 'mcp', 'workflow'] | None` in function `core.tools.tool_manager.ToolManager.list_providers_from_api` [bad-argument-type]
--> tests/unit_tests/core/tools/test_tool_manager.py:1160:96
+ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1196:27
+ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1259:27
+ERROR Argument `(**_kwargs: Unknown) -> tuple[ProviderConfigEncrypter, NoOpProviderCredentialCache]` is not assignable to parameter `encrypter_factory` with type `ToolProviderEncrypterFactory` in function `core.tools.tool_manager.ToolManager.user_get_api_provider` [bad-argument-type]
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1283:27
ERROR `SimpleNamespace` is not assignable to attribute `entity` with type `ToolProviderEntityWithPlugin` [bad-assignment]
- --> tests/unit_tests/core/tools/test_tool_manager.py:1310:30
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1380:30
ERROR `SimpleNamespace` is not assignable to attribute `entity` with type `ToolProviderEntityWithPlugin` [bad-assignment]
- --> tests/unit_tests/core/tools/test_tool_manager.py:1334:30
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1404:30
ERROR Cannot index into `str` [bad-index]
- --> tests/unit_tests/core/tools/test_tool_manager.py:1339:20
+ --> tests/unit_tests/core/tools/test_tool_manager.py:1409:20
ERROR `None` is not subscriptable [unsupported-operation]
--> tests/unit_tests/core/tools/utils/test_message_transformer.py:155:16
ERROR Argument `Literal['not a dict']` is not assignable to parameter `d` with type `dict[str, Any]` in function `core.tools.utils.message_transformer.safe_json_dict` [bad-argument-type]
</details>
Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.
<sub>dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.</sub>
<!-- dify-review:rule=inject-session;key=18f85edb6278532e -->
Rather than patching this in the test, change the production code to take the dependency as a parameter (pass the session / account / service in), so the test hands in a real one and needs no patch.
<sub>dify-codereview · tests-real-dependencies (inject-dependency) Learned from an earlier review. Reply here if this is wrong.</sub>
<!-- dify-review:rule=tests-real-dependencies;option=inject-dependency;key=0c73b87c2895ed92 -->
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=74bbdd5ee3f8f211 -->
3 inline suggestions at 8c1fd8d5d3, 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=8c1fd8d5d3b4a5af03a894e1bbbc7eab0cb56326 -->
Please don't pin the exact calls here (assert_called_once_with and friends): that breaks on harmless refactors and only proves the mock was hit. Assert the general behaviour instead: what is returned, persisted, raised or emitted.
<sub>dify-codereview · tests-behavior-not-calls Reply here if this is wrong.</sub>
<!-- dify-review:rule=tests-behavior-not-calls;key=5756b33498bc8b45 -->
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=56efa1482dc2808f -->
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=1f735db7b105bd98 -->
Rather than patching this in the test, change the production code to take the dependency as a parameter (pass the session / account / service in), so the test hands in a real one and needs no patch.
<sub>dify-codereview · tests-real-dependencies (inject-dependency) Learned from an earlier review. Reply here if this is wrong.</sub>
<!-- dify-review:rule=tests-real-dependencies;option=inject-dependency;key=04c6237b22513940 -->
4 inline suggestions at bddaa71a98, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 1 review thread is still unresolved.
<sub>dify-codereview</sub>
<!-- dify-review:head=bddaa71a98ae72b394f4ad913cc10e24693c0e07 -->
This branch has conflicts with main: please rebase onto the latest main. Checked bddaa71a98.
<sub>dify-codereview</sub>
<!-- dify-review:head=bddaa71a98ae72b394f4ad913cc10e24693c0e07;conflict=bddaa71a98ae72b394f4ad913cc10e24693c0e07 -->
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=0e86836197230c4b -->
1 inline suggestion at 82146d4d9e, from a rule learned from earlier reviews in this repository. Reply on the comment if it is wrong. 1 review thread is still unresolved.
<sub>dify-codereview</sub>
<!-- dify-review:head=82146d4d9e380371381e4debae8456e6561f46d7 -->
Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.
<sub>dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.</sub>
<!-- dify-review:rule=inject-session;key=61a4f63ddcc75efe -->
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=a7de908bc88c5540 -->
2 inline suggestions at b89154a1d4, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong. 1 review thread is still unresolved.
<sub>dify-codereview</sub>
<!-- dify-review:head=b89154a1d4cdc32136b18f8e1c41d6a8b9b227cb -->
This one looks like a false positive — the flagged code is the boundary model. ApiToolBundleDict was introduced in b89154a specifically to answer the previous round of this rule: it defines the shape of ApiToolBundle.model_dump(mode="json") once in production code, the payload is validated at the boundary through the pydantic TypeAdapter (_api_tool_bundles_adapter.validate_python), and the tests import the TypedDict from production code instead of building ad-hoc dicts. No key/type re-checks remain at use sites. Happy to adjust if you had a different spot in mind.
Fully agreed with the rule for methods that own a transaction — that's why get_api_provider_controller now takes the session as a required parameter. This call site is different, though: get_tool_runtime is a classmethod dispatcher with five production callers (workflow tool node, node runtime, the draft-workflow event handler, and two service adapters), so there is no __init__ to inject into, and adding a required session/factory parameter would ripple through every caller — well beyond this PR's zero-signature-change scope. The branch also mirrors the adjacent WORKFLOW branch, which opens Session(db.engine) directly. On the testing side, the unit-test conftest binds the global factory to the pristine sqlite schema via an autouse fixture, so tests already run against real sessions with no per-test monkeypatching. If you'd like the full factory injection threaded through the dispatcher and all its callers, I'd gladly take it on as a follow-up PR rather than grow this one.
asukaminato0721
Mattenhaim
Summary
Part of #45584 (refactor: use sqlalchemy engine instead of the global
db.session).ToolManager's API tool provider read path still went through the globaldb.session:get_api_provider_controllerqueriedApiToolProviderviadb.session.scalar(...)and handeddb.session()toApiToolProviderController.from_db.user_get_api_providerdid the same for the tenant/name lookup and controller construction.list_providers_from_apiopened an explicitSession(db.engine)for its own queries but still passed a freshdb.session()intoapi_provider_to_user_provider.This PR routes all three through explicitly owned sessions:
with Session(db.engine) as session:, run the tenant-scoped query and the controller construction inside it — the same pattern already used byget_mcp_provider_controllerin this file.from_dbreceives that session and derives its lazy-load session factory from it (#46983).list_providers_from_apipasses its already-opensessiontoapi_provider_to_user_providerinstead of a new global one.core/tools/tool_manager.pyno longer referencesdb.sessionat all.Behavior is unchanged: same tenant filtering, credential parsing/masking, icon fallback, labels and
ToolProviderNotFoundError/ValueErrorpaths.Verification
pytest tests/unit_tests/core/tools/— 671 passed (including the existing real-SQLite tests forget_api_provider_controller,user_get_api_providerandlist_providers_from_apiintest_tool_manager.py, which cover this refactor without modification)pytest tests/unit_tests/services/data_migration/test_export_service.py— passed (call-site coverage)ruff checkandruff format --checkpass on the touched fileChecklist
make lint && make type-check(backend) — ranruff check/ruff format --checkon the touched file; fullmake type-checkrequires the heavyweight backend env.🤖 Prepared with AI assistance (Kimi), reviewed and tested locally by the author.