Skip to content

Commit fad86f0

Browse files
eschuthoclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 8d06e5d commit fad86f0

2 files changed

Lines changed: 96 additions & 1 deletion

File tree

‎superset/models/helpers.py‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from datetime import datetime, time, timedelta, timezone
3333
from decimal import Decimal
3434
from enum import Enum
35-
from functools import cache, partial
35+
from functools import cache, partial, wraps
3636
from typing import (
3737
Any,
3838
Callable,
@@ -43,6 +43,7 @@
4343
Optional,
4444
TYPE_CHECKING,
4545
TypedDict,
46+
TypeVar,
4647
Union,
4748
)
4849
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
@@ -219,6 +220,30 @@
219220
)
220221
from superset.utils.timing_metrics import timed
221222

223+
_F = TypeVar("_F", bound=Callable[..., Any])
224+
225+
226+
def _rolling_back_failed_flush(func: _F) -> _F:
227+
"""
228+
Roll back a session deactivated by a failed flush before the error escapes.
229+
230+
Building a chart query looks up the engine, and an OAuth2 token refresh staged
231+
by one lookup is flushed by the next ORM read, which can be any lazy load of
232+
the query builder (the next engine lookup, columns, metrics). The flush
233+
failure would otherwise leave the request session inactive.
234+
"""
235+
236+
@wraps(func)
237+
def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
238+
# Not via ``self.database``: that relationship can itself be the lazy load
239+
# that flushes the failing write.
240+
from superset.models.core import Database
241+
242+
with Database._rolling_back_failed_flush(): # pylint: disable=protected-access
243+
return func(self, *args, **kwargs)
244+
245+
return cast(_F, wrapper)
246+
222247

223248
class ValidationResultDict(TypedDict):
224249
"""Type for validation result objects returned by validate_expression."""
@@ -6963,6 +6988,7 @@ def convert_tbl_column_to_sqla_col(
69636988
col = self.make_sqla_column_compatible(col, label)
69646989
return col
69656990

6991+
@_rolling_back_failed_flush
69666992
def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements # noqa: C901
69676993
self,
69686994
apply_fetch_values_predicate: bool = False,

‎tests/unit_tests/models/core_test.py‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5030,3 +5030,72 @@ def _get_engine(catalog=None, schema=None, **kwargs):
50305030
assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
50315031
f"OFFSET must precede LIMIT for Trino, got: {sql!r}"
50325032
)
5033+
5034+
5035+
@pytest.fixture
5036+
def persisted_table(persisted_database: Database, session: Session) -> SqlaTable:
5037+
table = SqlaTable(
5038+
table_name="t",
5039+
database=persisted_database,
5040+
columns=[TableColumn(column_name="a", type="INTEGER")],
5041+
)
5042+
session.add(table)
5043+
session.commit()
5044+
# Drop loaded state so columns and metrics lazy-load, as in a fresh request.
5045+
session.expire_all()
5046+
return table
5047+
5048+
5049+
def test_get_sqla_query_rolls_back_a_failed_flush_at_the_engine_lookup(
5050+
persisted_table: SqlaTable,
5051+
session: Session,
5052+
app_context: None,
5053+
) -> None:
5054+
"""
5055+
Building a chart query looks up the engine first, and a refreshed OAuth2
5056+
token staged earlier is flushed by that lookup's ORM reads, before any
5057+
guard in ``compile_sqla_query`` or ``get_df``.
5058+
"""
5059+
_stage_failing_flush(session)
5060+
5061+
with pytest.raises(sqlalchemy.exc.IntegrityError):
5062+
persisted_table.get_sqla_query(columns=["a"])
5063+
5064+
assert session.is_active
5065+
assert session.query(Database).count() == 1
5066+
5067+
5068+
def test_get_sqla_query_rolls_back_a_failed_flush_at_a_lazy_load(
5069+
persisted_table: SqlaTable,
5070+
session: Session,
5071+
app_context: None,
5072+
mocker: MockerFixture,
5073+
) -> None:
5074+
"""The flush can also land at the lazy load of unloaded columns/metrics."""
5075+
mocker.patch.object(Database, "get_sqla_engine", return_value=nullcontext())
5076+
mocker.patch(
5077+
"superset.models.helpers.ExploreMixin.get_template_processor",
5078+
return_value=mocker.MagicMock(),
5079+
)
5080+
_stage_failing_flush(session)
5081+
5082+
with pytest.raises(sqlalchemy.exc.IntegrityError):
5083+
persisted_table.get_sqla_query(columns=["a"])
5084+
5085+
assert session.is_active
5086+
assert session.query(Database).count() == 1
5087+
5088+
5089+
def test_datasource_query_rolls_back_a_failed_flush(
5090+
persisted_table: SqlaTable,
5091+
session: Session,
5092+
app_context: None,
5093+
) -> None:
5094+
"""The chart-data entry point, ``SqlaTable.query``, leaves a usable session."""
5095+
_stage_failing_flush(session)
5096+
5097+
with pytest.raises(sqlalchemy.exc.IntegrityError):
5098+
persisted_table.query({"columns": ["a"], "metrics": [], "is_timeseries": False})
5099+
5100+
assert session.is_active
5101+
assert session.query(Database).count() == 1

0 commit comments

Comments
 (0)