Database Session Management#
Dify uses Flask-SQLAlchemy with a context-local db.session proxy. Historically, services, controllers, and model classes accessed this global directly, causing three recurring error classes :
DetachedInstanceErrorโ ORM object accessed after its session closes (common across thread boundaries)PendingRollbackErrorโdb.session.refresh()called while a session has a pending rollback- Transaction isolation violations โ
db.session.commit()inside a helper or decorator flushes all pending dirty state, making upstream rollbacks impossible
Two overlapping refactoring tracks address this:
- Issue #37403 โ threads an explicit
sessionparameter through ~153 service, controller, and core files - Issue #40372 โ converts ~113
@propertyaccessors on ORM model classes inapi/models/*.pythat internally calldb.session
PR #38559 is the largest single refactor, covering explicit session propagation across 150+ files .
Session Ownership Patterns#
Four patterns are used across the codebase. Choose the one that matches the call site's ownership model.
Pattern 1 โ Caller-Injected (@with_session)#
The default for HTTP handlers. The @with_session decorator in api/controllers/common/session.py opens one request-scoped session, commits on success, and rolls back on any exception . Write mode is the default; pass write=False for read-only handlers. The session is injected as the first positional argument after self.
Streaming responses: The node output inspector uses @with_session(write=False) to read its initial snapshot before building the SSE Response, preserving an HTTP 404 for a missing run. The streamed body runs after the handler's session closes and the Flask app context is gone, so it must not reuse that session or access db.session. Before returning, the handler derives a maker with sessionmaker_for(session), which preserves the injected session's bind and expire_on_commit setting without consulting the process-wide factory or opening a session. Each node refresh opens its own short session and closes it on success or failure, without committing; the returned view contains plain values and is yielded after the session closes.
Critical rule: service methods within a caller-owned transaction must call session.flush() rather than session.commit(). Calling commit() inside a sessionmaker().begin() context closes the transaction and raises InvalidRequestError: Can't operate on closed transaction inside context manager . PR #36150 is the canonical fix, replacing all internal commits in the RAG pipeline DSL service with flush() .
MCP controllers are an exception: they use a plain Session(db.engine, expire_on_commit=False) with explicit commit() to avoid conflicts when downstream generation code also commits .
RAG import controllers are another exception: when a service catches exceptions internally rather than re-raising, use a plain Session with explicit commit()/rollback() โ sessionmaker().begin() will attempt to auto-commit a dead transaction on exit, raising InvalidRequestError .
Pattern 2 โ Detached Query Service#
For anonymous or trial-admission flows. The service opens a session per query method and returns frozen dataclasses to the controller; the controller never holds a live ORM instance. See api/repositories/app_preview_query_repository.py .
The shared suggested-questions flow (Console app/agent, Explore, Trial, Web and Service API) follows the same rule. AppDefinitionQueryService and its repository, plus api/repositories/message_repository.py, run short query sessions that return detached data โ a frozen SuggestedQuestionsContext and a PreparedHistory โ so every session closes before attachment processing, token counting and LLM invocation. SuggestedQuestionsGenerator.prepare() (api/services/message_suggested_questions_generator.py) opens one isolated app context (current_app.app_context()) for model resolution, quota and tracing. It calls db.session.remove() before provider I/O and again before tracing, so no session stays open during the LLM call and the caller's scoped session is protected. History reaches the generator as detached data rather than a live ORM object.
Pattern 3 โ Independent Session for Side-Effect Writes#
For writes that must commit immediately and independently of the caller's transaction โ audit logs, rate-limit records, hit counts:
with sessionmaker(bind=db.engine, expire_on_commit=False).begin() as session:
session.add(record)
The canonical example is _on_query in api/core/rag/retrieval/dataset_retrieval.py for DatasetQuery records. Issue #37886 originally reported the bug: using db.session.commit() in _on_query flushed all pending dirty objects in the request session, making upstream rollbacks impossible .
โ ๏ธ Do not use Pattern 3 for writes the caller reads back in the same transaction. Under MySQL's REPEATABLE READ default, the caller's open snapshot will not see rows committed by a Pattern 3 session after the snapshot was frozen. This causes 400 "One or more files not found." on MySQL but not PostgreSQL โ see the Database Transaction Isolation article .
Pattern 4 โ Console RequestContext (Application Service Boundary)#
Refactored console routes use @console_account_admission and a RequestContext parameter (no session). Application services and their repositories own session lifecycles internally via sessionmaker. Controllers receive detached data, such as frozen dataclasses or dictionary payloads. This pattern is also used for account/workspace operations. See api/controllers/console/app/app.py and api/repositories/app/console_repository.py .
The four Console Agent observability routes use this boundary. SQLAlchemyAgentObservabilityRepository resolves the runtime App and reads logs or statistics in the same session, scoped to the admitted workspace, then closes the session before returning dictionary payloads. The shared runtime App resolver commits a hidden backing App when one must be created for a workflow-only Agent.
Console Agent chat, Build finalization, and task stop also use this boundary. AgentConsoleRuntime selects the admitted account's Build or Preview conversation and prepares generation in a runtime-owned session. It commits and closes that session before the controller consumes the stream. Task stop resolves the runtime App in a repository session that closes before the stop service is called.
Console Agent audio uses the same boundary with the shared AppAudioRuntime. The Agent App repository revalidates the admitted App and reads the effective speech-to-text setting before the upload is read. For text-to-speech it returns an App reference and, when requested and available, the account-owned message answer rather than a live ORM object. Voice discovery checks for an existing runtime App first. In each case the repository session closes before provider calls begin.
OpenAPI admission sessions: The OpenAPI auth pipeline (api/controllers/openapi/auth/pipelines.py) opens an admission session to run requirements. Each endpoint's EndpointSpec.context declares the handler context it needs: "orm" (default), "workspace", "app", or None. Only "orm" keeps the admission session open for the handler. For every other value the pipeline commits and closes the session before the handler runs, so the handler never holds it. Handler arguments are bound while the session is still open:
"workspace"passes theRequestContext"app"passes anAppRequestContext(tenant_id,app_id)Nonepasses noctx
App discovery and export logic lives in application services (application_services().apps...), which own their own sessions, rather than in controllers using db.session directly. For example, the inner API DSL export calls application_services().apps.exports.export_for_inner.
RequestContext also carries resource_app_ids (None for account callers; an empty set admits no apps). Its account_id falls back to token_id when the subject has no account_id.
Model Property Refactoring (Issue #40372)#
Issue #40372 targets ~113 @property accessors on ORM model classes in api/models/*.py that implicitly read db.session . The canonical conversion, established in PR #40370 :
- Remove the
@propertydecorator - Add
session: Sessionto the method signature - Replace internal
db.sessioncalls with the passed-insession - Update all call sites to pass an explicit session
Zero-call-site rule: Properties with no external callers are deleted rather than converted . Verify via repository-wide grep before claiming a work slice.
Pydantic compatibility: When Pydantic models use from_attributes=True, wrap the ORM instance with a SessionResponseSource subclass (defined in api/fields/base.py) that defines @property delegates to session-backed accessors. This pattern was introduced in PR #42034 .
Write-only properties: When a property is write-heavy but read-light, keep only the setter as property(fset=_set_inputs) โ reading raises AttributeError rather than silently using the global session. Applied to Conversation.inputs and Message.inputs in PR #42335 .
Representative merged PRs:
| PR | Change |
|---|---|
| #41831 | InstalledApp.tenant โ tenant_with_session(self, *, session: Session) |
| #41885 | AppAnnotationSetting.collection_binding_detail โ session-param method |
| #41721 | Removed four legacy db.session wrappers on Document where session-aware twins existed |
| #42034 | Converted WorkflowRun accessors; introduced SessionResponseSource base class |
| #42335 | Write-only setter pattern for Conversation.inputs, Message.inputs |
Contributors coordinate in issue #40372 to avoid duplicate work by claiming non-overlapping file/class scopes .
Common Failure Modes#
| Symptom | Root Cause | Fix |
|---|---|---|
DetachedInstanceError | ORM object accessed after its implicit session closes (e.g., across threads) | Inject session param; keep object in same session scope |
PendingRollbackError in load_user | db.session.refresh() called while session has a pending rollback | Replace with session.expunge() or use injected session |
InvalidRequestError: Can't operate on closed transaction | Service calls session.commit() inside a controller-owned sessionmaker().begin() context | Use session.flush() in services; let @with_session own the final commit |
| Dirty data committed mid-request | db.session.commit() inside a helper flushes all pending dirty objects | Move side-effect writes to an independent sessionmaker(...).begin() context |
DetachedInstanceError from ToolEngine._create_message_files | Premature db.session.close() detaches objects | Remove the premature close |
400 "One or more files not found." on MySQL only | FileService commits UploadFile in an independent session; caller's REPEATABLE READ snapshot predates the commit | Refactor to Pattern 1, or set MySQL to READ COMMITTED |
| Dataset hit-count deadlock | Concurrent retrieval/update flows with inconsistent lock ordering | Fix lock ordering in dataset_retrieval.py |
| Celery task reads stale data | Task dispatched before its creating transaction commits | Dispatch tasks after session.commit(), not inside the open transaction |
Vector store lookup misses newly created DatasetCollectionBinding | Vector factory received a different session than the one that flushed the binding | Pass the same session to Vector(dataset, ..., session=session) and DatasetCollectionBindingService |
Celery Task Sessions#
Celery task sessions have been refactored to use session_factory.create_session() rather than the global db.session. A task that dispatches sub-tasks (e.g., triggering re-indexing) must commit its own session first โ otherwise the dispatched Celery worker may read a stale or missing row . The enable_annotation_reply_task illustrates the correct Celery pattern: a single session_factory.create_session() context wraps all queries and writes, passes the same session to both DatasetCollectionBindingService and Vector(...), and calls session.commit() only after all work is complete .
Testing with Explicit Sessions#
Explicit session injection enables unit tests without a running PostgreSQL instance. api/tests/unit_tests/conftest.py provides three fixtures :
| Fixture | Purpose |
|---|---|
sqlite_session | Real SQLAlchemy session backed by a per-test in-process SQLite database |
sqlite_session_factory | sessionmaker bound to the SQLite engine for code paths that manage their own session lifecycle |
unbound_session | For testing code paths that must abort before any DB access |
An autouse _sqlite_session_factory fixture monkeypatches core.db.session_factory._session_maker so every call to session_factory.create_session() โ and therefore @with_session โ automatically returns a SQLite-backed session with no per-test mock setup required .
CI enforcement: A gate blocks new session = MagicMock() / session = Mock() assignments in api/tests/unit_tests/ via an ast-grep rule (no-new-session-mock). The gate uses a baseline diff approach โ only net-new violations in PR-changed files fail the check. Suppress with a same-line comment # guard-ignore: no-new-session-mock -- <reason> .
Two further, independent ast-grep guards run via scripts/check_no_new_test_doubles.py (rules in scripts/ast_grep_rules/; the CLI requires --staged or --base-rev). Like the session-mock gate, they compare old and new Git contents, so only net-new violations in changed files fail:
no_new_mock.yml(no-new-mock) rejects newMock,MagicMock, andSimpleNamespaceconstructor calls in changed Python sources, including qualified names, common import aliases, and direct factory aliases. Comments and string literals are ignored;AsyncMockand method patching are out of scope. This rule has no ignore marker.no_new_stub_subclass.yml(no-new-stub-subclass) rejects new test subclasses ofModelInstance,ModelManager,DatasetRetrieval,TraceQueueManager,MessageBasedAppQueueManager, andThreadthat bypass the parent constructor โ an__init__that does not delegate tosuper().__init__()/Base.__init__(self, ...), or a dataclass subclass withinit=Falseor a__post_init__that does not delegate. Exceptions need a reason on the class header:# guard-ignore: no-new-stub-subclass -- <reason>.
Instantiate the real production class instead, using SQLite-backed sessions and real objects. The guards' tests live in api/tests/unit_tests/commands/test_check_no_new_test_doubles.py.
PR #38784 tracks the migration from MagicMock sessions to real SQLite sessions across the test suite .
Key Files and References#
| File | Role |
|---|---|
api/controllers/common/session.py | @with_session decorator โ opens one request-scoped session, commits on success, rolls back on failure |
api/core/db/session_factory.py | SessionFactory and _session_maker โ the monkeypatch target in unit tests; sessionmaker_for(session) derives a maker for independent sessions on the injected session's bind |
api/core/rag/retrieval/dataset_retrieval.py | Mixed patterns: Pattern 1 in _retriever, Pattern 3 in _on_query |
api/core/rag/datasource/vdb/vector_factory.py | Vector.__init__ accepts session: Session | None; required when vector type is not pre-resolved |
api/services/knowledge/dataset_service.py | DatasetCollectionBindingService.get_dataset_collection_binding uses session.flush() after creating a new binding |
api/tasks/annotation/enable_annotation_reply_task.py | Celery task example: single session_factory.create_session() context, session passed to DatasetCollectionBindingService and Vector(...), explicit session.commit() at end |
api/models/model.py | Largest target in issue #40372 (~47 properties) |
api/tests/unit_tests/conftest.py | SQLite test fixtures (sqlite_session, sqlite_session_factory, unbound_session) |
Tracking issues:
- #37403 โ explicit session threading across ~153 service/controller/core files
- #40372 โ model
@propertyrefactoring (~113 properties across 9 files)
Related articles:
- Database Transaction Isolation โ MySQL REPEATABLE READ visibility gap when Pattern 3 is misapplied
- SQLite Test Infrastructure โ full fixture architecture and migration history