Skip to content

sentry_sdk.init breaks import exceptiongroup in virtualenv activated with activate_this.py #3097

Closed
@andersk

Description

@andersk

How do you use Sentry?

Sentry Saas (sentry.io)

Version

2.2.1

Steps to Reproduce

$ docker run --rm -it ubuntu:22.04
root@e264f830878b:/# apt update
root@e264f830878b:/# apt install -y python3-apport virtualenv
root@e264f830878b:/# virtualenv venv
root@e264f830878b:/# venv/bin/pip install exceptiongroup sentry-sdk

Successfully installed certifi-2024.2.2 exceptiongroup-1.2.1 sentry-sdk-2.2.1 urllib3-2.2.1
root@e264f830878b:/# cat > test.py <<EOF
exec(open("venv/bin/activate_this.py").read(), {"__file__": "venv/bin/activate_this.py"})
import sentry_sdk
sentry_sdk.init(dsn="https://[email protected]/1234")
import exceptiongroup
EOF
root@e264f830878b:/# python3 test.py

Expected Result

No error.

Actual Result

Traceback (most recent call last):
  File "//test.py", line 4, in <module>
    import exceptiongroup
  File "/venv/lib/python3.10/site-packages/exceptiongroup/__init__.py", line 20, in <module>
    from ._formatting import (
  File "/venv/lib/python3.10/site-packages/exceptiongroup/_formatting.py", line 394, in <module>
    assert sys.excepthook is apport_python_hook.apport_excepthook
AssertionError
Sentry is attempting to send 2 pending events
Waiting up to 2 seconds
Press Ctrl-C to quit

The relevant code within exceptiongroup is

if getattr(sys.excepthook, "__name__", None) in (
    "apport_excepthook",
    # on ubuntu 22.10 the hook was renamed to partial_apport_excepthook
    "partial_apport_excepthook",
):
    …
    import apport_python_hook

    assert sys.excepthook is apport_python_hook.apport_excepthook

which fails because Sentry has patched sys.excepthook but retained the same __name__, due to functools.wraps within the ensure_integration_enabled decorator, used by _make_excepthook as of

(cc @sentrivana)

This is arguably poor code within exceptiongroup (I opened agronholm/exceptiongroup#123), but Sentry should avoid breaking it since it’s a popular library; for example, it’s a dependency of IPython.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

Status

Waiting for: Product Owner

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions