Skip to content

fix(api): return 422 instead of 500 when table_metadata reflection fails - #46380

Merged
sadpandajoe merged 4 commits into
apache:masterfrom
eschutho:fix-table-metadata-reflection-4xx
Nov 27, 2026
Merged

sadpandajoe merged 4 commits into
apache:masterfrom
eschutho:fix-table-metadata-reflection-4xx

Conversation

@eschutho

Copy link
Copy Markdown
Member

Summary

  • DatabaseRestApi.table_metadata (GET /api/v1/database/<pk>/table_metadata/) calls db_engine_spec.get_table_metadata, which reflects pk/fk/index/comment info via SQLAlchemy against the customer's connected database.
  • A database that declares the postgres dialect but doesn't fully implement its catalog (e.g. a postgres-wire-protocol engine missing pg_catalog.pg_index columns the postgres dialect now queries) raises a SQLAlchemyError from that reflection, which was previously unhandled and crashed to an unhandled 500.
  • The sibling deprecated endpoint (table_metadata_deprecated) already catches SQLAlchemyError here and returns a 422; this brings the current (non-deprecated) endpoint in line with that existing pattern, so a target database's own catalog limitations surface as a typed 422 instead of an unhandled 500.
  • Caught via a Sentry error: psycopg2.InternalError: Binder Error: Referenced table "pg_catalog.pg_index" not found! from DatabaseRestApi.table_metadata.

Test plan

  • Added test_get_table_metadata_reflection_error, mocking db_engine_spec.get_table_metadata to raise SQLAlchemyError and asserting a 422 (not 500) response.
  • CI

🤖 Generated with Claude Code

DatabaseRestApi.table_metadata calls db_engine_spec.get_table_metadata,
which reflects pk/fk/index/comment info via SQLAlchemy. A database that
declares the postgres dialect but doesn't fully implement its catalog
(e.g. a postgres-wire-protocol engine missing pg_catalog.pg_index
columns the postgres dialect now queries) raises a SQLAlchemyError here
that was previously unhandled, crashing to a 500. The sibling deprecated
endpoint already catches this the same way; bring the current endpoint
in line.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Comment thread superset/databases/api.py
payload = database.db_engine_spec.get_table_metadata(
database, table, partition
)
except SQLAlchemyError as ex:

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.

Suggestion: This also catches OperationalError during a database outage, returning 422 instead of the 500 used for connection failures and making transient failures look permanent.

Assessment: 🟠 Major · 🔁 Occurrence: Rarely · 🏷️ Api mismatch

Use CodeAnt Skill Fix in Cursor Fix in VSCode Claude

Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** superset/databases/api.py
**Line:** 1236:1236
**Comment:**
	*Api Mismatch: This also catches `OperationalError` during a database outage, returning 422 instead of the 500 used for connection failures and making transient failures look permanent.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
👍 | 👎

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.

Confirmed: a refused connection raises OperationalError inside this try (SQLAlchemy 2.0.55), so an outage becomes a 422 + WARNING, not the 500 that handle_api_exception and the schemas endpoint return. The reported Binder Error is an InternalError and keeps its 422.

Suggested change
except SQLAlchemyError as ex:
except OperationalError:
# A connection-level failure is a server fault, not a dialect gap.
raise
except SQLAlchemyError as ex:

@codeant-ai-for-open-source

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

Copy link
Copy Markdown
Contributor

CodeAnt  CodeAnt PR Risk

🟡  Medium Risk

  • The PR needs attention before merging.
  • The broad SQLAlchemyError handler also converts connection outages into 422 responses, masking transient server failures as client errors.

Assessed commit: bdea9335b2fe

@github-actions github-actions Bot added the api Related to the REST API label Nov 19, 2026
@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.74%. Comparing base (f357ec3) to head (bdea933).
⚠️ Report is 104 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #46380      +/-   ##
==========================================
+ Coverage   85.66%   85.74%   +0.07%     
==========================================
  Files        3111     3112       +1     
  Lines      214938   216191    +1253     
  Branches    50908    51072     +164     
==========================================
+ Hits       184136   185373    +1237     
- Misses      27381    27399      +18     
+ Partials     3421     3419       -2     
Flag Coverage Δ
hive 33.86% <0.00%> (-0.14%) ⬇️
mysql 51.55% <100.00%> (-0.12%) ⬇️
postgres 51.58% <100.00%> (?)
presto 35.53% <0.00%> (-0.16%) ⬇️
python 88.43% <100.00%> (+0.13%) ⬆️
sqlite 51.25% <100.00%> (-0.13%) ⬇️
unit 83.87% <50.00%> (+0.29%) ⬆️

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.

@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Nov 20, 2026
@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 422 mapping fixes the reported reflection failure, but the new manual stats calls double-count what @statsd_metrics already records.

Comment thread superset/databases/api.py Resolved
Comment thread superset/databases/api.py Resolved
Comment thread superset/databases/api.py Resolved
@statsd_metrics already records success/warning for the response, so the
extra incr_stats calls double-counted. Also make a comment timeless.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@rebenitez1802 rebenitez1802 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.

Approve: the fix works, nothing blocks, and it matches #46288 on the sibling table_extra_metadata. CI is green, and the new test fails on master and passes here.

On the OperationalError thread: a blanket except OperationalError: raise would bring back 500s for the dialect gaps this PR targets. mysqlclient/pymysql raise OperationalError for MySQL 1054 and 1105 (StarRocks, Doris, TiDB), and sqlite raises it for semantic errors too. The suggestion on L1237 re-raises only connect failures and dropped connections. All inline suggestions are optional.

Comment thread superset/databases/api.py
payload = database.db_engine_spec.get_table_metadata(
database, table, partition
)
except SQLAlchemyError as ex:

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.

🟡 Outages now return 422 instead of 500

A refused or dropped connection now returns 422 with a WARNING, so 5xx alerting no longer sees outages on this endpoint. get_inspector uses NullPool, so a server that is down always fails at connect time with statement=None. A connection dropped mid-query sets connection_invalidated. Re-raising only those keeps dialect gaps (MySQL 1054, sqlite no such table, Postgres 42703, statement timeouts) at 422. Checked with unit probes: connect refused → 500, dropped → 500, mysql-1054/sqlite/pg-42703/InternalError → 422. Trino and other HTTP drivers only fail when the query runs, so their outages stay 422 either way.

Suggested change
except SQLAlchemyError as ex:
except SQLAlchemyError as ex:
if isinstance(ex, OperationalError) and (
ex.statement is None or ex.connection_invalidated
):
# Failed to connect, or the connection dropped mid-reflection:
# an outage rather than a dialect gap, so keep the 500.
raise

Comment thread superset/databases/api.py
Comment on lines +1235 to +1236
database, table, partition
)

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.

🟢 Optional: a missing table could return 404

NoSuchTableError is also a SQLAlchemyError, so a missing table returns 422 here. Mapping it to the existing TableNotFoundException gives the same 404 "No such table" as the access-denied branch above, so the response doesn't reveal whether the table exists.

Suggested change
database, table, partition
)
database, table, partition
)
except NoSuchTableError as ex:
raise TableNotFoundException("No such table") from ex

Comment thread superset/databases/api.py
table_name,
exc_info=True,
)
return self.response_422(error_msg_from_exception(ex))

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.

🟢 Optional: guest error sanitization is skipped on this path

On master the 500 handler gives guests the generic "An error occurred while fetching the data.". response_422 returns the raw engine error, including the [SQL: ...] text. A guest only reaches this route if the operator grants it access, so this is hardening, not a vulnerability. Fix: return self.response_422(sanitize_error_message(error_msg_from_exception(ex), 422)), with sanitize_error_message imported from superset.utils.error_sanitization. The import is outside the diff, so there's no applyable suggestion here.

side_effect=SQLAlchemyError("Binder Error: Referenced table not found"),
):
rv = self.client.get(uri)
assert rv.status_code == 422

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.

🟢 Optional: also assert the response body, so the test pins the message as well as the status.

Suggested change
assert rv.status_code == 422
assert rv.status_code == 422
assert rv.json == {"message": "Binder Error: Referenced table not found"}

@sadpandajoe
sadpandajoe merged commit bd0b585 into apache:master Nov 27, 2026
72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API doc Namespace | Anything related to documentation size/M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants