Skip to content

make db.session pass from parameter. #37403

Closed

Description

@asukaminato0721

example: #37402

So we can know whether a function or sub call use session or not.

And this change is safe.

Activity

  1. asukaminato0721 commented on Jun 13, 2026

    @asukaminato0721
    ContributorAuthor

    @dosu how is this change

  2. dosubot commented on Jun 13, 2026

    @dosubot

    This is a reasonable refactoring pattern. Making db.session an explicit parameter instead of relying on the implicit global db.session has some clear benefits:

    1. Explicitness — callers and readers can immediately see which functions touch the database, improving readability and traceability.
    2. Testability — passing session as a parameter makes it straightforward to inject a mock or test session without monkeypatching globals.
    3. Safety — as you noted, it's a safe, non-behavioral change since db.session is still the same object being passed; the difference is only in how it's threaded through.

    A few considerations worth noting:

    • Incremental adoption — since the codebase is large, doing this incrementally (as in your example PR) is practical, but it may create inconsistency in the interim where some functions accept session and others still use the global. A linting rule or type annotation convention could help track progress.
    • Type errors — your example PR already surfaced some type-checking issues (e.g., missing session arguments in ParagraphIndexProcessor methods), which validates the point that the refactor makes implicit dependencies visible and catches missing plumbing at compile time.
    • API surface — for deeply nested call chains, threading session through many layers can get verbose. Some projects address this with a context-local pattern or a unit-of-work abstraction, but explicit parameter passing is the simplest and most transparent approach.

    Overall, it's a solid incremental improvement to code quality. The main trade-off is verbosity vs. explicitness, and for a production codebase like Dify, explicitness generally wins.

    To reply, just mention @dosu.


    Docs are dead. Just use Dosu.

    Leave Feedback Ask Dosu about dify

  3. added
    good first issue
    on Jun 13, 2026
  4. nexiouscaliver commented on Jun 14, 2026

    @nexiouscaliver
    Contributor

    Hi, I opened #37417 to handle RecommendedAppService for this issue. It adds an explicit session: scoped_session parameter to the three classmethods (get_recommended_apps_and_categories, get_recommend_app_detail, and add_trial_app_record) and passes db.session in from the explore controllers, following the same approach as #37402.

  5. Uttamxalpha commented on Jun 15, 2026

    @Uttamxalpha

    Hi! I'm interested in working on this issue and would like to submit a fix. Could you please assign it to me?
    Thanks for maintaining the project!

  6. Kunal152000 commented on Jun 15, 2026

    @Kunal152000
    Contributor

    @asukaminato0721 I have implemented the db.session parameter for one of the services. The documents specifically suggests creating an issue and talk about the changes which needs to be implemented, before creating a pr, but i am not sure under which criteria should the issue be opened, can you please help here. Or should i directly create a pr.

  7. asukaminato0721 commented on Jun 15, 2026

    @asukaminato0721
    ContributorAuthor

    @asukaminato0721 I have implemented the db.session parameter for one of the services. The documents specifically suggests creating an issue and talk about the changes which needs to be implemented, before creating a pr, but i am not sure under which criteria should the issue be opened, can you please help here. Or should i directly create a pr.

    create a pr

  8. asukaminato0721 commented on Jun 17, 2026

    @asukaminato0721
    ContributorAuthor

    @dosu give me a full file list that patch db.session.

  9. dosubot commented on Jun 17, 2026

    @dosubot

    Here's the full file list of files that use db.session in the codebase (~153+ files):

    api/controllers/ (62 files)

    Inner API:

    • api/controllers/inner_api/wraps.py
    • api/controllers/inner_api/workspace/workspace.py
    • api/controllers/inner_api/app/dsl.py
    • api/controllers/inner_api/plugin/plugin.py
    • api/controllers/inner_api/plugin/wraps.py

    Console:

    • api/controllers/console/datasets/datasets_segments.py
    • api/controllers/console/datasets/datasets_document.py
    • api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
    • api/controllers/console/datasets/rag_pipeline/rag_pipeline_draft_variable.py
    • api/controllers/console/datasets/wraps.py
    • api/controllers/console/datasets/datasets.py
    • api/controllers/console/datasets/data_source.py
    • api/controllers/console/auth/oauth.py
    • api/controllers/console/auth/forgot_password.py
    • api/controllers/console/auth/activate.py
    • api/controllers/console/setup.py
    • api/controllers/console/wraps.py
    • api/controllers/console/apikey.py
    • api/controllers/console/agent/roster.py
    • api/controllers/console/agent/app_helpers.py
    • api/controllers/console/workspace/account.py
    • api/controllers/console/workspace/workspace.py
    • api/controllers/console/workspace/tool_providers.py
    • api/controllers/console/workspace/members.py
    • api/controllers/console/snippets/snippet_workflow_draft_variable.py
    • api/controllers/console/app/workflow_draft_variable.py
    • api/controllers/console/app/site.py
    • api/controllers/console/app/workflow_run.py
    • api/controllers/console/app/agent.py
    • api/controllers/console/app/agent_app_access.py
    • api/controllers/console/app/wraps.py
    • api/controllers/console/app/conversation.py
    • api/controllers/console/app/workflow.py
    • api/controllers/console/app/model_config.py
    • api/controllers/console/app/message.py
    • api/controllers/console/app/mcp_server.py
    • api/controllers/console/tag/tags.py
    • api/controllers/console/explore/banner.py
    • api/controllers/console/explore/wraps.py
    • api/controllers/console/explore/installed_app.py
    • api/controllers/console/explore/completion.py
    • api/controllers/console/explore/recommended_app.py
    • api/controllers/console/explore/trial.py

    Web:

    • api/controllers/web/site.py
    • api/controllers/web/human_input_form.py
    • api/controllers/web/forgot_password.py
    • api/controllers/web/passport.py

    Service API:

    • api/controllers/service_api/wraps.py
    • api/controllers/service_api/dataset/segment.py
    • api/controllers/service_api/dataset/rag_pipeline/rag_pipeline_workflow.py
    • api/controllers/service_api/dataset/document.py
    • api/controllers/service_api/dataset/dataset.py
    • api/controllers/service_api/app/site.py
    • api/controllers/service_api/app/file_preview.py

    OpenAPI:

    • api/controllers/openapi/auth/verify.py
    • api/controllers/openapi/auth/prepare.py
    • api/controllers/openapi/account.py
    • api/controllers/openapi/oauth_device_sso.py
    • api/controllers/openapi/apps_permitted_external.py
    • api/controllers/openapi/apps.py
    • api/controllers/openapi/workspaces.py
    • api/controllers/openapi/oauth_device.py

    api/services/ (51 files)

    • api/services/agent_drive_service.py
    • api/services/workflow/node_output_inspector_service.py
    • api/services/data_migration/import_service.py
    • api/services/data_migration/export_service.py
    • api/services/workflow/workflow_converter.py
    • api/services/conversation_service.py
    • api/services/file_service.py
    • api/services/tools/builtin_tools_manage_service.py
    • api/services/credential_permission_service.py
    • api/services/feedback_service.py
    • api/services/tag_service.py
    • api/services/ops_service.py
    • api/services/agent_app_sandbox_service.py
    • api/services/webapp_auth_service.py
    • api/services/workflow_collaboration_service.py
    • api/services/async_workflow_service.py
    • api/services/plugin/plugin_auto_upgrade_service.py
    • api/services/plugin/plugin_permission_service.py
    • api/services/auth/api_key_auth_service.py
    • api/services/datasource_provider_service.py
    • api/services/app_service.py
    • api/services/web_conversation_service.py
    • api/services/model_load_balancing_service.py
    • api/services/workspace_service.py
    • api/services/agent_service.py
    • api/services/dataset_service.py
    • api/services/workflow_service.py
    • api/services/rag_pipeline/pipeline_generate_service.py
    • api/services/enterprise/account_deletion_sync.py
    • api/services/rag_pipeline/pipeline_template/database/database_retrieval.py
    • api/services/external_knowledge_service.py
    • api/services/annotation_service.py
    • api/services/rag_pipeline/pipeline_template/customized/customized_retrieval.py
    • api/services/vector_service.py
    • api/services/audio_service.py
    • api/services/metadata_service.py
    • api/services/hit_testing_service.py
    • api/services/account_service.py
    • api/services/message_service.py
    • api/services/saved_message_service.py
    • api/services/credit_pool_service.py
    • api/services/rag_pipeline/rag_pipeline_transform_service.py
    • api/services/rag_pipeline/rag_pipeline.py
    • api/services/agent/composer_service.py
    • api/services/billing_service.py
    • api/services/agent/skill_tool_inference_service.py
    • api/services/api_based_extension_service.py
    • api/services/clear_free_plan_tenant_expired_logs.py
    • api/services/summary_index_service.py
    • api/services/recommend_app/database/database_retrieval.py

    api/core/ (68 files)

    • api/core/repositories/human_input_repository.py
    • api/core/workflow/nodes/agent_v2/binding_resolver.py
    • api/core/workflow/nodes/agent_v2/session_store.py
    • api/core/workflow/nodes/agent_v2/output_file_rebacker.py
    • api/core/workflow/nodes/agent_v2/file_tenant_validator.py
    • api/core/workflow/nodes/agent_v2/ask_human_resume.py
    • api/core/workflow/node_factory.py
    • api/core/moderation/api/api.py
    • api/core/helper/encrypter.py
    • api/core/callback_handler/index_tool_callback_handler.py
    • api/core/tools/workflow_as_tool/tool.py
    • api/core/tools/workflow_as_tool/provider.py
    • api/core/tools/tool_engine.py
    • api/core/tools/custom_tool/provider.py
    • api/core/tools/tool_file_manager.py
    • api/core/tools/tool_manager.py
    • api/core/tools/utils/dataset_retriever/dataset_multi_retriever_tool.py
    • api/core/tools/utils/dataset_retriever/dataset_retriever_tool.py
    • api/core/tools/utils/model_invocation_utils.py
    • api/core/plugin/backwards_invocation/app.py
    • api/core/rag/rerank/rerank_model.py
    • api/core/rag/docstore/dataset_docstore.py
    • api/core/rag/datasource/keyword/jieba/jieba.py
    • api/core/rag/datasource/vdb/vector_factory.py
    • api/core/rag/datasource/retrieval_service.py
    • api/core/rag/extractor/excel_extractor.py
    • api/core/rag/extractor/notion_extractor.py
    • api/core/rag/extractor/pdf_extractor.py
    • api/core/rag/extractor/word_extractor.py
    • api/core/rag/retrieval/dataset_retrieval.py
    • api/core/rag/summary_index/summary_index.py
    • api/core/rag/embedding/cached_embedding.py
    • api/core/rag/index_processor/index_processor_base.py
    • api/core/rag/index_processor/index_processor.py
    • api/core/rag/index_processor/processor/parent_child_index_processor.py
    • api/core/rag/index_processor/processor/qa_index_processor.py
    • api/core/rag/index_processor/processor/paragraph_index_processor.py
    • api/core/llm_generator/llm_generator.py
    • api/core/external_data_tool/api/api.py
    • api/core/provider_manager.py
    • api/core/agent/base_agent_runner.py
    • api/core/datasource/datasource_file_manager.py
    • api/core/datasource/datasource_manager.py
    • api/core/file/remote_fetcher.py
    • api/core/prompt/utils/get_thread_messages_length.py
    • api/core/app/workflow/file_runtime.py
    • api/core/app/layers/trigger_post_layer.py
    • api/core/app/features/annotation_reply/annotation_reply.py
    • api/core/app/apps/workflow/app_generator.py
    • api/core/app/apps/advanced_chat/app_runner.py
    • api/core/app/apps/advanced_chat/app_generator.py
    • api/core/app/apps/base_app_runner.py
    • api/core/app/apps/agent_app/app_generator.py
    • api/core/app/apps/agent_app/session_store.py
    • api/core/app/apps/agent_chat/app_runner.py
    • api/core/app/apps/agent_chat/app_generator.py
    • api/core/app/apps/message_based_app_generator.py
    • api/core/app/apps/chat/app_runner.py
    • api/core/app/apps/chat/app_generator.py
    • api/core/app/apps/completion/app_runner.py
    • api/core/app/apps/completion/app_generator.py
    • api/core/app/apps/pipeline/pipeline_runner.py
    • api/core/app/apps/pipeline/pipeline_generator.py
    • api/core/app/task_pipeline/message_cycle_manager.py
    • api/core/memory/token_buffer_memory.py
    • api/core/ops/ops_trace_manager.py
    • api/core/ops/utils.py
    • api/core/indexing_runner.py

    api/tasks/ (42 files)

    • api/tasks/disable_segment_from_index_task.py
    • api/tasks/duplicate_document_indexing_task.py
    • api/tasks/disable_segments_from_index_task.py
    • api/tasks/clean_notion_document_task.py
    • api/tasks/workflow_execution_tasks.py
    • api/tasks/deal_dataset_index_update_task.py
    • api/tasks/async_workflow_tasks.py
    • api/tasks/document_indexing_sync_task.py
    • api/tasks/delete_segment_from_index_task.py
    • api/tasks/deal_dataset_vector_index_task.py
    • api/tasks/retry_document_indexing_task.py
    • api/tasks/batch_create_segment_to_index_task.py
    • api/tasks/regenerate_summary_index_task.py
    • api/tasks/batch_clean_document_task.py
    • api/tasks/app_generate/resume_agent_app_task.py
    • api/tasks/clean_dataset_task.py
    • api/tasks/trigger_processing_tasks.py
    • api/tasks/workflow_node_execution_tasks.py
    • api/tasks/rag_pipeline/rag_pipeline_run_task.py
    • api/tasks/rag_pipeline/priority_rag_pipeline_run_task.py
    • api/tasks/add_document_to_index_task.py
    • api/tasks/annotation/batch_import_annotations_task.py
    • api/tasks/remove_document_from_index_task.py
    • api/tasks/document_indexing_task.py
    • api/tasks/recover_document_indexing_task.py
    • api/tasks/annotation/disable_annotation_reply_task.py
    • api/tasks/annotation/enable_annotation_reply_task.py
    • api/tasks/workflow_schedule_tasks.py
    • api/tasks/delete_conversation_task.py
    • api/tasks/enable_segment_to_index_task.py
    • api/tasks/remove_app_and_related_data_task.py
    • api/tasks/clean_document_task.py
    • api/tasks/sync_website_document_indexing_task.py
    • api/tasks/enable_segments_to_index_task.py
    • api/tasks/delete_account_task.py
    • api/tasks/trigger_subscription_refresh_tasks.py
    • api/tasks/document_indexing_update_task.py
    • api/tasks/workflow_draft_var_tasks.py
    • api/tasks/create_segment_to_index_task.py
    • api/tasks/generate_summary_index_task.py

    Other directories

    api/models/ (10 files): model.py, comment.py, dataset.py, account.py, trigger.py, snippet.py, provider.py, workflow.py, web.py, tools.py

    api/commands/ (5 files): storage.py, plugin.py, system.py, data_migration.py, vector.py

    api/schedule/ (8 files): queue_monitor_task.py, create_tidb_serverless_task.py, mail_clean_document_notify_task.py, clean_unused_datasets_task.py, clean_embedding_cache_task.py, clean_oauth_access_tokens_task.py, update_tidb_serverless_status_task.py, check_upgradable_plugin_task.py

    api/extensions/ (3 files): ext_session_factory.py, ext_oauth_bearer.py, ext_login.py

    api/events/ (5 files): create_document_index.py, update_app_dataset_join_when_app_model_config_updated.py, create_installed_app_when_app_created.py, create_site_record_when_app_created.py, update_app_dataset_join_when_app_published_workflow_updated.py

    api/libs/ (2 files): oauth_bearer.py, oauth_data_source.py

    api/factories/ (1 file): file_factory/builders.py

    api/providers/ (18 files): trace providers (13) and vector DB providers (5)


    Total: ~153+ files. The heaviest areas are api/core/ (68), api/controllers/ (62), api/services/ (51), and api/tasks/ (42). A natural approach would be to tackle services first (since controllers call into them), then core/tasks, doing it incrementally per-module as contributors are already doing with PRs like #37402 and #37417.

    Note: this list was generated via deep search and may not be 100% exhaustive — there could be a handful of additional files, especially in test code or newer additions. Running grep -rl "db.session" api/ locally would give you the definitive count.

    To reply, just mention @dosu.


    Share context across your team and agents. Try Dosu.

    Leave Feedback Learn about dify with Dosu

  10. EvanYao826 commented on Jun 22, 2026

    @EvanYao826
    Contributor

    I'd like to work on this issue. I see that PR #37402 has been merged for paragraph_index_processor.py. Are there other functions that need to be refactored to pass db.session as a parameter? I can continue the work.

  11. Kunal152000 commented on Jun 22, 2026

    @Kunal152000
    Contributor

    @asukaminato0721 I have implemented the db.session parameter for one of the services. The documents specifically suggests creating an issue and talk about the changes which needs to be implemented, before creating a pr, but i am not sure under which criteria should the issue be opened, can you please help here. Or should i directly create a pr.

    create a pr

    Sorry for the delayed reply, Created a pr please check :- #37763

  12. 17 remaining items

  13. ShousenZHANG commented on Sep 17, 2026

    @ShousenZHANG
    Contributor

    Taking the runtime_credentials slice.

    _resolve_model and _resolve_tool in api/controllers/inner_api/runtime_credentials.py each open their own Session(db.engine) for a single read. Moving both to core.db.session_factory matches what inner_api/wraps.py and web/wraps.py already do. Both blocks are pure reads and neither commits, so no commit boundary moves.

    Opened as #42400 — a slice, not a fix for the whole issue.

  14. ShousenZHANG commented on Sep 24, 2026

    @ShousenZHANG
    Contributor

    Taking the workflow-run repository slice. service_api/app/workflow.py, service_api/app/workflow_events.py, web/workflow_events.py and console/human_input_form.py each build sessionmaker(db.engine) only to pass it to DifyAPIRepositoryFactory.create_api_workflow_run_repository(...). Moving them to session_factory.get_session_maker(), as controllers/openapi/workflow_events.py already does. The repository calls are single reads that never commit, so no commit boundary moves.

    Opened as #42927 — a slice, not a fix for the whole issue.

  15. ShousenZHANG commented on Sep 25, 2026

    @ShousenZHANG
    Contributor

    Taking the conversation endpoints: service_api/app/conversation.py and web/conversation.py (conversation list) and console/app/conversation_variables.py each open sessionmaker(db.engine…).begin() per request. Moving them to session_factory.get_session_maker().begin(), the form console/snippets/snippet_workflow.py already uses. The .begin() block and its commit stay where they are.

    Opened as #42954 — a slice, not a fix for the whole issue.

  16. Bear0117 commented on Oct 1, 2026

    @Bear0117
    Contributor

    Hi @asukaminato0721 , I'd like to take a narrow, non-overlapping slice of this refactor: the audio controllers.

    Scope (4 call sites, 2 files):

    • api/controllers/web/audio.py — AudioApi.post (ASR) and TextApi.post (TTS)
    • api/controllers/service_api/app/audio.py — AudioApi.post (ASR) and TextApi.post (TTS)

    On current main all four handlers call AudioService.transcript_asr(...) / AudioService.transcript_tts(...) with session=db.session(), i.e. they hand the global scoped session to the service instead of owning a request-scoped one.

    Plan:

    • Adopt @with_session from controllers.common.session on the four handlers, following the pattern already used in service_api/app/completion.py and the merged refactor(controllers): adopt with_session in web saved_message #41859. The decorator injects a request-scoped session: Session which I'll pass straight through to AudioService.
    • Both handlers only read through the session (ASR feature / app config lookups and the TTS message lookup), so I intend to use @with_session(write=False); I'll double-check the service path during implementation and switch to the default write mode if anything commits.
    • Drop the now-unused from extensions.ext_database import db import from both controllers.
    • No change to AudioService: transcript_asr / transcript_tts already accept an explicit session: Session.
    • Update tests/unit_tests/controllers/web/test_audio.py and tests/unit_tests/controllers/service_api/app/test_audio.py so they assert the session kwarg comes from the injected session rather than db.session.

    Non-overlapping with the open slices I can see (#42954, #42927, #42400 by @ShousenZHANG, and #43288). Will run make lint, make type-check and the targeted unit tests, and link the PR here once it's up.

  17. Bear0117 commented on Oct 1, 2026

    @Bear0117
    Contributor

    Opened #43322 for the audio controllers slice.

    As planned, the four handlers in controllers/web/audio.py and controllers/service_api/app/audio.py now use @with_session(write=False) and forward the injected session to AudioService; the unused db import is gone. Verified AudioService and the helpers it calls only read through the session, so write=False holds. ruff, pyrefly, response-contract lint, import linter and the two audio test files (41 passed) are clean locally.

  18. 41tair commented on Oct 1, 2026

    @41tair
    Member

    Now we have #39993 in progress, this issue could be closed.

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 issueproject#difyrefactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions