Skip to content

fix: fix sqlalchemy.orm.exc.DetachedInstanceError#34845

Merged
asukaminato0721 merged 1 commit intolanggenius:mainfrom
fatelei:issue-34844
Apr 9, 2026
Merged

fix: fix sqlalchemy.orm.exc.DetachedInstanceError#34845
asukaminato0721 merged 1 commit intolanggenius:mainfrom
fatelei:issue-34844

Conversation

@fatelei
Copy link
Copy Markdown
Contributor

@fatelei fatelei commented Apr 9, 2026

Important

  1. Make sure you have read our contribution guidelines
  2. Ensure there is an associated issue and you have been assigned to it
  3. Use the correct syntax to link this PR: Fixes #<issue number>.

Summary

fix #34844

Screenshots

Before After
... ...

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 added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.
  • I ran make lint and make type-check (backend) and cd web && pnpm exec vp staged (frontend) to appease the lint gods

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Apr 9, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 9, 2026

Pyrefly Diff

No changes detected.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Apr 9, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 9, 2026

Pyrefly Diff

No changes detected.

@asukaminato0721 asukaminato0721 added this pull request to the merge queue Apr 9, 2026
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Apr 9, 2026
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to fix sqlalchemy.orm.exc.DetachedInstanceError seen when reading plugin auto-upgrade strategy preferences by changing how SQLAlchemy sessions are created/managed in the plugin auto-upgrade service.

Changes:

  • Switched PluginAutoUpgradeService from sessionmaker(bind=db.engine).begin() to session_factory.create_session().
  • Updated unit tests to patch session_factory instead of patching sessionmaker/db.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
api/services/plugin/plugin_auto_upgrade_service.py Refactors DB session creation for strategy reads/updates to use the shared session_factory.
api/tests/unit_tests/services/plugin/test_plugin_auto_upgrade_service.py Updates mocks to match the new session factory usage.
Comments suppressed due to low confidence (1)

api/services/plugin/plugin_auto_upgrade_service.py:30

  • change_strategy() performs inserts/updates but this session scope never starts a transaction or commits. Session used as a context manager will close/rollback on exit, so changes won’t be persisted. Use an explicit transaction (with session_factory.create_session() as session, session.begin():) or call session.commit() before returning.
        with session_factory.create_session() as session:
            exist_strategy = session.scalar(
                select(TenantPluginAutoUpgradeStrategy)
                .where(TenantPluginAutoUpgradeStrategy.tenant_id == tenant_id)
                .limit(1)

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 52 to 56
def exclude_plugin(tenant_id: str, plugin_id: str) -> bool:
with sessionmaker(bind=db.engine).begin() as session:
with session_factory.create_session() as session:
exist_strategy = session.scalar(
select(TenantPluginAutoUpgradeStrategy)
.where(TenantPluginAutoUpgradeStrategy.tenant_id == tenant_id)
Copy link

Copilot AI Apr 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exclude_plugin() mutates exist_strategy but doesn’t commit. Without session.begin() / session.commit(), updates to mode and include/exclude lists won’t be saved. Wrap this session scope in an explicit transaction (or commit before returning).

Copilot uses AI. Check for mistakes.
Comment on lines 8 to +12
def _patched_session():
"""Patch sessionmaker(bind=db.engine).begin() to return a mock session as context manager."""
"""Patch session_factory.create_session() to return a mock session as context manager."""
session = MagicMock()
mock_sessionmaker = MagicMock()
mock_sessionmaker.return_value.begin.return_value.__enter__ = MagicMock(return_value=session)
mock_sessionmaker.return_value.begin.return_value.__exit__ = MagicMock(return_value=False)
patcher = patch(f"{MODULE}.sessionmaker", mock_sessionmaker)
db_patcher = patch(f"{MODULE}.db")
return patcher, db_patcher, session
session.__enter__ = MagicMock(return_value=session)
session.__exit__ = MagicMock(return_value=False)
Copy link

Copilot AI Apr 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests patch session_factory.create_session() to act as a context manager, but they don’t model/verify the transaction boundary (session.begin() / session.commit()) that production code should use for writes. After fixing the service to commit, update this helper to also mock the transaction context and assert it was invoked so the tests catch missing commits.

Copilot uses AI. Check for mistakes.
Merged via the queue into langgenius:main with commit 41eeb1f Apr 9, 2026
31 checks passed
@fatelei fatelei deleted the issue-34844 branch April 10, 2026 01:40
HanqingZ pushed a commit to HanqingZ/dify that referenced this pull request Apr 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sqlalchemy.orm.exc.DetachedInstanceError

3 participants