Repository navigation
refactor(api): use explicit sessions in ApiToolManageService - #45587
matheussilvano wants to merge 3 commits into
Conversation
Replace the two remaining db.session() calls in api_tools_manage_service.py with short-lived sessionmaker(db.engine).begin() sessions, matching the other session blocks in the same module. The sessions only serve the provider's user lookup, so transactions stay short. Part of langgenius#45584
Pyrefly Diffbase → PR--- /tmp/pyrefly_base.txt 2026-11-07 03:22:49.202277234 +0000
+++ /tmp/pyrefly_pr.txt 2026-11-07 03:22:37.362229245 +0000
@@ -6096,6 +6096,8 @@
--> tests/unit_tests/services/test_workflow_service.py:3945:24
ERROR Argument `dict[str, str | dict[str, str]]` is not assignable to parameter `node_config` with type `NodeConfigDict` in function `services.workflow_service.WorkflowService._build_human_input_node_for_debugging` [bad-argument-type]
--> tests/unit_tests/services/test_workflow_service.py:3976:69
+ERROR Argument `list[_Provider]` is not assignable to parameter `rows` with type `list[object] | None` in function `_RecordedSession.__init__` [bad-argument-type]
+ --> tests/unit_tests/services/tools/test_api_tools_manage_service.py:119:36
ERROR Object of class `MCPToolProvider` has no attribute `provider_icon` [missing-attribute]
--> tests/unit_tests/services/tools/test_tools_transform_service.py:82:9
ERROR Object of class `MCPToolProvider` has no attribute `masked_server_url` [missing-attribute]
|
Pyrefly Type Coverage
|
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #45587 +/- ##
==========================================
+ Coverage 89.88% 89.95% +0.07%
==========================================
Files 6245 6259 +14
Lines 391154 391792 +638
Branches 78435 78467 +32
==========================================
+ Hits 351575 352454 +879
+ Misses 33481 33250 -231
+ Partials 6098 6088 -10
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ice session tests Signed-off-by: matheussilvano2005@gmail.com <matheussilvano2005@gmail.com>
…ol_preview The console controller now opens the session and the service uses it, as the review asked. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| return self._rows | ||
|
|
||
|
|
||
| class _RecordedSession: |
asukaminato0721
left a comment
There was a problem hiding this comment.
CI is failing: Style Check / Python Style. Please fix it. 2 inline suggestions at 97cb081395, 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.
dify-codereview
| def _patch_database(monkeypatch: pytest.MonkeyPatch, sessions: list[_RecordedSession]) -> _RecordingSessionMaker: | ||
| """Route sessions through ``_RecordingSessionMaker`` and fail on any use of the global scoped session.""" | ||
| maker = _RecordingSessionMaker(sessions) | ||
| monkeypatch.setattr(api_tools_manage_service, "sessionmaker", maker) |
There was a problem hiding this comment.
Please use the shared sqlite_session fixture with real rows (session.add(Model(...))) instead of a hand-built database or a mocked session.
dify-codereview · tests-real-dependencies (use-sqlite-session) Learned from an earlier review. Reply here if this is wrong.
|
|
||
|
|
||
| class _Encrypter: | ||
| def decrypt(self, credentials: dict[str, object]) -> dict[str, object]: |
There was a problem hiding this comment.
Parse, don't validate (https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/): model this data once at the boundary as a pydantic model / dataclass / TypedDict (Model.model_validate(raw)), and pass the typed value on, instead of passing dicts around and re-checking keys and types where they are used. In a test, don't build this as an ad hoc dict[str, object]: define the shape (TypedDict / model) in the production code and import it here.
dify-codereview · parse-dont-validate Learned from an earlier review. Reply here if this is wrong.
Part of #45584 (first step; this does not close the issue).
Summary
api/services/tools/api_tools_manage_service.pystill passed the global scoped session (db.session()) in two places, while the rest of the module already usessessionmaker(db.engine, expire_on_commit=False).begin(). This PR replaces both:test_api_tool_preview:ApiToolProviderController.from_db(..., session=...)now gets a short-lived explicit session.list_api_tools:ToolTransformService.api_provider_to_user_provider(..., session=...)gets a short-lived explicit session opened per provider.In both cases the session is only used for the provider's user lookup (
db_provider.user(session=...)), so the transactions stay short and no tool/label work runs inside them, asdocs/BACKEND_SQLALCHEMY.mdasks. No behavior change is intended.Left for follow-ups from the list in the issue:
tools_transform_service.py(api_provider_to_controller,mcp_*helpers; they have more callers, including tests) and the other files.Contract (per
api/AGENTS.md)db.engineis bound, as for the othersessionmakerblocks in this module.db.session(); each session is closed when itswithblock exits, and the returned values are unchanged.Tests
Added to
tests/unit_tests/services/tools/test_api_tools_manage_service.py; they swapsessionmakeranddbfor fakes and fail ifdb.session()is called:list_api_toolspasses a distinct explicit session per provider.test_api_tool_previewbuilds the controller with an explicit session.Both new tests fail on
mainand pass with this change. Also run locally:tests/unit_tests/services/tools,tests/unit_tests/controllers/console/workspace/test_tool_providers.pyandtests/unit_tests/core/tools(782 passed);ruff format --checkandruff checkon the changed files pass;pyrefly checkon the two changed files reports only informational diagnostics. I did not run the fullmake lint && make type-check, and did not run the Docker-based e2e suites.Screenshots
N/A (backend refactor).
Checklist
make lint && make type-check: ranruffandpyreflyon the changed files only (see above).From Claude Code