Repository navigation
fix(api): return 422 instead of 500 when table_metadata reflection fails - #46380
Conversation
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>
| payload = database.db_engine_spec.get_table_metadata( | ||
| database, table, partition | ||
| ) | ||
| except SQLAlchemyError as ex: |
There was a problem hiding this comment.
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
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 fixThere was a problem hiding this comment.
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.
| except SQLAlchemyError as ex: | |
| except OperationalError: | |
| # A connection-level failure is a server fault, not a dialect gap. | |
| raise | |
| except SQLAlchemyError as ex: |
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
aminghadersohi
left a comment
There was a problem hiding this comment.
The 422 mapping fixes the reported reflection failure, but the new manual stats calls double-count what @statsd_metrics already records.
@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
left a comment
There was a problem hiding this comment.
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.
| payload = database.db_engine_spec.get_table_metadata( | ||
| database, table, partition | ||
| ) | ||
| except SQLAlchemyError as ex: |
There was a problem hiding this comment.
🟡 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.
| 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 |
| database, table, partition | ||
| ) |
There was a problem hiding this comment.
🟢 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.
| database, table, partition | |
| ) | |
| database, table, partition | |
| ) | |
| except NoSuchTableError as ex: | |
| raise TableNotFoundException("No such table") from ex |
| table_name, | ||
| exc_info=True, | ||
| ) | ||
| return self.response_422(error_msg_from_exception(ex)) |
There was a problem hiding this comment.
🟢 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 |
There was a problem hiding this comment.
🟢 Optional: also assert the response body, so the test pins the message as well as the status.
| assert rv.status_code == 422 | |
| assert rv.status_code == 422 | |
| assert rv.json == {"message": "Binder Error: Referenced table not found"} |
Summary
DatabaseRestApi.table_metadata(GET /api/v1/database/<pk>/table_metadata/) callsdb_engine_spec.get_table_metadata, which reflects pk/fk/index/comment info via SQLAlchemy against the customer's connected database.pg_catalog.pg_indexcolumns the postgres dialect now queries) raises aSQLAlchemyErrorfrom that reflection, which was previously unhandled and crashed to an unhandled 500.table_metadata_deprecated) already catchesSQLAlchemyErrorhere 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.psycopg2.InternalError: Binder Error: Referenced table "pg_catalog.pg_index" not found!fromDatabaseRestApi.table_metadata.Test plan
test_get_table_metadata_reflection_error, mockingdb_engine_spec.get_table_metadatato raiseSQLAlchemyErrorand asserting a 422 (not 500) response.🤖 Generated with Claude Code