Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions bench/corpus/sentry-python-4121-logging-mapping-args/case.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"schema_version": "1",
"id": "sentry-python-4121-logging-mapping-args",
"kind": "real",
"language": "python",
"provenance": {
"kind": "real",
"repo": "getsentry/sentry-python",
"pr": 4121,
"base_sha": "42ad8df79815cc6113d4106ce19c32a195a18cfb",
"head_sha": "4c9731bbe68b6523cccec73fb764e04e61e441cb",
"fix_commit": "https://github.com/getsentry/sentry-python/commit/e71ccbf19f644fe7928db37f6e4a09e1febbc4e2",
"source": "PR #4121 \"Coerce None values into strings in logentry params\", squash-merged 2025-03-12; the fix commit e71ccbf19 reverts it and says why (fixes #4267)",
"note": "introduced by this PR: the base passes record.args through untouched, and the PR replaces it with a tuple built by iterating record.args, which flattens a mapping argument to its keys. The fix commit reverts the hunk on 2025-04-14 and states the consequence: 'Because we iterate over `record.args`, that change caused us to only send the dictionary's keys, not the values.' By then the statement had moved to logging.py:268-272 (identical text), so the revert deletes the five lines this diff adds at a shifted line number, restores `\"params\": record.args,`, and adds two tests asserting the params are the dict."
},
"bugs": [
{
"path": "sentry_sdk/integrations/logging.py",
"line": 252,
"kind": "mapping-args-sent-as-keys",
"severity": "important",
"keywords": [
"only the mapping's keys reach the report",
"the values of a dictionary passed as arguments are lost",
"a mapping logged with percent placeholders keeps just its key names",
"dict arguments are flattened into their keys",
"the message renders with key names instead of the substituted values",
"mapping-style interpolation receives the key names",
"the interpolated parameters collapse to the dictionary keys",
"keys instead of values",
"flattens a mapping",
"only keys survive"
],
"note": "stdlib logging accepts a single mapping as record.args for %(name)s templates; the generator iterates it, so keys, not values, are sent. The generator also rewrites a None argument to the string \"None\", which was the PR's intent.",
"also_lines": [251]
}
]
}
17 changes: 17 additions & 0 deletions bench/corpus/sentry-python-4121-logging-mapping-args/full.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
diff --git a/sentry_sdk/integrations/logging.py b/sentry_sdk/integrations/logging.py
index b792510d6..28809de4a 100644
--- a/sentry_sdk/integrations/logging.py
+++ b/sentry_sdk/integrations/logging.py
@@ -248,7 +248,11 @@ class EventHandler(_BaseHandler):
else:
event["logentry"] = {
"message": to_string(record.msg),
- "params": record.args,
+ "params": (
+ tuple(str(arg) if arg is None else arg for arg in record.args)
+ if record.args
+ else ()
+ ),
}

event["extra"] = self._extra_from_record(record)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
sentry_sdk/integrations/logging.py OLD 248 254
sentry_sdk/integrations/logging.py NEW 248 258
34 changes: 34 additions & 0 deletions bench/corpus/sentry-python-4133-debug-parent-logger/case.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"schema_version": "1",
"id": "sentry-python-4133-debug-parent-logger",
"kind": "real",
"language": "python",
"provenance": {
"kind": "real",
"repo": "getsentry/sentry-python",
"pr": 4133,
"base_sha": "4f51ff37a26b1e774b8050119da75074d1a1d5ed",
"head_sha": "37930840dcefba96e7708b19e461013a919e83a5",
"fix_commit": "https://github.com/getsentry/sentry-python/commit/5689bc09fd223f80f65290e2ccb685b8acb9a5f2",
"source": "PR #4133 \"fix(debug): Take into account parent handlers for debug logger\", squash-merged 2025-03-13; the fix commit 5689bc09 reverts it (fixes #4266)",
"note": "introduced by the one-line change: the SDK's own logger is configured only when no handler is attached anywhere in the hierarchy, so once an application configures the root logger the SDK never installs its own handler. The fix commit reverts to the attribute check on 2025-04-14: 'we should not consider parent loggers, since we only want the SDK to log debug messages when configured to do so via debug=True ... With 37930840d... a custom root logger configuration would also cause SDK logs to be emitted.' The revert names the emission direction; the converse is what the same line does to a host root level above DEBUG, where the SDK's own diagnostics disappear entirely."
},
"bugs": [
{
"path": "sentry_sdk/debug.py",
"line": 22,
"kind": "debug-output-hijacked",
"severity": "important",
"keywords": [
"an application root configuration silently suppresses the diagnostics",
"the library's diagnostics end up in the host application's log stream instead of its own",
"the library prints nothing when the host has its own log configuration",
"a parent log setup decides whether anything is emitted",
"debug=true produces nothing",
"debug=true fails",
"leaked to the root"
],
"note": "init_debug_support runs when the debug option is on; the inherited-handler walk makes it a no-op whenever the application has a root handler, so the SDK either emits nothing (host root level above DEBUG) or emits its diagnostics through the application's own handler and formatter. Both are observable; the keywords cover the suppression direction and the emission direction, and the revert cites the emission one."
}
]
}
13 changes: 13 additions & 0 deletions bench/corpus/sentry-python-4133-debug-parent-logger/full.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
diff --git a/sentry_sdk/debug.py b/sentry_sdk/debug.py
index e4c686a3e..f740d92de 100644
--- a/sentry_sdk/debug.py
+++ b/sentry_sdk/debug.py
@@ -19,7 +19,7 @@ class _DebugFilter(logging.Filter):

def init_debug_support():
# type: () -> None
- if not logger.handlers:
+ if not logger.hasHandlers():
configure_logger()


Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
sentry_sdk/debug.py OLD 19 25
sentry_sdk/debug.py NEW 19 25
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"schema_version": "1",
"id": "sentry-python-4281-threading-channels-version",
"kind": "real",
"language": "python",
"provenance": {
"kind": "real",
"repo": "getsentry/sentry-python",
"pr": 4281,
"base_sha": "706d2d29e68848a3cb085f043287d908255344b5",
"head_sha": "2d392af3ea6da91ddbdde55d18e15c24dce6b59b",
"fix_commit": "https://github.com/getsentry/sentry-python/commit/a350506948ad12ffc6d564cef3985f0dd5435b20",
"source": "PR #4281 \"fix: Data leak in ThreadingIntegration between threads\", squash-merged 2025-04-15; fix commit a35050694 \"fix(threading): Handle channels shadowing (#5299)\", closes #5298",
"note": "introduced by this PR, which reads channels.__version__ inside a block whose only failure handler is ImportError, so a module named channels that has no __version__ raises AttributeError out of setup_once(). By the time of the fix the file had gained an unrelated constant and the block sits two lines lower; the two lines the fix deletes are the ones this diff adds."
},
"bugs": [
{
"path": "sentry_sdk/integrations/threading.py",
"line": 57,
"kind": "shadowed-module-crashes-setup",
"severity": "critical",
"keywords": [
"a lookalike package without a version attribute aborts the initialization",
"a shadowing module makes the attribute access raise instead of skipping",
"initialization crashes instead of disabling the integration",
"the guard only covers a missing package, so a missing attribute crashes setup",
"bootstrapping the client fails when a local module of that name has no version",
"crashes init",
"crashes the client"
],
"note": "ThreadingIntegration is a default integration and setup_integrations only catches DidNotEnable around its setup_once, so the AttributeError reaches sentry_sdk.init() and the application fails to start. The fix moves `import channels` and the version read into their own try whose handler is `(ImportError, AttributeError)`.",
"also_lines": [55, 58]
}
]
}
204 changes: 204 additions & 0 deletions bench/corpus/sentry-python-4281-threading-channels-version/full.diff
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
diff --git a/sentry_sdk/integrations/threading.py b/sentry_sdk/integrations/threading.py
index 5de736e23..9c99a8e89 100644
--- a/sentry_sdk/integrations/threading.py
+++ b/sentry_sdk/integrations/threading.py
@@ -1,4 +1,5 @@
import sys
+import warnings
from functools import wraps
from threading import Thread, current_thread

@@ -49,6 +50,15 @@ class ThreadingIntegration(Integration):
# type: () -> None
old_start = Thread.start

+ try:
+ from django import VERSION as django_version # noqa: N811
+ import channels # type: ignore[import-not-found]
+
+ channels_version = channels.__version__
+ except ImportError:
+ django_version = None
+ channels_version = None
+
@wraps(old_start)
def sentry_start(self, *a, **kw):
# type: (Thread, *Any, **Any) -> Any
@@ -57,8 +67,27 @@ class ThreadingIntegration(Integration):
return old_start(self, *a, **kw)

if integration.propagate_scope:
- isolation_scope = sentry_sdk.get_isolation_scope()
- current_scope = sentry_sdk.get_current_scope()
+ if (
+ sys.version_info < (3, 9)
+ and channels_version is not None
+ and channels_version < "4.0.0"
+ and django_version is not None
+ and django_version >= (3, 0)
+ and django_version < (4, 0)
+ ):
+ warnings.warn(
+ "There is a known issue with Django channels 2.x and 3.x when using Python 3.8 or older. "
+ "(Async support is emulated using threads and some Sentry data may be leaked between those threads.) "
+ "Please either upgrade to Django channels 4.0+, use Django's async features "
+ "available in Django 3.1+ instead of Django channels, or upgrade to Python 3.9+.",
+ stacklevel=2,
+ )
+ isolation_scope = sentry_sdk.get_isolation_scope()
+ current_scope = sentry_sdk.get_current_scope()
+
+ else:
+ isolation_scope = sentry_sdk.get_isolation_scope().fork()
+ current_scope = sentry_sdk.get_current_scope().fork()
else:
isolation_scope = None
current_scope = None
diff --git a/tests/integrations/django/asgi/test_asgi.py b/tests/integrations/django/asgi/test_asgi.py
index 063aed63a..82eae30b1 100644
--- a/tests/integrations/django/asgi/test_asgi.py
+++ b/tests/integrations/django/asgi/test_asgi.py
@@ -38,9 +38,25 @@ async def test_basic(sentry_init, capture_events, application):

events = capture_events()

- comm = HttpCommunicator(application, "GET", "/view-exc?test=query")
- response = await comm.get_response()
- await comm.wait()
+ import channels # type: ignore[import-not-found]
+
+ if (
+ sys.version_info < (3, 9)
+ and channels.__version__ < "4.0.0"
+ and django.VERSION >= (3, 0)
+ and django.VERSION < (4, 0)
+ ):
+ # We emit a UserWarning for channels 2.x and 3.x on Python 3.8 and older
+ # because the async support was not really good back then and there is a known issue.
+ # See the TreadingIntegration for details.
+ with pytest.warns(UserWarning):
+ comm = HttpCommunicator(application, "GET", "/view-exc?test=query")
+ response = await comm.get_response()
+ await comm.wait()
+ else:
+ comm = HttpCommunicator(application, "GET", "/view-exc?test=query")
+ response = await comm.get_response()
+ await comm.wait()

assert response["status"] == 500

diff --git a/tests/integrations/threading/test_threading.py b/tests/integrations/threading/test_threading.py
index 0d14fae35..4395891d6 100644
--- a/tests/integrations/threading/test_threading.py
+++ b/tests/integrations/threading/test_threading.py
@@ -1,5 +1,6 @@
import gc
from concurrent import futures
+from textwrap import dedent
from threading import Thread

import pytest
@@ -172,3 +173,103 @@ def test_wrapper_attributes(sentry_init):
assert Thread.run.__qualname__ == original_run.__qualname__
assert t.run.__name__ == "run"
assert t.run.__qualname__ == original_run.__qualname__
+
+
+@pytest.mark.parametrize(
+ "propagate_scope",
+ (True, False),
+ ids=["propagate_scope=True", "propagate_scope=False"],
+)
+def test_scope_data_not_leaked_in_threads(sentry_init, propagate_scope):
+ sentry_init(
+ integrations=[ThreadingIntegration(propagate_scope=propagate_scope)],
+ )
+
+ sentry_sdk.set_tag("initial_tag", "initial_value")
+ initial_iso_scope = sentry_sdk.get_isolation_scope()
+
+ def do_some_work():
+ # check if we have the initial scope data propagated into the thread
+ if propagate_scope:
+ assert sentry_sdk.get_isolation_scope()._tags == {
+ "initial_tag": "initial_value"
+ }
+ else:
+ assert sentry_sdk.get_isolation_scope()._tags == {}
+
+ # change data in isolation scope in thread
+ sentry_sdk.set_tag("thread_tag", "thread_value")
+
+ t = Thread(target=do_some_work)
+ t.start()
+ t.join()
+
+ # check if the initial scope data is not modified by the started thread
+ assert initial_iso_scope._tags == {
+ "initial_tag": "initial_value"
+ }, "The isolation scope in the main thread should not be modified by the started thread."
+
+
+@pytest.mark.parametrize(
+ "propagate_scope",
+ (True, False),
+ ids=["propagate_scope=True", "propagate_scope=False"],
+)
+def test_spans_from_multiple_threads(
+ sentry_init, capture_events, render_span_tree, propagate_scope
+):
+ sentry_init(
+ traces_sample_rate=1.0,
+ integrations=[ThreadingIntegration(propagate_scope=propagate_scope)],
+ )
+ events = capture_events()
+
+ def do_some_work(number):
+ with sentry_sdk.start_span(
+ op=f"inner-run-{number}", name=f"Thread: child-{number}"
+ ):
+ pass
+
+ threads = []
+
+ with sentry_sdk.start_transaction(op="outer-trx"):
+ for number in range(5):
+ with sentry_sdk.start_span(
+ op=f"outer-submit-{number}", name="Thread: main"
+ ):
+ t = Thread(target=do_some_work, args=(number,))
+ t.start()
+ threads.append(t)
+
+ for t in threads:
+ t.join()
+
+ (event,) = events
+ if propagate_scope:
+ assert render_span_tree(event) == dedent(
+ """\
+ - op="outer-trx": description=null
+ - op="outer-submit-0": description="Thread: main"
+ - op="inner-run-0": description="Thread: child-0"
+ - op="outer-submit-1": description="Thread: main"
+ - op="inner-run-1": description="Thread: child-1"
+ - op="outer-submit-2": description="Thread: main"
+ - op="inner-run-2": description="Thread: child-2"
+ - op="outer-submit-3": description="Thread: main"
+ - op="inner-run-3": description="Thread: child-3"
+ - op="outer-submit-4": description="Thread: main"
+ - op="inner-run-4": description="Thread: child-4"\
+"""
+ )
+
+ elif not propagate_scope:
+ assert render_span_tree(event) == dedent(
+ """\
+ - op="outer-trx": description=null
+ - op="outer-submit-0": description="Thread: main"
+ - op="outer-submit-1": description="Thread: main"
+ - op="outer-submit-2": description="Thread: main"
+ - op="outer-submit-3": description="Thread: main"
+ - op="outer-submit-4": description="Thread: main"\
+"""
+ )
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
sentry_sdk/integrations/threading.py OLD 1 4
sentry_sdk/integrations/threading.py NEW 1 5
sentry_sdk/integrations/threading.py OLD 49 54
sentry_sdk/integrations/threading.py NEW 50 64
sentry_sdk/integrations/threading.py OLD 57 64
sentry_sdk/integrations/threading.py NEW 67 93
tests/integrations/django/asgi/test_asgi.py OLD 38 46
tests/integrations/django/asgi/test_asgi.py NEW 38 62
tests/integrations/threading/test_threading.py OLD 1 5
tests/integrations/threading/test_threading.py NEW 1 6
tests/integrations/threading/test_threading.py OLD 172 174
tests/integrations/threading/test_threading.py NEW 173 275
Loading
Loading