Skip to content

refactor: pass session explicitly in schedule tasks (#37403) - #41017

Open
gggsaasdv wants to merge 4 commits into
langgenius:mainfrom
gggsaasdv:pass-session-schedule-tasks
Open

gggsaasdv wants to merge 4 commits into
langgenius:mainfrom
gggsaasdv:pass-session-schedule-tasks

Conversation

@gggsaasdv

Copy link
Copy Markdown

Summary

Part of #37403.

Migrates the remaining scheduled tasks in api/schedule/ from the implicit global db.session to explicitly managed sessions, following the established patterns of this refactor: entry-point tasks open a session via session_factory.create_session() (as in clean_unused_datasets_task.py and mail_clean_document_notify_task.py), and helpers receive the session as a parameter (as in #37402).

Changes:

  • create_tidb_serverless_task.py: task body opens an explicit session; create_clusters now takes session as a parameter
  • update_tidb_serverless_status_task.py: query and update_clusters run within one explicit session scope
  • clean_oauth_access_tokens_task.py: candidate selection, deletion and commit use an explicit session
  • clean_embedding_cache_task.py: cleanup loop uses an explicit session
  • check_upgradable_plugin_task.py: strategy query uses an explicit session
  • queue_monitor_task.py: removed the redundant finally: db.session.close() block — this task performs no database work, and the app context pushed around every Celery task (FlaskTask.__call__ in extensions/ext_celery.py) already removes the scoped session via Flask-SQLAlchemy teardown

Tests:

  • Added api/tests/unit_tests/schedule/ with 10 SQLite-backed unit tests covering both cleanup tasks, both TiDB serverless tasks, and the plugin upgrade check task

Verified locally: ruff format/check, pyrefly check (repo and tests configs), mypy, and lint-imports all clean; new tests pass 10/10.

Screenshots

...

Checklist

  • This PR contains a single, focused change
  • I have run make lint and make type-check
  • I have added tests for this change
  • This PR does not close the umbrella issue (it is one slice of make db.session pass from parameter. #37403)

From Claude Code

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. refactor labels Aug 20, 2026
@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → PR
--- /tmp/pyrefly_base.txt	2026-10-29 02:44:48.664773456 +0000
+++ /tmp/pyrefly_pr.txt	2026-10-29 02:44:38.376672764 +0000
@@ -166,6 +166,24 @@
   --> tests/unit_tests/migrations/versions/test_2025_07_02_2332-1c9ba48be8e4_add_uuidv7_function_in_sql.py:31:46
 ERROR Object of class `NoneType` has no attribute `loader` [missing-attribute]
   --> tests/unit_tests/migrations/versions/test_2025_07_02_2332-1c9ba48be8e4_add_uuidv7_function_in_sql.py:32:5
+ERROR Could not find name `db` [unknown-name]
+  --> schedule/create_tidb_serverless_task.py:26:17
+ERROR Missing argument `session` in function `create_clusters` [missing-argument]
+  --> schedule/create_tidb_serverless_task.py:32:28
+ERROR Parse error: Expected a statement [parse-error]
+  --> schedule/create_tidb_serverless_task.py:34:13
+ERROR Parse error: Expected a statement [parse-error]
+  --> schedule/create_tidb_serverless_task.py:34:30
+ERROR Parse error: Expected an expression [parse-error]
+  --> schedule/create_tidb_serverless_task.py:34:35
+ERROR Parse error: Unexpected indentation [parse-error]
+  --> schedule/create_tidb_serverless_task.py:35:1
+ERROR `e` is uninitialized [unbound-name]
+  --> schedule/create_tidb_serverless_task.py:35:50
+ERROR Parse error: Expected `except` or `finally` after `try` block [parse-error]
+  --> schedule/create_tidb_serverless_task.py:38:5
+ERROR Could not find name `db` [unknown-name]
+  --> schedule/update_tidb_serverless_status_task.py:21:32
 ERROR Argument `Literal['normal']` is not assignable to parameter `status` with type `ConversationStatus | SQLCoreOperations[ConversationStatus]` in function `models.model.Conversation.__init__` [bad-argument-type]
   --> tests/e2e_tests/containers/controllers/console/app/test_chat_conversation_status_count_api.py:75:16
 ERROR Argument `Literal['app-run']` is not assignable to parameter `triggered_from` with type `SQLCoreOperations[WorkflowRunTriggeredFrom] | WorkflowRunTriggeredFrom` in function `models.workflow.WorkflowRun.__init__` [bad-argument-type]

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 80.00% 80.01% +0.01%
Strict coverage 79.69% 79.70% +0.01%
Typed symbols 76,999 77,039 +40
Untyped symbols 19,322 19,319 -3
Modules 3987 3993 +6

@github-actions github-actions Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Oct 29, 2026
@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 72.73%. Comparing base (3ec3865) to head (f367623).
⚠️ Report is 723 commits behind head on main.

❌ Your project check has failed because the head coverage (72.73%) is below the adjusted base coverage (88.54%). You can increase the head coverage or adjust the Removed Code Behavior.

Additional details and impacted files
@@             Coverage Diff             @@
##             main   #41017       +/-   ##
===========================================
- Coverage   89.54%   72.73%   -16.82%     
===========================================
  Files        6011     5861      -150     
  Lines      377081   349771    -27310     
  Branches    76342    74598     -1744     
===========================================
- Hits       337666   254397    -83269     
- Misses      33421    91863    +58442     
+ Partials     5994     3511     -2483     
Flag Coverage Δ
api 58.97% <ø> (-30.44%) ⬇️

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.

ci

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

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

dify-codereview

def test_create_clusters_persists_bindings_through_passed_session(
sqlite_session_factory: sessionmaker[Session],
) -> None:
with patch.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.

This is an external boundary: define a small typing.Protocol for what the code needs, have the production code accept it as a parameter, and pass a fake that implements the Protocol in the test, instead of patching or mocking it.

dify-codereview · tests-real-dependencies (protocol-di) Learned from an earlier review. Reply here if this is wrong.

TenantPluginAutoUpgradeStrategy.strategy_setting != TenantPluginAutoUpgradeStrategySetting.DISABLED,
)
).all()
with session_factory.create_session() as session:

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.

Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.

db.session.execute(delete(OAuthAccessToken).where(OAuthAccessToken.id.in_(ids)))
db.session.commit()
total += len(ids)
with session_factory.create_session() as session:

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.

Take the session as a required parameter instead of reaching for a global (@with_session injects it in controllers). If this code must open and commit its own short transaction, take the session factory as a parameter instead (e.g. in __init__). Then tests pass sqlite_session / sqlite_session_factory directly and need no monkeypatch, and can assert the committed row from another session instead of counting commits.

dify-codereview · inject-session Learned from an earlier review. Reply here if this is wrong.

asukaminato0721

This comment was marked as outdated.

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

This branch has conflicts with main: please rebase onto the latest main. Checked f3676236be.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

refactor size:XL This PR changes 500-999 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