Skip to content
74 changes: 64 additions & 10 deletions superset/models/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1080,13 +1080,49 @@ 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
@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:
"""
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.
Expand All @@ -1097,6 +1133,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():
Expand All @@ -1106,10 +1147,16 @@ 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:
if rollback_failed_flush:
self._rollback_deactivated_session()
raise
yield value

def get_default_catalog(self) -> str | None:
"""
Expand Down Expand Up @@ -1268,10 +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)

with self.get_sqla_engine(catalog=catalog, schema=schema) as engine:
engine_url = engine.url
# 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

log_query = app.config["QUERY_LOGGER"]

Expand Down Expand Up @@ -1426,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.
Comment thread
aminghadersohi marked this conversation as resolved.
Resolved
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
Expand Down
28 changes: 27 additions & 1 deletion superset/models/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -43,6 +43,7 @@
Optional,
TYPE_CHECKING,
TypedDict,
TypeVar,
Union,
)
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured: when SQLExecutor renders a dataset() macro, a failed flush at a lazy load in get_sqla_query is now rolled back here first, so executor.py:718 returns the statement and its parameters instead of base's driver-only message; the compile_sqla_query and get_df guards do the same.

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,
Expand Down
4 changes: 4 additions & 0 deletions superset/utils/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading