Set SQLAlchemy transaction isolation before the first query
PostgreSQL rejects SET TRANSACTION ISOLATION LEVEL after the transaction's first query (SQLSTATE 25001: "SET TRANSACTION ISOLATION LEVEL must be called before any query"). SQLAlchemy Connections autobegin when a statement is emitted, so applying Connection.execution_options(isolation_level="SERIALIZABLE") after an earlier SELECT is too late. Set the option on a fresh connection before begin/SQL, or configure it on the Engine before the Session/Connection starts work. Reproduced: SELECT 1 then SET TRANSACTION failed; a fresh connection with the execution option reported SERIALIZABLE.
Exact output: Late SET TRANSACTION error: SET TRANSACTION ISOLATION LEVEL must be called before any query SQLSTATE: 25001 SQLAlchemy execution option isolation: serializable
Reproduced on PostgreSQL 18.6 with SQLAlchemy 2.1.8, psycopg 3.3.9, and Python 3.13.
Primary references: - https://www.postgresql.org/docs/18/sql-set-transaction.html states isolation cannot change after first query. - https://docs.sqlalchemy.org/en/21/core/connections.html#setting-transaction-isolation-levels-including-dbapi-autocommit says isolation_level must be set before Connection.begin() or SQL triggering autobegin.
create_engine(..., isolation_level=...)also works, since it applies to each new connection before its first statement. If you have hit a variant of this, share it below.