We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
deadlock on __heartbeat__
If I set up the same postgresql database/user for the storage, cache and permission connectors, I get a thread deadlock on the second call to **heartbeat**, leading to a blocking call, that makes the HB fails.

Looks like a DB connector race condition issue


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kinto/core/views/heartbeat.py`
Content:
```
1 from concurrent.futures import ThreadPoolExecutor, wait
2 from pyramid.security import NO_PERMISSION_REQUIRED
3 
4 from kinto import logger
5 from kinto.core import Service
6 
7 
8 heartbeat = Service(name="heartbeat", path='/__heartbeat__',
9                     description="Server health")
10 
11 
12 @heartbeat.get(permission=NO_PERMISSION_REQUIRED)
13 def get_heartbeat(request):
14     """Return information about server health."""
15     status = {}
16 
17     def heartbeat_check(name, func):
18         status[name] = False
19         status[name] = func(request)
20 
21     # Start executing heartbeats concurrently.
22     heartbeats = request.registry.heartbeats
23     pool = ThreadPoolExecutor(max_workers=max(1, len(heartbeats.keys())))
24     futures = []
25     for name, func in heartbeats.items():
26         future = pool.submit(heartbeat_check, name, func)
27         future.__heartbeat_name = name  # For logging purposes.
28         futures.append(future)
29 
30     # Wait for the results, with timeout.
31     seconds = float(request.registry.settings['heartbeat_timeout_seconds'])
32     done, not_done = wait(futures, timeout=seconds)
33 
34     # A heartbeat is supposed to return True or False, and never raise.
35     # Just in case, go though results to spot any potential exception.
36     for future in done:
37         exc = future.exception()
38         if exc is not None:
39             logger.error("%r heartbeat failed." % future.__heartbeat_name)
40             logger.error(exc)
41 
42     # Log timed-out heartbeats.
43     for future in not_done:
44         name = future.__heartbeat_name
45         error_msg = "%r heartbeat has exceeded timeout of %s seconds."
46         logger.error(error_msg % (name, seconds))
47 
48     # If any has failed, return a 503 error response.
49     has_error = not all([v or v is None for v in status.values()])
50     if has_error:
51         request.response.status = 503
52 
53     return status
54 
55 
56 lbheartbeat = Service(name="lbheartbeat", path='/__lbheartbeat__',
57                       description="Web head health")
58 
59 
60 @lbheartbeat.get(permission=NO_PERMISSION_REQUIRED)
61 def get_lbheartbeat(request):
62     """Return successful healthy response.
63 
64     If the load-balancer tries to access this URL and fails, this means the
65     Web head is not operational and should be dropped.
66     """
67     status = {}
68     return status
69
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kinto/core/views/heartbeat.py b/kinto/core/views/heartbeat.py
--- a/kinto/core/views/heartbeat.py
+++ b/kinto/core/views/heartbeat.py
@@ -1,4 +1,6 @@
 from concurrent.futures import ThreadPoolExecutor, wait
+
+import transaction
 from pyramid.security import NO_PERMISSION_REQUIRED
 
 from kinto import logger
@@ -17,6 +19,11 @@
     def heartbeat_check(name, func):
         status[name] = False
         status[name] = func(request)
+        # Since the heartbeat checks run concurrently, their transactions
+        # overlap and might end in shared lock errors. By aborting here
+        # we clean-up the state on each heartbeat call instead of once at the
+        # end of the request. See bug Kinto/kinto#804
+        transaction.abort()
 
     # Start executing heartbeats concurrently.
     heartbeats = request.registry.heartbeats

{"golden_diff": "diff --git a/kinto/core/views/heartbeat.py b/kinto/core/views/heartbeat.py\n--- a/kinto/core/views/heartbeat.py\n+++ b/kinto/core/views/heartbeat.py\n@@ -1,4 +1,6 @@\n from concurrent.futures import ThreadPoolExecutor, wait\n+\n+import transaction\n from pyramid.security import NO_PERMISSION_REQUIRED\n \n from kinto import logger\n@@ -17,6 +19,11 @@\n     def heartbeat_check(name, func):\n         status[name] = False\n         status[name] = func(request)\n+        # Since the heartbeat checks run concurrently, their transactions\n+        # overlap and might end in shared lock errors. By aborting here\n+        # we clean-up the state on each heartbeat call instead of once at the\n+        # end of the request. See bug Kinto/kinto#804\n+        transaction.abort()\n \n     # Start executing heartbeats concurrently.\n     heartbeats = request.registry.heartbeats\n", "issue": "deadlock on __heartbeat__\nIf I set up the same postgresql database/user for the storage, cache and permission connectors, I get a thread deadlock on the second call to **heartbeat**, leading to a blocking call, that makes the HB fails.\n\nLooks like a DB connector race condition issue\n\n", "before_files": [{"content": "from concurrent.futures import ThreadPoolExecutor, wait\nfrom pyramid.security import NO_PERMISSION_REQUIRED\n\nfrom kinto import logger\nfrom kinto.core import Service\n\n\nheartbeat = Service(name=\"heartbeat\", path='/__heartbeat__',\n                    description=\"Server health\")\n\n\n@heartbeat.get(permission=NO_PERMISSION_REQUIRED)\ndef get_heartbeat(request):\n    \"\"\"Return information about server health.\"\"\"\n    status = {}\n\n    def heartbeat_check(name, func):\n        status[name] = False\n        status[name] = func(request)\n\n    # Start executing heartbeats concurrently.\n    heartbeats = request.registry.heartbeats\n    pool = ThreadPoolExecutor(max_workers=max(1, len(heartbeats.keys())))\n    futures = []\n    for name, func in heartbeats.items():\n        future = pool.submit(heartbeat_check, name, func)\n        future.__heartbeat_name = name  # For logging purposes.\n        futures.append(future)\n\n    # Wait for the results, with timeout.\n    seconds = float(request.registry.settings['heartbeat_timeout_seconds'])\n    done, not_done = wait(futures, timeout=seconds)\n\n    # A heartbeat is supposed to return True or False, and never raise.\n    # Just in case, go though results to spot any potential exception.\n    for future in done:\n        exc = future.exception()\n        if exc is not None:\n            logger.error(\"%r heartbeat failed.\" % future.__heartbeat_name)\n            logger.error(exc)\n\n    # Log timed-out heartbeats.\n    for future in not_done:\n        name = future.__heartbeat_name\n        error_msg = \"%r heartbeat has exceeded timeout of %s seconds.\"\n        logger.error(error_msg % (name, seconds))\n\n    # If any has failed, return a 503 error response.\n    has_error = not all([v or v is None for v in status.values()])\n    if has_error:\n        request.response.status = 503\n\n    return status\n\n\nlbheartbeat = Service(name=\"lbheartbeat\", path='/__lbheartbeat__',\n                      description=\"Web head health\")\n\n\n@lbheartbeat.get(permission=NO_PERMISSION_REQUIRED)\ndef get_lbheartbeat(request):\n    \"\"\"Return successful healthy response.\n\n    If the load-balancer tries to access this URL and fails, this means the\n    Web head is not operational and should be dropped.\n    \"\"\"\n    status = {}\n    return status\n", "path": "kinto/core/views/heartbeat.py"}], "after_files": [{"content": "from concurrent.futures import ThreadPoolExecutor, wait\n\nimport transaction\nfrom pyramid.security import NO_PERMISSION_REQUIRED\n\nfrom kinto import logger\nfrom kinto.core import Service\n\n\nheartbeat = Service(name=\"heartbeat\", path='/__heartbeat__',\n                    description=\"Server health\")\n\n\n@heartbeat.get(permission=NO_PERMISSION_REQUIRED)\ndef get_heartbeat(request):\n    \"\"\"Return information about server health.\"\"\"\n    status = {}\n\n    def heartbeat_check(name, func):\n        status[name] = False\n        status[name] = func(request)\n        # Since the heartbeat checks run concurrently, their transactions\n        # overlap and might end in shared lock errors. By aborting here\n        # we clean-up the state on each heartbeat call instead of once at the\n        # end of the request. See bug Kinto/kinto#804\n        transaction.abort()\n\n    # Start executing heartbeats concurrently.\n    heartbeats = request.registry.heartbeats\n    pool = ThreadPoolExecutor(max_workers=max(1, len(heartbeats.keys())))\n    futures = []\n    for name, func in heartbeats.items():\n        future = pool.submit(heartbeat_check, name, func)\n        future.__heartbeat_name = name  # For logging purposes.\n        futures.append(future)\n\n    # Wait for the results, with timeout.\n    seconds = float(request.registry.settings['heartbeat_timeout_seconds'])\n    done, not_done = wait(futures, timeout=seconds)\n\n    # A heartbeat is supposed to return True or False, and never raise.\n    # Just in case, go though results to spot any potential exception.\n    for future in done:\n        exc = future.exception()\n        if exc is not None:\n            logger.error(\"%r heartbeat failed.\" % future.__heartbeat_name)\n            logger.error(exc)\n\n    # Log timed-out heartbeats.\n    for future in not_done:\n        name = future.__heartbeat_name\n        error_msg = \"%r heartbeat has exceeded timeout of %s seconds.\"\n        logger.error(error_msg % (name, seconds))\n\n    # If any has failed, return a 503 error response.\n    has_error = not all([v or v is None for v in status.values()])\n    if has_error:\n        request.response.status = 503\n\n    return status\n\n\nlbheartbeat = Service(name=\"lbheartbeat\", path='/__lbheartbeat__',\n                      description=\"Web head health\")\n\n\n@lbheartbeat.get(permission=NO_PERMISSION_REQUIRED)\ndef get_lbheartbeat(request):\n    \"\"\"Return successful healthy response.\n\n    If the load-balancer tries to access this URL and fails, this means the\n    Web head is not operational and should be dropped.\n    \"\"\"\n    status = {}\n    return status\n", "path": "kinto/core/views/heartbeat.py"}]}