Skip to content

Commit 4485ca1

Browse files
eschuthoclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 1ee4bd1 commit 4485ca1

3 files changed

Lines changed: 96 additions & 18 deletions

File tree

‎superset/models/core.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,6 +1055,22 @@ def open_connection() -> Iterator[Connection]:
10551055
) as conn:
10561056
yield conn
10571057

1058+
@staticmethod
1059+
@contextmanager
1060+
def _rolling_back_failed_flush() -> Iterator[None]:
1061+
"""
1062+
Roll back a session deactivated by a failed flush before re-raising.
1063+
1064+
For callers that look up the engine outside ``get_raw_connection``, such
1065+
as chart data compiling its query: a refreshed OAuth2 token staged by an
1066+
earlier engine lookup is flushed by the next ORM read, wherever that is.
1067+
"""
1068+
try:
1069+
yield
1070+
except Exception:
1071+
Database._rollback_deactivated_session()
1072+
raise
1073+
10581074
@staticmethod
10591075
def _rollback_deactivated_session() -> None:
10601076
"""
@@ -1269,16 +1285,13 @@ def _execute_sql_with_mutation_and_logging(
12691285
:return: Tuple of (cursor, rows, description) where rows and description
12701286
are None if not fetching.
12711287
"""
1272-
script = SQLScript(sql, self.db_engine_spec.engine)
1273-
1274-
try:
1288+
# With Redis locking, a refresh staged by an earlier engine call is
1289+
# flushed by the first ORM read here, outside ``get_raw_connection``'s
1290+
# own rollback.
1291+
with self._rolling_back_failed_flush():
1292+
script = SQLScript(sql, self.db_engine_spec.engine)
12751293
with self.get_sqla_engine(catalog=catalog, schema=schema) as engine:
12761294
engine_url = engine.url
1277-
except Exception:
1278-
# With Redis locking, a refresh staged by an earlier engine call is
1279-
# flushed here, outside ``get_raw_connection``'s own rollback.
1280-
self._rollback_deactivated_session()
1281-
raise
12821295

12831296
log_query = app.config["QUERY_LOGGER"]
12841297

@@ -1433,7 +1446,11 @@ def compile_sqla_query(
14331446
schema: str | None = None,
14341447
is_virtual: bool = False,
14351448
) -> str:
1436-
with self.get_sqla_engine(catalog=catalog, schema=schema) as engine:
1449+
# A refresh staged by get_sqla_query's engine lookup is flushed here.
1450+
with (
1451+
self._rolling_back_failed_flush(),
1452+
self.get_sqla_engine(catalog=catalog, schema=schema) as engine,
1453+
):
14371454
sql = str(qry.compile(engine, compile_kwargs={"literal_binds": True}))
14381455

14391456
# pylint: disable=protected-access

‎superset/utils/oauth2.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,10 @@ def check_for_oauth2(database: Database) -> Iterator[None]:
636636
try:
637637
yield
638638
except Exception as ex:
639+
# A failed flush deactivates the session, and the checks below read the
640+
# database. Leave the original error, and the rollback, to the caller.
641+
if not db.session.is_active:
642+
raise
639643
if (
640644
not is_oauth2_retry_active()
641645
# The `OAuth2TokenRefreshError` arm below reaches the dance without

‎tests/unit_tests/models/core_test.py‎

Lines changed: 66 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3353,21 +3353,78 @@ def test_rollback_deactivated_session_does_not_mask_the_original_error(
33533353
db_mock.session.rollback.assert_called_once_with()
33543354

33553355

3356+
def _stage_failing_flush(session: Session) -> None:
3357+
"""Stage two rows that violate a unique constraint on the next flush."""
3358+
session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://"))
3359+
session.add(Database(database_name="dup", sqlalchemy_uri="sqlite://"))
3360+
3361+
3362+
@pytest.fixture
3363+
def persisted_database(session: Session) -> Database:
3364+
Database.metadata.create_all(session.get_bind())
3365+
database = Database(database_name="login_db", sqlalchemy_uri="sqlite://")
3366+
session.add(database)
3367+
session.commit()
3368+
return database
3369+
3370+
3371+
def test_compile_sqla_query_rolls_back_a_session_deactivated_by_a_failed_flush(
3372+
persisted_database: Database,
3373+
session: Session,
3374+
app_context: None,
3375+
) -> None:
3376+
"""
3377+
Chart data compiles its query right after building it, and a refreshed
3378+
OAuth2 token staged by the earlier engine lookup is flushed here. The failed
3379+
flush must leave the session usable, or the caller's next ORM read raises
3380+
``PendingRollbackError`` in place of the real error.
3381+
"""
3382+
_stage_failing_flush(session)
3383+
3384+
with pytest.raises(sqlalchemy.exc.IntegrityError):
3385+
persisted_database.compile_sqla_query(select(1))
3386+
3387+
assert session.is_active
3388+
assert session.query(Database).count() == 1
3389+
3390+
33563391
def test_get_df_rolls_back_a_session_deactivated_by_a_failed_engine_flush(
3392+
persisted_database: Database,
3393+
session: Session,
33573394
app_context: None,
3358-
mocker: MockerFixture,
33593395
) -> None:
33603396
"""A staged refresh flushed by get_df's own engine lookup is rolled back."""
3361-
database = Database(database_name="db", sqlalchemy_uri="sqlite://")
3362-
mocker.patch.object(
3363-
Database, "get_sqla_engine", side_effect=RuntimeError("flush failed")
3364-
)
3365-
rollback = mocker.patch.object(Database, "_rollback_deactivated_session")
3397+
_stage_failing_flush(session)
33663398

3367-
with pytest.raises(RuntimeError, match="flush failed"):
3368-
database.get_df("SELECT 1")
3399+
with pytest.raises(sqlalchemy.exc.IntegrityError):
3400+
persisted_database.get_df("SELECT 1")
3401+
3402+
assert session.is_active
3403+
assert session.query(Database).count() == 1
3404+
3405+
3406+
def test_get_df_keeps_the_flush_error_when_oauth2_is_checked_on_a_dead_session(
3407+
persisted_database: Database,
3408+
session: Session,
3409+
app_context: None,
3410+
mocker: MockerFixture,
3411+
) -> None:
3412+
"""
3413+
A flush that fails inside the engine's OAuth2 check must surface as itself:
3414+
the check reads the database, which a deactivated session cannot load.
3415+
"""
3416+
3417+
def failing_engine(*args: Any, **kwargs: Any) -> None:
3418+
_stage_failing_flush(session)
3419+
session.flush()
33693420

3370-
rollback.assert_called_once_with()
3421+
mocker.patch.object(Database, "_get_sqla_engine", side_effect=failing_engine)
3422+
mocker.patch.object(Database, "is_oauth2_enabled", return_value=True)
3423+
3424+
with pytest.raises(sqlalchemy.exc.IntegrityError):
3425+
persisted_database.get_df("SELECT 1")
3426+
3427+
assert session.is_active
33713428

33723429

33733430
def test_get_raw_connection_without_oauth2_is_unchanged(

0 commit comments

Comments
 (0)