Skip to content

Sanitize error message in DatabricksExecutionTrigger - #70385

Merged
eladkal merged 3 commits into
apache:mainfrom
fabbuc-gyg:fix/databricks-sanitize-failed-task-error-jsonb
Nov 5, 2026
Merged

eladkal merged 3 commits into
apache:mainfrom
fabbuc-gyg:fix/databricks-sanitize-failed-task-error-jsonb

Conversation

@fabbuc-gyg

@fabbuc-gyg fabbuc-gyg commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

What

Strip characters that Postgres jsonb cannot store (NUL bytes and unpaired UTF-16 surrogates) from a failed Databricks task's error text, in both extract_failed_task_errors and extract_failed_task_errors_async.

Why

DatabricksExecutionTrigger puts each failed task's error into its TriggerEvent which gets persisted in the deferred task instance's next_kwargs, which is a Postgres jsonb column. Since Databricks output can contain NUL bytes, postgres rejects this with an error like this:

sqlalchemy.exc.DataError: (psycopg2.errors.UntranslatableCharacter) unsupported Unicode escape sequence
DETAIL: \u0000 cannot be converted to text.

Because the invalid event is retried, the triggerer enters a CrashLoopBackOff which makes it unhealthy.

How

A small make_jsonb_safe() helper regex-strips \x00 and \ud800-\udfff from the error string (non-string values pass through unchanged). It is applied to the extracted error in both the sync and async helpers, so the emitted trigger event is always persistable.

Tests

Added unit tests in providers/databricks/tests/unit/databricks/utils/test_databricks.py:

  • direct make_jsonb_safe cases (NUL strip, unpaired-surrogate strip, clean-text passthrough, non-string passthrough)
  • extract_failed_task_errors and extract_failed_task_errors_async sanitize error output

Was generative AI tooling used to co-author this PR?
  • Yes - Cursor was used to help draft this change; the author reviewed it.

Generated-by: Cursor

Made with Cursor

@boring-cyborg

boring-cyborg Bot commented Jul 24, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: dev@airflow.apache.org
    Slack: https://s.apache.org/airflow-slack

@fabbuc-gyg fabbuc-gyg changed the title fix(databricks): sanitize failed-task error text so it can be stored in jsonb Sanitze error message Jul 24, 2026
@shahar1 shahar1 changed the title Sanitze error message Sanitize error message in DatabricksExecutionTrigger Jul 24, 2026
@eladkal

eladkal commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

cc @moomindani for Databricks team review

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

Thanks for this, and welcome — this is a real bug with a real operational impact, and the diagnosis is correct.

I verified it end-to-end against a local Postgres 16.13 rather than reasoning about it, writing the actual payload shapes into a jsonb column:

Case Result
errors[].error with NUL, unsanitized rejected: UntranslatableCharacter: unsupported Unicode escape sequence — exactly the error you reported
same, via make_jsonb_safe stored OK
unpaired surrogate, unsanitized rejected: InvalidTextRepresentation: invalid input syntax for type json
same, sanitized stored OK

So both classes you strip are genuinely rejected by Postgres, and the fix genuinely resolves them. The triggerer CrashLoopBackOff consequence follows from the event being retried, which makes this worth fixing rather than working around.

I also checked the regex is not over-broad: \x01, \x1f, newlines, tabs, and non-BMP characters (emoji) are all accepted by jsonb, and your pattern preserves all of them. It strips exactly the two rejected classes and nothing else — that scoping is right.

One thing I want to record because I initially suspected it was a gap and it turned out not to be: the same TriggerEvent carries run_state, which embeds Databricks-controlled state_message. That is not a second hole, because RunState.to_json() stringifies it first, so a NUL becomes a literal \u0000 escape inside a JSON string value and Postgres accepts it. I confirmed that stores fine. Scoping the fix to errors is correct — no need to widen it.

One blocker before this can merge: a ruff failure, flagged inline. CI's Static checks job is already failing on it.


Drafted-by: Claude Code (Opus 5)

@eladkal

eladkal commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

@fabbuc-gyg can you please fix the open items?

@fabbuc-gyg

Copy link
Copy Markdown
Contributor Author

Hi @eladkal, So sorry for the delay. Will check this out today.

@fabbuc-gyg
fabbuc-gyg force-pushed the fix/databricks-sanitize-failed-task-error-jsonb branch from 1b79983 to f1bb073 Compare September 4, 2026 12:09
@fabbuc-gyg

Copy link
Copy Markdown
Contributor Author

Should be fine now :-)

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

Both points from my July review are closed on f1bb073570. LGTM.

Worth recording because it is not visible from the diff: I mutation-tested the sanitization tests, since tests like these easily pass either way. Making make_jsonb_safe return its argument unchanged fails exactly the four stripping tests and leaves the clean-text and non-string cases green — they pin the behaviour.

#72313 touches the same two failed_tasks.append(...) sites, so whichever lands second needs a trivial rebase; the changes compose.


Drafted-by: Claude Code (Opus 5); reviewed by @moomindani before posting

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

Thanks for tracking this down — we hit this exact crash in production yesterday: Airflow 3.1.8, triggerer stuck in CrashLoopBackOff for ~10h on a DatabricksExecutionTrigger whose failed task's error output carried a raw NUL byte from a Spark stack trace ("col" was called from <command--1> — a column-not-found AnalysisException). Confirmed make_jsonb_safe() on extract_failed_task_errors/_async would have prevented that specific crash. Nice, tight fix.

One gap I'd flag before merge, though: RunState.to_json() (hooks/databricks.py:147) does json.dumps(self.__dict__) on state_message with no sanitization, and DatabricksExecutionTrigger embeds that string verbatim as the "run_state" key of the same TriggerEvent — at triggers/databricks.py:155, and again at :181/:208 in the workflow-task retry/terminal branches. state_message is the exact same Databricks free-text field this PR already treats as untrusted (it's the error fallback here) — so a NUL byte or lone surrogate landing in state_message instead of run_output["error"] reproduces the identical crash, entirely bypassing make_jsonb_safe():

>>> import json
>>> json.dumps({"state_message": "boom \u0000 more"})
'{"state_message": "boom \\u0000 more"}'

That \u0000 escape survives nested inside the "run_state" string, and hits the same Postgres UntranslatableCharacter once the outer payload lands in next_kwargs (jsonb) — same failure mode, different field, and it ships unfixed even after this PR merges.

Worth noting this isn't unique to RunState either — ClusterState.to_json() and SQLStatementState.to_json() (same file) follow the identical state_message → unsanitized json.dumps(self.__dict__) pattern, so the same class of bug likely reaches other Databricks triggers too.

Given that, I'd suggest sanitizing at the source — inside to_json() itself (or wherever state_message gets assigned) — rather than only at the two extract_failed_task_errors call sites, so every caller gets the protection instead of just this one. Doesn't need to block this PR if you'd rather land the reported-crash fix now and follow up separately, but I'd hate to see this merge as "the NUL byte fix" and have the next crash report be the same root cause from a different field.


Drafted-by: Claude Code (Sonnet 5); reviewed by @seanmuth before posting

@moomindani

Copy link
Copy Markdown
Contributor

The production case is useful — an independent report with a real AnalysisException payload is better evidence for this fix than my synthetic one.

The second hole is not there, though, and I checked rather than reasoned. I replayed both payload shapes into a real Postgres 16.13 jsonb column the way SQLAlchemy writes them (json.dumps text cast to jsonb), with the same dirty string — a NUL plus a lone surrogate — in each:

payload result
errors[].error, unsanitized rejected: UntranslatableCharacter: unsupported Unicode escape sequence
run_state = RunState.to_json() carrying that state_message stored
run_state as a nested dict instead of a to_json() string rejected

The double encoding is what saves it. json.dumps turns a NUL into the six ASCII characters \u0000; serializing the event payload for the column escapes that backslash in turn, so Postgres sees literal text rather than an escape it must interpret. Rejection needs a live \u0000 in the wire JSON, and only the raw errors[] path produces one — the third row is what that would take.

