internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: getsentry/sentry-python

Issue:
Check if aiohttp client integration needs special baggage handling
### Problem Statement

Once the [instrumentation for aiohttp client requests](https://github.com/getsentry/sentry-python/pull/1761) is in, see if we need special handling for existing baggage [like here](https://github.com/getsentry/sentry-python/pull/2191).

### Solution Brainstorm

Do it.


Discussion:

Resolving patch:
diff --git a/sentry_sdk/integrations/aiohttp.py b/sentry_sdk/integrations/aiohttp.py
--- a/sentry_sdk/integrations/aiohttp.py
+++ b/sentry_sdk/integrations/aiohttp.py
@@ -12,7 +12,11 @@
     _filter_headers,
     request_body_within_bounds,
 )
-from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE
+from sentry_sdk.tracing import (
+    BAGGAGE_HEADER_NAME,
+    SOURCE_FOR_STYLE,
+    TRANSACTION_SOURCE_ROUTE,
+)
 from sentry_sdk.tracing_utils import should_propagate_trace
 from sentry_sdk.utils import (
     capture_internal_exceptions,
@@ -220,7 +224,13 @@ async def on_request_start(session, trace_config_ctx, params):
                         key=key, value=value, url=params.url
                     )
                 )
-                params.headers[key] = value
+                if key == BAGGAGE_HEADER_NAME and params.headers.get(
+                    BAGGAGE_HEADER_NAME
+                ):
+                    # do not overwrite any existing baggage, just append to it
+                    params.headers[key] += "," + value
+                else:
+                    params.headers[key] = value
 
         trace_config_ctx.span = span
 


Test patch:
diff --git a/tests/integrations/aiohttp/test_aiohttp.py b/tests/integrations/aiohttp/test_aiohttp.py
--- a/tests/integrations/aiohttp/test_aiohttp.py
+++ b/tests/integrations/aiohttp/test_aiohttp.py
@@ -505,3 +505,32 @@ async def handler(request):
             parent_span_id=request_span.span_id,
             sampled=1,
         )
+
+
+@pytest.mark.asyncio
+async def test_outgoing_trace_headers_append_to_baggage(
+    sentry_init, aiohttp_raw_server, aiohttp_client
+):
+    sentry_init(
+        integrations=[AioHttpIntegration()],
+        traces_sample_rate=1.0,
+        release="d08ebdb9309e1b004c6f52202de58a09c2268e42",
+    )
+
+    async def handler(request):
+        return web.Response(text="OK")
+
+    raw_server = await aiohttp_raw_server(handler)
+
+    with start_transaction(
+        name="/interactions/other-dogs/new-dog",
+        op="greeting.sniff",
+        trace_id="0123456789012345678901234567890",
+    ):
+        client = await aiohttp_client(raw_server)
+        resp = await client.get("/", headers={"bagGage": "custom=value"})
+
+        assert (
+            resp.request_info.headers["baggage"]
+            == "custom=value,sentry-trace_id=0123456789012345678901234567890,sentry-environment=production,sentry-release=d08ebdb9309e1b004c6f52202de58a09c2268e42,sentry-transaction=/interactions/other-dogs/new-dog,sentry-sample_rate=1.0"
+        )
Repository: getsentry/sentry-python

Issue:
Add "replay" context to errors 
### Problem Statement

If there is a `replay_id` in the baggage header in incoming HTTP requests there should be an "replay" context added to the events payload: https://develop.sentry.dev/sdk/event-payloads/contexts/#replay-context

use case when can't use envelopes. For PHP & Python still use /store which doesn't have the correct context with /store


### Solution Brainstorm

Add replay context to baggage, so that BE errors can be connected with FE errors

.


Discussion:

Resolving patch:
diff --git a/sentry_sdk/scope.py b/sentry_sdk/scope.py
--- a/sentry_sdk/scope.py
+++ b/sentry_sdk/scope.py
@@ -614,6 +614,16 @@ def _drop(cause, ty):
             else:
                 contexts["trace"] = self.get_trace_context()
 
+        try:
+            replay_id = contexts["trace"]["dynamic_sampling_context"]["replay_id"]
+        except (KeyError, TypeError):
+            replay_id = None
+
+        if replay_id is not None:
+            contexts["replay"] = {
+                "replay_id": replay_id,
+            }
+
         exc_info = hint.get("exc_info")
         if exc_info is not None:
             for error_processor in self._error_processors:


Test patch:
diff --git a/tests/integrations/flask/test_flask.py b/tests/integrations/flask/test_flask.py
--- a/tests/integrations/flask/test_flask.py
+++ b/tests/integrations/flask/test_flask.py
@@ -875,3 +875,34 @@ def index():
 
     assert event["request"]["data"]["password"] == "[Filtered]"
     assert event["request"]["headers"]["Authorization"] == "[Filtered]"
+
+
+@pytest.mark.parametrize("traces_sample_rate", [None, 1.0])
+def test_replay_event_context(sentry_init, capture_events, app, traces_sample_rate):
+    """
+    Tests that the replay context is added to the event context.
+    This is not strictly a Flask integration test, but it's the easiest way to test this.
+    """
+    sentry_init(traces_sample_rate=traces_sample_rate)
+
+    @app.route("/error")
+    def error():
+        return 1 / 0
+
+    events = capture_events()
+
+    client = app.test_client()
+    headers = {
+        "baggage": "other-vendor-value-1=foo;bar;baz,sentry-trace_id=771a43a4192642f0b136d5159a501700,sentry-public_key=49d0f7386ad645858ae85020e393bef3, sentry-sample_rate=0.01337,sentry-user_id=Am%C3%A9lie,other-vendor-value-2=foo;bar,sentry-replay_id=12312012123120121231201212312012",
+        "sentry-trace": "771a43a4192642f0b136d5159a501700-1234567890abcdef-1",
+    }
+    with pytest.raises(ZeroDivisionError):
+        client.get("/error", headers=headers)
+
+    event = events[0]
+
+    assert event["contexts"]
+    assert event["contexts"]["replay"]
+    assert (
+        event["contexts"]["replay"]["replay_id"] == "12312012123120121231201212312012"
+    )
Repository: getsentry/sentry-python

Issue:
sample_rate option affecting crons checkin events
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

1.28.1

### Steps to Reproduce

Error event specific option `sample_rate` is affecting crons check in events

```
sentry_sdk.init(
    dsn="https://da93b3386b344b3182ed201d7a18bab0@o1407376.ingest.sentry.io/4504091267497984",
    sample_rate=0,
    debug=True,
    )
```

An init like the one above will cause no crons check in events to send.

### Expected Result

Crons checkin events should not be affected by the `sample_rate` option.

### Actual Result

Crons checkin events are being sampled.  Currently it looks like each event is also being sampled separately.  So if you have the `sample_rate` option set, even if the `in_progress` event gets sampled and sent, the `ok` event may not get sampled.


Discussion:

Resolving patch:
diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py
--- a/sentry_sdk/client.py
+++ b/sentry_sdk/client.py
@@ -530,12 +530,16 @@ def capture_event(
             self._update_session_from_event(session, event)
 
         is_transaction = event_opt.get("type") == "transaction"
+        is_checkin = event_opt.get("type") == "check_in"
 
-        if not is_transaction and not self._should_sample_error(event):
+        if (
+            not is_transaction
+            and not is_checkin
+            and not self._should_sample_error(event)
+        ):
             return None
 
         tracing_enabled = has_tracing_enabled(self.options)
-        is_checkin = event_opt.get("type") == "check_in"
         attachments = hint.get("attachments")
 
         trace_context = event_opt.get("contexts", {}).get("trace") or {}


Test patch:
diff --git a/tests/test_crons.py b/tests/test_crons.py
--- a/tests/test_crons.py
+++ b/tests/test_crons.py
@@ -81,6 +81,18 @@ def test_capture_checkin_simple(sentry_init):
     assert check_in_id == "112233"
 
 
+def test_sample_rate_doesnt_affect_crons(sentry_init, capture_envelopes):
+    sentry_init(sample_rate=0)
+    envelopes = capture_envelopes()
+
+    capture_checkin(check_in_id="112233")
+
+    assert len(envelopes) == 1
+
+    check_in = envelopes[0].items[0].payload.json
+    assert check_in["check_in_id"] == "112233"
+
+
 def test_capture_checkin_new_id(sentry_init):
     sentry_init()
 
diff --git a/tests/tracing/test_sampling.py b/tests/tracing/test_sampling.py
--- a/tests/tracing/test_sampling.py
+++ b/tests/tracing/test_sampling.py
@@ -2,7 +2,7 @@
 
 import pytest
 
-from sentry_sdk import Hub, start_span, start_transaction
+from sentry_sdk import Hub, start_span, start_transaction, capture_exception
 from sentry_sdk.tracing import Transaction
 from sentry_sdk.utils import logger
 
@@ -226,6 +226,18 @@ def test_passes_custom_samling_context_from_start_transaction_to_traces_sampler(
     )
 
 
+def test_sample_rate_affects_errors(sentry_init, capture_events):
+    sentry_init(sample_rate=0)
+    events = capture_events()
+
+    try:
+        1 / 0
+    except Exception:
+        capture_exception()
+
+    assert len(events) == 0
+
+
 @pytest.mark.parametrize(
     "traces_sampler_return_value",
     [
Repository: getsentry/sentry-python

Issue:
AttributeError: 'NoOpSpan' object has no attribute 'set_measurement'
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

1.19.1

### Steps to Reproduce

1. in this PR https://github.com/getsentry/sentry/pull/47486 i am attempting to set a custom measurment

I get this type error when I run tests https://github.com/getsentry/sentry/pull/47486/commits/89b400dd7fee61e603a6c554ddb981214a0cbeb2


### Expected Result

i shouldn't get an error if the transaction isn't sampled

### Actual Result

My usage of the python SDK causes the backend to throw with this type error here.


Discussion:
I am experiencing this (in 1.16.0 though) for the `set_context` attribute as well. I believe the problem is that `start_transaction` returns an instance of `NoOpSpan` when the client hasn't been configured. `NoOpSpan` inherits `Span` that doesn't implement `set_context` either. Probably there is need for a `NoOpTransaction` class to handle this case.
@Majsvaffla are you using the OTel instrumenter?
@JoshFerge as the `NoOpSpan` should only be retruned if the OTel instrumenter is used this feels strange. You are not using the Otel instrumenter, right?
this was in Sentry -- you can replicate by looking at the PR I linked and checking out the commit before I removed the `set_measurement` call
Hmm @antonpirker ~~I don't think so~~ no. I'm doing `import sentry_sdk` and then `with sentry_sdk.start_transaction(...): ...`.
@antonpirker any updates on this? 
@antonpirker any updates here?
Sorry this one kind of fell through the cracks. I have put this now on our board, so it should be handled soonish.


Resolving patch:
diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py
--- a/sentry_sdk/tracing.py
+++ b/sentry_sdk/tracing.py
@@ -876,6 +876,11 @@ def __repr__(self):
         # type: () -> str
         return self.__class__.__name__
 
+    @property
+    def containing_transaction(self):
+        # type: () -> Optional[Transaction]
+        return None
+
     def start_child(self, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
         # type: (str, **Any) -> NoOpSpan
         return NoOpSpan()
@@ -892,6 +897,10 @@ def to_baggage(self):
         # type: () -> Optional[Baggage]
         return None
 
+    def get_baggage(self):
+        # type: () -> Optional[Baggage]
+        return None
+
     def iter_headers(self):
         # type: () -> Iterator[Tuple[str, str]]
         return iter(())
@@ -928,6 +937,22 @@ def finish(self, hub=None, end_timestamp=None):
         # type: (Optional[sentry_sdk.Hub], Optional[datetime]) -> Optional[str]
         pass
 
+    def set_measurement(self, name, value, unit=""):
+        # type: (str, float, MeasurementUnit) -> None
+        pass
+
+    def set_context(self, key, value):
+        # type: (str, Any) -> None
+        pass
+
+    def init_span_recorder(self, maxlen):
+        # type: (int) -> None
+        pass
+
+    def _set_initial_sampling_decision(self, sampling_context):
+        # type: (SamplingContext) -> None
+        pass
+
 
 def trace(func=None):
     # type: (Any) -> Any


Test patch:
Repository: getsentry/sentry-python

Issue:
Span `code.filepath` property has the absolute path, rather than the in-app path
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

1.37.0

### Steps to Reproduce

1. Enable the `enable_db_query_source` SDK option
2. Instrument a path that has a query > 100ms
3. Examine the span that comes into Sentry

### Expected Result

The `code.filepath` property is an in-app path, something like `/app/controllers/view.py`

The span's `code.filepath` contains the full absolute path to the file. This is different from Laravel, which attaches the in-app path. Is it possible for the Python SDK to put the app path into `code.filepath`?

### Actual Result

The `code.filepath` property is an absolute path, something like `/usr/george/server/app/controllers/view.py`


Discussion:

Resolving patch:
diff --git a/sentry_sdk/tracing_utils.py b/sentry_sdk/tracing_utils.py
--- a/sentry_sdk/tracing_utils.py
+++ b/sentry_sdk/tracing_utils.py
@@ -238,7 +238,8 @@ def add_query_source(hub, span):
         except Exception:
             filepath = None
         if filepath is not None:
-            span.set_data(SPANDATA.CODE_FILEPATH, frame.f_code.co_filename)
+            in_app_path = filepath.replace(project_root, "")
+            span.set_data(SPANDATA.CODE_FILEPATH, in_app_path)
 
         try:
             code_function = frame.f_code.co_name


Test patch:
Repository: getsentry/sentry-python

Issue:
Memory leak with unclosed span in opentelemetry integration
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

1.40.3

### Steps to Reproduce

`SentrySpanProcessor` stores all open span in `self.otel_span_map` dict. This leads to a memory leak if otel span is deleted without closing. E.g. due to a bug: https://github.com/open-telemetry/opentelemetry-python-contrib/issues/2149

### Expected Result

Sentry span should be deleted after otel span is deleted by GC.

### Actual Result

Sentry spans are stored in self.otel_span_map forever.


Discussion:
Thanks for the report @vanchaxy, putting this in our backlog.
Same problem, docker containing the flask process crashes about once an hour due to memory overflow when no heavy tasks are performed.
isn't this a p0? it's def a p0 in .NET

Resolving patch:
diff --git a/sentry_sdk/scrubber.py b/sentry_sdk/scrubber.py
--- a/sentry_sdk/scrubber.py
+++ b/sentry_sdk/scrubber.py
@@ -1,8 +1,3 @@
-try:
-    from typing import cast
-except ImportError:
-    cast = lambda _, obj: obj
-
 from sentry_sdk.utils import (
     capture_internal_exceptions,
     AnnotatedValue,
@@ -94,6 +89,8 @@ def scrub_dict(self, d):
             return
 
         for k, v in d.items():
+            # The cast is needed because mypy is not smart enough to figure out that k must be a
+            # string after the isinstance check.
             if isinstance(k, str) and k.lower() in self.denylist:
                 d[k] = AnnotatedValue.substituted_because_contains_sensitive_data()
             elif self.recursive:


Test patch:
Repository: getsentry/sentry-python

Issue:
[SDK 2.0] Fix Client `should_send_default_pii` implementation
`should_send_default_pii` is defined on the `BaseClient` with a simple implementation that always returns `False`. This implementation should be overridden in the `_Client` class. 


Discussion:

Resolving patch:
diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py
--- a/sentry_sdk/client.py
+++ b/sentry_sdk/client.py
@@ -403,6 +403,15 @@ def is_active(self):
         """
         return True
 
+    def should_send_default_pii(self):
+        # type: () -> bool
+        """
+        .. versionadded:: 2.0.0
+
+        Returns whether the client should send default PII (Personally Identifiable Information) data to Sentry.
+        """
+        return self.options.get("send_default_pii", False)
+
     @property
     def dsn(self):
         # type: () -> Optional[str]
diff --git a/sentry_sdk/hub.py b/sentry_sdk/hub.py
--- a/sentry_sdk/hub.py
+++ b/sentry_sdk/hub.py
@@ -60,10 +60,12 @@ def overload(x):
 
 def _should_send_default_pii():
     # type: () -> bool
+    # TODO: Migrate existing code to client.should_send_default_pii() and remove this function.
+    # New code should not use this function!
     client = Hub.current.client
     if not client:
         return False
-    return client.options["send_default_pii"]
+    return client.should_send_default_pii()
 
 
 class _InitGuard:


Test patch:
Repository: getsentry/sentry-python

Issue:
Send Celery Message ID
Specifically, we want to include the consumer and message IDs in the Celery transactions/spans

```[tasklist]
### Tasks
- [ ] #3015
- [x] ~consumer id (unique id of the consumer) (`messaging.client_id`) - dont know yet where to get.~ (not needed per https://develop-git-queue-module.sentry.dev/sdk/performance/modules/queue/)
```



Discussion:

Resolving patch:
diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py
--- a/sentry_sdk/consts.py
+++ b/sentry_sdk/consts.py
@@ -270,6 +270,11 @@ class SPANDATA:
     e.g. the queue name or topic.
     """
 
+    MESSAGING_MESSAGE_ID = "messaging.message.id"
+    """
+    The message's identifier.
+    """
+
     MESSAGING_MESSAGE_RETRY_COUNT = "messaging.message.retry.count"
     """
     Number of retries/attempts to process a message.
diff --git a/sentry_sdk/integrations/celery/__init__.py b/sentry_sdk/integrations/celery/__init__.py
--- a/sentry_sdk/integrations/celery/__init__.py
+++ b/sentry_sdk/integrations/celery/__init__.py
@@ -356,6 +356,8 @@ def _inner(*args, **kwargs):
                 op=OP.QUEUE_PROCESS, description=task.name
             ) as span:
                 _set_messaging_destination_name(task, span)
+                with capture_internal_exceptions():
+                    span.set_data(SPANDATA.MESSAGING_MESSAGE_ID, task.request.id)
                 with capture_internal_exceptions():
                     span.set_data(
                         SPANDATA.MESSAGING_MESSAGE_RETRY_COUNT, task.request.retries


Test patch:
diff --git a/tests/integrations/celery/test_celery.py b/tests/integrations/celery/test_celery.py
--- a/tests/integrations/celery/test_celery.py
+++ b/tests/integrations/celery/test_celery.py
@@ -661,6 +661,20 @@ def task(): ...
     assert "messaging.destination.name" not in span["data"]
 
 
+def test_messaging_id(init_celery, capture_events):
+    celery = init_celery(enable_tracing=True)
+    events = capture_events()
+
+    @celery.task
+    def example_task(): ...
+
+    example_task.apply_async()
+
+    (event,) = events
+    (span,) = event["spans"]
+    assert "messaging.message.id" in span["data"]
+
+
 def test_retry_count_zero(init_celery, capture_events):
     celery = init_celery(enable_tracing=True)
     events = capture_events()
Repository: getsentry/sentry-python

Issue:
`sentry-sdk[grpcio]` requires `protobuf`
### How do you use Sentry?

Sentry Saas (sentry.io)

### Version

2.2.0

### Steps to Reproduce

See: https://stackoverflow.com/questions/78488561

Followed Sentry documentation [gRPC](https://docs.sentry.io/platforms/python/integrations/grpc/)

```bash
python3 -m venv venv
source venv/bin/activate
python3 -m pip install --upgrade 'sentry-sdk[grpcio]'

python3 -m pip freeze
```
```
certifi==2024.2.2
grpcio==1.63.0
sentry-sdk==2.2.0
urllib3==2.2.1
```
`main.py`:
```python3
import grpc

import sentry_sdk
from sentry_sdk.integrations.grpc import GRPCIntegration

sentry_sdk.init(
    dsn="https://...",
    enable_tracing=True,
    integrations=[
        GRPCIntegration(),
    ],
)

with grpc.insecure_channel("example.com:12345") as channel:
    print(channel)
```


### Expected Result

Happy path.

### Actual Result

```bash
python3 main.py
Traceback (most recent call last):
  File "[redacted]/venv/lib/python3.10/site-packages/sentry_sdk/integrations/grpc/client.py", line 15, in <module>
    from google.protobuf.message import Message
ModuleNotFoundError: No module named 'google'
```
`integrations/grpc/client.py`:
```python3
try:
    import grpc
    from grpc import ClientCallDetails, Call
    from grpc._interceptor import _UnaryOutcome
    from grpc.aio._interceptor import UnaryStreamCall
    from google.protobuf.message import Message      <-------------- curious
except ImportError:
    raise DidNotEnable("grpcio is not installed")
```

#### Solution

```bash
python3 -m pip install protobuf
python3 -m pip freeze
```
```
certifi==2024.2.2
grpcio==1.63.0
protobuf==5.26.1
sentry-sdk==2.2.0
urllib3==2.2.1
```
Then works.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -57,7 +57,7 @@ def get_file_text(file_name):
         "falcon": ["falcon>=1.4"],
         "fastapi": ["fastapi>=0.79.0"],
         "flask": ["flask>=0.11", "blinker>=1.1", "markupsafe"],
-        "grpcio": ["grpcio>=1.21.1"],
+        "grpcio": ["grpcio>=1.21.1", "protobuf>=3.8.0"],
         "httpx": ["httpx>=0.16.0"],
         "huey": ["huey>=2"],
         "huggingface_hub": ["huggingface_hub>=0.22"],


Test patch:
Repository: ansible/molecule

Issue:
Search in test/integration/default/ for tests
Test-kitchen searches for tests in `test/integration/default/`, see here:
http://kitchen.ci/docs/getting-started/writing-test

It'd be nice if molecule could search there, too, so existing tests do not have to be changed (we test puppet/ansible/chef with the same tests, that reside in the aformentioned directory).

Maybe its also possible to let the user specify where to search for tests?



Discussion:
We have all the pieces in place to make this work by changing the directory in the config file (or even molecule.yml), but the rakefile template still hardcodes spec/.


Resolving patch:
diff --git a/molecule/core.py b/molecule/core.py
--- a/molecule/core.py
+++ b/molecule/core.py
@@ -259,7 +259,8 @@ def _create_templates(self):
         # rakefile
         kwargs = {
             'molecule_file': self._config.config['molecule']['molecule_file'],
-            'current_platform': self._env['MOLECULE_PLATFORM']
+            'current_platform': self._env['MOLECULE_PLATFORM'],
+            'serverspec_dir': self._config.config['molecule']['serverspec_dir']
         }
         utilities.write_template(self._config.config['molecule']['rakefile_template'],
                                  self._config.config['molecule']['rakefile_file'],


Test patch: