Skip to content

Fix blackd error handling: split SourceASTParseError from ASTSafetyError#5080

Open
Bahtya wants to merge 1 commit intopsf:mainfrom
Bahtya:fix/blackd-source-ast-parse-error
Open

Fix blackd error handling: split SourceASTParseError from ASTSafetyError#5080
Bahtya wants to merge 1 commit intopsf:mainfrom
Bahtya:fix/blackd-source-ast-parse-error

Conversation

@Bahtya
Copy link
Copy Markdown

@Bahtya Bahtya commented Apr 6, 2026

Summary

Per @JelleZijlstra's review feedback on #5074, this PR splits the error handling instead of treating all ASTSafetyError as 400.

Changes

  1. New exception: SourceASTParseError (src/black/parsing.py)

    • Raised when the source file cannot be parsed by ast.parse() but was accepted by Black's more lenient lib2to3 parser
    • This is a user input issue, not a Black bug
  2. Updated assert_equivalent (src/black/__init__.py)

    • Source AST parse failure → SourceASTParseError (user input issue)
    • Dest AST parse failure → ASTSafetyError (Black bug → 500)
    • Non-equivalent output → ASTSafetyError (Black bug → 500)
  3. Updated blackd (src/blackd/__init__.py)

    • SourceASTParseError → 400 Bad Request
    • ASTSafetyError → 500 Internal Server Error (unchanged, caught by generic Exception handler)

Closes

Fixes #4332

Analysis of all ASTSafetyError uses

Location Cause Error type blackd status
assert_equivalent src AST parse fail User input (lenient parser) SourceASTParseError 400
assert_equivalent dest AST parse fail Black bug ASTSafetyError 500
assert_equivalent src ≠ dst Black bug ASTSafetyError 500
check_stability_and_equivalence re-raise Depends on underlying Propagated 400 or 500

- Add SourceASTParseError exception for source file AST parse failures
  (user input issue, not a Black bug)
- Keep ASTSafetyError for Black output issues (invalid code, non-equivalent)
- In blackd, return 400 for SourceASTParseError, 500 for ASTSafetyError
- Per @JelleZijlstra review feedback on psf#5074
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant