Repository navigation
Return a 422 when the database rejects an API payload - #66888
Conversation
1f743e7 to
e0d8b96
Compare
e0d8b96 to
774c0f5
Compare
pierrejeambrun
left a comment
There was a problem hiding this comment.
Thanks for the PR, nice idea!
A few suggestions before we can merge.
|
@1fanwang — There are 10 unresolved review thread(s) on this PR, and you have engaged with each one (post-review commits and/or in-thread replies). Could you confirm whether you believe the feedback is fully addressed and the PR is ready for maintainer review confirmation? If yes, reply here (a short "yes / ready" is fine) and an Apache Airflow maintainer will pick the PR up from the review queue on the next sweep. If you are still working on a thread, please reply with what is outstanding so the threads stay unresolved on purpose. Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this two-stage triage process so that our maintainers' limited time is spent where it matters most: the conversation with you. Drafted-by: Claude Code (Opus 4.7); reviewed by @choo121600 before posting |
|
Thanks a lot for the review and support @pierrejeambrun, addressed the comments, ready for another scan! |
pierrejeambrun
left a comment
There was a problem hiding this comment.
Thanks for addressing the comments.
A few more comments/ suggestions before we can merge.
Mostly to mirror more closely the implementation of _UniqueConstraintErrorHandler. We're missing some pieces here.
Triggering a DAG run with an oversized 'conf' payload (and other DB-rejected writes across the API surface) currently produces a generic 500. The SQL error surfaces deep in SQLAlchemy as (1406, "Data too long for column 'conf' at row 1") on MySQL, the caller has no signal that payload size was the cause, and every write endpoint that touches a length-capped column has the same shape today (Connection.extra, Variable.val, XCom.value, TaskInstance.note, HITL fields, etc). Add a single FastAPI exception handler for sqlalchemy.exc.DataError on both the public REST API and the execution API. 'Data too long' / 'too large' / 'too big' errors map to 413 Content Too Large; other DataErrors (out-of-range, numeric overflow) map to 422. The response body carries the original DB error and an actionable hint pointing at either reducing the payload or widening the column type on MySQL. Every existing and future write endpoint inherits the translation automatically. Postgres deployments never hit it (JSONB has no length cap); MySQL deployments get a clear 4xx + remediation hint instead of a generic 500. Closes apache#66779 Signed-off-by: 1fanwang <[email protected]>
Signed-off-by: 1fanwang <[email protected]>
Pass DataError directly to add_exception_handler instead of via the BaseErrorHandler.exception_cls attribute (typed as instance T, not type[T]) so the call type-checks against Starlette's expected type[Exception]. The variance issue between Callable[Request, DataError] and Callable[Request, Exception] is silenced with a type-ignore matching the existing pattern used in the core_api ERROR_HANDLERS loop. In the new TestDataErrorHandler tests, extract HTTPException.detail into a typed dict before subscripting so mypy stops inferring it as str. Signed-off-by: 1fanwang <[email protected]>
Drop the 413/'too long' marker special-case and always return 422 to match the rest of the app. Add `statement` to the response detail so the shape mirrors the unique-constraint handler. Drop the manual handler block in the execution API since `init_error_handlers` already loops over `ERROR_HANDLERS` for both apps. Rename `_DataErrorHandler` to `DataErrorHandler`. Remove the newsfragment.
The DataError handler now mirrors _UniqueConstraintErrorHandler: it logs the statement and underlying database error under a lookup id and only echoes them back to the caller when [api] expose_stacktrace is set. By default the response carries an opaque message plus the id, so column names and rejected values are no longer leaked to API clients. Tests cover both expose_stacktrace False (internals hidden) and True (internals exposed) across the dialect error shapes.
4d0bfbb to
0dc3e9f
Compare
ti_run and ti_update_state wrap their DB writes in catches broader than DataError: SQLAlchemyError becomes an opaque 500, and a bare Exception in ti_update_state silently marks the task FAILED and returns 204. Those fire before the app-level DataErrorHandler can translate the rejection, so an oversized field (note, rendered_map_index, next_kwargs, ...) either returns a generic 500 or leaves the worker believing the update succeeded while the server marked the task FAILED. Re-raise DataError ahead of each broad catch so it reaches the handler and the caller gets the actionable 422. The fallbacks for other unexpected errors are unchanged.
Drop the per-dialect enumeration in the handler docstring and collapse the multi-line re-raise comments to one line each.
Add MySQL/Postgres-only route tests (SQLite ignores varchar limits): an oversized field the database rejects returns 422 from ti_run and ti_update_state, and the deferred-state path no longer silently marks the TI FAILED.
cc: @1fanwang for a small clean up follow up PR. |
* Translate DataError to 413/422 instead of generic 500 Triggering a DAG run with an oversized 'conf' payload (and other DB-rejected writes across the API surface) currently produces a generic 500. The SQL error surfaces deep in SQLAlchemy as (1406, "Data too long for column 'conf' at row 1") on MySQL, the caller has no signal that payload size was the cause, and every write endpoint that touches a length-capped column has the same shape today (Connection.extra, Variable.val, XCom.value, TaskInstance.note, HITL fields, etc). Add a single FastAPI exception handler for sqlalchemy.exc.DataError on both the public REST API and the execution API. 'Data too long' / 'too large' / 'too big' errors map to 413 Content Too Large; other DataErrors (out-of-range, numeric overflow) map to 422. The response body carries the original DB error and an actionable hint pointing at either reducing the payload or widening the column type on MySQL. Every existing and future write endpoint inherits the translation automatically. Postgres deployments never hit it (JSONB has no length cap); MySQL deployments get a clear 4xx + remediation hint instead of a generic 500. Closes apache#66779 Signed-off-by: 1fanwang <[email protected]> * Rename newsfragment to PR number Signed-off-by: 1fanwang <[email protected]> * Fix mypy errors on execution_api handler registration + test indexing Pass DataError directly to add_exception_handler instead of via the BaseErrorHandler.exception_cls attribute (typed as instance T, not type[T]) so the call type-checks against Starlette's expected type[Exception]. The variance issue between Callable[Request, DataError] and Callable[Request, Exception] is silenced with a type-ignore matching the existing pattern used in the core_api ERROR_HANDLERS loop. In the new TestDataErrorHandler tests, extract HTTPException.detail into a typed dict before subscripting so mypy stops inferring it as str. Signed-off-by: 1fanwang <[email protected]> * Simplify DataError handling per review Drop the 413/'too long' marker special-case and always return 422 to match the rest of the app. Add `statement` to the response detail so the shape mirrors the unique-constraint handler. Drop the manual handler block in the execution API since `init_error_handlers` already loops over `ERROR_HANDLERS` for both apps. Rename `_DataErrorHandler` to `DataErrorHandler`. Remove the newsfragment. * Hide DataError API response internals behind expose_stacktrace The DataError handler now mirrors _UniqueConstraintErrorHandler: it logs the statement and underlying database error under a lookup id and only echoes them back to the caller when [api] expose_stacktrace is set. By default the response carries an opaque message plus the id, so column names and rejected values are no longer leaked to API clients. Tests cover both expose_stacktrace False (internals hidden) and True (internals exposed) across the dialect error shapes. * Stop task-instance execution routes from masking DataError ti_run and ti_update_state wrap their DB writes in catches broader than DataError: SQLAlchemyError becomes an opaque 500, and a bare Exception in ti_update_state silently marks the task FAILED and returns 204. Those fire before the app-level DataErrorHandler can translate the rejection, so an oversized field (note, rendered_map_index, next_kwargs, ...) either returns a generic 500 or leaves the worker believing the update succeeded while the server marked the task FAILED. Re-raise DataError ahead of each broad catch so it reaches the handler and the caller gets the actionable 422. The fallbacks for other unexpected errors are unchanged. * Tighten DataError docstring and re-raise comments Drop the per-dialect enumeration in the handler docstring and collapse the multi-line re-raise comments to one line each. * Test DataError handling in the task-instance execution routes Add MySQL/Postgres-only route tests (SQLite ignores varchar limits): an oversized field the database rejects returns 422 from ti_run and ti_update_state, and the deferred-state path no longer silently marks the TI FAILED. --------- Signed-off-by: 1fanwang <[email protected]>
When the database rejects an API payload (too large or malformed for its column), Airflow returns an opaque
500. That mis-categorizes a client error as a server fault: the payload is the caller's, so the correct status is a4xx, not a5xxthat signals "our problem, retry" — and the retry fails identically. On MySQL the real cause —(1406, "Data too long for column 'conf' at row 1")— only appears in the api-server log. A common trigger is inlining large job configs into a Dag runconf.What changed
DataErrorHandler, registered on both the public REST API and the execution API, mapssqlalchemy.exc.DataErrorto a422. It mirrors_UniqueConstraintErrorHandler: the statement and underlying DB error go to the log under a lookup id and are returned to the caller only when[api] expose_stacktraceis set, so column names and rejected values aren't leaked by default.ti_runandti_update_statestop masking it. Both wrapped their DB writes in catches broader thanDataError(SQLAlchemyError→ 500, and a bareExceptionthat silently marks the task FAILED). They now re-raiseDataErrorfirst so it reaches the handler.Postgres
text/JSONBcolumns are uncapped, so this only bites MySQL; those deployments get a422instead of a500or a silent FAILED.Live e2e (real MySQL 8.0, real execution API)
Oversized payload fields overflowing real capped columns, driven through the real execution API:
rendered_map_index→varchar(250), at the stateUPDATE500 {"detail":"Database error occurred"}422classpath→varchar(1000), at the trigger flushSetting the task to failed)422The old
500body was just{"detail":"Database error occurred"}. The422names the offending column. Default (expose_stacktrace=False) keeps DB internals out of the response, behind a log lookup id;expose_stacktrace=Truereturns the statement and DB error inline:Tests
TestDataErrorHandler):expose_stacktraceon and off across the dialect error shapes (MySQL 1406/1264/1366, Postgres value-too-long / numeric-overflow / invalid-syntax, SQLite blob-too-big), plus dispatch through the registered handlers.test_task_instances.py, MySQL/Postgres-only — SQLite ignoresvarcharlimits): an oversized field returns 422 fromti_runandti_update_state, and the deferred path no longer silently marks the TI FAILED.related: #66779, #66889