Skip to content

break exception context cycle from BaseExceptionGroup in middleware#3341

Open
balochy wants to merge 1 commit into
Kludex:mainfrom
balochy:bugfix/exception-loop-fix
Open

break exception context cycle from BaseExceptionGroup in middleware#3341
balochy wants to merge 1 commit into
Kludex:mainfrom
balochy:bugfix/exception-loop-fix

Conversation

@balochy

@balochy balochy commented Jun 24, 2026

Copy link
Copy Markdown

Summary

When BaseHTTPMiddleware catches a route exception, anyio wraps it in a BaseExceptionGroup. create_collapsing_task_group extracts the single exception and re-raises it — but does so inside the except ذbock.
Python implicitly sets exc.__context__ to the caught BaseExceptionGroup which contains exc itself, creating a reference cycle:
exc.context → BaseExceptionGroup → BaseExceptionGroup.exceptions[0] → exc

Traceback formatters (e.g. Rich) following the __context__ chain hit infinite recursion when middleware is present.

Fix by raising outside the except block so Python does not overwrite __context__ with the BaseExceptionGroup. Also add the missing __suppress_context__ guard in call_next so suppressed contexts are not incorrectly promoted to cause.

please see discussion: #2942

Checklist

  • [ x ] I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • [ x ] I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • [ x ] I've updated the documentation accordingly.

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 2 files

Re-trigger cubic

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