You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Postgres: the pre-ping opens a transaction that stays open while Python model code runs #6252
On Postgres, EngineAdapter.transaction() runs its pre-ping (SELECT 1) before BEGIN. psycopg2 isn't in autocommit mode, so that SELECT 1 starts a transaction. The snapshot evaluator opens adapter.transaction() before it runs a model's pre-statements and Python code (sqlmesh/core/snapshot/evaluator.py, around run_pre_statements(inside_transaction=True)), so the session stays idle in transaction for as long as the Python code runs.
A server or pooler that limits idle transactions then closes the connection mid-model. Postgres does this with idle_in_transaction_session_timeout, and PgBouncer has idle_transaction_timeout. This is the likely cause of the slow model in #6228, whose Python pull takes over 30 minutes.
Reproduction
Postgres 16, SQLMesh at 28d53c2, concurrent_tasks: 1, state in DuckDB. A Python model that sleeps 5 seconds:
After an initial plan, I restated it with sqlmesh plan --restate-model demo.slow_full --auto-apply and sampled pg_stat_activity once a second during the sleep:
pre_ping
Session during the sleep
true (the default)
idle in transaction, last query SELECT 1
false
idle, last query COMMIT
An INCREMENTAL_BY_TIME_RANGE Python model behaved the same way. With idle_in_transaction_session_timeout = 3s on the server, the model fails with InterfaceError: connection already closed.
When the target table doesn't exist yet, SQLMesh runs a CREATE inside the transaction before the Python code. The session is then idle in transaction whatever pre_ping is set to, and it holds the lock on the new table until the model finishes.
Possible fixes
End the implicit transaction the ping starts, for example by rolling back right after a successful ping when the connection isn't in autocommit. The transaction would then start at the first real statement, which for an existing table comes after the Python code has returned its DataFrame.
For the first-build case, produce the DataFrame before opening the transaction. Python models can yield DataFrames in batches, so this can't always mean materializing everything up front.
I only checked Postgres with psycopg2. Other drivers that start transactions implicitly may behave the same way.
Activity
fix(postgres): commit the transaction opened by the pre-ping