prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <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
  
  
  </issue>
  <code>
  [start of kinto/core/views/heartbeat.py]
  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 of kinto/core/views/heartbeat.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: 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
  
verification_info: {"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"}]}