Skip to content

fix(postgres): end pre-ping transaction and defer Python table creation - #6257

Open
codewithsruthi wants to merge 1 commit into
SQLMesh:mainfrom
codewithsruthi:fix/6252-postgres-pre-ping
Open

codewithsruthi wants to merge 1 commit into
SQLMesh:mainfrom
codewithsruthi:fix/6252-postgres-pre-ping

Conversation

@codewithsruthi

@codewithsruthi codewithsruthi commented Nov 25, 2026 •

Copy link
Copy Markdown

Description

Fixes #6252

Problem & Root Cause

  1. EngineAdapter.ping() leaves an implicit transaction open: When pre_ping=True on DB-API 2.0 drivers with autocommit=False (e.g., psycopg2/pg8000 on Postgres, GCP Postgres, Redshift, MSSQL, Db2), EngineAdapter.ping() executes SELECT 1 before BEGIN, which implicitly starts a database transaction. The connection then sits idle in transaction for the entire duration of Python model execution (and for direct ping() callers like sqlmesh info), triggering idle_in_transaction_session_timeout or PgBouncer disconnects.
  2. First-build Python models create the table before running Python code: In SnapshotEvaluator._evaluate_snapshot(), when target_table_exists=False, _execute_create() runs inside with adapter.transaction(): before evaluating the Python model, opening a transaction and holding an ACCESS EXCLUSIVE lock while Python runs.
  3. PostgresConnectionConfig.role reopens an implicit transaction on every cursor: Setting SET ROLE {role} inside _cursor_init ran on every new cursor (including immediately after ping() closed its cursor) and could silently revert if the first transaction rolled back.

Changes

  • sqlmesh/core/engine_adapter/base.py:
    • Added ROLLBACK_AFTER_PING = True and _is_autocommit(conn=None) (checking isinstance(..., bool) on autocommit / autocommit_state to stay safe across pymssql and mocked connections).
    • Updated EngineAdapter.ping() to close its cursor in finally:, fetch the connection once, and call rollback() (when callable) after a successful SELECT 1 if SUPPORTS_TRANSACTIONS, ROLLBACK_AFTER_PING, not is_transaction_active, and not _is_autocommit(conn).
  • sqlmesh/core/engine_adapter/snowflake.py:
    • Set ROLLBACK_AFTER_PING = False to avoid unnecessary ROLLBACK round-trips on Snowflake.
  • sqlmesh/core/config/connection.py:
    • Moved PostgresConnectionConfig.role (SET ROLE {role}) from _cursor_init into _connection_factory (with cursor.close() + conn.commit(), and safely guarded conn.close() on error so close failures cannot mask the original error).
  • sqlmesh/core/snapshot/evaluator.py & sqlmesh/core/context.py:
    • Deferred _execute_create() (with table_name eagerly bound) for first-build, non-self-referential, non-WAP Python models until right before inserting batch 0 (or after 0-yield completion).
    • Added BaseContext._resolve_normalized_table() and an on_table_resolve callback on ExecutionContext so Python models that call context.resolve_table / context.table on themselves without declaring depends_on_self (e.g. sushi.raw_marketing) normalize once and still have their empty table created on demand.

Test Plan

  • Added unit and integration tests in:
    • tests/core/engine_adapter/test_base.py (call order SELECT 1 -> close_cursor -> rollback, failure/autocommit/pymssql autocommit_state/active-tx/no-rollback/non-transactional DuckDB/Snowflake guards)
    • tests/core/engine_adapter/test_postgres.py (pre_ping ends implicit transaction)
    • tests/core/test_connection_config.py (PostgresConnectionConfig role via _connection_factory, error cleanup including failing conn.close(), _cursor_init is None)
    • tests/core/test_snapshot_evaluator.py (deferred create_table for FULL, INCREMENTAL_BY_TIME_RANGE, INCREMENTAL_BY_UNIQUE_KEY, SCD_TYPE_2_BY_TIME, streaming, empty generator, pre-yield exception, lazy resolve_table(self) / table(self), and upfront creation for depends_on_self & WAP)
    • tests/core/engine_adapter/integration/test_integration_postgres.py (real Postgres TRANSACTION_STATUS_IDLE + idle_in_transaction_session_timeout, first-build FULL Python model timeout test, and PostgresConnectionConfig(role=..., pre_ping=True) persistence test)
  • Executed checks:
    • 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 (against postgres:18 Docker): Passed (34 passed, 0 failed)
    • make doc-test: Passed (29 passed)

Checklist

  • I have run make py-style and fixed any issues
  • I have added tests for my changes (if applicable)
  • All existing tests pass (make fast-test)
  • My commits are signed off (git commit -s) per the DCO

Summary by CodeRabbit

  • Bug Fixes
    • PostgreSQL connections now preserve configured roles across connection checks and transactions, and connection checks no longer leave unintended transactions open.
    • Python model builds defer table creation until execution needs it, avoiding empty tables when execution fails before producing results. Empty results still create the table.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

PostgreSQL connections now apply configured roles during connection creation, and eligible pings roll back implicit transactions. Python model evaluation can defer target table creation until the model resolves its own table or produces results.

Changes: Connection Lifecycle and Python Model Evaluation

Layer / File(s) Summary
PostgreSQL role setup
sqlmesh/core/config/connection.py, tests/core/test_connection_config.py
When a role is configured, the connection factory executes SET ROLE, closes the cursor, and commits before returning the connection. Tests cover setup failures and cleanup.
Ping transaction cleanup
sqlmesh/core/engine_adapter/*, tests/core/engine_adapter/*
EngineAdapter.ping() rolls back after a successful ping when transactions are supported, rollback is enabled, the connection is not in autocommit, and no transaction is active. Snowflake disables this behavior. Tests cover rollback conditions, PostgreSQL connection state, and role retention.
Deferred Python model table creation
sqlmesh/core/context.py, sqlmesh/core/snapshot/evaluator.py, tests/core/test_snapshot_evaluator.py, tests/core/engine_adapter/integration/test_integration_postgres.py
ExecutionContext reports normalized table resolutions. Snapshot evaluation uses that callback to create eligible Python-model tables on self-resolution or before applying results. Tests cover streaming, empty and failed generators, self-referential models, WAP, and PostgreSQL evaluation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant SnapshotEvaluator
  participant PythonModel
  participant ExecutionContext
  participant EngineAdapter
  SnapshotEvaluator->>PythonModel: Render with ExecutionContext
  PythonModel->>ExecutionContext: Resolve snapshot table
  ExecutionContext->>SnapshotEvaluator: Invoke table-creation callback
  SnapshotEvaluator->>EngineAdapter: Create target table
  PythonModel-->>SnapshotEvaluator: Return or yield result
  SnapshotEvaluator->>EngineAdapter: Apply result
Loading

Possibly related PRs

  • SQLMesh/sqlmesh#6260: Implements overlapping fixes for PostgreSQL pre-ping transactions and first-build Python model table creation.

Suggested reviewers: izeigerman, mday-io, themisvaltinos

Merge Risk: Minimal · up to 26ba7

This change stops Postgres pre-ping and first-build Python model runs from leaving connections idle in a transaction. It does so by rolling back after eligible pings, setting the role at connection creation, and deferring table creation until a model's first output. No concrete defect was found, and the changed behavior is covered by targeted unit and integration tests. It looks safe to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the two main changes: ending the pre-ping implicit transaction in Postgres and deferring Python model table creation. It follows the conventional-commit style. It is specific and match…
Description check Passed The description covers the problem, root cause, specific file-level changes, and a detailed test plan with reported results. It lists the checklist items with their status. It does not use the templat…
Linked Issues check Passed Issue #6252 has one direct, open coding objective with two parts.

(1) Pre-ping leaves an implicit transaction open. The diff in sqlmesh/core/engine_adapter/base.py adds ROLLBACK_AFTER_PING = True. Af…
Out of Scope Changes check Passed All changed areas connect to the idle-in-transaction problem in #6252.

- base.py: ROLLBACK_AFTER_PING, is_autocommit, and the ping() rollback. These implement the core fix.
- snowflake.py: ROLLBACK
…
Full details: Title check

Explanation

The title names the two main changes: ending the pre-ping implicit transaction in Postgres and deferring Python model table creation. It follows the conventional-commit style. It is specific and matches the changeset, though it omits the role and rollback details.

Full details: Description check

Explanation

The description covers the problem, root cause, specific file-level changes, and a detailed test plan with reported results. It lists the checklist items with their status. It does not use the template's placeholder comments, but it fills each template section. The required sections are present and complete.

Full details: Linked Issues check

Explanation

Issue #6252 has one direct, open coding objective with two parts.

(1) Pre-ping leaves an implicit transaction open. The diff in sqlmesh/core/engine_adapter/base.py adds ROLLBACK_AFTER_PING = True. After a successful SELECT 1, ping() calls rollback() when SUPPORTS_TRANSACTIONS is set, no transaction is active, and the connection is not in autocommit. The issue's first suggested fix is implemented. Postgres tests in test_postgres.py and the integration tests check the idle state and the idle_in_transaction_session_timeout behavior. The issue names psycopg2 only, and the tests cover the Postgres path.

(2) First-build Python models create the table before Python runs. The diff in sqlmesh/core/snapshot/evaluator.py defers _create_table for model.is_python, non-depends_on_self, non-WAP models. Creation runs before the first batch is applied, or after an empty generator completes. Lazy creation also runs when the model resolves its own table through on_table_resolve. Self-referential and WAP models keep upfront creation. This matches the issue's second suggestion, and the issue's note on batched yields is handled by creating before batch 0 instead of materializing all output.

The PR description and the changes summary both list unit tests for these paths in test_base.py, test_postgres.py, test_snapshot_evaluator.py, and the Postgres integration suite. I did not run these tests. The evidence for behavior is the diff and the reported test results.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to the idle-in-transaction problem in #6252.

  • base.py: ROLLBACK_AFTER_PING, _is_autocommit, and the ping() rollback. These implement the core fix.
  • snowflake.py: ROLLBACK_AFTER_PING = False. This is a targeted opt-out of the new rollback for an adapter where the extra ROLLBACK is not needed. It is part of the same change.
  • connection.py: moves Postgres SET ROLE from _cursor_init into _connection_factory. The PR description states that SET ROLE in _cursor_init runs after each ping closes its cursor, which reopens an implicit transaction. This is a direct cause of the reported problem, so the change is in scope.
  • context.py: _resolve_normalized_table and on_table_resolve. These support the lazy first-build creation in evaluator.py for Python models that resolve their own table without depends_on_self. Without them, that deferral would miss the table. This is in scope.
  • Tests: added in the files listed for the above changes. They cover these behaviors.

I found no change unrelated to #6252.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5b86c186-4918-4c17-8e8b-61b9d7536278
Commits

Reviewing files that changed from the base of the PR and between ce229ae and 26ba72d.

Files selected for processing: 10

  • sqlmesh/core/config/connection.py
  • sqlmesh/core/context.py
  • sqlmesh/core/engine_adapter/base.py
  • sqlmesh/core/engine_adapter/snowflake.py
  • sqlmesh/core/snapshot/evaluator.py
  • tests/core/engine_adapter/integration/test_integration_postgres.py
  • tests/core/engine_adapter/test_base.py
  • tests/core/engine_adapter/test_postgres.py
  • tests/core/test_connection_config.py
  • tests/core/test_snapshot_evaluator.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

@codewithsruthi
codewithsruthi force-pushed the fix/6252-postgres-pre-ping branch from ff32a78 to df14358 Compare November 26, 2026 00:22
@codewithsruthi codewithsruthi changed the title fix(postgres): end implicit pre-ping transaction and defer first-build Python table creation fix(engine): end pre-ping transaction and defer Python table creation Nov 26, 2026
@codewithsruthi
codewithsruthi marked this pull request as ready for review November 26, 2026 00:29
Signed-off-by: Sruthi <codewithsruthi@users.noreply.github.com>
@codewithsruthi codewithsruthi changed the title fix(engine): end pre-ping transaction and defer Python table creation fix(postgres): end pre-ping transaction and defer Python table creation Nov 26, 2026
@codewithsruthi
codewithsruthi force-pushed the fix/6252-postgres-pre-ping branch from df14358 to 26ba72d Compare November 26, 2026 00:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Postgres: the pre-ping opens a transaction that stays open while Python model code runs

1 participant