I suspect the repro is what led there: in Python "boom \^@ more" is a literal backslash-caret-at rather than a NUL, since \^ is not an escape sequence — \^@ is how psql renders a NUL, not how Python writes one. A real \x00 comes out as \u0000. Every state in these triggers goes through to_json() (triggers/databricks.py:155, :181, :208, :320, :331, :424, and operators/databricks.py:280), so ClusterState and SQLStatementState are covered by the same stringification.

One thing does remain, and it is not this: from_json() revives the real NUL, so if a revived state_message is ever put into a payload unstringified, that is the hole. Today it only reaches exception text and logs. Sanitizing inside to_json() would also change the string that databricks_repair_reason_new_settings matching reads (operators/databricks.py:210, :226) — an argument for keeping this at the persistence boundary, where the PR already has it.

So this looks right to me as it stands, and my approval holds.


Drafted-by: Claude Code (Opus 5); reviewed by @moomindani before posting

@fabbuc-gyg

Copy link
Copy Markdown
Contributor Author

Is there anything blocking this from a merge? :-)

@moomindani

Copy link
Copy Markdown
Contributor

Nothing from my side — the approval stands, and the rebase I flagged in my merge-order note is not needed.

#72313 landed since then, and the two changes sit on different lines: it rewrote the loop header (_latest_attempts(...)), while this one rewrites the failed_tasks.append(...) payload. I merged current main into f1bb073570 locally to be sure — no conflict, and the combined utils/test_databricks.py is 24 passed, with both the attempt-dedup tests and the sanitization tests green.

So it is waiting on a committer to merge.


Drafted-by: Claude Code (Opus 5); reviewed by @moomindani before posting

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 5 days if no further activity occurs. Thank you for your contributions.

@github-actions github-actions Bot added the stale Stale PRs per the .github/workflows/stale.yml policy file label Nov 3, 2026
@fabbuc-gyg

fabbuc-gyg commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@eladkal , Can we merge this sometime? At my company, we will need this feature.. Or is there anything else required from my side?

@github-actions github-actions Bot removed the stale Stale PRs per the .github/workflows/stale.yml policy file label Nov 5, 2026
fabbuc-gyg and others added 3 commits November 5, 2026 07:59
…in jsonb

Databricks run output is arbitrary external text and can contain NUL bytes or
unpaired UTF-16 surrogates (e.g. when a task emits binary data). A failed
task's error is placed in the DatabricksExecutionTrigger event and persisted
by Airflow into the deferred task instance's next_kwargs (a jsonb column).
Postgres jsonb rejects those characters, so the triggerer crashes on write
(psycopg2 UntranslatableCharacter) and, because the invalid event is retried,
enters a CrashLoopBackOff that stalls all deferrable tasks.

Strip these characters from the extracted error in both the sync and async
extract_failed_task_errors helpers before it is emitted in the event.

Signed-off-by: Fabian Bücheler <fabian.bucheler@getyourguide.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
change comment
Signed-off-by: Fabian Bücheler <fabian.bucheler@getyourguide.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
@eladkal
eladkal force-pushed the fix/databricks-sanitize-failed-task-error-jsonb branch from f1bb073 to 89a7a43 Compare November 5, 2026 05:59
@eladkal
eladkal requested a review from seanmuth November 5, 2026 05:59
@seanmuth

seanmuth commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Followup on my 9/4 review: I'm retracting the RunState.to_json() concern. I re-ran the escaping and @moomindani is right. json.dumps writes a NUL as \u0000, and the nested stringification escapes the backslash again, so Postgres sees literal text and run_state doesn't hit the jsonb error. My \^@ repro was a literal backslash-caret-at in Python, not a NUL, so it didn't show what I thought it did. Keeping the sanitization at the persistence boundary, as this PR does, also avoids changing the string that databricks_repair_reason_new_settings matches on.

I also re-checked the head after the 11/05 rebase. The PR's own changes (make_jsonb_safe, the two call sites, the tests) are identical to what was approved. The only new lines come from #72313 on main, and they don't overlap. I found nothing else blocking. LGTM.

@eladkal
eladkal merged commit 3eacdb9 into apache:main Nov 5, 2026
76 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants