Skip to content

refactor(api): use explicit sessions in ApiToolManageService - #45587

Open
matheussilvano wants to merge 3 commits into
langgenius:mainfrom
matheussilvano:refactor/api-tools-manage-service-explicit-session
Open

matheussilvano wants to merge 3 commits into
langgenius:mainfrom
matheussilvano:refactor/api-tools-manage-service-explicit-session

Conversation

@matheussilvano

Copy link
Copy Markdown

Part of #45584 (first step; this does not close the issue).

Summary

api/services/tools/api_tools_manage_service.py still passed the global scoped session (db.session()) in two places, while the rest of the module already uses sessionmaker(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, as docs/BACKEND_SQLALCHEMY.md asks. 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)

  • Precondition: db.engine is bound, as for the other sessionmaker blocks in this module.
  • Postcondition: neither method calls db.session(); each session is closed when its with block exits, and the returned values are unchanged.

Tests

Added to tests/unit_tests/services/tools/test_api_tools_manage_service.py; they swap sessionmaker and db for fakes and fail if db.session() is called:

  • list_api_tools passes a distinct explicit session per provider.
  • test_api_tool_preview builds the controller with an explicit session.

Both new tests fail on main and pass with this change. Also run locally: tests/unit_tests/services/tools, tests/unit_tests/controllers/console/workspace/test_tool_providers.py and tests/unit_tests/core/tools (782 passed); ruff format --check and ruff check on the changed files pass; pyrefly check on the two changed files reports only informational diagnostics. I did not run the full make lint && make type-check, and did not run the Docker-based e2e suites.

Screenshots

N/A (backend refactor).

Checklist

  • This change does not require a documentation update.
  • I understand that this PR may be closed in case there was no previous discussion or issues. (Linked to [Chore/Refactor] use sqlalchemy engine #45584.)
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I ran make lint && make type-check: ran ruff and pyrefly on the changed files only (see above).

From Claude Code

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
@github-actions github-actions Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Nov 4, 2026
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → 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]

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 83.97% 83.98% +0.00%
Strict coverage 83.63% 83.63% +0.00%
Typed symbols 87,711 87,717 +6
Untyped symbols 16,808 16,807 -1
Modules 4422 4422 0

@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.50000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.95%. Comparing base (0d97e36) to head (97cb081).
⚠️ Report is 463 commits behind head on main.

Files with missing lines Patch % Lines
...pi/controllers/console/workspace/tool_providers.py 0.00% 3 Missing ⚠️
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     
Flag Coverage Δ
api 89.80% <62.50%> (+0.12%) ⬆️

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.

…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:

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.

use real session

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

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)

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.

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]:

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.

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.

@asukaminato0721 asukaminato0721 added the waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address label Nov 17, 2026
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