Skip to content

Return a 422 when the database rejects an API payload - #66888

Merged
pierrejeambrun merged 8 commits into
apache:mainfrom
1fanwang:fix/db-data-error-actionable
Jun 12, 2026
Merged

pierrejeambrun merged 8 commits into
apache:mainfrom
1fanwang:fix/db-data-error-actionable

Conversation

@1fanwang

@1fanwang 1fanwang commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

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 a 4xx, not a 5xx that 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 run conf.

What changed

  • DataErrorHandler, registered on both the public REST API and the execution API, maps sqlalchemy.exc.DataError to a 422. 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_stacktrace is set, so column names and rejected values aren't leaked by default.
  • ti_run and ti_update_state stop masking it. Both wrapped their DB writes in catches broader than DataError (SQLAlchemyError → 500, and a bare Exception that silently marks the task FAILED). They now re-raise DataError first so it reaches the handler.

Postgres text/JSONB columns are uncapped, so this only bites MySQL; those deployments get a 422 instead of a 500 or 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:

Overflow Before (main) After
rendered_map_index → varchar(250), at the state UPDATE 500 {"detail":"Database error occurred"} 422
deferred classpath → varchar(1000), at the trigger flush swallowed; TI silently marked FAILED (logs Setting the task to failed) 422

The old 500 body was just {"detail":"Database error occurred"}. The 422 names the offending column. Default (expose_stacktrace=False) keeps DB internals out of the response, behind a log lookup id; expose_stacktrace=True returns the statement and DB error inline:

// expose_stacktrace=False (default)
{"detail": {"reason": "Value rejected by database", "statement": "hidden", "orig_error": "hidden",
            "message": "Serious error when handling your request. Check logs for more details - ... ID <id>"}}

// expose_stacktrace=True
{"detail": {"reason": "Value rejected by database",
            "statement": "UPDATE task_instance SET ..., rendered_map_index=%s, ... WHERE task_instance.id = %s",
            "orig_error": "(1406, \"Data too long for column 'rendered_map_index' at row 1\")",
            "message": "Error with id <id>, statement: UPDATE task_instance SET ...  <full traceback in server log>"}}

Tests

  • Handler (TestDataErrorHandler): expose_stacktrace on 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.
  • Execution routes (test_task_instances.py, MySQL/Postgres-only — SQLite ignores varchar limits): an oversized field returns 422 from ti_run and ti_update_state, and the deferred path no longer silently marks the TI FAILED.

related: #66779, #66889

@boring-cyborg boring-cyborg Bot added area:API Airflow's REST/HTTP API area:task-sdk labels May 13, 2026
@1fanwang
1fanwang force-pushed the fix/db-data-error-actionable branch from 1f743e7 to e0d8b96 Compare May 13, 2026 22:33
@1fanwang 1fanwang changed the title Translate sqlalchemy DataError to 413/422 instead of generic 500 Return actionable 4xx when the database rejects an API payload May 13, 2026
@1fanwang
1fanwang force-pushed the fix/db-data-error-actionable branch from e0d8b96 to 774c0f5 Compare May 14, 2026 06:05
@choo121600 choo121600 added the ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green. label May 15, 2026

@pierrejeambrun pierrejeambrun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR, nice idea!

A few suggestions before we can merge.

@choo121600

Copy link
Copy Markdown
Member

@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

@1fanwang

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the review and support @pierrejeambrun, addressed the comments, ready for another scan!

@pierrejeambrun pierrejeambrun left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

1fanwang added 5 commits June 11, 2026 16:23
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]>
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.
@1fanwang
1fanwang force-pushed the fix/db-data-error-actionable branch from 4d0bfbb to 0dc3e9f Compare June 11, 2026 23:27
1fanwang added 2 commits June 11, 2026 16:32
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.
@1fanwang 1fanwang changed the title Return actionable 4xx when the database rejects an API payload Return a 422 when the database rejects an API payload Jun 11, 2026
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.
@eladkal eladkal added this to the Airflow 3.3.0 milestone Jun 12, 2026
@pierrejeambrun

Copy link
Copy Markdown
Member

As a follow up we can probably factorize this code which is really the same as _UniqueConstraintErrorHandler, but non blocking for now.

cc: @1fanwang for a small clean up follow up PR.

@pierrejeambrun
pierrejeambrun merged commit ab2851b into apache:main Jun 12, 2026
77 checks passed
imrichardwu pushed a commit to imrichardwu/airflow that referenced this pull request Jun 16, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:API Airflow's REST/HTTP API area:task-sdk ready for maintainer review Set by triage when all criteria pass, or by the fork CI reconciler when fork CI is green.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants