internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: DataDog/dd-trace-py

Issue:
1.1.0 asyncio.Lock replacement missing __aexit__


### Which version of dd-trace-py are you using?

`1.1.0`

### Which version of pip are you using?

`22.0.4`

_ddtrace requires pip>=18 to install one of our pre-built wheels_

### Which version of the libraries are you using?

https://gist.github.com/alangenfeld/d824c96dfbae796888b13fd4fc8b56cd

### How can we reproduce your problem?

Discovered with `starlette` `uvicorn` + websocket usage 

should repro with any async context manager use (while collector is active)
```
repro_lock = asyncio.Lock()
async with repro_lock:
    ...
```

### What is the result that you get?

`AttributeError: __aexit__` on an `asyncio.Lock`
https://gist.github.com/alangenfeld/6da10298e02d79b73da1ad5ebec8473c

### What is the result that you expected?

asyncio.Lock use via async context manager works


related PR: https://github.com/DataDog/dd-trace-py/pull/3459


Discussion:
I've encountered a similar problem with `__aenter__` missing from the replacement lock when using it through the context manager.

Resolving patch:
diff --git a/ddtrace/profiling/collector/_lock.py b/ddtrace/profiling/collector/_lock.py
--- a/ddtrace/profiling/collector/_lock.py
+++ b/ddtrace/profiling/collector/_lock.py
@@ -77,6 +77,12 @@ def __init__(self, wrapped, recorder, tracer, max_nframes, capture_sampler, endp
         code = frame.f_code
         self._self_name = "%s:%d" % (os.path.basename(code.co_filename), frame.f_lineno)
 
+    def __aenter__(self):
+        return self.__wrapped__.__aenter__()
+
+    def __aexit__(self, *args, **kwargs):
+        return self.__wrapped__.__aexit__(*args, **kwargs)
+
     def acquire(self, *args, **kwargs):
         if not self._self_capture_sampler.capture():
             return self.__wrapped__.acquire(*args, **kwargs)


Test patch:
diff --git a/tests/profiling/collector/test_asyncio.py b/tests/profiling/collector/test_asyncio.py
--- a/tests/profiling/collector/test_asyncio.py
+++ b/tests/profiling/collector/test_asyncio.py
@@ -64,6 +64,10 @@ async def test_lock_events_tracer(tracer):
             trace_id = t.trace_id
             span_id = t.span_id
         lock2.release()
+
+        lock_ctx = asyncio.Lock()
+        async with lock_ctx:
+            pass
     events = r.reset()
     # The tracer might use locks, so we need to look into every event to assert we got ours
     for event_type in (collector_asyncio.AsyncioLockAcquireEvent, collector_asyncio.AsyncioLockReleaseEvent):
Repository: DataDog/dd-trace-py

Issue:
mypy invalid syntax error with python 2
### Which version of dd-trace-py are you using?

v1.2.0

### Which version of pip are you using?

22.1.2

### Which version of the libraries are you using?

```
ddtrace==1.2.0
mypy[python2]==0.961
```

### How can we reproduce your problem?

1. Clone https://gist.github.com/majorgreys/720201c4bdd33131e4c231207ef716ce
2. Run `docker run --rm -it (docker build .)`

### What is the result that you get?

```
usr/local/lib/python3.9/site-packages/ddtrace/contrib/redis/asyncio_patch.py:12: error: invalid syntax
Found 1 error in 1 file (errors prevented further checking)
```

### What is the result that you expected?

```
Success: no issues found in 1 source file
```



Discussion:

Resolving patch:
diff --git a/ddtrace/contrib/redis/patch.py b/ddtrace/contrib/redis/patch.py
--- a/ddtrace/contrib/redis/patch.py
+++ b/ddtrace/contrib/redis/patch.py
@@ -1,4 +1,5 @@
 import redis
+from six import PY3
 
 from ddtrace import config
 from ddtrace.vendor import wrapt
@@ -36,7 +37,8 @@ def patch():
         _w("redis", "Redis.pipeline", traced_pipeline)
         _w("redis.client", "Pipeline.execute", traced_execute_pipeline)
         _w("redis.client", "Pipeline.immediate_execute_command", traced_execute_command)
-        if redis.VERSION >= (4, 2, 0):
+        # Avoid mypy invalid syntax errors when parsing Python 2 files
+        if PY3 and redis.VERSION >= (4, 2, 0):
             from .asyncio_patch import traced_async_execute_command
             from .asyncio_patch import traced_async_execute_pipeline
 


Test patch:
Repository: DataDog/dd-trace-py

Issue:
Disabling intrument_middleware via code not working in Django
### Which version of dd-trace-py are you using?

1.1.2

### Which version of pip are you using?

22.0.4

### Which version of the libraries are you using?

/

### How can we reproduce your problem?

Disable `instrument_middleware` via config code in Django integration does not work:

Example: (neither of these work):

```python
ddtrace.config.django.instrument_middleware = False
ddtrace.config.django["instrument_middleware"] = False
```


Configuring this via env variable (`DD_DJANGO_INSTRUMENT_MIDDLEWARE`) works.


Discussion:
hey @Meemaw thank you for opening this issue.

it is probably misleading that this is configurable in code. this configuration needs to happen before we patch django.

this means it needs to happen before `ddtrace.patch_all()` is called. if you are using `ddtrace-run`, then you must you the env variable because you won't have an opportunity to set the configuration option before patching occurs.


Resolving patch:
diff --git a/ddtrace/contrib/django/__init__.py b/ddtrace/contrib/django/__init__.py
--- a/ddtrace/contrib/django/__init__.py
+++ b/ddtrace/contrib/django/__init__.py
@@ -29,6 +29,13 @@
 
 Configuration
 ~~~~~~~~~~~~~
+
+.. important::
+
+    Note that the in-code configuration must be run before Django is instrumented. This means that in-code configuration
+    will not work with ``ddtrace-run`` and before a call to ``patch`` or ``patch_all``.
+
+
 .. py:data:: ddtrace.config.django['distributed_tracing_enabled']
 
    Whether or not to parse distributed tracing headers from requests received by your Django app.


Test patch:
Repository: DataDog/dd-trace-py

Issue:
Upstream issue encode/databases#298 closed
Upstream issue encode/databases#298 referenced in the file:

  - [riotfile.py:1298](https://github.com/DataDog/dd-trace-py/blob/1.x/riotfile.py#L1298)

has been closed.

The code referencing this issue could potentially be updated.
    


Discussion:

Resolving patch:
diff --git a/riotfile.py b/riotfile.py
--- a/riotfile.py
+++ b/riotfile.py
@@ -1295,8 +1295,7 @@ def select_pys(min_version=MIN_PYTHON_VERSION, max_version=MAX_PYTHON_VERSION):
                 "pytest-asyncio": latest,
                 "requests": latest,
                 "aiofiles": latest,
-                # Pinned until https://github.com/encode/databases/issues/298 is resolved.
-                "sqlalchemy": "~=1.3.0",
+                "sqlalchemy": latest,
                 "aiosqlite": latest,
                 "databases": latest,
             },


Test patch:
Repository: DataDog/dd-trace-py

Issue:
Throws exception when reloading module in REPL (specifically with iPython), even when `DD_TRACE_ENABLED=false`
<!--
Thanks for taking the time for reporting an issue!

Before reporting an issue on dd-trace-py, please be sure to provide all
necessary information.

If you're hitting a bug, make sure that you're using the latest version of this
library.
-->

### Summary of problem

The exception includes this stack trace:
```python
[autoreload of my_module failed: Traceback (most recent call last):
  File "/home/ory/.pyenv/versions/3.10.7/envs/my_module/lib/python3.10/site-packages/IPython/extensions/autoreload.py", line 261, in check
    superreload(m, reload, self.old_objects)
  File "/home/ory/.pyenv/versions/3.10.7/envs/my_module/lib/python3.10/site-packages/IPython/extensions/autoreload.py", line 459, in superreload
    module = reload(module)
  File "/home/ory/.pyenv/versions/3.10.7/lib/python3.10/importlib/__init__.py", line 166, in reload
    spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
  File "<frozen importlib._bootstrap>", line 945, in _find_spec
  File "/home/ory/.pyenv/versions/3.10.7/envs/my_module/lib/python3.10/site-packages/ddtrace/internal/module.py", line 368, in find_spec
    spec = find_spec(fullname)
  File "/home/ory/.pyenv/versions/3.10.7/lib/python3.10/importlib/util.py", line 111, in find_spec
    raise ValueError('{}.__spec__ is not set'.format(name)) from None
ValueError: my_module.__spec__ is not set
```

### Which version of dd-trace-py are you using?

1.8.0 

### Which version of pip are you using?

22.2.2


Discussion:
Thank you for reporting this issue, @oryband. How can I reproduce it locally?
I was able to reproduce this issue. I'll prepare a fix for it.

Resolving patch:
diff --git a/ddtrace/internal/module.py b/ddtrace/internal/module.py
--- a/ddtrace/internal/module.py
+++ b/ddtrace/internal/module.py
@@ -404,7 +404,12 @@ def find_spec(self, fullname, path=None, target=None):
         self._finding.add(fullname)
 
         try:
-            spec = find_spec(fullname)
+            try:
+                # Best effort
+                spec = find_spec(fullname)
+            except Exception:
+                return None
+
             if spec is None:
                 return None
 


Test patch:
Repository: DataDog/dd-trace-py

Issue:
Algoliasearch non-text argument used in set_tag_str
See https://github.com/DataDog/dd-trace-py/pull/4727#issuecomment-1511668474, we changed a usage of `set_tag()` to `set_tag_str()` in our algoliasearch integration, but that patched function involves non-text arguments that `set_tag_str()` throws an error for.



Discussion:

Resolving patch:
diff --git a/ddtrace/contrib/algoliasearch/patch.py b/ddtrace/contrib/algoliasearch/patch.py
--- a/ddtrace/contrib/algoliasearch/patch.py
+++ b/ddtrace/contrib/algoliasearch/patch.py
@@ -130,7 +130,7 @@ def _patched_search(func, instance, wrapt_args, wrapt_kwargs):
             for query_arg, tag_name in QUERY_ARGS_DD_TAG_MAP.items():
                 value = query_args.get(query_arg)
                 if value is not None:
-                    span.set_tag_str("query.args.{}".format(tag_name), value)
+                    span.set_tag("query.args.{}".format(tag_name), value)
 
         # Result would look like this
         # {


Test patch:
diff --git a/tests/contrib/algoliasearch/test.py b/tests/contrib/algoliasearch/test.py
--- a/tests/contrib/algoliasearch/test.py
+++ b/tests/contrib/algoliasearch/test.py
@@ -100,6 +100,19 @@ def test_algoliasearch_with_query_text(self):
         spans = self.get_spans()
         span = spans[0]
         assert span.get_tag("query.text") == "test search"
+        assert span.get_tag("query.args.attributes_to_retrieve") == "firstname,lastname"
+        assert span.get_tag("query.args.unsupportedTotallyNewArgument") is None
+
+    def test_algoliasearch_with_query_args_nontext(self):
+        self.patch_algoliasearch()
+        config.algoliasearch.collect_query_text = True
+
+        self.perform_search("test search", {"hitsPerPage": 1, "page": 3})
+        spans = self.get_spans()
+        span = spans[0]
+        assert span.get_tag("query.text") == "test search"
+        assert span.get_metric("query.args.page") == 3
+        assert span.get_metric("query.args.hits_per_page") == 1
 
     def test_patch_unpatch(self):
         self.patch_algoliasearch()
Repository: DataDog/dd-trace-py

Issue:
Decreased success rate of integration_agent CircleCI job
The `integration_agent` CircleCI job has been failing more often this past week. This job runs the integration tests with the Datadog Agent. 

We see the same two tests failing for 3.11 in two failing pipelines on 1.x ([[1]](https://app.circleci.com/pipelines/github/DataDog/dd-trace-py/31440/workflows/392068c8-7b66-4ea3-b5ae-21879d9820b1/jobs/2129132/parallel-runs/0/steps/0-106), [[2]](https://app.circleci.com/pipelines/github/DataDog/dd-trace-py/31771/workflows/80a433f7-4d5f-42e2-92aa-4439df620fc6/jobs/2150184/parallel-runs/0/steps/0-106)):

```
FAILED tests/integration/test_integration.py::test_regression_logging_in_context[True-True-True]
FAILED tests/integration/test_integration.py::test_regression_logging_in_context[True-True-False]
```



Discussion:

Resolving patch:
diff --git a/riotfile.py b/riotfile.py
--- a/riotfile.py
+++ b/riotfile.py
@@ -298,6 +298,7 @@ def select_pys(min_version=MIN_PYTHON_VERSION, max_version=MAX_PYTHON_VERSION):
         ),
         Venv(
             name="integration",
+            # Enabling coverage for integration tests breaks certain tests in CI
             command="pytest --no-cov {cmdargs} tests/integration/",
             pkgs={"msgpack": [latest]},
             venvs=[
@@ -1576,9 +1577,9 @@ def select_pys(min_version=MIN_PYTHON_VERSION, max_version=MAX_PYTHON_VERSION):
                     pys=["2.7"],
                     # pytest==4.6 is last to support python 2.7
                     pkgs={
-                        "pytest": ">=4.0,<4.6",
+                        "pytest": ">=4.0,<=4.6",
                         "msgpack": latest,
-                        "pytest-cov": "==2.5.0",
+                        "pytest-cov": "==2.12.1",
                     },
                 ),
                 Venv(


Test patch:
diff --git a/tests/integration/test_integration.py b/tests/integration/test_integration.py
--- a/tests/integration/test_integration.py
+++ b/tests/integration/test_integration.py
@@ -771,7 +771,7 @@ def test_regression_logging_in_context(tmpdir, logs_injection, debug_mode, patch
         [sys.executable, "test.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=str(tmpdir), env=env
     )
     try:
-        p.wait(timeout=2)
+        p.wait(timeout=10)
     except TypeError:
         # timeout argument added in Python 3.3
         p.wait()
Repository: microsoft/ptvsd

Issue:
Error on F5 with latest master
```
---------------------------
Microsoft Visual Studio
---------------------------
Traceback (most recent call last):
  File "G:\pyenv\test1\lib\site-packages\ptvsd\ipcjson.py", line 319, in on_request
    target(request, args)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\wrapper.py", line 288, in f
    fut = m(self, self.loop, *args, **kwargs)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\futures.py", line 133, in g
    it = f(self, *args, **kwargs)
  File "G:\pyenv\test1\lib\site-packages\ptvsd\wrapper.py", line 519, in on_setBreakpoints
    msg = msgfmt.format(vsc_bpid, path. line)
AttributeError: 'str' object has no attribute 'line'
---------------------------
OK   
---------------------------

```


Discussion:
Should ` msgfmt.format(vsc_bpid, path. line)` be ` msgfmt.format(vsc_bpid, path, line)` ?

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -516,7 +516,7 @@ def on_setBreakpoints(self, request, args):
             line = src_bp['line']
             vsc_bpid = self.bp_map.add(
                     lambda vsc_bpid: (path, vsc_bpid))
-            msg = msgfmt.format(vsc_bpid, path. line)
+            msg = msgfmt.format(vsc_bpid, path, line)
             self.pydevd_notify(cmd, msg)
             bps.append({
                 'id': vsc_bpid,


Test patch:
Repository: microsoft/ptvsd

Issue:
Setting variable values
This is about editing variable values in the Locals window and equivalents (but not in Watch; i.e. not arbitrary expressions - that one is #15  ). 

Need to implement `setVariable` request.


Discussion:

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -307,6 +307,7 @@ def on_initialize(self, request, args):
             request,
             supportsExceptionInfoRequest=True,
             supportsConfigurationDoneRequest=True,
+            supportsSetVariable=True,
             exceptionBreakpointFilters=[
                 {'filter': 'raised', 'label': 'Raised Exceptions'},
                 {'filter': 'uncaught', 'label': 'Uncaught Exceptions'},
@@ -456,6 +457,29 @@ def on_variables(self, request, args):
 
         self.send_response(request, variables=variables)
 
+    @async_handler
+    def on_setVariable(self, request, args):
+        vsc_var = int(args['variablesReference'])
+        pyd_var = self.var_map.to_pydevd(vsc_var)
+
+        # VSC gives us variablesReference to the parent of the variable being set, and
+        # variable name; but pydevd wants the ID (or rather path) of the variable itself.
+        pyd_var += (args['name'],)
+        vsc_var = self.var_map.to_vscode(pyd_var)
+        
+        cmd_args = [str(s) for s in pyd_var] + [args['value']]
+        _, _, resp_args = yield self.pydevd_request(pydevd_comm.CMD_CHANGE_VARIABLE, '\t'.join(cmd_args))
+        xml = untangle.parse(resp_args).xml
+        xvar = xml.var
+
+        response = {
+            'type': unquote(xvar['type']),
+            'value': unquote(xvar['value']),
+        }
+        if bool(xvar['isContainer']):
+            response['variablesReference'] = vsc_var
+        self.send_response(request, **response)
+
     @async_handler
     def on_pause(self, request, args):
         # TODO: docstring


Test patch:
Repository: microsoft/ptvsd

Issue:
Debugging doesn't work on unix
The wrapper.py is hardcoded for debugging on windows only.
```python
    @async_handler
    def on_initialize(self, request, args):
        # TODO: docstring
        cmd = pydevd_comm.CMD_VERSION
        msg = '1.1\tWINDOWS\tID'

```


Discussion:

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -12,6 +12,7 @@
 import threading
 import traceback
 import untangle
+import platform 
 
 try:
     import urllib
@@ -306,7 +307,8 @@ def done(fut):
     def on_initialize(self, request, args):
         # TODO: docstring
         cmd = pydevd_comm.CMD_VERSION
-        msg = '1.1\tWINDOWS\tID'
+        os_id = 'WINDOWS' if platform.system() == 'Windows' else 'UNIX'
+        msg = '1.1\t{}\tID'.format(os_id)
         yield self.pydevd_request(cmd, msg)
         self.send_response(
             request,


Test patch:
Repository: microsoft/ptvsd

Issue:
Debugger does not send terminated event when it ends
The debugger should send the terminated event as the last response when it ends (this is a protocol requirement).

https://code.visualstudio.com/docs/extensionAPI/api-debugging

`In both cases and in the case that the target terminated normally or crashed the debug adapter must fire a terminated event.`
Debugger does not send terminated event when it ends
The debugger should send the terminated event as the last response when it ends (this is a protocol requirement).

https://code.visualstudio.com/docs/extensionAPI/api-debugging

`In both cases and in the case that the target terminated normally or crashed the debug adapter must fire a terminated event.`


Discussion:

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -249,6 +249,7 @@ def close(self):
         # TODO: docstring
         global ptvsd_sys_exit_code
         self.send_event('exited', exitCode=ptvsd_sys_exit_code)
+        self.send_event('terminated')
         if self.socket:
             self.socket.close()
 


Test patch:
Repository: microsoft/ptvsd

Issue:
Arbitrary expression evaluation
This is required to support the watch window, and also Intermediate window in VS.  It will also likely be needed by the new debug REPL implementation in VS.

Need to implement `EvaluateRequest` in the protocol.


Discussion:
Must also provide `evaluateName` attribute when enumerating variables, to enable "Add to Watch" in VS.

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -573,6 +573,31 @@ def on_setVariable(self, request, args):
             response['variablesReference'] = vsc_var
         self.send_response(request, **response)
 
+    @async_handler
+    def on_evaluate(self, request, args):
+        # pydevd message format doesn't permit tabs in expressions
+        expr = args['expression'].replace('\t', ' ')
+
+        vsc_fid = int(args['frameId'])
+        pyd_tid, pyd_fid = self.frame_map.to_pydevd(vsc_fid)
+
+        cmd_args = (pyd_tid, pyd_fid, 'LOCAL', expr, '1')
+        _, _, resp_args = yield self.pydevd_request(
+            pydevd_comm.CMD_EVALUATE_EXPRESSION,
+            '\t'.join(str(s) for s in cmd_args))
+        xml = untangle.parse(resp_args).xml
+        xvar = xml.var
+
+        pyd_var = (pyd_tid, pyd_fid, 'EXPRESSION', expr)
+        vsc_var = self.var_map.to_vscode(pyd_var)
+        response = {
+            'type': unquote(xvar['type']),
+            'result': unquote(xvar['value']),
+        }
+        if bool(xvar['isContainer']):
+            response['variablesReference'] = vsc_var
+        self.send_response(request, **response)
+
     @async_handler
     def on_pause(self, request, args):
         # TODO: docstring


Test patch:
Repository: microsoft/ptvsd

Issue:
Stack request fails when stackFrame and levels are empty
VS Code sends requests for `stackTrace` with just the `threadId`
However the `on_stackTrace` method in `wrapper.py` assumes the `startFrame` and `levels` args will be provided.
However these args are options (https://github.com/Microsoft/vscode-debugadapter-node/blob/master/protocol/src/debugProtocol.ts#L677)




Discussion:

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -518,8 +518,8 @@ def on_threads(self, request, args):
     def on_stackTrace(self, request, args):
         # TODO: docstring
         tid = int(args['threadId'])
-        startFrame = int(args['startFrame'])
-        levels = int(args['levels'])
+        startFrame = int(args.get('startFrame', 0))
+        levels = int(args.get('levels', 0))
 
         tid = self.thread_map.to_pydevd(tid)
         with self.stack_traces_lock:


Test patch:
Repository: microsoft/ptvsd

Issue:
Breaking on raised or uncaught exceptions does not work in VS Code



Discussion:

Resolving patch:
diff --git a/ptvsd/wrapper.py b/ptvsd/wrapper.py
--- a/ptvsd/wrapper.py
+++ b/ptvsd/wrapper.py
@@ -727,10 +727,9 @@ def on_setBreakpoints(self, request, args):
     def on_setExceptionBreakpoints(self, request, args):
         # TODO: docstring
         filters = args['filters']
-        exception_options = args['exceptionOptions']
-        use_exception_options = len(exception_options) > 0
+        exception_options = args.get('exceptionOptions', [])
 
-        if use_exception_options:
+        if exception_options:
             self.exceptions_mgr.apply_exception_options(exception_options)
         else:
             self.exceptions_mgr.remove_all_exception_breaks()


Test patch:
Repository: microsoft/ptvsd

Issue:
Debugging modules (using -m switch)
This is currently not supported


Discussion:

Resolving patch:
diff --git a/ptvsd/debugger.py b/ptvsd/debugger.py
--- a/ptvsd/debugger.py
+++ b/ptvsd/debugger.py
@@ -19,11 +19,16 @@ def debug(filename, port_num, debug_id, debug_options, run_as):
     import ptvsd.wrapper
     import pydevd
 
-    sys.argv[1:0] = [
+    args = [
             '--port', str(port_num),
             '--client', '127.0.0.1',
-            '--file', filename,
             ]
+    if run_as == 'module':
+        args.append('--module')
+        args.extend(('--file', filename + ":"))
+    else:
+        args.extend(('--file', filename))
+    sys.argv[1:0] = args
     try:
         pydevd.main()
     except SystemExit as ex:


Test patch: