SQLAlchemy db_session.rollback() inside a begin_nested() context manager invalidates the outer savepoint, causing 'Can't operate on closed transaction inside context manager' on subsequent operations
When running inside a task processor that wraps execution in db_session.begin_nested(), never call bare db_session.rollback() in exception handlers — it rolls back the OUTER transaction, not just the failed operation, leaving the savepoint context permanently broken. Instead, wrap each failable operation in its own with db_session.begin_nested(): block. On exception, only that inner savepoint rolls back; the outer savepoint stays valid and the loop/function can continue. Before: try: do_work(db_session) except: db_session.rollback(). After: try: with db_session.begin_nested(): do_work(db_session) except: pass # inner savepoint auto-rolled-back.