Skip to content

refactor(api): write tool model invoke logs through short-lived sessions - #46632

Merged
asukaminato0721 merged 4 commits into
langgenius:mainfrom
vaibhav375:refactor/tool-model-invoke-sessions
Nov 23, 2026
Merged

asukaminato0721 merged 4 commits into
langgenius:mainfrom
vaibhav375:refactor/tool-model-invoke-sessions

Conversation

@vaibhav375

@vaibhav375 vaibhav375 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of #45584

ModelInvocationUtils.invoke (used by built-in tools and plugin backwards invocation) wrote its ToolModelInvoke log row through the global db.session: add + commit before invoke_llm, then a second db.session.commit() after the model returned. That second commit runs on the caller's scoped session, so it also committed anything else the caller had pending, and the log row stayed attached to that session for the whole model call.

invoke now takes a required keyword-only session_maker: sessionmaker[Session], and the row and the response update each go through their own session_maker.begin() scope. No session is held during invoke_llm, and the module no longer imports extensions.ext_database or the global session factory. The two callers, BuiltinTool.invoke_model and PluginModelBackwardsInvocation.invoke_system_model, pass session_factory.get_session_maker(). Behaviour is otherwise the same: the row is committed with an empty response before the call, and updated with the response and usage only on success.

Contract (also in the invoke docstring, per api/AGENTS.md):

  • Pre: session_maker is bound to the app database (callers pass session_factory.get_session_maker()).
  • Post, success: the row holds the model response and usage; the caller's session is not committed.
  • Post, failure: the row stays with an empty response and answer_tokens == 0, and InvokeModelError is raised.

Tests (tests/unit_tests/core/tools/utils/test_model_invocation_utils.py):

  • Dropped the patch that swapped model_invocation_utils.db for the test session; the tests pass sqlite_session_factory as session_maker.
  • The success test checks, from inside invoke_llm, that a separate session already sees the committed row with an empty response, then checks the final persisted values.
  • The error-mapping tests check the row persisted with an empty response.
  • tests/unit_tests/core/tools/builtin_tool/test_tool.py asserts invoke_model forwards the session maker.
  • Without the production change, the 7 invoke tests fail (The current Flask app is not registered with this 'SQLAlchemy' instance); with it they pass.

Local results on this branch (based on main e316d5b5a8):

  • pytest api/tests/unit_tests/core/tools api/tests/unit_tests/core/plugin: 1255 passed
  • make lint: passed (102 import contracts kept)
  • make type-check: passed
  • scripts/check_no_new_session_mock.py --base-rev upstream/main: clean

Screenshots

N/A (no UI change)

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

From Claude Code

ModelInvocationUtils.invoke added the ToolModelInvoke row through the
global db.session and committed the response update through it after
the model call, which also committed anything else pending in the
caller's scoped session. Write the row and the update through their
own session_factory sessions so no session is held across invoke_llm.

Part of langgenius#45584
@github-actions github-actions Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Nov 17, 2026
@vaibhav375
vaibhav375 marked this pull request as ready for review November 17, 2026 19:13
@asukaminato0721 asukaminato0721 self-assigned this Nov 17, 2026
@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 87.07% 87.07% -0.00%
Strict coverage 86.73% 86.73% -0.00%
Typed symbols 96,262 96,251 -11
Untyped symbols 14,348 14,348 0
Modules 4646 4646 0

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.33333% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 90.30%. Comparing base (8b6fbfb) to head (dc4ef62).
⚠️ Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
api/core/tools/utils/model_invocation_utils.py 92.30% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #46632      +/-   ##
==========================================
- Coverage   90.31%   90.30%   -0.01%     
==========================================
  Files        6495     6495              
  Lines      408368   408371       +3     
  Branches    81903    81903              
==========================================
- Hits       368800   368792       -8     
- Misses      33164    33175      +11     
  Partials     6404     6404              
Flag Coverage Δ
api 90.12% <93.33%> (-0.01%) ⬇️

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.

@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.

2 inline suggestions at 282afe9eb2, each from a rule learned from earlier reviews in this repository. Reply on a comment if it is wrong.

dify-codereview

@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
invoke now takes the session maker for its log row writes as a required
keyword-only argument instead of reaching for the global session
factory. BuiltinTool.invoke_model and the plugin system-model
invocation pass session_factory.get_session_maker(), and the tests
hand in sqlite_session_factory directly.

Part of langgenius#45584
@vaibhav375
vaibhav375 requested a review from WH-2099 as a code owner November 17, 2026 19:53
@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 18, 2026
@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 20, 2026
@asukaminato0721 asukaminato0721 added waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 21, 2026
@vaibhav375

Copy link
Copy Markdown
Contributor Author

Both suggestions are addressed in 06ff8ef: invoke now takes the session maker as a parameter, and the tests hand in sqlite_session_factory instead of patching the database. The remaining patches are on the model side (details in the resolved thread). Could you take another look when you have a moment?

@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.

Nothing to flag at dc4ef62762.

dify-codereview

@asukaminato0721
asukaminato0721 dismissed their stale review November 22, 2026 04:01

Nothing left to flag at dc4ef62.

@asukaminato0721 asukaminato0721 added waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn and removed waiting-for-author dify-codereview: the author has suggestions, a conflict, failing CI or unresolved threads to address labels Nov 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-11-22 12:50:36.359486913 +0000
+++ /tmp/pyrefly_pr.txt	2026-11-22 12:50:16.935319531 +0000
@@ -4004,45 +4004,45 @@
 ERROR Cannot instantiate `TextSplitter` because the following members are abstract: `split_text` [bad-instantiation]
     --> tests/unit_tests/core/rag/splitter/test_text_splitter.py:2208:21
 ERROR Argument `Literal[core.entities.provider_entities.ProviderQuotaType.TRIAL]` is not assignable to parameter `quota_type` with type `models.enums.ProviderQuotaType | SQLCoreOperations[models.enums.ProviderQuotaType | None] | None` in function `models.provider.Provider.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:101:20
+   --> tests/unit_tests/core/test_provider_manager.py:125:20
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.ProviderModelSetting.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:159:20
+   --> tests/unit_tests/core/test_provider_manager.py:183:20
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:172:24
+   --> tests/unit_tests/core/test_provider_manager.py:196:24
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:181:24
+   --> tests/unit_tests/core/test_provider_manager.py:205:24
 ERROR Argument `list[ProviderModelSetting]` is not assignable to parameter `provider_model_settings` with type `list[_ProviderModelSettingCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:202:37
+   --> tests/unit_tests/core/test_provider_manager.py:226:37
 ERROR Argument `list[LoadBalancingModelConfig]` is not assignable to parameter `load_balancing_model_configs` with type `list[_LoadBalancingModelConfigCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:203:42
+   --> tests/unit_tests/core/test_provider_manager.py:227:42
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.ProviderModelSetting.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:246:20
+   --> tests/unit_tests/core/test_provider_manager.py:270:20
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:255:24
+   --> tests/unit_tests/core/test_provider_manager.py:279:24
 ERROR Argument `list[ProviderModelSetting]` is not assignable to parameter `provider_model_settings` with type `list[_ProviderModelSettingCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:269:67
+   --> tests/unit_tests/core/test_provider_manager.py:293:67
 ERROR Argument `list[LoadBalancingModelConfig]` is not assignable to parameter `load_balancing_model_configs` with type `list[_LoadBalancingModelConfigCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:269:77
+   --> tests/unit_tests/core/test_provider_manager.py:293:77
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.ProviderModelSetting.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:465:20
+   --> tests/unit_tests/core/test_provider_manager.py:489:20
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:476:24
+   --> tests/unit_tests/core/test_provider_manager.py:500:24
 ERROR Argument `list[ProviderModelSetting]` is not assignable to parameter `provider_model_settings` with type `list[_ProviderModelSettingCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:496:37
+   --> tests/unit_tests/core/test_provider_manager.py:520:37
 ERROR Argument `list[LoadBalancingModelConfig]` is not assignable to parameter `load_balancing_model_configs` with type `list[_LoadBalancingModelConfigCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:497:42
+   --> tests/unit_tests/core/test_provider_manager.py:521:42
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.ProviderModelSetting.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:515:20
+   --> tests/unit_tests/core/test_provider_manager.py:539:20
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:526:24
+   --> tests/unit_tests/core/test_provider_manager.py:550:24
 ERROR Argument `Literal['llm']` is not assignable to parameter `model_type` with type `ModelType | SQLCoreOperations[ModelType]` in function `models.provider.LoadBalancingModelConfig.__init__` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:535:24
+   --> tests/unit_tests/core/test_provider_manager.py:559:24
 ERROR Argument `list[ProviderModelSetting]` is not assignable to parameter `provider_model_settings` with type `list[_ProviderModelSettingCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:556:37
+   --> tests/unit_tests/core/test_provider_manager.py:580:37
 ERROR Argument `list[LoadBalancingModelConfig]` is not assignable to parameter `load_balancing_model_configs` with type `list[_LoadBalancingModelConfigCacheEntry] | None` in function `core.provider_manager.ProviderManager._to_model_settings` [bad-argument-type]
-   --> tests/unit_tests/core/test_provider_manager.py:557:42
+   --> tests/unit_tests/core/test_provider_manager.py:581:42
 WARN Identity comparison `False is True` is always False [unnecessary-comparison]
-    --> tests/unit_tests/core/test_provider_manager.py:1555:30
+    --> tests/unit_tests/core/test_provider_manager.py:1500:30
 ERROR Object of type `ToolInvokeMessage.BlobChunkMessage | ToolInvokeMessage.BlobMessage | ToolInvokeMessage.FileMessage | ToolInvokeMessage.JsonMessage | ToolInvokeMessage.LogMessage | ToolInvokeMessage.RetrieverResourceMessage | ToolInvokeMessage.TextMessage | ToolInvokeMessage.VariableMessage | None` has no attribute `text` [missing-attribute]
   --> tests/unit_tests/core/tools/builtin_tool/providers/time/tools/test_localtime_to_timestamp.py:56:16
 ERROR Object of type `ToolInvokeMessage.BlobChunkMessage | ToolInvokeMessage.BlobMessage | ToolInvokeMessage.FileMessage | ToolInvokeMessage.JsonMessage | ToolInvokeMessage.LogMessage | ToolInvokeMessage.RetrieverResourceMessage | ToolInvokeMessage.TextMessage | ToolInvokeMessage.VariableMessage | None` has no attribute `text` [missing-attribute]

@asukaminato0721
asukaminato0721 added this pull request to the merge queue Nov 23, 2026
Merged via the queue into langgenius:main with commit c4134ca Nov 23, 2026
51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files. waiting-for-reviewer dify-codereview: checked, nothing left for the author; a reviewer's turn

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants