Skip to content

fix: roll back session after OAuth2 token refresh flush failure - #46363

Open
eschutho wants to merge 7 commits into
apache:masterfrom
eschutho:fix/oauth2-token-timeout-rollback
Open

eschutho wants to merge 7 commits into
apache:masterfrom
eschutho:fix/oauth2-token-timeout-rollback

Conversation

@eschutho

Copy link
Copy Markdown
Member

Summary

When a database's per-user OAuth2 access/refresh token is refreshed during query execution (e.g. a chart data request against a BigQuery/Snowflake/GSheets connection), the write to the token row is done on the request-scoped SQLAlchemy session. If that write fails to flush -- for example a statement timeout while updating the token row -- the session becomes deactivated (session.is_active is False) until an explicit rollback() is issued.

execute_with_oauth2_retry (in superset/utils/oauth2.py) already detects this case:

except Exception as ex:
    # 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:
        raise

but it deliberately skips calling db.session.rollback(), assuming some caller further up the stack ("the execution owner") will do it. In practice nothing does. The original exception propagates, but the broken session persists for the rest of the request. Any later ORM access in the same request (e.g. loading an expired attribute while building the response) then raises PendingRollbackError instead of the real error, surfacing to the client as an unhandled 500 far away from the actual root cause (a timed-out write to the OAuth2 token table).

Fix

Roll back the session immediately once we detect it has been deactivated by a failed flush, before re-raising the original exception:

if not db.session.is_active:
    db.session.rollback()
    raise

This keeps the original exception visible (still handled by the normal error-response machinery, e.g. as an OperationalError -> 500 for a genuine DB timeout) while leaving the session in a usable state for whatever runs next in the request, instead of letting it degrade into an opaque PendingRollbackError.

Also updated the existing unit test test_execute_with_oauth2_retry_preserves_failed_flush_error, which asserted db.session.rollback.assert_not_called() -- that assertion encoded the behavior being fixed here. It now asserts rollback is called exactly once, while still confirming the original exception is preserved and propagated unchanged.

Test plan

  • tests/unit_tests/utils/oauth2_tests.py (47 tests) passes, including the updated regression test
  • tests/unit_tests/commands/databases/oauth2_test.py, tests/unit_tests/databases/oauth2_tokens_test.py, tests/unit_tests/databases/oauth2_api_test.py (89 tests) pass unaffected

🤖 Generated with Claude Code

@codeant-ai-for-open-source

codeant-ai-for-open-source Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; no actionable issues were identified in the review.

Assessed commit: 8add51ae8cf5

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.98%. Comparing base (f4c26d8) to head (8add51a).
⚠️ Report is 99 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #46363      +/-   ##
==========================================
+ Coverage   85.97%   85.98%   +0.01%     
==========================================
  Files        3127     3128       +1     
  Lines      217726   217859     +133     
  Branches    51618    51644      +26     
==========================================
+ Hits       187183   187325     +142     
+ Misses      27119    27111       -8     
+ Partials     3424     3423       -1     
Flag Coverage Δ
hive 33.81% <31.70%> (-0.02%) ⬇️
mysql 51.62% <65.85%> (+0.01%) ⬆️
postgres 51.65% <65.85%> (+<0.01%) ⬆️
presto 35.51% <56.09%> (+0.01%) ⬆️
python 88.49% <100.00%> (+0.02%) ⬆️
sqlite 51.32% <65.85%> (+0.01%) ⬆️
unit 83.98% <100.00%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@aminghadersohi
aminghadersohi self-requested a review November 21, 2026 16:39

@aminghadersohi aminghadersohi left a comment

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.

The new rollback breaks SQLExecutor's failed-flush error handling; rolling back in the caller that has no rollback owner keeps both paths correct.

Comment thread superset/utils/oauth2.py Resolved
Comment thread tests/unit_tests/utils/oauth2_tests.py Resolved
@pull-request-size pull-request-size Bot added size/M and removed size/S labels Nov 23, 2026

@aminghadersohi aminghadersohi left a comment

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.

The moved rollback alters the executor's prepare-path error text and misses the flush site chart data reaches.

Nit: The description still describes the earlier oauth2.py rollback; the diff now changes Database._open_with_oauth2_retry.

Comment thread superset/models/core.py Resolved
Comment thread superset/models/core.py Resolved
Comment thread tests/unit_tests/models/core_test.py Resolved
Comment thread tests/unit_tests/models/core_test.py Resolved
Comment thread superset/models/core.py Resolved
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Nov 23, 2026

@aminghadersohi aminghadersohi left a comment

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.

The chart-data flush still fails outside the new guards, so the PendingRollbackError this PR targets remains on that path.

Comment thread superset/models/core.py Resolved
Comment thread tests/unit_tests/models/core_test.py Resolved

@aminghadersohi aminghadersohi left a comment

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.

The staged token flush still escapes the new guards on real chart-data orders, so the session can stay inactive.

Comment thread superset/models/core.py Resolved
eschutho and others added 6 commits November 24, 2026 00:26
…th2_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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…llback, 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 <noreply@anthropic.com>
…'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>
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>
@eschutho
eschutho force-pushed the fix/oauth2-token-timeout-rollback branch from 8f1b07e to fad86f0 Compare November 24, 2026 00:27

@aminghadersohi aminghadersohi left a comment

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.

The new get_sqla_query rollback changes the executor's sanitized prepare-path error text.

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.

Comment thread tests/unit_tests/models/core_test.py Resolved
…okup

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 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants