internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: sanic-org/sanic

Issue:
FALLBACK_ERROR_FORMAT does not work with empty()
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

Today I tested a handler which always returns `empty()` (see example below). 
I was quite confused by the format of the errors, as they were all in HTML format, even though the fallback was set to json.
It took me a while to figure out that this was because of the `empty()` statement returned by the function, which somehow hijacks the error format, so that the errors are converted to html. 

I could use the `error_format` from now on for handlers returning `empty()`, but was wondering if this is a feature or a bug.

### Code snippet

```python
from sanic import Sanic, empty
from sanic.exceptions import Unauthorized


app = Sanic(__name__)
app.config.FALLBACK_ERROR_FORMAT = "json"

# Returns error in html format
@app.post("/empty")
async def empty_(request):
    raise Unauthorized("bli bla blub")

    return empty()

# Returns error in json format
@app.post("/nothing")
async def nothing(request):
    raise Unauthorized("bli bla blub")


if __name__ == '__main__':
    app.run("127.0.0.1", port=3000, auto_reload=True, debug=True, dev=True)
```

### How do you run Sanic?

As a script

### Operating System

Ubuntu

### Sanic Version

22.9.1


Discussion:
Triage. Sanic tries to determine the response type automatically using various heuristics. The one you hit is that the handler returns empty(), which Sanic maps to HTML and considers the case solved, no fallback, error page in HTML. @ahopkins Can we make empty() unopinionated and use the fallback instead?

One way to avoid this is to add an `accept: application/json` header to your requests, then Sanic will always respond in JSON and not use any of these heuristics.
@simon-lund Thanks for the report and a useful test case, made triaging much easier! The heuristics are quite complicated but we can probably let empty run to the fallback which also gets what you need without the header.

Resolving patch:
diff --git a/sanic/errorpages.py b/sanic/errorpages.py
--- a/sanic/errorpages.py
+++ b/sanic/errorpages.py
@@ -406,16 +406,13 @@ def escape(text):
     v: k for k, v in RENDERERS_BY_CONTENT_TYPE.items()
 }
 
+# Handler source code is checked for which response types it returns with the
+# route error_format="auto" (default) to determine which format to use.
 RESPONSE_MAPPING = {
-    "empty": "html",
     "json": "json",
     "text": "text",
-    "raw": "text",
     "html": "html",
-    "file": "html",
-    "file_stream": "text",
-    "stream": "text",
-    "redirect": "html",
+    "JSONResponse": "json",
     "text/plain": "text",
     "text/html": "html",
     "application/json": "json",


Test patch:
Repository: sanic-org/sanic

Issue:
Deprecate __blueprintname__
This code no longer seems like it is necessary: https://github.com/sanic-org/sanic/blob/5d683c6ea4b615e80c51d80189436437b824cce6/sanic/blueprints.py#L309

Since you can get access to the name of the blueprint from the request object, the route object, and the blueprint object, I do not think there is any need for `__blueprintname__` anymore.

See #2440 


Discussion:
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this  is incorrect, please respond with an update. Thank you for your contributions.

Hello, @ahopkins. Since I'm experiencing the same error as mentioned in #2440, and, making the functions `static` works just fine for me too, I would prefer to keep my functions the way they are.

That said, I would like to open a PR to fix this issue, but I have never contributed to the Sanic codebase before, and I'm not 100% sure of what to do. 

What are your suggestions to fix this? Removing the `future.handler.__blueprintname__ = self.name` completely, or do you have anything else in mind for this? If you have any directions for me, I would be happy to open a PR to fix that.
Awesome. I would love to have your first contribution, and happy to walk you thru it. There is some [information already](https://github.com/sanic-org/sanic/blob/main/CONTRIBUTING.rst), but certainly reach out and let me know if you have questions.

As for the specifics here, I think we probably can just remove it. However I am reluctant for backwards compat to do anything before v23 at this point. One of the things I would like to introduce is to wrap all handlers with some sort of a parent object to make the API a little more consistent and we do not do hacky things like adding properties to functions.
Thanks, @ahopkins! I will see if I can provide a patch by today. 

I tested locally with a project, and removing that line worked just fine for me. Not sure if it broke anything else, but I will see if I can do that today and give that a proper test.

Resolving patch:
diff --git a/sanic/blueprints.py b/sanic/blueprints.py
--- a/sanic/blueprints.py
+++ b/sanic/blueprints.py
@@ -304,9 +304,6 @@ def register(self, app, options):
 
         # Routes
         for future in self._future_routes:
-            # attach the blueprint name to the handler so that it can be
-            # prefixed properly in the router
-            future.handler.__blueprintname__ = self.name
             # Prepend the blueprint URI prefix if available
             uri = self._setup_uri(future.uri, url_prefix)
 


Test patch:
Repository: sanic-org/sanic

Issue:
Send keep-alive header and increase the default timeout
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe.

Nginx doesn't notice Sanic closing its keep-alive connection by timeout, and then another request will fail for no good reason. High latency connections suffer of having to do frequent reconnections when a client or proxy loads additional resources 5+ seconds later, despite keeping such connections open being practically free with the async server.

### Describe the solution you'd like

Sanic http1 server should send `keep-alive: timeout=<KEEP_ALIVE_TIMEOUT>`, to inform the client of the duration it allows. Also Sanic should not limit max number of requests per pipeline (no reason to) and use a higher default `KEEP_ALIVE_TIMEOUT` setting of at least 70 seconds to exceed that of Nginx to avoid connection problems.

Sanic should also investigate ways of closing the connection so that Nginx or another client gets the notice of connection RST and won't attempt to send another request once those are no longer accepted. Could be problematic with TLS but this is also broken in plain HTTP in current version.

### Additional context

HTTP/3 does not use keep-alive header. On ASGI this might be up to the ASGI server, needs investigation.


Discussion:

Resolving patch:
diff --git a/sanic/config.py b/sanic/config.py
--- a/sanic/config.py
+++ b/sanic/config.py
@@ -43,14 +43,14 @@
     "DEPRECATION_FILTER": "once",
     "FORWARDED_FOR_HEADER": "X-Forwarded-For",
     "FORWARDED_SECRET": None,
-    "GRACEFUL_SHUTDOWN_TIMEOUT": 15.0,  # 15 sec
+    "GRACEFUL_SHUTDOWN_TIMEOUT": 15.0,
     "INSPECTOR": False,
     "INSPECTOR_HOST": "localhost",
     "INSPECTOR_PORT": 6457,
     "INSPECTOR_TLS_KEY": _default,
     "INSPECTOR_TLS_CERT": _default,
     "INSPECTOR_API_KEY": "",
-    "KEEP_ALIVE_TIMEOUT": 5,  # 5 seconds
+    "KEEP_ALIVE_TIMEOUT": 120,
     "KEEP_ALIVE": True,
     "LOCAL_CERT_CREATOR": LocalCertCreator.AUTO,
     "LOCAL_TLS_KEY": _default,
@@ -61,16 +61,16 @@
     "NOISY_EXCEPTIONS": False,
     "PROXIES_COUNT": None,
     "REAL_IP_HEADER": None,
-    "REQUEST_BUFFER_SIZE": 65536,  # 64 KiB
-    "REQUEST_MAX_HEADER_SIZE": 8192,  # 8 KiB, but cannot exceed 16384
+    "REQUEST_BUFFER_SIZE": 65536,
+    "REQUEST_MAX_HEADER_SIZE": 8192,  # Cannot exceed 16384
     "REQUEST_ID_HEADER": "X-Request-ID",
-    "REQUEST_MAX_SIZE": 100000000,  # 100 megabytes
-    "REQUEST_TIMEOUT": 60,  # 60 seconds
-    "RESPONSE_TIMEOUT": 60,  # 60 seconds
+    "REQUEST_MAX_SIZE": 100_000_000,
+    "REQUEST_TIMEOUT": 60,
+    "RESPONSE_TIMEOUT": 60,
     "TLS_CERT_PASSWORD": "",
     "TOUCHUP": _default,
     "USE_UVLOOP": _default,
-    "WEBSOCKET_MAX_SIZE": 2**20,  # 1 megabyte
+    "WEBSOCKET_MAX_SIZE": 2**20,  # 1 MiB
     "WEBSOCKET_PING_INTERVAL": 20,
     "WEBSOCKET_PING_TIMEOUT": 20,
 }


Test patch:
Repository: sanic-org/sanic

Issue:
JSONResponse defaults to None content-type
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

```python
@app.get("/")
async def handler(request: Request):
    return JSONResponse({"message": "Hello World!"})
```
```sh
╰─▶ curl localhost:9999   
HTTP/1.1 200 OK
content-length: 26
connection: keep-alive
alt-svc: 
content-type: None

{"message":"Hello World!"}
```

### Code snippet

_No response_

### Expected Behavior

`content-type: application/json`

### How do you run Sanic?

Sanic CLI

### Operating System

all

### Sanic Version

LTS+

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/sanic/response/types.py b/sanic/response/types.py
--- a/sanic/response/types.py
+++ b/sanic/response/types.py
@@ -345,7 +345,7 @@ def __init__(
         body: Optional[Any] = None,
         status: int = 200,
         headers: Optional[Union[Header, Dict[str, str]]] = None,
-        content_type: Optional[str] = None,
+        content_type: str = "application/json",
         dumps: Optional[Callable[..., str]] = None,
         **kwargs: Any,
     ):


Test patch:
diff --git a/tests/test_response_json.py b/tests/test_response_json.py
--- a/tests/test_response_json.py
+++ b/tests/test_response_json.py
@@ -213,3 +213,12 @@ def do_pop(request: Request, response: JSONResponse):
 
     _, resp = json_app.test_client.get("/json-pop")
     assert resp.body == json_dumps(["b"]).encode()
+
+
+def test_json_response_class_sets_proper_content_type(json_app: Sanic):
+    @json_app.get("/json-class")
+    async def handler(request: Request):
+        return JSONResponse(JSON_BODY)
+
+    _, resp = json_app.test_client.get("/json-class")
+    assert resp.headers["content-type"] == "application/json"
Repository: sanic-org/sanic

Issue:
Improve type of `MiddlewareType`
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe.

When using a custom Request class and type hinting the middleware with that custom Request class, type checkers complain that the argument types of the middleware function is invalid. 

```python

from sanic import Request, Sanic

class MyRequest(Request):
    ...

async def some_middleware(request: MyRequest) -> None:
    ...

app = Sanic("trial-app")

# This raises a type error.
app.register_middleware(some_middleware, "request")

# Pyright Error
# Argument of type "(request: MyRequest) -> Coroutine[Any, Any, None]" cannot be assigned to parameter
# "middleware" of type "MiddlewareType | Middleware" in function "register_middleware"
# Type "(request: MyRequest) -> Coroutine[Any, Any, None]" cannot be assigned to type "MiddlewareType | Middleware"
#  Type "(request: MyRequest) -> Coroutine[Any, Any, None]" cannot be assigned to type "RequestMiddlewareType"
#      Parameter 1: type "Request" cannot be assigned to type "MyRequest"
#        "Request" is incompatible with "MyRequest"
#    Type "(request: MyRequest) -> Coroutine[Any, Any, None]" cannot be assigned to type "ResponseMiddlewareType"
#      Function accepts too many positional parameters; expected 1 but received 2
#        Parameter 1: type "Request" cannot be assigned to type "MyRequest"
#          "Request" is incompatible with "MyRequest"

```

### Describe the solution you'd like

Using a subclass of Request shouldn't raise this error by the type checkers.

### Additional context

I think the fix is to make the `Request` type in `MiddlewareType` in [`handler_types`](https://github.com/sanic-org/sanic/blob/main/sanic/models/handler_types.py) a generic with the generic being bound to `Request` like it's done for the `Sanic` type. 


Discussion:
Thanks. Do you think you can create the PR for this? 😎
Yeah I would love to. I'll get it ready in a day or two.

Resolving patch:
diff --git a/sanic/models/handler_types.py b/sanic/models/handler_types.py
--- a/sanic/models/handler_types.py
+++ b/sanic/models/handler_types.py
@@ -3,11 +3,12 @@
 
 import sanic
 
-from sanic.request import Request
+from sanic import request
 from sanic.response import BaseHTTPResponse, HTTPResponse
 
 
 Sanic = TypeVar("Sanic", bound="sanic.Sanic")
+Request = TypeVar("Request", bound="request.Request")
 
 MiddlewareResponse = Union[
     Optional[HTTPResponse], Coroutine[Any, Any, Optional[HTTPResponse]]


Test patch:
Repository: sanic-org/sanic

Issue:
Multiplexer and Manager out of sync on number of expected arguments
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

The manager is expecting the wrong number of arguments. Therefore app.m.manage is not working as intended.

```
[ERROR] Monitor received an invalid message: ('foobar', <function foo at 0x7fd1c8ce34c0>, {}, False, None, False, True, 1)
```

### Code snippet

_No response_

### Expected Behavior

_No response_

### How do you run Sanic?

Sanic CLI

### Operating System

Linux

### Sanic Version

23.12.0

### Additional context

_No response_


Discussion:

Resolving patch:
diff --git a/sanic/__version__.py b/sanic/__version__.py
--- a/sanic/__version__.py
+++ b/sanic/__version__.py
@@ -1 +1 @@
-__version__ = "23.12.0"
+__version__ = "23.12.1"
diff --git a/sanic/worker/manager.py b/sanic/worker/manager.py
--- a/sanic/worker/manager.py
+++ b/sanic/worker/manager.py
@@ -452,7 +452,7 @@ def _poll_monitor(self) -> Optional[MonitorCycle]:
             elif message == "__TERMINATE__":
                 self._handle_terminate()
                 return MonitorCycle.BREAK
-            elif isinstance(message, tuple) and len(message) == 7:
+            elif isinstance(message, tuple) and len(message) == 8:
                 self._handle_manage(*message)  # type: ignore
                 return MonitorCycle.CONTINUE
             elif not isinstance(message, str):


Test patch:
Repository: sanic-org/sanic

Issue:
(websockets 12.0) DeprecationWarning: websockets.connection was renamed to websockets.protocol and Connection was renamed to Protocol
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

The DeprecationWarning is thrown here:

https://github.com/sanic-org/sanic/blob/82bf46bea3b55e6b1371107cccda280add8e70eb/sanic/server/protocols/websocket_protocol.py#L4-L9

With websockets 12 the try block would run successfully with the warning while the catch block does not have chance to be run.

### Code snippet

_No response_

### Expected Behavior

The catch block is being run instead.

### How do you run Sanic?

Sanic CLI

### Operating System

MacOS

### Sanic Version

Sanic 23.6.0; Routing 23.6.0

### Additional context

_No response_


Discussion:
Although it triggers a deprecation warning, the `try...except...` block will work when the classes are actually removed in `websockets` package in the future. Checking version of a package requires an additional dependency `packaging`, which we wouldn't like to add, thus I think we can just ignore the warning.

See more discussion in https://github.com/sanic-org/sanic/pull/2880
> Although it triggers a deprecation warning, the `try...except...` block will work when the classes are actually removed in `websockets` package in the future. Checking version of a package requires an additional dependency `packaging`, which we wouldn't like to add, thus I think we can just ignore the warning.

Can't you `try` the new API, which will give ImportError or such but no deprecation warnings, and `except` fallback to old API?

Looks like you can also use `websockets.__version__` for a version string.
@Tronic You are right, lol. I will try that way.

Resolving patch:
diff --git a/sanic/server/protocols/websocket_protocol.py b/sanic/server/protocols/websocket_protocol.py
--- a/sanic/server/protocols/websocket_protocol.py
+++ b/sanic/server/protocols/websocket_protocol.py
@@ -1,12 +1,12 @@
 from typing import Optional, Sequence, cast
 
 
-try:  # websockets < 11.0
-    from websockets.connection import State
-    from websockets.server import ServerConnection as ServerProtocol
-except ImportError:  # websockets >= 11.0
+try:  # websockets >= 11.0
     from websockets.protocol import State  # type: ignore
     from websockets.server import ServerProtocol  # type: ignore
+except ImportError:  # websockets < 11.0
+    from websockets.connection import State
+    from websockets.server import ServerConnection as ServerProtocol
 
 from websockets import http11
 from websockets.datastructures import Headers as WSHeaders


Test patch:
Repository: ray-project/ray

Issue:
Test failure in actor checkpointing ActorReconstruction.testCheckpointing in actor_test.py.
I just saw this error in a recently introduced test (and the test hung).

```
testCheckpointing (__main__.ActorReconstruction) ... Waiting for redis server at 127.0.0.1:14868 to respond...
Waiting for redis server at 127.0.0.1:48841 to respond...
Starting local scheduler with 2 CPUs, 0 GPUs
Starting local scheduler with 2 CPUs, 0 GPUs
Failed to start the UI, you may need to run 'pip install jupyter'.
Traceback (most recent call last):
  File "/home/travis/.local/lib/python2.7/site-packages/ray-0.1.2-py2.7-linux-x86_64.egg/ray/workers/default_worker.py", line 87, in <module>
    ray.worker.global_worker)
  File "/home/travis/.local/lib/python2.7/site-packages/ray-0.1.2-py2.7-linux-x86_64.egg/ray/actor.py", line 222, in reconstruct_actor_state
    worker.actor_class.__ray_restore_from_checkpoint__(checkpoint))
AttributeError: 'Worker' object has no attribute 'actor_class'


  You can inspect errors by running

      ray.error_info()

  If this driver is hanging, start a new one with

      ray.init(redis_address="127.0.0.1:14868")
```

https://s3.amazonaws.com/archive.travis-ci.org/jobs/262150716/log.txt?X-Amz-Expires=30&X-Amz-Date=20170808T170129Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJRYRXRSVGNKPKO5A/20170808/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=71e3540e370a11f66c599879fdee3dda5d9333e9984d3205fface3f3f2fe68e8


Discussion:

Resolving patch:
diff --git a/python/ray/actor.py b/python/ray/actor.py
--- a/python/ray/actor.py
+++ b/python/ray/actor.py
@@ -6,6 +6,7 @@
 import hashlib
 import inspect
 import json
+import time
 import traceback
 
 import ray.local_scheduler
@@ -215,7 +216,8 @@ def reconstruct_actor_state(actor_id, worker):
         print("Loading actor state from checkpoint {}"
               .format(checkpoint_index))
         # Wait for the actor to have been defined.
-        worker._wait_for_actor()
+        while not hasattr(worker, "actor_class"):
+            time.sleep(0.001)
         # TODO(rkn): Restoring from the checkpoint may fail, so this should be
         # in a try-except block and we should give a good error message.
         worker.actors[actor_id] = (


Test patch:
diff --git a/python/ray/test/test_utils.py b/python/ray/test/test_utils.py
--- a/python/ray/test/test_utils.py
+++ b/python/ray/test/test_utils.py
@@ -4,7 +4,6 @@
 
 import json
 import os
-import psutil
 import redis
 import time
 
@@ -115,18 +114,12 @@ def _pid_alive(pid):
         pid: The pid to check.
 
     Returns:
-        This returns false if the process is dead or defunct. Otherwise, it
-            returns true.
+        This returns false if the process is dead. Otherwise, it returns true.
     """
     try:
         os.kill(pid, 0)
     except OSError:
         return False
-    else:
-        if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:
-            return False
-        else:
-            return True
 
 
 def wait_for_pid_to_exit(pid, timeout=20):
Repository: ray-project/ray

Issue:
Segfault when putting object whose class closes over an ObjectID.
The following causes a segfault.

```python
import ray

class Foo():
    def __init__(self):
        self.val = ray.put(0)
    def method(self):
        f

ray.init()

f = Foo()

ray.put(f)
```

The error appears to happen when trying to pickle the class `Foo`. We prevent object IDs from being pickled at 

https://github.com/ray-project/ray/blob/b1d89026cdd41d7437972de256eb3371bb3bc5c1/src/common/lib/python/common_extension.cc#L205-L208

However, we never registered `CommonError` with the python extension module. I think that's the problem. Should be fixed by #1316.


Discussion:

Resolving patch:
diff --git a/python/ray/local_scheduler/__init__.py b/python/ray/local_scheduler/__init__.py
--- a/python/ray/local_scheduler/__init__.py
+++ b/python/ray/local_scheduler/__init__.py
@@ -4,9 +4,9 @@
 
 from ray.core.src.local_scheduler.liblocal_scheduler_library import (
     Task, LocalSchedulerClient, ObjectID, check_simple_value, task_from_string,
-    task_to_string, _config)
+    task_to_string, _config, common_error)
 from .local_scheduler_services import start_local_scheduler
 
 __all__ = ["Task", "LocalSchedulerClient", "ObjectID", "check_simple_value",
            "task_from_string", "task_to_string", "start_local_scheduler",
-           "_config"]
+           "_config", "common_error"]


Test patch:
diff --git a/test/runtest.py b/test/runtest.py
--- a/test/runtest.py
+++ b/test/runtest.py
@@ -284,6 +284,24 @@ def __init__(self):
 
         ray.worker.cleanup()
 
+    def testPuttingObjectThatClosesOverObjectID(self):
+        # This test is here to prevent a regression of
+        # https://github.com/ray-project/ray/issues/1317.
+        ray.init(num_workers=0)
+
+        class Foo(object):
+            def __init__(self):
+                self.val = ray.put(0)
+
+            def method(self):
+                f
+
+        f = Foo()
+        with self.assertRaises(ray.local_scheduler.common_error):
+            ray.put(f)
+
+        ray.worker.cleanup()
+
 
 class WorkerTest(unittest.TestCase):
     def testPythonWorkers(self):
Repository: ray-project/ray

Issue:
[rllib] [docs] Document multi-agent support
We should document the new multi-agent support in rllib and have some examples in readthedocs. It would be good to cover the supported cases and which ones are not yet supported (or provide workarounds).


Discussion:

Resolving patch:
diff --git a/python/ray/rllib/examples/multiagent_mountaincar_env.py b/python/ray/rllib/examples/multiagent_mountaincar_env.py
--- a/python/ray/rllib/examples/multiagent_mountaincar_env.py
+++ b/python/ray/rllib/examples/multiagent_mountaincar_env.py
@@ -22,8 +22,8 @@ def __init__(self):
         self.viewer = None
 
         self.action_space = [Discrete(3) for _ in range(2)]
-        self.observation_space = Tuple(tuple(Box(self.low, self.high)
-                                             for _ in range(2)))
+        self.observation_space = Tuple([
+            Box(self.low, self.high) for _ in range(2)])
 
         self._seed()
         self.reset()
diff --git a/python/ray/rllib/examples/multiagent_pendulum_env.py b/python/ray/rllib/examples/multiagent_pendulum_env.py
--- a/python/ray/rllib/examples/multiagent_pendulum_env.py
+++ b/python/ray/rllib/examples/multiagent_pendulum_env.py
@@ -24,8 +24,8 @@ def __init__(self):
         self.action_space = [Box(low=-self.max_torque / 2,
                                  high=self.max_torque / 2, shape=(1,))
                              for _ in range(2)]
-        self.observation_space = Tuple(tuple(Box(low=-high, high=high)
-                                             for _ in range(2)))
+        self.observation_space = Tuple([
+            Box(low=-high, high=high) for _ in range(2)])
 
         self._seed()
 


Test patch: