Skip to content

[Chore/Refactor] use sqlalchemy engine #45584

Open

Description

@asukaminato0721

Yes. As of the November 4 checkout, these files still have direct db.session usage beyond cleanup. Paths are relative to api/; this is a verified shortlist, not an exhaustive backlog:

File Remaining usage
core/agent/base_agent_runner.py Adds, commits and queries agent thoughts. [1]
core/app/apps/agent_app/app_runner.py Reads, deletes and commits agent thoughts. [2]
core/provider_manager.py Looks up the tenant’s default model. [3]
core/rag/embedding/cached_embedding.py Queries the embedding cache. [4]
services/tools/api_tools_manage_service.py Passes db.session() into provider construction. [5]
services/tools/tools_transform_service.py Uses the global session for provider construction and user lookups. [6] [7]
services/workflow_run_service.py Passes db.session() into execution-trace assembly. [8]
models/workflow.py _resolve_workflow_app_tenant_id() queries through the global session. [9]
tasks/initialize_created_app_rbac_access_task.py Owner lookup and resource batching use db.session(). [10] [11]

I’d start with the two tool-service files: thread the caller’s session into those helpers, following #35934’s endpoint-owned session and downstream injection pattern. The shared @with_session decorator already provides that controller boundary. [12] [13]

For the eventual dependency removal, models/engine.py still constructs Flask-SQLAlchemy’s SQLAlchemy object. That is separate from converting individual callers. [14] [15]

To reply, just mention @dosu.


Docs are dead. Just use Dosu.

Leave Feedback Ask Dosu about dify

Originally posted by @dosubot in #24138

Activity

  1. added
    good first issue
    on Nov 4, 2026
  2. matheussilvano commented on Nov 4, 2026

    @matheussilvano

    I opened #45587 as a first step: it moves the two remaining db.session() calls in api_tools_manage_service.py to explicit short-lived sessions. tools_transform_service.py and the other files from the list are not touched yet; I can follow up on those next.

  3. paulhuiseismic commented on Nov 5, 2026

    @paulhuiseismic
    Contributor

    Hi there, I will take the workflow_run_service.py and initialize_created_app_rbac_access_task.py, and have the PR opening soon. cc: @asukaminato0721

  4. zuizhuai commented on Nov 6, 2026

    @zuizhuai
    Contributor

    Opened #45711 for the first file on this list — services/tools/tools_transform_service.py.

    Both MCP transformers (mcp_provider_to_user_provider, mcp_tool_to_user_tool) now take a keyword-only session and read the provider owner through it, so the internal provider → tool hop forwards the caller's session instead of reopening the global one. Call sites: the two controller endpoints pass the session they already opened, MCPToolManageService passes self._session.

    api_provider_to_controller() is left unchanged — it is handed a session-bound controller by its caller rather than opening a session itself, so it does not have the same problem.

    Happy to continue with services/tools/api_tools_manage_service.py once this shape looks right.

  5. paulhuiseismic commented on Nov 6, 2026

    @paulhuiseismic
    Contributor

    Hi there, the workflow_run_service.py and initialize_created_app_rbac_access_task.py have been refactored. And next I will pick up below places as the follow up actions to avoid any conflict.

    • models/workflow.py
    • core/rag/embedding/cached_embedding.py
    • core/provider_manager.py
  6. ojasarora77 commented on Nov 8, 2026

    @ojasarora77
    Contributor

    Taking api/events/event_handlers/update_app_dataset_join_when_app_published_workflow_updated.py as a non-overlapping slice.

    Plan: match the sibling update_app_dataset_join_when_app_model_config_updated pattern — require the caller-provided session (already passed from WorkflowService.publish) and stop using/committing the global db.session.

  7. ojasarora77 commented on Nov 8, 2026

    @ojasarora77
    Contributor

    Taking api/events/event_handlers/clean_when_dataset_deleted.py as a non-overlapping slice.

    Plan: require the caller-provided session (already available in DatasetService.delete_dataset) instead of opening db.session(), and pass session=session at the send site.

  8. Winkless213 commented on Nov 9, 2026

    @Winkless213

    Taking api/events/event_handlers/sync_knowledge_fs_bindings_when_app_published_workflow_updated.py. It handles the same signal as #45838 but is a separate file, so no overlap.

    Plan: the only sender, WorkflowService.publish_workflow, always passes session, so the fallback to the global db.session and the publish_session is None branch are never reached. I'll make session a required keyword argument (same as update_app_dataset_join_when_app_model_config_updated), remove the fallback and the db import, and add tests for the path where the workflow has no control spaces.

  9. ojasarora77 commented on Nov 10, 2026

    @ojasarora77
    Contributor

    Taking api/events/event_handlers/update_provider_when_message_created.py as a non-overlapping slice.

    Plan: require the caller-provided session instead of opening db.session() for credit deduction, and pass session=session from the message_was_created send sites in easy_ui_based_generate_task_pipeline (where _save_message already owns a session).

  10. salmoniscute commented on Nov 11, 2026

    @salmoniscute
    Contributor

    Taking api/core/rag/extractor/pdf_extractor.py, word_extractor.py and notion_extractor.py as a non-overlapping slice.

    Plan: when no caller session is passed, PdfExtractor / WordExtractor fall back to the global db.session; replace that fallback with a session_factory.create_session() scope that owns its commit, keeping the caller-owned path unchanged (caller commits). Move NotionExtractor.update_last_edited_time off db.session the same way. Update the existing unit tests for both session paths.

  11. vaibhav375 commented on Nov 15, 2026

    @vaibhav375
    Contributor

    I’d like to take api/core/agent/base_agent_runner.py.

    Plan: BaseAgentRunner.init already receives a session but doesn’t keep it, and save_agent_thought / create_agent_thought still query/add/commit/close through the global db.session. I’d store the passed-in session and use it in both methods, drop the close() calls since the caller owns it, and cover both paths with tests on the real SQLite session.

    Before I start: #43677 adds services/agent/chat/base_runner.py and #43689 rewrites the agent runner tests. Is core/agent/base_agent_runner.py still worth changing, or will that stack replace it? Happy to pick another slice if so.

  12. Rajkumar2119 commented on Nov 16, 2026

    @Rajkumar2119

    Hi! I'd like to take api/core/app/apps/agent_app/app_runner.py as a non-overlapping slice.

    It still reads, deletes and commits agent thoughts through the global db.session. Plan: use the session already available from the caller and pass it down, following the pattern in #45711, with no behaviour change. I'll update or add tests for the touched paths.

    @vaibhav375 is working on base_agent_runner.py, which is closely related. I'll keep my change limited to app_runner.py and make sure the two stay compatible.

    I'll open a PR referencing "Part of #45584" within ~3 days.

  13. vaibhav375 commented on Nov 17, 2026

    @vaibhav375
    Contributor

    Taking api/core/tools/utils/model_invocation_utils.py as a non-overlapping slice. (I closed #46464 since #45775 already covers base_agent_runner.py.)

    Plan: ModelInvocationUtils.invoke adds the ToolModelInvoke row through the global db.session and keeps that session open across invoke_llm before committing the response update. I'll write the row in one short-lived session_factory.create_session() scope and the update in another, so no session is held during the model call, and update the SQLite tests to cover both writes.

  14. Mattenhaim commented on Nov 22, 2026

    @Mattenhaim
    Contributor

    @dosu any remaining files? I would like to take a non-overlapping slice of this cleanup.

  15. dosubot commented on Nov 22, 2026

    @dosubot

    Hi @Mattenhaim! I'm Dosu and I'm helping the Dify team.

    Yes. I’d suggest api/core/tools/custom_tool/provider.py, specifically ApiToolProviderController.get_tools(). It still queries ApiToolProvider through global db.session, filters by tenant and provider name, then builds and caches the tools. [1]

    A narrow proposed slice:

    • Replace that query with an explicitly owned short-lived session, keeping provider-to-tool conversion inside its scope.
    • Preserve tenant/name filtering and the cached-tools fast path.
    • Add real-session tests for matching providers, tenant isolation, no matches and cached results. [1]

    As of November 22, I found no claim for this file in this thread, and no matching open cleanup PR in the filename/class searches. It looks like a non-overlapping candidate, rather than a guaranteed reservation.

    Avoid the scheduled-task files even though they still contain db.session: #41017 already includes the OAuth-token and embedding-cache cleanup tasks, plus the TiDB tasks.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about dify

  16. Mattenhaim commented on Nov 22, 2026

    @Mattenhaim
    Contributor

    Taking api/core/tools/custom_tool/provider.py (ApiToolProviderController.get_tools) as a non-overlapping slice.

    Plan: replace the global db.session query with a short-lived explicitly owned session, keep the tenant/name filtering and the cached-tools fast path unchanged, and cover matching / tenant-isolation / no-match / cached-result paths with real SQLite-session tests, following the pattern in #45711. I will open a PR referencing "Part of #45584".

  17. Vijay431 commented on Nov 26, 2026

    @Vijay431

    Thank you for the clear write-up and for labelling this a good first issue.

    I'm interested in working on it. My background is full-stack TypeScript (React, Next.js, Node). Could you please assign it to me? I'll post a plan here as I go.

  18. keith991001 commented on Nov 27, 2026

    @keith991001
    Contributor

    I'm taking the read-only plugin auto-upgrade strategy endpoint (GET /workspaces/current/plugin/auto-upgrade/fetch) as a small part of this cleanup. PR #47365 replaces its global db.session() with a short-lived session and verifies tenant/category scoping and the missing-strategy defaults with SQLite tests. This is limited to the auto-upgrade read endpoint; permission endpoints and write paths are outside its scope.

  19. goodchickenkor commented on Nov 27, 2026

    @goodchickenkor

    Taking WorkflowToolProviderController.get_tools (api/core/tools/workflow_as_tool/provider.py)
    as a non-overlapping slice. #47397 left it out of scope: when tools is not preloaded, it
    still opens Session(db.engine, expire_on_commit=False).

    Plan, following #46983 (the ApiToolProviderController counterpart):

    • Add a required keyword-only session_maker: sessionmaker[Session] to the constructor.
    • In from_db, pass sessionmaker_for(session) from the session it already opens.
    • In get_tools, open the session from the injected maker. Keep expire_on_commit=False,
      the session.begin() scope, the tenant/provider filtering, and the cached-tools path
      unchanged.
    • Update the direct constructions in the unit and e2e tests (test_provider.py,
      test_tool_manager.py, test_tools_transform_service.py).

    Tests: real SQLite rows through sqlite_session_factory for the matching provider, tenant
    isolation, a missing provider, a missing app, and the cached path (with an unbound maker,
    so it proves no DB access). I'll also confirm the lookup test fails if get_tools ignores
    the injected maker.

    No open PR touches this controller. #46459 adds strict typing to the workflow-as-tool tests,
    so I'll keep my test changes focused and rebase on whichever lands first.
    I will open a PR referencing "Part of #45584".

  20. goodchickenkor commented on Nov 27, 2026

    @goodchickenkor

    Opened #47402 for this slice.

  21. onkardongare commented on Nov 28, 2026

    @onkardongare

    Hi, I am new to contributing to dify and would like to work on a small API task. I saw that several parts of #45584 are already being handled. Could you suggest an unclaimed, beginner friendly file or task from this issue? I’ll keep my change limited to that scope and run the relevant checks before opening a PR.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    good first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions