From 2a157fdcff87059b2f05c05ca4a59a4813153b00 Mon Sep 17 00:00:00 2001 From: Vamsi-klu Date: Wed, 25 Nov 2026 10:43:03 +0100 Subject: [PATCH 1/2] fix(postgres): roll back implicit pre-ping transaction and commit SET ROLE on connect On Postgres (and Redshift), psycopg2, pg8000, and redshift_connector run with autocommit=False and implicitly start a transaction on the first statement. EngineAdapter.transaction() executes pre-ping (SELECT 1) before BEGIN, leaving the session idle in transaction for the entire duration of Python model execution and triggering idle_in_transaction_session_timeout or PgBouncer idle_transaction_timeout disconnects. - Override BasePostgresEngineAdapter.ping() to call connection.rollback() after super().ping() closes its cursor when transactions are supported, no transaction is active, and autocommit is not True (leaving RisingWave, DuckDB, MSSQL, and Snowflake unaffected). - Move PostgresConnectionConfig role initialization (SET ROLE) from _cursor_init into _connection_factory followed by an immediate commit (closing the connection safely on error) so cursor creation inside begin() does not immediately re-open an implicit transaction. Fixes #6252 Signed-off-by: Vamsi-klu --- sqlmesh/core/config/connection.py | 26 +- sqlmesh/core/engine_adapter/base_postgres.py | 9 + tests/core/engine_adapter/test_duckdb.py | 5 + tests/core/engine_adapter/test_postgres.py | 117 +++++++++ tests/core/engine_adapter/test_redshift.py | 45 ++++ tests/core/engine_adapter/test_risingwave.py | 28 +++ tests/core/test_connection_config.py | 238 +++++++++++++++++++ 7 files changed, 460 insertions(+), 8 deletions(-) diff --git a/sqlmesh/core/config/connection.py b/sqlmesh/core/config/connection.py index c23c468841..73bf94dfb1 100644 --- a/sqlmesh/core/config/connection.py +++ b/sqlmesh/core/config/connection.py @@ -1501,17 +1501,27 @@ def _engine_adapter(self) -> t.Type[EngineAdapter]: def _connection_factory(self) -> t.Callable: from psycopg2 import connect - return connect - - @property - def _cursor_init(self) -> t.Optional[t.Callable[[t.Any], None]]: if not self.role: - return None + return connect - def init(cursor: t.Any) -> None: - cursor.execute(f"SET ROLE {self.role}") + role = self.role - return init + def _connect(*args: t.Any, **kwargs: t.Any) -> t.Any: + conn = connect(*args, **kwargs) + try: + with conn.cursor() as cursor: + cursor.execute(f"SET ROLE {role}") + if getattr(conn, "autocommit", False) is not True: + conn.commit() + except Exception: + try: + conn.close() + except Exception: + logger.exception("Failed to close connection") + raise + return conn + + return _connect class MySQLConnectionConfig(ConnectionConfig): diff --git a/sqlmesh/core/engine_adapter/base_postgres.py b/sqlmesh/core/engine_adapter/base_postgres.py index e2347b1263..ab92af6e92 100644 --- a/sqlmesh/core/engine_adapter/base_postgres.py +++ b/sqlmesh/core/engine_adapter/base_postgres.py @@ -72,6 +72,15 @@ def columns( def catalog_support(self) -> CatalogSupport: return CatalogSupport.SINGLE_CATALOG_ONLY + def ping(self) -> None: + super().ping() + if ( + self.SUPPORTS_TRANSACTIONS + and not self._connection_pool.is_transaction_active + and getattr(self.connection, "autocommit", False) is not True + ): + self.connection.rollback() + def table_exists(self, table_name: TableName) -> bool: """ Postgres doesn't support describe so I'm using what the redshift cursor does to check if a table diff --git a/tests/core/engine_adapter/test_duckdb.py b/tests/core/engine_adapter/test_duckdb.py index 6e8097d7eb..66a2d0eafd 100644 --- a/tests/core/engine_adapter/test_duckdb.py +++ b/tests/core/engine_adapter/test_duckdb.py @@ -232,3 +232,8 @@ def test_drop_object_cascade_by_catalog_type(make_mocked_engine_adapter: t.Calla 'DROP SCHEMA IF EXISTS "lake"."virt" CASCADE', 'DROP TABLE IF EXISTS "native"."phys"."t" CASCADE', ] + + +def test_ping_succeeds_without_active_transaction(adapter: EngineAdapter): + adapter.ping() + assert adapter.fetchone("SELECT 1") == (1,) diff --git a/tests/core/engine_adapter/test_postgres.py b/tests/core/engine_adapter/test_postgres.py index ebcdd03f55..eb8ad11a11 100644 --- a/tests/core/engine_adapter/test_postgres.py +++ b/tests/core/engine_adapter/test_postgres.py @@ -282,3 +282,120 @@ def test_sync_grants_config_with_default_schema( "WHERE table_schema = 'public' AND table_name = 'test_table' " "AND grantor = current_role AND grantee <> current_role" ) + + +class _FakePsycopg2Cursor: + def __init__(self, conn: "_FakePsycopg2Connection") -> None: + self._conn = conn + + def execute(self, sql: str, *args: t.Any, **kwargs: t.Any) -> None: + self._conn.events.append(f"execute:{sql}") + if not self._conn.autocommit: + self._conn.in_tx = True + + def close(self) -> None: + self._conn.events.append("cursor.close") + + def __enter__(self) -> "_FakePsycopg2Cursor": + return self + + def __exit__(self, *args: t.Any) -> None: + self.close() + + +class _FakePsycopg2Connection: + def __init__( + self, + autocommit: bool = False, + rollback_error: t.Optional[Exception] = None, + ) -> None: + self.autocommit = autocommit + self.in_tx = False + self.closed = False + self.events: t.List[str] = [] + self._rollback_error = rollback_error + + def cursor(self) -> _FakePsycopg2Cursor: + return _FakePsycopg2Cursor(self) + + def rollback(self) -> None: + self.events.append("conn.rollback") + if self._rollback_error is not None: + raise self._rollback_error + self.in_tx = False + + def commit(self) -> None: + self.events.append("conn.commit") + self.in_tx = False + + def close(self) -> None: + self.events.append("conn.close") + self.closed = True + + +def test_pre_ping_rolls_back_implicit_transaction(): + conn = _FakePsycopg2Connection(autocommit=False) + adapter = PostgresEngineAdapter(lambda: conn, pre_ping=True) + + with adapter.transaction(): + assert conn.events == ["execute:SELECT 1", "cursor.close", "conn.rollback"] + assert conn.in_tx is False + adapter.execute("INSERT INTO tbl VALUES (1)") + assert conn.in_tx is True + + assert conn.in_tx is False + assert conn.events[-1] == "conn.commit" + + +def test_pre_ping_skips_rollback_when_autocommit_true(): + conn = _FakePsycopg2Connection(autocommit=True) + adapter = PostgresEngineAdapter(lambda: conn, pre_ping=True) + + adapter.ping() + + assert conn.events == ["execute:SELECT 1", "cursor.close"] + assert "conn.rollback" not in conn.events + + +def test_ping_skips_rollback_inside_active_transaction(): + conn = _FakePsycopg2Connection(autocommit=False) + adapter = PostgresEngineAdapter(lambda: conn, pre_ping=False) + + with adapter.transaction(): + adapter.execute("INSERT INTO tbl VALUES (1)") + assert conn.in_tx is True + adapter.ping() + assert conn.in_tx is True + assert "conn.rollback" not in conn.events + + assert conn.in_tx is False + assert conn.events[-1] == "conn.commit" + + +def test_pre_ping_reconnects_if_rollback_fails(): + conns: t.List[_FakePsycopg2Connection] = [] + + def factory() -> _FakePsycopg2Connection: + error = RuntimeError("connection already closed") if not conns else None + conn = _FakePsycopg2Connection(autocommit=False, rollback_error=error) + conns.append(conn) + return conn + + adapter = PostgresEngineAdapter(factory, pre_ping=True) + + with adapter.transaction(): + assert len(conns) == 2 + assert conns[0].closed is True + assert conns[0].events == [ + "execute:SELECT 1", + "cursor.close", + "conn.rollback", + "conn.close", + ] + assert conns[1].closed is False + assert conns[1].in_tx is False + adapter.execute("SELECT 2") + assert conns[1].in_tx is True + + assert conns[1].in_tx is False + assert conns[1].events[-1] == "conn.commit" diff --git a/tests/core/engine_adapter/test_redshift.py b/tests/core/engine_adapter/test_redshift.py index a3260ed4cd..97f8e76b23 100644 --- a/tests/core/engine_adapter/test_redshift.py +++ b/tests/core/engine_adapter/test_redshift.py @@ -956,3 +956,48 @@ def test_redshift_multiple_column_drops_no_clustering_operations( assert len(operations) == 2 assert all(isinstance(op, TableAlterDropColumnOperation) for op in operations) + + +def test_pre_ping_rolls_back_implicit_transaction() -> None: + events: t.List[str] = [] + + class FakeRedshiftCursor: + def __init__(self, conn: "FakeRedshiftConnection") -> None: + self._conn = conn + self.paramstyle = "format" + + def execute(self, sql: str, *args: t.Any, **kwargs: t.Any) -> None: + events.append(f"execute:{sql}") + if not self._conn.autocommit: + self._conn.in_tx = True + + def close(self) -> None: + events.append("cursor.close") + + class FakeRedshiftConnection: + def __init__(self) -> None: + self.autocommit = False + self.in_tx = False + + def cursor(self) -> FakeRedshiftCursor: + return FakeRedshiftCursor(self) + + def rollback(self) -> None: + events.append("conn.rollback") + self.in_tx = False + + def commit(self) -> None: + events.append("conn.commit") + self.in_tx = False + + conn = FakeRedshiftConnection() + adapter = RedshiftEngineAdapter(lambda: conn, pre_ping=True) + + with adapter.transaction(): + assert events == ["execute:SELECT 1", "cursor.close", "conn.rollback"] + assert conn.in_tx is False + adapter.execute("INSERT INTO tbl VALUES (1)") + assert conn.in_tx is True + + assert conn.in_tx is False + assert events[-1] == "conn.commit" diff --git a/tests/core/engine_adapter/test_risingwave.py b/tests/core/engine_adapter/test_risingwave.py index ed3cd77a3f..63c9da76ca 100644 --- a/tests/core/engine_adapter/test_risingwave.py +++ b/tests/core/engine_adapter/test_risingwave.py @@ -84,3 +84,31 @@ def test_drop_view(adapter: t.Callable): call('DROP VIEW IF EXISTS "db"."view"'), ] ) + + +def test_ping_skips_rollback_when_transactions_unsupported(): + events: t.List[str] = [] + + class FakeCursor: + def execute(self, sql: str, *args: t.Any, **kwargs: t.Any) -> None: + events.append(f"execute:{sql}") + + def close(self) -> None: + events.append("cursor.close") + + class FakeConnection: + autocommit = False + + def cursor(self) -> FakeCursor: + return FakeCursor() + + def rollback(self) -> None: + events.append("conn.rollback") + + conn = FakeConnection() + adapter = RisingwaveEngineAdapter(lambda: conn, pre_ping=True) + + adapter.ping() + + assert events == ["execute:SELECT 1", "cursor.close"] + assert "conn.rollback" not in events diff --git a/tests/core/test_connection_config.py b/tests/core/test_connection_config.py index d0ba023273..830378e1a4 100644 --- a/tests/core/test_connection_config.py +++ b/tests/core/test_connection_config.py @@ -1192,6 +1192,244 @@ def test_postgres(make_config): assert config.is_recommended_for_state_sync is True +class _FakePostgresCursor: + def __init__( + self, + conn: "_FakePostgresConnection", + execute_error: t.Optional[Exception] = None, + fail_on_sql: t.Optional[str] = None, + ) -> None: + self._conn = conn + self._execute_error = execute_error + self._fail_on_sql = fail_on_sql + + def execute(self, sql: str, *args: t.Any, **kwargs: t.Any) -> None: + self._conn.events.append(f"execute:{sql}") + if self._execute_error is not None and ( + self._fail_on_sql is None or sql == self._fail_on_sql + ): + raise self._execute_error + if not self._conn.autocommit: + self._conn.in_tx = True + + def close(self) -> None: + self._conn.events.append("cursor.close") + + def __enter__(self) -> "_FakePostgresCursor": + return self + + def __exit__(self, *args: t.Any) -> None: + self.close() + + +class _FakePostgresConnection: + def __init__( + self, + autocommit: bool = False, + execute_error: t.Optional[Exception] = None, + commit_error: t.Optional[Exception] = None, + close_error: t.Optional[Exception] = None, + fail_on_sql: t.Optional[str] = None, + ) -> None: + self.autocommit = autocommit + self.in_tx = False + self.closed = False + self.events: t.List[str] = [] + self._execute_error = execute_error + self._commit_error = commit_error + self._close_error = close_error + self._fail_on_sql = fail_on_sql + + def cursor(self) -> _FakePostgresCursor: + return _FakePostgresCursor( + self, + execute_error=self._execute_error, + fail_on_sql=self._fail_on_sql, + ) + + def commit(self) -> None: + self.events.append("conn.commit") + if self._commit_error is not None: + raise self._commit_error + self.in_tx = False + + def rollback(self) -> None: + self.events.append("conn.rollback") + self.in_tx = False + + def close(self) -> None: + self.events.append("conn.close") + if self._close_error is not None: + raise self._close_error + self.closed = True + + +def test_postgres_role_set_and_committed_on_connect(make_config): + fake_conn = _FakePostgresConnection(autocommit=False) + config = make_config( + type="postgres", + host="host", + user="user", + password="password", + port=5432, + database="database", + role="analytics", + ) + assert isinstance(config, PostgresConnectionConfig) + assert config._cursor_init is None + + with patch("psycopg2.connect", return_value=fake_conn): + adapter = config.create_engine_adapter() + _ = adapter.cursor + assert fake_conn.events == [ + "execute:SET ROLE analytics", + "cursor.close", + "conn.commit", + ] + assert fake_conn.in_tx is False + + # Re-creating a cursor must not re-execute SET ROLE. + adapter._connection_pool.close_cursor() + _ = adapter.cursor + assert fake_conn.events.count("execute:SET ROLE analytics") == 1 + assert fake_conn.in_tx is False + + # Entering a transaction with pre_ping=True leaves the session idle until SQL executes. + with adapter.transaction(): + assert fake_conn.in_tx is False + assert fake_conn.events.count("execute:SET ROLE analytics") == 1 + + +def test_postgres_role_closes_connection_on_failure(make_config): + fake_conn = _FakePostgresConnection( + autocommit=False, execute_error=RuntimeError("invalid role") + ) + config = make_config( + type="postgres", + host="host", + user="user", + password="password", + port=5432, + database="database", + role="bad_role", + ) + + with patch("psycopg2.connect", return_value=fake_conn): + adapter = config.create_engine_adapter() + with pytest.raises(RuntimeError, match="invalid role"): + _ = adapter.connection + + assert fake_conn.closed is True + + +def test_postgres_role_autocommit_skips_commit(make_config): + fake_conn = _FakePostgresConnection(autocommit=True) + config = make_config( + type="postgres", + host="host", + user="user", + password="password", + port=5432, + database="database", + role="analytics", + ) + + with patch("psycopg2.connect", return_value=fake_conn): + adapter = config.create_engine_adapter() + _ = adapter.connection + + assert fake_conn.events == ["execute:SET ROLE analytics", "cursor.close"] + assert "conn.commit" not in fake_conn.events + + +@pytest.mark.parametrize( + "execute_error, commit_error, close_error, expected_match", + [ + (None, RuntimeError("commit failed"), None, "commit failed"), + (None, RuntimeError("commit failed"), RuntimeError("close failed"), "commit failed"), + (RuntimeError("invalid role"), None, RuntimeError("close failed"), "invalid role"), + ], +) +def test_postgres_role_commit_and_close_failure_preserves_original_error( + make_config, + execute_error: t.Optional[Exception], + commit_error: t.Optional[Exception], + close_error: t.Optional[Exception], + expected_match: str, +): + fake_conn = _FakePostgresConnection( + autocommit=False, + execute_error=execute_error, + commit_error=commit_error, + close_error=close_error, + ) + config = make_config( + type="postgres", + host="host", + user="user", + password="password", + port=5432, + database="database", + role="analytics", + ) + + with patch("psycopg2.connect", return_value=fake_conn): + adapter = config.create_engine_adapter() + with pytest.raises(RuntimeError, match=expected_match): + _ = adapter.connection + + assert "conn.close" in fake_conn.events + if close_error is None: + assert fake_conn.closed is True + + +def test_postgres_role_reapplied_on_reconnect(make_config): + conns: t.List[_FakePostgresConnection] = [] + + def fake_connect(*args: t.Any, **kwargs: t.Any) -> _FakePostgresConnection: + # Second connection fails pre-ping SELECT 1 so transaction() reconnects to a third. + if len(conns) == 1: + conn = _FakePostgresConnection( + autocommit=False, + execute_error=RuntimeError("lost connection"), + fail_on_sql="SELECT 1", + ) + else: + conn = _FakePostgresConnection(autocommit=False) + conns.append(conn) + return conn + + config = make_config( + type="postgres", + host="host", + user="user", + password="password", + port=5432, + database="database", + role="analytics", + ) + + with patch("psycopg2.connect", side_effect=fake_connect): + adapter = config.create_engine_adapter() + _ = adapter.connection + assert len(conns) == 1 + assert conns[0].events == ["execute:SET ROLE analytics", "cursor.close", "conn.commit"] + + # Reconnecting after adapter.close() re-runs SET ROLE on the new connection. + adapter.close() + assert conns[0].closed is True + _ = adapter.connection + assert len(conns) == 2 + assert conns[1].events == ["execute:SET ROLE analytics", "cursor.close", "conn.commit"] + + # Reconnecting after a failed pre-ping re-runs SET ROLE and leaves session idle. + with adapter.transaction(): + assert len(conns) == 3 + assert conns[1].closed is True + assert conns[2].events == ["execute:SET ROLE analytics", "cursor.close", "conn.commit"] + assert conns[2].in_tx is False + + def test_gcp_postgres(make_config): config = make_config( type="gcp_postgres", From 2777c66eba9d07099cfa8e170c9e034355f5ddeb Mon Sep 17 00:00:00 2001 From: Vamsi-klu Date: Wed, 25 Nov 2026 10:43:04 +0100 Subject: [PATCH 2/2] fix(scheduler): emit CreateNode before evaluating annotated Python models On the first build of a materialized Python model (or after a breaking change), SnapshotEvaluator._evaluate_snapshot() previously ran CREATE TABLE inside adapter.transaction() before invoking Python model code, keeping the session idle in transaction and holding an AccessExclusiveLock for the full Python execution regardless of pre_ping. Extend Scheduler._dag() to emit a separate CreateNode before EvaluateNode for annotated materialized Python models without pre_statements or post_statements, matching how INCREMENTAL_BY_TIME_RANGE models already separate table creation from evaluation. Part of #6252 Signed-off-by: Vamsi-klu --- sqlmesh/core/scheduler.py | 13 +- tests/core/test_scheduler.py | 383 ++++++++++++++++++++++++++++++++++- 2 files changed, 392 insertions(+), 4 deletions(-) diff --git a/sqlmesh/core/scheduler.py b/sqlmesh/core/scheduler.py index 7345d92888..5224d80110 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -722,9 +722,18 @@ def _dag( snapshot.is_incremental_by_time_range or ((not batch_concurrency or batch_concurrency > 1) and batch_size) or not intervals + or ( + snapshot.is_model + and snapshot.is_materialized + and snapshot.model.is_python + and snapshot.model.annotated + and not snapshot.model.pre_statements + and not snapshot.model.post_statements + ) ): - # Add a separate node for table creation in case when there multiple concurrent - # evaluation nodes or when there are no intervals to evaluate. + # Add a separate node for table creation when there are multiple concurrent + # evaluation nodes, no intervals to evaluate, or a Python model whose + # execution should not hold a CREATE TABLE transaction open. create_node = CreateNode(snapshot_name=snapshot.name) dag.add(create_node, upstream_dependencies) snapshots_to_create.remove(snapshot.snapshot_id) diff --git a/tests/core/test_scheduler.py b/tests/core/test_scheduler.py index cd32d2451d..ab15811c3a 100644 --- a/tests/core/test_scheduler.py +++ b/tests/core/test_scheduler.py @@ -2,22 +2,27 @@ import pytest from pytest_mock.plugin import MockerFixture -from sqlglot import parse_one, parse +from sqlglot import exp, parse_one, parse from sqlglot.helper import first from sqlmesh.core.context import Context, ExecutionContext +from sqlmesh.core.engine_adapter.postgres import PostgresEngineAdapter from sqlmesh.core.environment import EnvironmentNamingInfo from sqlmesh.core.macros import RuntimeStage from sqlmesh.core.model import load_sql_based_model -from sqlmesh.core.model.definition import AuditResult, SqlModel +from sqlmesh.core.model.definition import AuditResult, PythonModel, SqlModel from sqlmesh.core.model.kind import ( + CustomKind, + FullKind, IncrementalByTimeRangeKind, IncrementalByUniqueKeyKind, TimeColumn, SCDType2ByColumnKind, + ViewKind, ) from sqlmesh.core.node import IntervalUnit from sqlmesh.core.scheduler import ( + CreateNode, Scheduler, interval_diff, compute_interval_params, @@ -26,6 +31,7 @@ SchedulingUnit, DummyNode, ) +from sqlmesh.utils.metaprogramming import Executable from sqlmesh.core.signal import signal from sqlmesh.core.snapshot import ( Snapshot, @@ -1213,3 +1219,376 @@ def test_dag_upstream_dependency_caching_with_complex_diamond(mocker: MockerFixt expected_g_node: {expected_a_node}, expected_h_node: {expected_a_node}, } + + +@pytest.mark.parametrize( + "kind, columns, pre_statements, post_statements, expect_create_node", + [ + (FullKind(), {"a": "INT"}, [], [], True), + (IncrementalByUniqueKeyKind(unique_key=["a"]), {"a": "INT"}, [], [], True), + (FullKind(), {"a": "INT"}, ["SELECT 1"], [], False), + (FullKind(), {"a": "INT"}, [], ["SELECT 1"], False), + (FullKind(), None, [], [], False), + (ViewKind(), {"a": "INT"}, [], [], False), + ], +) +def test_dag_emits_create_node_for_annotated_python_model( + mocker: MockerFixture, + make_snapshot, + kind, + columns, + pre_statements, + post_statements, + expect_create_node: bool, +): + model = PythonModel( + name="db.py_model", + entrypoint="execute", + kind=kind, + columns=columns, + pre_statements=[parse_one(s) for s in pre_statements], + post_statements=[parse_one(s) for s in post_statements], + python_env={ + "execute": Executable( + name="execute", + alias="execute", + path="test_scheduler.py", + payload="def execute(context, **kwargs):\n return []", + ) + }, + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + scheduler = Scheduler( + snapshots=[snapshot], + snapshot_evaluator=mocker.Mock(), + state_sync=mocker.Mock(), + default_catalog=None, + ) + + interval = (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + snapshots_to_create = {snapshot.snapshot_id} + + dag = scheduler._dag( + {snapshot: [interval]}, + snapshots_to_create=snapshots_to_create, + ) + + eval_node = EvaluateNode(snapshot_name=snapshot.name, interval=interval, batch_index=0) + create_node = CreateNode(snapshot_name=snapshot.name) + + if expect_create_node: + assert dag.graph == { + create_node: set(), + eval_node: {create_node}, + } + assert snapshot.snapshot_id not in snapshots_to_create + else: + assert dag.graph == {eval_node: set()} + assert snapshot.snapshot_id in snapshots_to_create + + +class _FakeSchedulerPsycopg2Cursor: + description: t.Optional[t.List[t.Tuple[t.Any, ...]]] + _rows: t.List[t.Tuple[t.Any, ...]] + + def __init__(self, conn: "_FakeSchedulerPsycopg2Connection") -> None: + self._conn = conn + self.rowcount = 1 + self.description = None + self._rows = [] + + def execute(self, sql: str, *args: t.Any, **kwargs: t.Any) -> None: + self._conn.events.append(f"execute:{sql}") + if not self._conn.autocommit: + self._conn.in_tx = True + upper_sql = sql.lstrip().upper() + if upper_sql.startswith("CREATE TABLE"): + self._conn.table_created = True + self.description = None + self._rows = [] + elif "FROM PG_TABLES" in upper_sql: + self.description = [ + ("schema_name", None, None, None, None, None, None), + ("name", None, None, None, None, None, None), + ("type", None, None, None, None, None, None), + ] + self._rows = ( + [(self._conn.physical_table.db, self._conn.physical_table.name, "TABLE")] + if self._conn.table_created + else [] + ) + elif "CURRENT_CATALOG" in upper_sql: + self.description = [("current_catalog", None, None, None, None, None, None)] + self._rows = [(None,)] + else: + self.description = None + self._rows = [] + + def fetchone(self) -> t.Optional[t.Tuple[t.Any, ...]]: + return self._rows[0] if self._rows else None + + def fetchall(self) -> t.List[t.Tuple[t.Any, ...]]: + return list(self._rows) + + def close(self) -> None: + self._conn.events.append("cursor.close") + + +class _FakeSchedulerPsycopg2Connection: + def __init__(self, physical_table: exp.Table, fail_next_python: bool = False) -> None: + self.physical_table = physical_table + self.autocommit = False + self.in_tx = False + self.table_created = False + self.fail_next_python = fail_next_python + self.events: t.List[str] = [] + self.tx_states_during_python: t.List[bool] = [] + + def cursor(self) -> _FakeSchedulerPsycopg2Cursor: + return _FakeSchedulerPsycopg2Cursor(self) + + def rollback(self) -> None: + self.events.append("conn.rollback") + self.in_tx = False + + def commit(self) -> None: + self.events.append("conn.commit") + self.in_tx = False + + def close(self) -> None: + self.events.append("conn.close") + + +def test_python_model_first_build_and_restatement_keep_postgres_idle( + mocker: MockerFixture, make_snapshot +): + model = PythonModel( + name="db.py_model", + dialect="postgres", + entrypoint="execute", + kind=FullKind(), + columns={"a": "INT"}, + python_env={ + "execute": Executable( + name="execute", + alias="execute", + path="test_scheduler.py", + payload=( + "import pandas as pd\n" + "def execute(context, **kwargs):\n" + " context.engine_adapter.connection.tx_states_during_python.append(\n" + " context.engine_adapter.connection.in_tx\n" + " )\n" + " return pd.DataFrame({'a': [1]})\n" + ), + ) + }, + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + physical_table = exp.to_table(snapshot.table_name(), dialect="postgres") + + conn = _FakeSchedulerPsycopg2Connection(physical_table=physical_table) + adapter = PostgresEngineAdapter( # type: ignore[abstract] + lambda: conn, multithreaded=False, pre_ping=True + ) + + evaluator = SnapshotEvaluator(adapter) + state_sync = mocker.MagicMock() + state_sync.get_environment_statements.return_value = [] + scheduler = Scheduler( + snapshots=[snapshot], + snapshot_evaluator=evaluator, + state_sync=state_sync, + default_catalog=None, + max_workers=1, + ) + + deployability_index = DeployabilityIndex.all_deployable() + env_naming_info = EnvironmentNamingInfo(name="prod") + interval = (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + + # First build: table does not yet exist; CreateNode commits DDL before EvaluateNode runs. + assert conn.table_created is False + errors_first, skipped_first = scheduler.run_merged_intervals( + merged_intervals={snapshot: [interval]}, + deployability_index=deployability_index, + environment_naming_info=env_naming_info, + ) + assert not errors_first + assert not skipped_first + assert conn.table_created is True + assert conn.in_tx is False + assert conn.tx_states_during_python == [False] + + # Restatement: table already exists; pre-ping rollback still keeps session idle during Python. + errors_restate, skipped_restate = scheduler.run_merged_intervals( + merged_intervals={snapshot: [interval]}, + deployability_index=deployability_index, + environment_naming_info=env_naming_info, + ) + assert not errors_restate + assert not skipped_restate + assert conn.in_tx is False + assert conn.tx_states_during_python == [False, False] + + +@pytest.mark.parametrize( + "kind, depends_on, expected_depends_on_past", + [ + ( + CustomKind( + materialization="custom", dialect="postgres", batch_size=1, batch_concurrency=1 + ), + set(), + False, + ), + ( + CustomKind(materialization="custom", dialect="postgres", batch_size=1), + {"db.py_model"}, + True, + ), + ( + IncrementalByUniqueKeyKind(unique_key=["a"], batch_size=1, batch_concurrency=1), + set(), + True, + ), + ], +) +def test_dag_annotated_python_model_batch_concurrency_one_ordering( + mocker: MockerFixture, + make_snapshot, + kind, + depends_on: t.Set[str], + expected_depends_on_past: bool, +): + model = PythonModel( + name="db.py_model", + entrypoint="execute", + kind=kind, + columns={"a": "INT"}, + depends_on=depends_on, + python_env={ + "execute": Executable( + name="execute", + alias="execute", + path="test_scheduler.py", + payload="def execute(context, **kwargs):\n return []", + ) + }, + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + assert snapshot.depends_on_past is expected_depends_on_past + + scheduler = Scheduler( + snapshots=[snapshot], + snapshot_evaluator=mocker.Mock(), + state_sync=mocker.Mock(), + default_catalog=None, + ) + + interval_0 = (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + interval_1 = (to_timestamp("2023-01-02"), to_timestamp("2023-01-03")) + snapshots_to_create = {snapshot.snapshot_id} + + dag = scheduler._dag( + {snapshot: [interval_0, interval_1]}, + snapshots_to_create=snapshots_to_create, + ) + + create_node = CreateNode(snapshot_name=snapshot.name) + eval_0 = EvaluateNode(snapshot_name=snapshot.name, interval=interval_0, batch_index=0) + eval_1 = EvaluateNode(snapshot_name=snapshot.name, interval=interval_1, batch_index=1) + dummy_node = DummyNode(snapshot_name=snapshot.name) + + assert dag.graph == { + create_node: set(), + eval_0: {create_node}, + eval_1: {create_node, eval_0}, + dummy_node: {eval_0, eval_1}, + } + assert snapshot.snapshot_id not in snapshots_to_create + + +def test_python_model_retry_after_eval_failure_preserves_first_insert_and_keeps_postgres_idle( + mocker: MockerFixture, make_snapshot +): + from sqlmesh.core.snapshot.evaluator import IncrementalByUniqueKeyStrategy + + model = PythonModel( + name="db.py_retry_model", + dialect="postgres", + entrypoint="execute", + kind=IncrementalByUniqueKeyKind(unique_key=["a"]), + columns={"a": "INT"}, + python_env={ + "execute": Executable( + name="execute", + alias="execute", + path="test_scheduler.py", + payload=( + "import pandas as pd\n" + "def execute(context, **kwargs):\n" + " conn = context.engine_adapter.connection\n" + " conn.tx_states_during_python.append(conn.in_tx)\n" + " if conn.fail_next_python:\n" + " conn.fail_next_python = False\n" + " raise RuntimeError('transient python failure')\n" + " return pd.DataFrame({'a': [1]})\n" + ), + ) + }, + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + physical_table = exp.to_table(snapshot.table_name(), dialect="postgres") + + conn = _FakeSchedulerPsycopg2Connection(physical_table=physical_table, fail_next_python=True) + adapter = PostgresEngineAdapter( # type: ignore[abstract] + lambda: conn, multithreaded=False, pre_ping=True + ) + + evaluator = SnapshotEvaluator(adapter) + insert_spy = mocker.spy(IncrementalByUniqueKeyStrategy, "insert") + state_sync = mocker.MagicMock() + state_sync.get_environment_statements.return_value = [] + scheduler = Scheduler( + snapshots=[snapshot], + snapshot_evaluator=evaluator, + state_sync=state_sync, + default_catalog=None, + max_workers=1, + ) + + deployability_index = DeployabilityIndex.all_deployable() + env_naming_info = EnvironmentNamingInfo(name="prod") + interval = (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + + # First attempt: CreateNode creates and commits table, then Python fails inside EvaluateNode. + errors_first, _ = scheduler.run_merged_intervals( + merged_intervals={snapshot: [interval]}, + deployability_index=deployability_index, + environment_naming_info=env_naming_info, + ) + assert len(errors_first) == 1 + assert conn.table_created is True + assert conn.in_tx is False + assert conn.tx_states_during_python == [False] + assert not snapshot.intervals + assert insert_spy.call_count == 0 + + # Retry: table already exists, but empty intervals preserve is_first_insert=True while staying idle. + errors_retry, skipped_retry = scheduler.run_merged_intervals( + merged_intervals={snapshot: [interval]}, + deployability_index=deployability_index, + environment_naming_info=env_naming_info, + ) + assert not errors_retry + assert not skipped_retry + assert conn.in_tx is False + assert conn.tx_states_during_python == [False, False] + assert insert_spy.call_count == 1 + assert insert_spy.call_args.kwargs["is_first_insert"] is True