Skip to content

Commit 8f1b07e

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 4485ca1 commit 8f1b07e

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
35+
from functools import cache, 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
@@ -214,6 +215,30 @@
214215
)
215216
from superset.utils.timing_metrics import timed
216217

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

218243
class ValidationResultDict(TypedDict):
219244
"""Type for validation result objects returned by validate_expression."""
@@ -6703,6 +6728,7 @@ def convert_tbl_column_to_sqla_col(
67036728
col = self.make_sqla_column_compatible(col, label)
67046729
return col
67056730

6731+
@_rolling_back_failed_flush
67066732
def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements # noqa: C901
67076733
self,
67086734
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
@@ -4959,3 +4959,72 @@ def _get_engine(catalog=None, schema=None, **kwargs):
49594959
assert upper.rfind("OFFSET") < upper.rfind("LIMIT"), (
49604960
f"OFFSET must precede LIMIT for Trino, got: {sql!r}"
49614961
)
4962+
4963+
4964+
@pytest.fixture
4965+
def persisted_table(persisted_database: Database, session: Session) -> SqlaTable:
4966+
table = SqlaTable(
4967+
table_name="t",
4968+
database=persisted_database,
4969+
columns=[TableColumn(column_name="a", type="INTEGER")],
4970+
)
4971+
session.add(table)
4972+
session.commit()
4973+
# Drop loaded state so columns and metrics lazy-load, as in a fresh request.
4974+
session.expire_all()
4975+
return table
4976+
4977+
4978+
def test_get_sqla_query_rolls_back_a_failed_flush_at_the_engine_lookup(
4979+
persisted_table: SqlaTable,
4980+
session: Session,
4981+
app_context: None,
4982+
) -> None:
4983+
"""
4984+
Building a chart query looks up the engine first, and a refreshed OAuth2
4985+
token staged earlier is flushed by that lookup's ORM reads, before any
4986+
guard in ``compile_sqla_query`` or ``get_df``.
4987+
"""
4988+
_stage_failing_flush(session)
4989+
4990+
with pytest.raises(sqlalchemy.exc.IntegrityError):
4991+
persisted_table.get_sqla_query(columns=["a"])
4992+
4993+
assert session.is_active
4994+
assert session.query(Database).count() == 1
4995+
4996+
4997+
def test_get_sqla_query_rolls_back_a_failed_flush_at_a_lazy_load(
4998+
persisted_table: SqlaTable,
4999+
session: Session,
5000+
app_context: None,
5001+
mocker: MockerFixture,
5002+
) -> None:
5003+
"""The flush can also land at the lazy load of unloaded columns/metrics."""
5004+
mocker.patch.object(Database, "get_sqla_engine", return_value=nullcontext())
5005+
mocker.patch(
5006+
"superset.models.helpers.ExploreMixin.get_template_processor",
5007+
return_value=mocker.MagicMock(),
5008+
)
5009+
_stage_failing_flush(session)
5010+
5011+
with pytest.raises(sqlalchemy.exc.IntegrityError):
5012+
persisted_table.get_sqla_query(columns=["a"])
5013+
5014+
assert session.is_active
5015+
assert session.query(Database).count() == 1
5016+
5017+
5018+
def test_datasource_query_rolls_back_a_failed_flush(
5019+
persisted_table: SqlaTable,
5020+
session: Session,
5021+
app_context: None,
5022+
) -> None:
5023+
"""The chart-data entry point, ``SqlaTable.query``, leaves a usable session."""
5024+
_stage_failing_flush(session)
5025+
5026+
with pytest.raises(sqlalchemy.exc.IntegrityError):
5027+
persisted_table.query({"columns": ["a"], "metrics": [], "is_timeseries": False})
5028+
5029+
assert session.is_active
5030+
assert session.query(Database).count() == 1

0 commit comments

Comments
 (0)