Skip to content
Latchkey

Python "sqlalchemy.orm.exc.DetachedInstanceError" in CI

DetachedInstanceError is raised when you access an unloaded (lazy) attribute on an ORM object whose Session has been closed or committed-and-expired. The object is detached and can no longer load from the database.

What this error means

A test fails with "sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceed" when reading a relationship outside the session.

pytest
sqlalchemy.orm.exc.DetachedInstanceError: Instance <User at 0x...> is not bound to a Session; attribute refresh operation cannot proceed

Common causes

Accessing a lazy attribute after the session closed

The fixture returned an object, the session ended, then the test touched a relationship that needed a query.

expire_on_commit leaving attributes unloaded

After commit, attributes are expired; accessing them outside an open session triggers a refresh that cannot run.

How to fix it

Keep the session open or eager-load what you need

  1. Keep the session alive for the scope where the object is used.
  2. Eager-load relationships you will access (joinedload/selectinload).
  3. Set expire_on_commit=False on the test session if you read attributes after commit.
Python
Session = sessionmaker(bind=engine, expire_on_commit=False)

How to prevent it

  • Scope object usage to an open session.
  • Eager-load relationships needed outside the session.
  • Use expire_on_commit=False where post-commit reads are intended.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →