Repository navigation
fix(postgres): end pre-ping transaction and defer Python table creation - #6257
codewithsruthi wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
ff32a78 to
df14358
Compare
Signed-off-by: Sruthi <codewithsruthi@users.noreply.github.com>
df14358 to
26ba72d
Compare
Description
Fixes #6252
Problem & Root Cause
EngineAdapter.ping()leaves an implicit transaction open: Whenpre_ping=Trueon DB-API 2.0 drivers withautocommit=False(e.g.,psycopg2/pg8000on Postgres, GCP Postgres, Redshift, MSSQL, Db2),EngineAdapter.ping()executesSELECT 1beforeBEGIN, which implicitly starts a database transaction. The connection then sitsidle in transactionfor the entire duration of Python model execution (and for directping()callers likesqlmesh info), triggeringidle_in_transaction_session_timeoutor PgBouncer disconnects.SnapshotEvaluator._evaluate_snapshot(), whentarget_table_exists=False,_execute_create()runs insidewith adapter.transaction():before evaluating the Python model, opening a transaction and holding anACCESS EXCLUSIVElock while Python runs.PostgresConnectionConfig.rolereopens an implicit transaction on every cursor: SettingSET ROLE {role}inside_cursor_initran on every new cursor (including immediately afterping()closed its cursor) and could silently revert if the first transaction rolled back.Changes
sqlmesh/core/engine_adapter/base.py:ROLLBACK_AFTER_PING = Trueand_is_autocommit(conn=None)(checkingisinstance(..., bool)onautocommit/autocommit_stateto stay safe acrosspymssqland mocked connections).EngineAdapter.ping()to close its cursor infinally:, fetch the connection once, and callrollback()(when callable) after a successfulSELECT 1ifSUPPORTS_TRANSACTIONS,ROLLBACK_AFTER_PING,not is_transaction_active, andnot _is_autocommit(conn).sqlmesh/core/engine_adapter/snowflake.py:ROLLBACK_AFTER_PING = Falseto avoid unnecessaryROLLBACKround-trips on Snowflake.sqlmesh/core/config/connection.py:PostgresConnectionConfig.role(SET ROLE {role}) from_cursor_initinto_connection_factory(withcursor.close()+conn.commit(), and safely guardedconn.close()on error so close failures cannot mask the original error).sqlmesh/core/snapshot/evaluator.py&sqlmesh/core/context.py:_execute_create()(withtable_nameeagerly bound) for first-build, non-self-referential, non-WAP Python models until right before inserting batch 0 (or after 0-yield completion).BaseContext._resolve_normalized_table()and anon_table_resolvecallback onExecutionContextso Python models that callcontext.resolve_table/context.tableon themselves without declaringdepends_on_self(e.g.sushi.raw_marketing) normalize once and still have their empty table created on demand.Test Plan
tests/core/engine_adapter/test_base.py(call orderSELECT 1 -> close_cursor -> rollback, failure/autocommit/pymssqlautocommit_state/active-tx/no-rollback/non-transactional DuckDB/Snowflake guards)tests/core/engine_adapter/test_postgres.py(pre_pingends implicit transaction)tests/core/test_connection_config.py(PostgresConnectionConfigrolevia_connection_factory, error cleanup including failingconn.close(),_cursor_init is None)tests/core/test_snapshot_evaluator.py(deferredcreate_tableforFULL,INCREMENTAL_BY_TIME_RANGE,INCREMENTAL_BY_UNIQUE_KEY,SCD_TYPE_2_BY_TIME, streaming, empty generator, pre-yield exception, lazyresolve_table(self)/table(self), and upfront creation fordepends_on_self& WAP)tests/core/engine_adapter/integration/test_integration_postgres.py(real PostgresTRANSACTION_STATUS_IDLE+idle_in_transaction_session_timeout, first-buildFULLPython model timeout test, andPostgresConnectionConfig(role=..., pre_ping=True)persistence test)make py-style: Passed (ruff,ruff-format,mypy,valid migrations)make fast-test: Passed (3,155 passed, 0 failed across all fast/isolated/fork/registry/dialect suites)pytest tests/core/engine_adapter/integration/test_integration_postgres.py(againstpostgres:18Docker): Passed (34 passed, 0 failed)make doc-test: Passed (29 passed)Checklist
make py-styleand fixed any issuesmake fast-test)git commit -s) per the DCOSummary by CodeRabbit