From 3276f3085d3899cb78d25912c67b66e3404a9222 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Thu, 19 Nov 2026 10:04:37 +0000 Subject: [PATCH 1/7] fix: roll back session after OAuth2 flush failure in execute_with_oauth2_retry When refreshing a database's per-user OAuth2 token (e.g. during chart data query execution) a DB write to the token fails to flush -- for example, a statement timeout while persisting a rotated access/refresh token -- the SQLAlchemy session is left deactivated (is_active=False). The existing `execute_with_oauth2_retry` except-block detected this case and re-raised the original exception, but deliberately skipped calling session.rollback(), assuming some other "execution owner" further up the stack would do it. Nothing further up actually does this, so the broken session persists for the rest of the request. Any later ORM access in the same request (e.g. loading an expired attribute) then raises PendingRollbackError instead of a sane error, surfacing as an unhandled 500 far away from the real cause. Roll back the session immediately when we detect it has been deactivated, before re-raising the original exception. This keeps the original error visible (still handled by the normal exception/error-response machinery) while leaving the session usable for whatever runs next in the request. Updated the existing unit test (test_execute_with_oauth2_retry_preserves_failed_flush_error) which had asserted rollback was *not* called -- that assertion encoded the bug. Co-Authored-By: Claude Sonnet 5 --- superset/utils/oauth2.py | 11 +++++++++-- tests/unit_tests/utils/oauth2_tests.py | 11 +++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/superset/utils/oauth2.py b/superset/utils/oauth2.py index 8456c6a5cd21..1390c12f9b1e 100644 --- a/superset/utils/oauth2.py +++ b/superset/utils/oauth2.py @@ -401,9 +401,16 @@ def execute_with_oauth2_retry( # noqa: C901 finally: _oauth2_retry_active.reset(retry_context) except Exception as ex: - # A metadata flush failure expires ORM configuration and is not an - # authentication failure. Leave rollback to the execution owner. + # A flush failure (e.g. a statement timeout while persisting a + # refreshed/rotated token) deactivates the request-scoped session. + # It is not an authentication failure, but leaving the session + # un-rolled-back here means every later ORM access in the same + # request raises ``PendingRollbackError`` instead of the original + # error, surfacing as an unhandled 500 far from the real cause. Roll + # back immediately so the session is usable again before we + # propagate the original exception. if not db.session.is_active: + db.session.rollback() raise # The guest check comes first, as in `check_for_oauth2`. is_oauth2_error = ( diff --git a/tests/unit_tests/utils/oauth2_tests.py b/tests/unit_tests/utils/oauth2_tests.py index efdc307918bc..4fad1885ce04 100644 --- a/tests/unit_tests/utils/oauth2_tests.py +++ b/tests/unit_tests/utils/oauth2_tests.py @@ -1230,7 +1230,14 @@ def operation() -> None: def test_execute_with_oauth2_retry_preserves_failed_flush_error( mocker: MockerFixture, ) -> None: - """Expired metadata must not mask an operation's failed-flush exception.""" + """Expired metadata must not mask an operation's failed-flush exception. + + A deactivated session (``is_active is False``) means a prior flush failed, + e.g. a statement timeout while persisting a refreshed OAuth2 token. The + request-scoped session must be rolled back here -- nothing else in the + call stack does it -- so later ORM access in the same request doesn't + raise ``PendingRollbackError`` instead of surfacing the real error. + """ error = RuntimeError("metadata flush failed") operation = mocker.Mock(side_effect=error) database = mocker.MagicMock() @@ -1247,5 +1254,5 @@ def test_execute_with_oauth2_retry_preserves_failed_flush_error( operation.assert_called_once_with() database.is_oauth2_enabled.assert_not_called() refresh.assert_not_called() - db.session.rollback.assert_not_called() + db.session.rollback.assert_called_once_with() assert not is_oauth2_retry_active() From 19b63d4798600ffdfbe999501f6009c6c9b6fec4 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Sat, 21 Nov 2026 04:13:32 +0000 Subject: [PATCH 2/7] fix(oauth2): suppress pylint consider-using-transaction for rollback in exception handler The rollback inside the except block is an exception-path cleanup pattern, not a general unit-of-work transaction, so the @transaction decorator does not apply. Suppress the warning inline to match existing codebase precedent (e.g. jinja_context.py:307, views/base.py:574, datasets/api.py:718). Co-Authored-By: Claude Sonnet 4.6 --- superset/utils/oauth2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/superset/utils/oauth2.py b/superset/utils/oauth2.py index 1390c12f9b1e..4b596d432789 100644 --- a/superset/utils/oauth2.py +++ b/superset/utils/oauth2.py @@ -410,7 +410,7 @@ def execute_with_oauth2_retry( # noqa: C901 # back immediately so the session is usable again before we # propagate the original exception. if not db.session.is_active: - db.session.rollback() + db.session.rollback() # pylint: disable=consider-using-transaction raise # The guest check comes first, as in `check_for_oauth2`. is_oauth2_error = ( From e6d1416e096437c0c690206d6f5b573cbff21f16 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Mon, 23 Nov 2026 16:05:23 +0000 Subject: [PATCH 3/7] fix: move OAuth2 flush-failure rollback to the connection-open caller Revert the rollback in execute_with_oauth2_retry, which reactivated the session before SQLExecutor checks db.session.is_active, and roll back in Database._open_with_oauth2_retry, the caller with no rollback owner. Add a real-session test that fails a flush while opening the connection. Co-Authored-By: Claude Sonnet 5.5 --- superset/models/core.py | 21 ++++++++--- superset/utils/oauth2.py | 11 ++---- tests/unit_tests/models/core_test.py | 50 ++++++++++++++++++++++---- tests/unit_tests/utils/oauth2_tests.py | 11 ++---- 4 files changed, 65 insertions(+), 28 deletions(-) diff --git a/superset/models/core.py b/superset/models/core.py index 86564b921f66..ed0a03d947c7 100755 --- a/superset/models/core.py +++ b/superset/models/core.py @@ -1106,10 +1106,23 @@ def _open_with_oauth2_retry( return with ExitStack() as stack: - yield execute_with_oauth2_retry( - self, - lambda: stack.enter_context(open_context()), - ) + try: + value = execute_with_oauth2_retry( + self, + lambda: stack.enter_context(open_context()), + ) + except Exception: + # Opening the connection can refresh and stage an OAuth2 token, + # and a failed flush of it deactivates the request-scoped + # session. Nothing on this path owns a rollback, so later ORM + # access in the same request would raise PendingRollbackError + # in place of the real error. (Other callers of + # ``execute_with_oauth2_retry`` own the rollback themselves and + # inspect ``db.session.is_active`` first.) + if not db.session.is_active: + db.session.rollback() # pylint: disable=consider-using-transaction + raise + yield value def get_default_catalog(self) -> str | None: """ diff --git a/superset/utils/oauth2.py b/superset/utils/oauth2.py index 4b596d432789..8456c6a5cd21 100644 --- a/superset/utils/oauth2.py +++ b/superset/utils/oauth2.py @@ -401,16 +401,9 @@ def execute_with_oauth2_retry( # noqa: C901 finally: _oauth2_retry_active.reset(retry_context) except Exception as ex: - # A flush failure (e.g. a statement timeout while persisting a - # refreshed/rotated token) deactivates the request-scoped session. - # It is not an authentication failure, but leaving the session - # un-rolled-back here means every later ORM access in the same - # request raises ``PendingRollbackError`` instead of the original - # error, surfacing as an unhandled 500 far from the real cause. Roll - # back immediately so the session is usable again before we - # propagate the original exception. + # A metadata flush failure expires ORM configuration and is not an + # authentication failure. Leave rollback to the execution owner. if not db.session.is_active: - db.session.rollback() # pylint: disable=consider-using-transaction raise # The guest check comes first, as in `check_for_oauth2`. is_oauth2_error = ( diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py index ffb84ee74ba8..8cf8ba6f3bfc 100644 --- a/tests/unit_tests/models/core_test.py +++ b/tests/unit_tests/models/core_test.py @@ -1517,9 +1517,9 @@ def test_prequeries_execute_on_real_connections( with database.get_raw_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE name = 'prequery_marker'") - assert cursor.fetchone() is not None, ( - "prequery did not run on the new connection" - ) + assert ( + cursor.fetchone() is not None + ), "prequery did not run on the new connection" assert _ENGINE_CACHE == {} @@ -3270,6 +3270,44 @@ def test_get_raw_connection_leaves_recovery_to_an_outer_retry( refresh.assert_not_called() +def test_get_raw_connection_rolls_back_a_session_deactivated_by_a_failed_flush( + session: Session, + app_context: None, + mocker: MockerFixture, +) -> None: + """ + A failed flush while opening the connection (for example persisting a + refreshed OAuth2 token) must not leave the request's session unusable, or + the next ORM read raises ``PendingRollbackError`` in place of the real error. + """ + Database.metadata.create_all(session.get_bind()) + + def failing_flush() -> None: + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + session.flush() + + engine = mocker.MagicMock() + engine.raw_connection.side_effect = failing_flush + database = Database(database_name="login_db", sqlalchemy_uri="snowflake://") + database.id = 1 + mocker.patch.object(Database, "_get_sqla_engine", return_value=engine) + mocker.patch.object(Database, "is_oauth2_enabled", return_value=True) + mocker.patch.object(Database, "get_oauth2_config", return_value={"id": "client-id"}) + mocker.patch.object(Database, "db_engine_spec").get_prequeries.return_value = [] + g = mocker.MagicMock() + g.user.id = 2 + mocker.patch("superset.models.core.g", g) + mocker.patch("superset.utils.oauth2.g", g) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + with database.get_raw_connection(): + pass + + assert session.is_active + assert session.query(Database).count() == 0 + + def test_get_raw_connection_without_oauth2_is_unchanged( app_context: None, mocker: MockerFixture, @@ -4868,6 +4906,6 @@ def _get_engine(catalog=None, schema=None, **kwargs): upper = sql.upper() assert "OFFSET" in upper assert "LIMIT" in upper - assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), ( - f"OFFSET must precede LIMIT for Trino, got: {sql!r}" - ) + assert upper.rfind("OFFSET") < upper.rfind( + "LIMIT" + ), f"OFFSET must precede LIMIT for Trino, got: {sql!r}" diff --git a/tests/unit_tests/utils/oauth2_tests.py b/tests/unit_tests/utils/oauth2_tests.py index 4fad1885ce04..efdc307918bc 100644 --- a/tests/unit_tests/utils/oauth2_tests.py +++ b/tests/unit_tests/utils/oauth2_tests.py @@ -1230,14 +1230,7 @@ def operation() -> None: def test_execute_with_oauth2_retry_preserves_failed_flush_error( mocker: MockerFixture, ) -> None: - """Expired metadata must not mask an operation's failed-flush exception. - - A deactivated session (``is_active is False``) means a prior flush failed, - e.g. a statement timeout while persisting a refreshed OAuth2 token. The - request-scoped session must be rolled back here -- nothing else in the - call stack does it -- so later ORM access in the same request doesn't - raise ``PendingRollbackError`` instead of surfacing the real error. - """ + """Expired metadata must not mask an operation's failed-flush exception.""" error = RuntimeError("metadata flush failed") operation = mocker.Mock(side_effect=error) database = mocker.MagicMock() @@ -1254,5 +1247,5 @@ def test_execute_with_oauth2_retry_preserves_failed_flush_error( operation.assert_called_once_with() database.is_oauth2_enabled.assert_not_called() refresh.assert_not_called() - db.session.rollback.assert_called_once_with() + db.session.rollback.assert_not_called() assert not is_oauth2_retry_active() From d92153f593f4096d7b21bcbb51481faec363331c Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Mon, 23 Nov 2026 20:06:38 +0000 Subject: [PATCH 4/7] fix: address review on OAuth2 flush rollback (get_df site, guarded rollback, scope) Limit the connection-open rollback to get_raw_connection so get_inspector keeps the executor's prepare-path error text, roll back the failed flush at get_df's own engine lookup, guard the rollback so it cannot mask the flush error, and restore ruff 0.9.7 layout on two unrelated test asserts. Co-Authored-By: Claude Sonnet 5.5 --- superset/models/core.py | 48 +++++++++++++----- tests/unit_tests/models/core_test.py | 76 +++++++++++++++++++++++++--- 2 files changed, 106 insertions(+), 18 deletions(-) diff --git a/superset/models/core.py b/superset/models/core.py index ed0a03d947c7..ba69056d357a 100755 --- a/superset/models/core.py +++ b/superset/models/core.py @@ -1080,13 +1080,33 @@ def open_connection() -> Iterator[Connection]: self.db_engine_spec.prepare_connection(conn.dbapi_connection) yield conn - with self._open_with_oauth2_retry(open_connection) as conn: + with self._open_with_oauth2_retry( + open_connection, rollback_failed_flush=True + ) as conn: yield conn + @staticmethod + def _rollback_deactivated_session() -> None: + """ + Roll back the request-scoped session if a failed flush deactivated it. + + Opening a connection can refresh and stage an OAuth2 token, and a failed + flush of it leaves the session unusable: later ORM access in the same + request would raise ``PendingRollbackError`` in place of the real error. + The rollback itself must not replace the error being raised. + """ + if db.session.is_active: + return + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except Exception: # pylint: disable=broad-except + logger.warning("Unable to roll back the session", exc_info=True) + @contextmanager def _open_with_oauth2_retry( self, open_context: Callable[[], AbstractContextManager[T]], + rollback_failed_flush: bool = False, ) -> Iterator[T]: """ Enter ``open_context()``, refreshing a rejected OAuth2 token once. @@ -1097,6 +1117,11 @@ def _open_with_oauth2_retry( again. Only entering the context is retried: the caller's block has not run, so nothing has been executed on the database. Errors raised by the caller's block are not retried here. + + ``rollback_failed_flush`` rolls back a session deactivated by a failed + flush before the error propagates. Callers whose own error handling + reads the deactivated session (``get_inspector`` under the executor) + leave it off. """ user_id = getattr(getattr(g, "user", None), "id", None) if user_id is None or not self.is_oauth2_enabled() or is_oauth2_retry_active(): @@ -1112,15 +1137,8 @@ def _open_with_oauth2_retry( lambda: stack.enter_context(open_context()), ) except Exception: - # Opening the connection can refresh and stage an OAuth2 token, - # and a failed flush of it deactivates the request-scoped - # session. Nothing on this path owns a rollback, so later ORM - # access in the same request would raise PendingRollbackError - # in place of the real error. (Other callers of - # ``execute_with_oauth2_retry`` own the rollback themselves and - # inspect ``db.session.is_active`` first.) - if not db.session.is_active: - db.session.rollback() # pylint: disable=consider-using-transaction + if rollback_failed_flush: + self._rollback_deactivated_session() raise yield value @@ -1283,8 +1301,14 @@ def _execute_sql_with_mutation_and_logging( """ script = SQLScript(sql, self.db_engine_spec.engine) - with self.get_sqla_engine(catalog=catalog, schema=schema) as engine: - engine_url = engine.url + try: + with self.get_sqla_engine(catalog=catalog, schema=schema) as engine: + engine_url = engine.url + except Exception: + # With Redis locking, a refresh staged by an earlier engine call is + # flushed here, outside ``get_raw_connection``'s own rollback. + self._rollback_deactivated_session() + raise log_query = app.config["QUERY_LOGGER"] diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py index 8cf8ba6f3bfc..eb4b454a432e 100644 --- a/tests/unit_tests/models/core_test.py +++ b/tests/unit_tests/models/core_test.py @@ -1517,9 +1517,9 @@ def test_prequeries_execute_on_real_connections( with database.get_raw_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE name = 'prequery_marker'") - assert ( - cursor.fetchone() is not None - ), "prequery did not run on the new connection" + assert cursor.fetchone() is not None, ( + "prequery did not run on the new connection" + ) assert _ENGINE_CACHE == {} @@ -3308,6 +3308,70 @@ def failing_flush() -> None: assert session.query(Database).count() == 0 +def test_get_inspector_leaves_a_failed_flush_to_the_caller( + session: Session, + app_context: None, + mocker: MockerFixture, +) -> None: + """ + ``get_inspector`` must not roll back: the executor's prepare path reads + the deactivated session to keep the original error text. + """ + Database.metadata.create_all(session.get_bind()) + + def failing_flush(*args: Any, **kwargs: Any) -> None: + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + session.flush() + + database = Database(database_name="login_db", sqlalchemy_uri="snowflake://") + database.id = 1 + mocker.patch.object(Database, "_get_sqla_engine", side_effect=failing_flush) + mocker.patch.object(Database, "is_oauth2_enabled", return_value=True) + mocker.patch.object(Database, "get_oauth2_config", return_value={"id": "client-id"}) + g = mocker.MagicMock() + g.user.id = 2 + mocker.patch("superset.models.core.g", g) + mocker.patch("superset.utils.oauth2.g", g) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + with database.get_inspector(): + pass + + assert not session.is_active + session.rollback() + + +def test_rollback_deactivated_session_does_not_mask_the_original_error( + mocker: MockerFixture, +) -> None: + """A failing rollback is logged, not raised over the flush failure.""" + db_mock = mocker.patch("superset.models.core.db") + db_mock.session.is_active = False + db_mock.session.rollback.side_effect = RuntimeError("connection lost") + + Database._rollback_deactivated_session() + + db_mock.session.rollback.assert_called_once_with() + + +def test_get_df_rolls_back_a_session_deactivated_by_a_failed_engine_flush( + app_context: None, + mocker: MockerFixture, +) -> None: + """A staged refresh flushed by get_df's own engine lookup is rolled back.""" + database = Database(database_name="db", sqlalchemy_uri="sqlite://") + mocker.patch.object( + Database, "get_sqla_engine", side_effect=RuntimeError("flush failed") + ) + rollback = mocker.patch.object(Database, "_rollback_deactivated_session") + + with pytest.raises(RuntimeError, match="flush failed"): + database.get_df("SELECT 1") + + rollback.assert_called_once_with() + + def test_get_raw_connection_without_oauth2_is_unchanged( app_context: None, mocker: MockerFixture, @@ -4906,6 +4970,6 @@ def _get_engine(catalog=None, schema=None, **kwargs): upper = sql.upper() assert "OFFSET" in upper assert "LIMIT" in upper - assert upper.rfind("OFFSET") < upper.rfind( - "LIMIT" - ), f"OFFSET must precede LIMIT for Trino, got: {sql!r}" + assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), ( + f"OFFSET must precede LIMIT for Trino, got: {sql!r}" + ) From 8d06e5db0e7ea5c93045d05d25606723c1b1293c Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Mon, 23 Nov 2026 22:15:54 +0000 Subject: [PATCH 5/7] fix: roll back a failed OAuth2 flush at compile_sqla_query and get_df's first ORM read Chart data compiles its query right after get_sqla_query's engine lookup, so the refresh staged there is flushed inside compile_sqla_query, before the get_df guard. In get_df, the first ORM read (db_engine_spec) preceded the guarded block, and check_for_oauth2 read the deactivated database and raised PendingRollbackError over the flush error. Share one rollback context manager across both sites, widen get_df's guard to cover its first ORM read, and have check_for_oauth2 re-raise on a deactivated session. Tests now fail a real flush on the session fixture. Co-Authored-By: Claude Sonnet 5.5 --- superset/models/core.py | 35 +++++++++---- superset/utils/oauth2.py | 4 ++ tests/unit_tests/models/core_test.py | 75 ++++++++++++++++++++++++---- 3 files changed, 96 insertions(+), 18 deletions(-) diff --git a/superset/models/core.py b/superset/models/core.py index ba69056d357a..c0f1bd1122e4 100755 --- a/superset/models/core.py +++ b/superset/models/core.py @@ -1085,6 +1085,22 @@ def open_connection() -> Iterator[Connection]: ) as conn: yield conn + @staticmethod + @contextmanager + def _rolling_back_failed_flush() -> Iterator[None]: + """ + Roll back a session deactivated by a failed flush before re-raising. + + For callers that look up the engine outside ``get_raw_connection``, such + as chart data compiling its query: a refreshed OAuth2 token staged by an + earlier engine lookup is flushed by the next ORM read, wherever that is. + """ + try: + yield + except Exception: + Database._rollback_deactivated_session() + raise + @staticmethod def _rollback_deactivated_session() -> None: """ @@ -1299,16 +1315,13 @@ def _execute_sql_with_mutation_and_logging( :return: Tuple of (cursor, rows, description) where rows and description are None if not fetching. """ - script = SQLScript(sql, self.db_engine_spec.engine) - - try: + # With Redis locking, a refresh staged by an earlier engine call is + # flushed by the first ORM read here, outside ``get_raw_connection``'s + # own rollback. + with self._rolling_back_failed_flush(): + script = SQLScript(sql, self.db_engine_spec.engine) with self.get_sqla_engine(catalog=catalog, schema=schema) as engine: engine_url = engine.url - except Exception: - # With Redis locking, a refresh staged by an earlier engine call is - # flushed here, outside ``get_raw_connection``'s own rollback. - self._rollback_deactivated_session() - raise log_query = app.config["QUERY_LOGGER"] @@ -1463,7 +1476,11 @@ def compile_sqla_query( schema: str | None = None, is_virtual: bool = False, ) -> str: - with self.get_sqla_engine(catalog=catalog, schema=schema) as engine: + # A refresh staged by get_sqla_query's engine lookup is flushed here. + with ( + self._rolling_back_failed_flush(), + self.get_sqla_engine(catalog=catalog, schema=schema) as engine, + ): sql = str(qry.compile(engine, compile_kwargs={"literal_binds": True})) # pylint: disable=protected-access diff --git a/superset/utils/oauth2.py b/superset/utils/oauth2.py index 8456c6a5cd21..40b4b5cb70cf 100644 --- a/superset/utils/oauth2.py +++ b/superset/utils/oauth2.py @@ -636,6 +636,10 @@ def check_for_oauth2(database: Database) -> Iterator[None]: try: yield except Exception as ex: + # A failed flush deactivates the session, and the checks below read the + # database. Leave the original error, and the rollback, to the caller. + if not db.session.is_active: + raise if ( not is_oauth2_retry_active() # The `OAuth2TokenRefreshError` arm below reaches the dance without diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py index eb4b454a432e..439143d86bb4 100644 --- a/tests/unit_tests/models/core_test.py +++ b/tests/unit_tests/models/core_test.py @@ -3355,21 +3355,78 @@ def test_rollback_deactivated_session_does_not_mask_the_original_error( db_mock.session.rollback.assert_called_once_with() +def _stage_failing_flush(session: Session) -> None: + """Stage two rows that violate a unique constraint on the next flush.""" + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://")) + + +@pytest.fixture +def persisted_database(session: Session) -> Database: + Database.metadata.create_all(session.get_bind()) + database = Database(database_name="login_db", sqlalchemy_uri="sqlite://") + session.add(database) + session.commit() + return database + + +def test_compile_sqla_query_rolls_back_a_session_deactivated_by_a_failed_flush( + persisted_database: Database, + session: Session, + app_context: None, +) -> None: + """ + Chart data compiles its query right after building it, and a refreshed + OAuth2 token staged by the earlier engine lookup is flushed here. The failed + flush must leave the session usable, or the caller's next ORM read raises + ``PendingRollbackError`` in place of the real error. + """ + _stage_failing_flush(session) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_database.compile_sqla_query(select(1)) + + assert session.is_active + assert session.query(Database).count() == 1 + + def test_get_df_rolls_back_a_session_deactivated_by_a_failed_engine_flush( + persisted_database: Database, + session: Session, app_context: None, - mocker: MockerFixture, ) -> None: """A staged refresh flushed by get_df's own engine lookup is rolled back.""" - database = Database(database_name="db", sqlalchemy_uri="sqlite://") - mocker.patch.object( - Database, "get_sqla_engine", side_effect=RuntimeError("flush failed") - ) - rollback = mocker.patch.object(Database, "_rollback_deactivated_session") + _stage_failing_flush(session) - with pytest.raises(RuntimeError, match="flush failed"): - database.get_df("SELECT 1") + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_database.get_df("SELECT 1") + + assert session.is_active + assert session.query(Database).count() == 1 + + +def test_get_df_keeps_the_flush_error_when_oauth2_is_checked_on_a_dead_session( + persisted_database: Database, + session: Session, + app_context: None, + mocker: MockerFixture, +) -> None: + """ + A flush that fails inside the engine's OAuth2 check must surface as itself: + the check reads the database, which a deactivated session cannot load. + """ + + def failing_engine(*args: Any, **kwargs: Any) -> None: + _stage_failing_flush(session) + session.flush() - rollback.assert_called_once_with() + mocker.patch.object(Database, "_get_sqla_engine", side_effect=failing_engine) + mocker.patch.object(Database, "is_oauth2_enabled", return_value=True) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_database.get_df("SELECT 1") + + assert session.is_active def test_get_raw_connection_without_oauth2_is_unchanged( From fad86f0efe2f2ebb431912e37550a66f8ef2fa25 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Tue, 24 Nov 2026 00:07:04 +0000 Subject: [PATCH 6/7] fix: roll back a failed OAuth2 flush anywhere in get_sqla_query The staged token refresh can be flushed by any ORM read while a chart query is built: the engine lookup, or the lazy load of unloaded columns and metrics. Guard get_sqla_query as a whole, resolving the rollback without touching the self.database relationship (itself a possible lazy load). Co-Authored-By: Claude Sonnet 5.5 --- superset/models/helpers.py | 28 ++++++++++- tests/unit_tests/models/core_test.py | 69 ++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/superset/models/helpers.py b/superset/models/helpers.py index 07e228a8bac2..7ae4b0a883a4 100644 --- a/superset/models/helpers.py +++ b/superset/models/helpers.py @@ -32,7 +32,7 @@ from datetime import datetime, time, timedelta, timezone from decimal import Decimal from enum import Enum -from functools import cache, partial +from functools import cache, partial, wraps from typing import ( Any, Callable, @@ -43,6 +43,7 @@ Optional, TYPE_CHECKING, TypedDict, + TypeVar, Union, ) from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -219,6 +220,30 @@ ) from superset.utils.timing_metrics import timed +_F = TypeVar("_F", bound=Callable[..., Any]) + + +def _rolling_back_failed_flush(func: _F) -> _F: + """ + Roll back a session deactivated by a failed flush before the error escapes. + + Building a chart query looks up the engine, and an OAuth2 token refresh staged + by one lookup is flushed by the next ORM read, which can be any lazy load of + the query builder (the next engine lookup, columns, metrics). The flush + failure would otherwise leave the request session inactive. + """ + + @wraps(func) + def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: + # Not via ``self.database``: that relationship can itself be the lazy load + # that flushes the failing write. + from superset.models.core import Database + + with Database._rolling_back_failed_flush(): # pylint: disable=protected-access + return func(self, *args, **kwargs) + + return cast(_F, wrapper) + class ValidationResultDict(TypedDict): """Type for validation result objects returned by validate_expression.""" @@ -6963,6 +6988,7 @@ def convert_tbl_column_to_sqla_col( col = self.make_sqla_column_compatible(col, label) return col + @_rolling_back_failed_flush def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements # noqa: C901 self, apply_fetch_values_predicate: bool = False, diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py index 439143d86bb4..ecb88656d242 100644 --- a/tests/unit_tests/models/core_test.py +++ b/tests/unit_tests/models/core_test.py @@ -5030,3 +5030,72 @@ def _get_engine(catalog=None, schema=None, **kwargs): assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), ( f"OFFSET must precede LIMIT for Trino, got: {sql!r}" ) + + +@pytest.fixture +def persisted_table(persisted_database: Database, session: Session) -> SqlaTable: + table = SqlaTable( + table_name="t", + database=persisted_database, + columns=[TableColumn(column_name="a", type="INTEGER")], + ) + session.add(table) + session.commit() + # Drop loaded state so columns and metrics lazy-load, as in a fresh request. + session.expire_all() + return table + + +def test_get_sqla_query_rolls_back_a_failed_flush_at_the_engine_lookup( + persisted_table: SqlaTable, + session: Session, + app_context: None, +) -> None: + """ + Building a chart query looks up the engine first, and a refreshed OAuth2 + token staged earlier is flushed by that lookup's ORM reads, before any + guard in ``compile_sqla_query`` or ``get_df``. + """ + _stage_failing_flush(session) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_table.get_sqla_query(columns=["a"]) + + assert session.is_active + assert session.query(Database).count() == 1 + + +def test_get_sqla_query_rolls_back_a_failed_flush_at_a_lazy_load( + persisted_table: SqlaTable, + session: Session, + app_context: None, + mocker: MockerFixture, +) -> None: + """The flush can also land at the lazy load of unloaded columns/metrics.""" + mocker.patch.object(Database, "get_sqla_engine", return_value=nullcontext()) + mocker.patch( + "superset.models.helpers.ExploreMixin.get_template_processor", + return_value=mocker.MagicMock(), + ) + _stage_failing_flush(session) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_table.get_sqla_query(columns=["a"]) + + assert session.is_active + assert session.query(Database).count() == 1 + + +def test_datasource_query_rolls_back_a_failed_flush( + persisted_table: SqlaTable, + session: Session, + app_context: None, +) -> None: + """The chart-data entry point, ``SqlaTable.query``, leaves a usable session.""" + _stage_failing_flush(session) + + with pytest.raises(sqlalchemy.exc.IntegrityError): + persisted_table.query({"columns": ["a"], "metrics": [], "is_timeseries": False}) + + assert session.is_active + assert session.query(Database).count() == 1 From 8add51ae8cf5e91aa3a58108b0cc01bf73d5de58 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Tue, 24 Nov 2026 20:03:28 +0000 Subject: [PATCH 7/7] test: preload columns and metrics so the flush lands at the engine lookup The engine-lookup test's staged flush landed at the self.dttm_cols lazy load, duplicating the lazy-load test. Load columns and metrics before staging so the flush lands at the database engine lookup. Co-Authored-By: Claude Sonnet 5.5 --- tests/unit_tests/models/core_test.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py index ecb88656d242..7c42ff7dc035 100644 --- a/tests/unit_tests/models/core_test.py +++ b/tests/unit_tests/models/core_test.py @@ -5056,6 +5056,9 @@ def test_get_sqla_query_rolls_back_a_failed_flush_at_the_engine_lookup( token staged earlier is flushed by that lookup's ORM reads, before any guard in ``compile_sqla_query`` or ``get_df``. """ + # Load columns and metrics first, so the staged flush cannot land at their + # lazy load and instead lands at the engine lookup. + _ = persisted_table.columns, persisted_table.metrics _stage_failing_flush(session) with pytest.raises(sqlalchemy.exc.IntegrityError):