patx/mrhttp-asgi

Add production ASGI transport and supervision

Commit e0d27c3 · patx · Nov 9 at 2:07AM

Changeset
e0d27c3429a6afc9dd405b58b8d3dd8efc96dce6
Parents
1955c8bdf7ae0cc5b6907470d3fc96a6c8e38683

View source at this commit

Add production ASGI transport and supervision

Dispatch requests at header completion and deliver bounded body chunks
with read backpressure and application-driven 100 Continue responses.
Stream ordered responses and support ASGI WebSockets through wsproto.

Recover crashed or stalled workers, recycle workers with jitter, and
perform readiness-gated rolling restarts that load fresh application code.
Add shared metrics, structured access logs, request IDs, health routes,
trusted proxy handling, IPv6, Unix sockets, and inherited descriptors.

Harden native framing, request ownership, queue bounds, cancellation, and
Python 3.14 compatibility. Add socket/process regressions, sanitizer CI,
release gates, and documentation of supported behavior and limits.

Validation: 69 tests pass; 68 transport/process tests pass with ASan/UBSan.
Python 3.14 wheel build and staged whitespace checks pass.

Comments

No comments yet.

Log in to comment

Diff

diff --git a/.github/workflows/asgi-tests.yml b/.github/workflows/asgi-tests.yml
new file mode 100644
index 0000000..196a29e
--- /dev/null
+++ b/.github/workflows/asgi-tests.yml
@@ -0,0 +1,42 @@
+name: ASGI transport tests
+on:
+  push:
+  pull_request:
+  workflow_dispatch:
+  workflow_call:
+
+jobs:
+  http:
+    runs-on: ubuntu-latest
+    strategy:
+      fail-fast: false
+      matrix:
+        python: ['3.10', '3.11', '3.12', '3.13', '3.14']
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-python@v5
+        with:
+          python-version: ${{ matrix.python }}
+      - run: python -m pip install '.[test]'
+      - run: python -m pytest tests/test_asgi_regressions.py tests/test_asgi_production.py tests/test_supervisor.py tests/test_asgi.py tests/test_asgi_frameworks.py tests/test_usererror.py -q
+
+  sanitizers:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v4
+      - uses: actions/setup-python@v5
+        with:
+          python-version: '3.12'
+      - run: python -m pip install '.[test]'
+      - name: Rebuild instrumented extension
+        env:
+          CFLAGS: -fsanitize=address,undefined -fno-omit-frame-pointer -O1
+          LDFLAGS: -fsanitize=address,undefined
+        run: python setup.py build_ext --inplace --force
+      - name: Exercise instrumented C transport
+        env:
+          PYTHONPATH: src
+          PYTHONMALLOC: malloc
+          ASAN_OPTIONS: detect_leaks=0:abort_on_error=1
+          UBSAN_OPTIONS: halt_on_error=1
+        run: LD_PRELOAD="$(gcc -print-file-name=libasan.so)" python -m pytest tests/test_asgi_regressions.py tests/test_asgi_production.py tests/test_supervisor.py tests/test_asgi.py tests/test_asgi_frameworks.py -q
diff --git a/.github/workflows/build_wheels.yml b/.github/workflows/build_wheels.yml
index f48c12b..7db5070 100644
--- a/.github/workflows/build_wheels.yml
+++ b/.github/workflows/build_wheels.yml
@@ -5,7 +5,11 @@ on:
     workflow_dispatch:
 
 jobs:
+  asgi_checks:
+    uses: ./.github/workflows/asgi-tests.yml
+
   build_wheels:
+    needs: [asgi_checks]
     name: Build wheels on ${{ matrix.os }}
     runs-on: ${{ matrix.os }}
     strategy:
@@ -27,6 +31,7 @@ jobs:
           path: wheelhouse/*.whl
 
   build_sdist:
+    needs: [asgi_checks]
     name: Build source distribution
     runs-on: ubuntu-latest
     steps:
diff --git a/README.md b/README.md
index f945a0e..901e6bf 100644
--- a/README.md
+++ b/README.md
@@ -1,44 +1,188 @@
-# Mrhttp-ASGI
+# MrHTTP-ASGI
 
-ASGI compatible Python 3.5+ web server written in C
+An HTTP/1.0, HTTP/1.1, and WebSocket ASGI server with a C HTTP transport and asyncio
+application handling. Requires Python 3.10+ on Unix x86_64 with AVX2 and BMI2.
+WebSocket framing uses wsproto. The legacy MrHTTP router and cache clients remain
+available separately.
 
+## Install and run
 
-# Install
+```sh
+python -m pip install .
+mrhttp myapp:app --host 127.0.0.1 --port 8080 --workers 4 --lifespan on
+```
+
+```python
+# myapp.py
+from fastapi import FastAPI
+
+app = FastAPI()
+
[email protected]("/")
+async def index():
+    return {"hello": "world"}
+```
 
-Clone the repo:
+For programmatic process management, use an import string:
+
+```python
+import mrhttp
+
+if __name__ == "__main__":
+    mrhttp.run("myapp:app", workers=4, lifespan="on")
+```
 
+`--factory` treats the imported attribute as a no-argument application factory.
+Import-string workers use fresh Python interpreters. Direct Python callables,
+including local functions, are also supported through Unix fork; restarting those
+workers refreshes their processes but does not re-import changed application code.
+Importing MrHTTP does not change the process-wide event-loop policy. Managed
+workers use uvloop; embedded servers use their caller's running loop.
+
+## Streaming and flow control
+
+The C parser dispatches an application as soon as request headers are complete.
+`receive()` delivers decoded body chunks with `more_body=True` until the final
+chunk. Applications must consume messages until `more_body=False`; one call to
+`receive()` is not guaranteed to return the complete upload.
+
+Incoming data pauses at the configured buffer watermark and resumes as the app
+consumes messages. `Expect: 100-continue` is acknowledged when the application
+calls `receive()`. An application can reject a request before reading its body;
+the response is sent and the connection closes without consuming the upload.
+
+Response chunks flush directly to the transport. `send()` waits for socket write
+backpressure. HTTP pipelined responses remain in request order. Duplicate request
+headers are preserved and lifespan state is shallow-copied per request.
+
+```python
+mrhttp.run(
+    "myapp:app",
+    max_body_size=16 * 1024 * 1024,   # cumulative decoded bytes per request
+    max_header_size=65536,          # request head; also at most 100 fields
+    read_buffer_size=65536,         # queued body bytes plus waiting request heads
+    max_pipeline_requests=1024,
+    max_connections=1000,           # per worker
+    timeout_request=30,             # incomplete request deadline
+    timeout_keep_alive=5,
+    timeout_graceful_shutdown=10,
+)
 ```
-$ git clone https://gitman.io/git/patx/mrhttp-asgi
-$ cd mrhttp-asgi
-$ pip3 install .
+
+A native body chunk is at most 16 KiB; the Python watermark can overshoot by one
+chunk or request head. The native staging buffer is capped at the header limit
+plus 1 MiB. The body limit applies cumulatively to fixed-length and chunked uploads,
+without retaining the full body. Invalid framing and oversized requests return
+HTTP 400 and close when an error response is still possible. Once a response has
+started, a protocol failure closes the connection instead of appending another
+HTTP response. Active streaming responses have no arbitrary duration limit.
+
+## Worker supervision and shutdown
+
+The supervisor replaces crashed workers and kills/replaces workers whose event
+loops stop sending heartbeats. Startup readiness follows lifespan startup and
+listener creation. Startup failure exits nonzero; repeated failures stop the
+supervisor instead of creating an unlimited restart loop.
+
+```sh
+mrhttp myapp:app --workers 4 \
+  --timeout-worker-healthcheck 5 --timeout-worker-startup 30 \
+  --limit-max-requests 10000 --limit-max-requests-jitter 1000
 ```
 
+The request limit requests a rolling replacement; it is a soft recycling target,
+so a worker may finish additional requests while its replacement starts. Jitter
+staggers recycling. It is disabled by default.
+
+Send `SIGHUP` to the supervisor PID to restart workers one at a time. A replacement
+must become ready before the old worker stops accepting connections and drains
+in-flight work. Import-string workers load fresh application code. SIGINT/SIGTERM
+stop acceptance, drain requests for the configured grace period, cancel remaining
+applications, and then run lifespan shutdown. WebSockets receive a 1001 close on
+server shutdown. Processes that exceed their shutdown deadline are killed.
 
-# Use an existing ASGI app
+`lifespan=auto` permits apps without lifespan support; `on` makes startup failures
+fatal; `off` disables lifespan events.
 
-Just import `mrhttp` and use `mrhttp.run()`:
+## Logs, request IDs, health, and metrics
 
+```sh
+mrhttp myapp:app --workers 4 \
+  --access-log --access-log-format json \
+  --health-check-path /healthz --metrics-path /metrics
+```
+
+Access logs contain request ID, method, decoded path, client, status, response-body
+bytes, and duration. Query strings are not logged. A valid incoming `X-Request-Id`
+is reused; otherwise the server generates one. The ID is available as
+`scope['request_id']` and is added to responses. `--request-id-header` changes the
+header name. Application errors include the request ID.
+
+Health and metrics routes are opt-in and handled before the application. Health
+returns 200 after worker startup. `/metrics` exposes Prometheus text counters for
+requests, decoded input bytes, response bytes, protocol errors, a duration
+histogram, and connection/active-request gauges. Managed workers share counters;
+scrapes aggregate all worker slots and are approximate concurrent snapshots.
+Worker death resets its gauges without discarding counters. No request-path or
+request-ID labels are used. Restrict the metrics path through deployment routing
+if it should not be public.
+
+## WebSockets
+
+ASGI applications receive `websocket.connect`, complete text/binary messages, and
+`websocket.disconnect` with close code/reason. Subprotocol negotiation, fragmented
+messages, ping/pong, close handshakes, and transport backpressure are supported.
+Closing before acceptance returns HTTP 403; invalid handshakes return HTTP 400.
+
+```sh
+mrhttp myapp:app --ws-max-size 16777216 --ws-max-queue 32 \
+  --ws-ping-interval 20 --ws-ping-timeout 20 --ws-close-timeout 5
 ```
-import mrhttp
-from micropie import App
 
-class Root(App):
-    async def index(self):
-        return {"hello": "world"}
+The message-size limit applies across fragments. The receive queue pauses input
+at its watermark. Set `--ws-ping-interval 0` to disable server pings. Compression
+extensions are not negotiated. An upgrade cannot follow an active pipelined HTTP
+request on the same connection.
 
-app = Root()
-mrhttp.run(app, host="127.0.0.1", port=8080, workers=2, lifespan="on")
+## Proxies and deployment sockets
+
+Forwarded headers are ignored by default. Enable them only for configured trusted
+immediate peers; the client address is selected from the right of the forwarded
+chain, skipping trusted proxy hops:
+
+```sh
+mrhttp myapp:app --proxy-headers --forwarded-allow-ips '127.0.0.1,::1,10.0.0.0/8'
+mrhttp myapp:app --host ::1 --port 8080
+mrhttp myapp:app --uds /run/myapp.sock --workers 4
+mrhttp myapp:app --fd 3 --workers 4
 ```
 
+`X-Forwarded-For` and `X-Forwarded-Proto` update ASGI client and scheme metadata;
+`Forwarded` and `X-Forwarded-Host` are not interpreted. `*` explicitly trusts every
+peer. IPv6 listeners are IPv6-only. Unix paths must not already exist, and paths
+created by the server are removed on shutdown only if their inode still matches.
+Inherited descriptors are duplicated; the caller retains ownership of its FD.
+`--backlog` sets the listen backlog. `--root-path` supports mounted applications.
+All limits and timeout settings above are also available as CLI flags; use
+`mrhttp --help` for the complete configuration.
 
-# Benchmarks
+For an existing event loop, use `await server.start_server(host=..., port=...)`
+(or `uds=...` / `fd=...`) and `await server.shutdown()` on an `ASGIServer` instance.
 
-The above app was ran with 8 workers on `uvicorn`, `granian`, and `mrhttp-asi`.
-It was tested with `wrk` using 4 threads and 1000 connections for 15 seconds.
+## Validation and remaining scope
+
+```sh
+python -m pip install '.[test]'
+./runtests
+```
 
-| Server          | Requests/sec | Avg Latency | Max Latency | Total Requests | Transfer/sec |
-| --------------- | ------------ | ----------- | ----------- | -------------- | ------------ |
-| **Mrhttp-ASGI** | **369,706**  | **2.49ms**  | 209.48ms    | 5,581,724      | 51.48MB      |
-| **Granian**     | 314,993      | 2.81ms      | **16.44ms** | 4,750,339      | 42.66MB      |
-| **Uvicorn**     | 95,578       | 10.90ms     | 341.61ms    | 1,436,933      | 14.68MB      |
+CI runs the HTTP, WebSocket, FastAPI, proxy, socket-binding, observability, and
+supervisor suites on Python 3.10–3.14 and under AddressSanitizer/UndefinedBehaviorSanitizer.
+The launcher propagates failures; benchmarks are separate (`./runtests --benchmarks`).
 
+HTTP/2, HTTP/3, direct TLS, WSGI, response trailers, WebSocket compression, and
+file-watching development reload are not implemented. Use a reverse proxy for TLS.
+The legacy router, multipart parser, serializers, and external cache/session
+backends are outside this ASGI validation scope; their tests need extra packages
+and services. Load and soak validation for a deployment's workload remains
+necessary. Historical benchmark results do not describe this implementation.
diff --git a/dotests.py b/dotests.py
index f80ada7..ccf4ea7 100644
--- a/dotests.py
+++ b/dotests.py
@@ -35,26 +35,14 @@ import atexit
 
 
 async def run_tests():
-  package = tests
-  for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
-    if modname.startswith("test"):
-      m = importlib.import_module('tests.'+modname)
-      functions = inspect.getmembers(m, inspect.isfunction)
-      for f in functions:
-        if f[0] == 'setup':
-          if f[1]():
-            exit()
-      for f in functions:
-        if f[0].startswith("test_"):
-          try:
-            f[1]()
-          except Exception as e:
-            print(e)
-      for f in functions:
-        if f[0] == 'teardown':
-          f[1]()
-  
-    
+  process = await asyncio.create_subprocess_exec(
+    sys.executable, "-m", "pytest", "tests/test_asgi_regressions.py",
+    "tests/test_asgi_production.py", "tests/test_supervisor.py", "tests/test_asgi.py",
+    "tests/test_asgi_frameworks.py", "tests/test_usererror.py", "-q")
+  code = await process.wait()
+  if code:
+    raise SystemExit(code)
+
 
 #from misc import cpu
 
@@ -89,6 +77,7 @@ async def run_wrk(loop, endpoint=None, lua=None, options=None):
 
 
 async def run_benchmarks():
+  loop = asyncio.get_running_loop()
   proc = await asyncio.create_subprocess_exec( 'python', 'tests/s_bench.py', stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE )
   process = psutil.Process(proc.pid)
 
@@ -155,9 +144,9 @@ async def run_benchmarks():
 
 async def main():
   await run_tests()
-  await run_benchmarks()
+  if "--benchmarks" in sys.argv:
+    await run_benchmarks()
 
-loop = uvloop.new_event_loop()
-asyncio.set_event_loop(loop)
-asyncio.run( main() )
+if __name__ == "__main__":
+  asyncio.run(main())
 
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..cb60049
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,3 @@
+[build-system]
+requires = ["setuptools>=77", "wheel"]
+build-backend = "setuptools.build_meta"
diff --git a/runtests b/runtests
index 5e92ad4..0cfdde5 100755
--- a/runtests
+++ b/runtests
@@ -1,5 +1,3 @@
-
-sudo sh -c "echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor"
-python dotests.py
-sudo sh -c "echo powersave | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor"
-
+#!/bin/sh
+set -eu
+exec python dotests.py "$@"
diff --git a/setup.py b/setup.py
index 5ffb768..6c38211 100644
--- a/setup.py
+++ b/setup.py
@@ -1,5 +1,6 @@
 
 from setuptools import setup, Extension, find_packages
+from glob import glob
 
 m1 = Extension(
     'mrhttp.internals',
@@ -24,6 +25,7 @@ m1 = Extension(
       './src/mrhttp/internals/hash/assoc.c',
       './src/mrhttp/utils/unpack.c',
      ],
+     depends=glob('src/mrhttp/internals/**/*.h', recursive=True) + glob('src/mrhttp/utils/*.h'),
      include_dirs = ['./src/mrhttp/internals','./src/mrhttp/utils'],
      extra_compile_args = ['-msse4.2', '-mavx2', '-mbmi2', '-Wunused-variable','-std=gnu99','-Wno-discarded-qualifiers', '-Wno-unused-variable','-Wno-unused-function'],
      extra_link_args = [],
@@ -49,8 +51,11 @@ setup(
   #package_data={'prof': ['prof.so']},
   install_requires=[
     #'uvloop<0.9.0',
-    'uvloop>0.9.0',
+    'uvloop>=0.17',
+    'wsproto>=1.2,<2',
   ],
+  python_requires='>=3.10',
+  extras_require={"test": ["pytest", "requests", "psutil", "fastapi"]},
   platforms='x86_64 Linux and MacOS X',
   url='http://github.com/MarkReedZ/mrhttp/',
   author='Mark Reed',
@@ -64,8 +69,8 @@ setup(
     'Operating System :: MacOS :: MacOS X',
     'Operating System :: POSIX :: Linux',
     'Programming Language :: C',
-    'Programming Language :: Python :: 3.5',
-    'Programming Language :: Python :: 3.6',
+    'Programming Language :: Python :: 3',
+    'Programming Language :: Python :: 3 :: Only',
     'Programming Language :: Python :: Implementation :: CPython',
     'Topic :: Internet :: WWW/HTTP'
    ]
diff --git a/src/mrhttp/app.py b/src/mrhttp/app.py
index 148c659..09b86ff 100644
--- a/src/mrhttp/app.py
+++ b/src/mrhttp/app.py
@@ -44,7 +44,7 @@ except ImportError:
 #import mrmemcache
 
 import uvloop
-asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
+
 
 signames = {
     int(v): v.name for k, v in signal.__dict__.items()
diff --git a/src/mrhttp/asgi.py b/src/mrhttp/asgi.py
index f3120ec..f9b3839 100644
--- a/src/mrhttp/asgi.py
+++ b/src/mrhttp/asgi.py
@@ -2,34 +2,29 @@ import argparse
 import asyncio
 import email.utils
 import importlib
-import multiprocessing
-import os
 import signal
-import socket
 import sys
+import math
+import logging
+import re
 from http.client import responses
 
 import uvloop
 
 import mrhttp
 from mrhttp import Protocol
-from mrhttp.internals import _build_asgi_response
 from mrhttp.request import Request
+from .exceptions import ASGIConnectionClosed, ASGIProtocolError
+from .headers import _normalize_header
+from .streams import HTTPInput
+from .observability import Metrics, configure_access_log, access_record
+from .proxy import TrustedProxies
+from .networking import bind_socket, cleanup_socket
+from .websocket import WebSocketSession
+import uuid
 
 
-asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
 
-
-class ASGIConnectionClosed(OSError):
-  pass
-
-
-class ASGIProtocolError(RuntimeError):
-  pass
-
-
-_EMPTY_HTTP_REQUEST = {"type": "http.request", "body": b"", "more_body": False}
-_HTTP_DISCONNECT = {"type": "http.disconnect"}
 _STATUS_LINE_CACHE = {}
 
 
@@ -46,162 +41,295 @@ def _status_line(version, status):
   return line
 
 
+class ASGIProtocol(Protocol):
+  """Native HTTP parsing, bounded input, and ordered ASGI execution."""
+  def __init__(self, app):
+    super().__init__(app)
+    self.server = app
+    self.response_lock = asyncio.Lock()
+    self.disconnected = asyncio.Event()
+    self.writable = asyncio.Event()
+    self.writable.set()
+    self.timeout_handle = None
+    self.disconnect_handle = None
+    self.resume_handle = None
+    self.reading_request = False
+    self.read_paused = False
+    self.buffered_input = 0
+    self.queued_headers = 0
+    self.request_tasks = {}
+    self.websocket = None
+    self.active_response = None
+    self.admitted = False
+
+  @property
+  def pipeline_empty(self):
+    return not self.request_tasks and (not self.websocket or self.websocket.closed)
+
+  def connection_made(self, transport):
+    super().connection_made(transport)
+    if self.server.draining or len(self.server._connections) >= self.server.max_connections:
+      transport.close()
+      return
+    self.admitted = True
+    self.server._connections.add(self)
+    self.server.metrics.connection(1)
+    self._arm_timeout(self.server.timeout_request)
+
+  def _arm_timeout(self, seconds):
+    if self.timeout_handle:
+      self.timeout_handle.cancel()
+    self.timeout_handle = self.server.loop.call_later(seconds, self.transport.close)
+
+  def data_received(self, data):
+    if self.disconnected.is_set() or not self.admitted:
+      return
+    if not self.reading_request and not self.websocket:
+      self.reading_request = True
+      self._arm_timeout(self.server.timeout_request)
+    super().data_received(data)
+    if not self.request_incomplete and (not self.websocket or self.websocket.accepted):
+      self.reading_request = False
+      if self.timeout_handle:
+        self.timeout_handle.cancel()
+      self.response_finished()
+
+  def request_started(self, scope, keep_alive):
+    if len(self.request_tasks) >= self.server.max_pipeline_requests:
+      raise ASGIProtocolError('HTTP pipeline capacity exceeded')
+    raw_peer = scope.get('client')
+    scope['client'] = tuple(raw_peer[:2]) if isinstance(raw_peer, tuple) else None
+    raw_server = scope.get('server')
+    scope['server'] = tuple(raw_server[:2]) if isinstance(raw_server, tuple) else (raw_server, None) if raw_server else None
+    if self.server.proxy_headers:
+      self.server.trusted_proxies.apply(scope, raw_peer)
+    request_id = next((v.decode('ascii') for n, v in scope['headers']
+                       if n == self.server.request_id_header and re.fullmatch(rb'[A-Za-z0-9._:-]{1,128}', v)), None)
+    scope['request_id'] = request_id or uuid.uuid4().hex
+    is_websocket = any(n == b'upgrade' and v.lower() == b'websocket' for n, v in scope['headers'])
+    if is_websocket:
+      if self.request_tasks:
+        raise ASGIProtocolError('WebSocket upgrade cannot follow an active HTTP request')
+      stream = WebSocketSession(self, scope)
+      self.websocket = stream
+    else:
+      stream = HTTPInput(self, scope, keep_alive)
+    stream.reject_for_shutdown = self.server.draining
+    self.queued_headers += stream.header_bytes
+    task = self.server.loop.create_task(self.server._run_asgi(scope, stream, keep_alive, self))
+    self.request_tasks[task] = stream
+    self.server._tasks.add(task)
+    task.add_done_callback(self._request_done)
+    return stream
+
+  def request_running(self, stream):
+    self.queued_headers -= stream.header_bytes
+    stream.header_bytes = 0
+    self.schedule_resume()
+
+  def _request_done(self, task):
+    stream = self.request_tasks.pop(task)
+    self.queued_headers -= stream.header_bytes
+    if isinstance(stream, HTTPInput):
+      stream.finish()
+    else:
+      stream.release_messages()
+    self.server._tasks.discard(task)
+    if not task.cancelled():
+      exception = task.exception()
+      if exception and not isinstance(exception, ASGIConnectionClosed):
+        logging.getLogger('mrhttp.error').error('Request task failed', exc_info=(type(exception), exception, exception.__traceback__))
+        if not self.disconnected.is_set():
+          self.transport.close()
+    self.schedule_resume()
+    self.response_finished()
+
+  def parser_error(self):
+    self.server.metrics.protocol_error()
+    if self.websocket and self.websocket.accepted:
+      self.websocket.fail(1002, 'Invalid WebSocket data')
+      return
+    if not self.active_response or not self.active_response.wire_started:
+      self.transport.write(_error_response(400, 'Invalid Request'))
+      if self.active_response:
+        self.active_response.status = 400
+      else:
+        self.server.metrics.completed(400, 0, 0)
+        if self.server.access_log:
+          access_record({'request_id': uuid.uuid4().hex, 'method': '-', 'path': '-', 'client': None},
+                        400, 0, 0, self.server.access_log_format)
+    self.pipeline_cancel()
+    self.transport.close()
+
+  def check_read_flow(self):
+    ready = (self.buffered_input + self.queued_headers < self.server.read_buffer_size
+             and self.writable.is_set() and (not self.websocket or self.websocket.can_read()))
+    if not ready and not self.read_paused:
+      self.transport.pause_reading()
+      self.read_paused = True
+    return ready
+
+  def schedule_resume(self):
+    if self.resume_handle is None and not self.disconnected.is_set():
+      self.resume_handle = self.server.loop.call_soon(self.resume_input)
+
+  def resume_input(self):
+    self.resume_handle = None
+    if self.disconnected.is_set() or self.transport.is_closing():
+      return
+    if self.websocket:
+      self.websocket.drain_events()
+    if self.check_read_flow():
+      if self.read_paused:
+        self.read_paused = False
+        self.transport.resume_reading()
+      self.data_received(b'')
+
+  def pause_writing(self):
+    self.writable.clear()
+    self.check_read_flow()
+
+  def resume_writing(self):
+    self.writable.set()
+    self.schedule_resume()
+
+  async def write(self, data):
+    await self.writable.wait()
+    if self.disconnected.is_set() or self.transport.is_closing():
+      raise ASGIConnectionClosed('Client disconnected')
+    self.transport.write(data)
+    await self.writable.wait()
+    if self.disconnected.is_set():
+      raise ASGIConnectionClosed('Client disconnected')
+
+  def response_finished(self):
+    if self.pipeline_empty and self.disconnect_handle:
+      self.disconnect_handle.cancel()
+      self.disconnect_handle = None
+    if self.pipeline_empty and not self.disconnected.is_set() and not self.request_incomplete:
+      self.reading_request = False
+      self._arm_timeout(self.server.timeout_keep_alive)
+
+  def pipeline_cancel(self):
+    for task in list(self.request_tasks):
+      task.cancel()
+
+  def connection_lost(self, exc):
+    self.disconnected.set()
+    self.writable.set()
+    if self.admitted:
+      self.server.metrics.connection(-1)
+      self.admitted = False
+    for handle in (self.timeout_handle, self.resume_handle):
+      if handle:
+        handle.cancel()
+    self.server._connections.discard(self)
+    for stream in self.request_tasks.values():
+      if isinstance(stream, HTTPInput):
+        stream.finish()
+    if self.websocket:
+      self.websocket.disconnect()
+    if self.request_tasks:
+      self.disconnect_handle = self.server.loop.call_later(0.1, self.pipeline_cancel)
+    super().connection_lost(exc)
+
+
 class _ASGIResponder:
-  __slots__ = (
-    "scope",
-    "request_message",
-    "_request_sent",
-    "started",
-    "closed",
-    "status",
-    "headers",
-    "body",
-    "body_parts",
-    "date",
-    "has_content_length",
-    "has_connection",
-    "has_date",
-    "has_server",
-    "http_version",
-    "head_response",
-    "status_line",
-  )
-
-  def __init__(self, scope, body, date):
+  def __init__(self, scope, input_stream, date, protocol):
     self.scope = scope
-    self.request_message = {"type": "http.request", "body": body or b"", "more_body": False}
-    self._request_sent = False
+    self.protocol = protocol
+    self.input = input_stream
+    self.date = date
     self.started = False
+    self.wire_started = False
     self.closed = False
     self.status = 500
     self.headers = []
-    self.body = b""
-    self.body_parts = None
-    self.date = date
-    self.has_content_length = False
-    self.has_connection = False
-    self.has_date = False
-    self.has_server = False
-    self.http_version = scope.get("http_version", "1.1")
-    self.head_response = scope.get("method") == "HEAD"
-    self.status_line = _status_line(self.http_version, self.status)
+    self.content_length = None
+    self.sent_length = 0
+    self.chunked = False
+    self.keep_alive = True
+    self.head = scope["method"] == "HEAD"
 
   async def receive(self):
-    if not self._request_sent:
-      self._request_sent = True
-      return self.request_message
-    if self.closed:
-      return _HTTP_DISCONNECT
-    return _EMPTY_HTTP_REQUEST
+    return await self.input.receive()
 
   async def send(self, message):
-    if self.closed:
+    if self.closed or self.protocol.disconnected.is_set():
       raise ASGIConnectionClosed("ASGI connection is already closed")
     if not isinstance(message, dict):
       raise ASGIProtocolError("ASGI send message must be a dict")
-
     typ = message.get("type")
     if typ == "http.response.start":
       if self.started:
         raise ASGIProtocolError("http.response.start sent twice")
       status = message.get("status")
-      if not isinstance(status, int):
-        raise ASGIProtocolError("http.response.start status must be an int")
-      raw_headers = message.get("headers", [])
+      if type(status) is not int or not 200 <= status <= 599:
+        raise ASGIProtocolError("Response status must be an integer from 200 to 599")
+      if message.get("trailers"):
+        raise ASGIProtocolError("Response trailers are not supported")
       headers = []
-      has_content_length = False
-      has_connection = False
-      has_date = False
-      has_server = False
-
-      for header in raw_headers:
+      for header in message.get("headers", []):
         name, value = _normalize_header(header)
-        if name.startswith(b":"):
-          raise ASGIProtocolError("HTTP/2 pseudo headers are not valid in HTTP responses")
         if name == b"transfer-encoding":
           continue
         if name == b"content-length":
-          has_content_length = True
-        elif name == b"connection":
-          has_connection = True
-        elif name == b"date":
-          has_date = True
-        elif name == b"server":
-          has_server = True
+          if self.content_length is not None or not value or not value.isdigit():
+            raise ASGIProtocolError("Invalid or duplicate Content-Length")
+          self.content_length = int(value)
+        if name == b"connection" and b"close" in [v.strip() for v in value.lower().split(b",")]:
+          self.keep_alive = False
         headers.append((name, value))
-
-      self.headers = headers
-      self.has_content_length = has_content_length
-      self.has_connection = has_connection
-      self.has_date = has_date
-      self.has_server = has_server
-      self.status = status
-      self.status_line = _status_line(self.http_version, status)
-      self.started = True
+      self.status, self.headers, self.started = status, headers, True
       return
-
-    if typ == "http.response.body":
-      if not self.started:
-        raise ASGIProtocolError("http.response.body sent before http.response.start")
-      body = message.get("body", b"")
-      if isinstance(body, str):
-        body = body.encode("latin-1")
-      if body:
-        if not isinstance(body, (bytes, bytearray, memoryview)):
-          raise ASGIProtocolError("http.response.body body must be bytes")
-        if not isinstance(body, bytes):
-          body = bytes(body)
-        if self.body_parts is not None:
-          self.body_parts.append(body)
-        elif self.body:
-          self.body_parts = [self.body, body]
-          self.body = b""
+    if typ != "http.response.body" or not self.started:
+      raise ASGIProtocolError("Expected response start followed by response body")
+    body = message.get("body", b"")
+    if not isinstance(body, bytes):
+      raise ASGIProtocolError("ASGI response body must be bytes")
+    more = message.get("more_body", False)
+    no_body = self.head or self.status in (204, 304)
+    if not no_body:
+      self.sent_length += len(body)
+      if self.content_length is not None:
+        if self.sent_length > self.content_length or (not more and self.sent_length != self.content_length):
+          raise ASGIProtocolError("Response body does not match Content-Length")
+    if not more and not self.input.complete:
+      self.keep_alive = False
+    if not self.wire_started:
+      headers = list(self.headers)
+      if self.status == 204:
+        headers = [(n, v) for n, v in headers if n != b"content-length"]
+      elif self.content_length is None and not no_body:
+        if not more:
+          headers.append((b"content-length", str(len(body)).encode("ascii")))
+        elif self.scope["http_version"] == "1.1":
+          self.chunked = True
+          headers.append((b"transfer-encoding", b"chunked"))
         else:
-          self.body = body
-      if not message.get("more_body", False):
-        self.closed = True
-      return
-
-    raise ASGIProtocolError("Unsupported ASGI send message type: {}".format(typ))
-
-  def to_http(self, keep_alive):
-    if self.body_parts is None:
-      body = self.body
-    else:
-      body = b"".join(self.body_parts)
-    return _build_asgi_response(
-      self.status_line,
-      self.headers,
-      body,
-      self.date,
-      bool(keep_alive),
-      self.head_response,
-      self.has_content_length,
-      self.has_server,
-      self.has_date,
-      self.has_connection,
-    )
-
-
-def _normalize_header(header):
-  if not isinstance(header, (tuple, list)) or len(header) != 2:
-    raise ASGIProtocolError("ASGI headers must be two-item byte pairs")
-  name, value = header
-  if isinstance(name, str):
-    name = name.encode("latin-1")
-  if isinstance(value, str):
-    value = value.encode("latin-1")
-  if not isinstance(name, (bytes, bytearray, memoryview)):
-    raise ASGIProtocolError("ASGI header names must be bytes")
-  if not isinstance(value, (bytes, bytearray, memoryview)):
-    raise ASGIProtocolError("ASGI header values must be bytes")
-  name = bytes(name).lower()
-  value = bytes(value)
-  if b"\r" in name or b"\n" in name or b":" in name:
-    raise ASGIProtocolError("Invalid ASGI response header name")
-  if b"\r" in value or b"\n" in value:
-    raise ASGIProtocolError("Invalid ASGI response header value")
-  return name, value
+          self.keep_alive = False
+      names = {n for n, v in headers}
+      if self.protocol.server.request_id_header not in names:
+        headers.append((self.protocol.server.request_id_header, self.scope['request_id'].encode('ascii')))
+      if b"date" not in names:
+        headers.append((b"date", self.date))
+      if b"server" not in names:
+        headers.append((b"server", b"MrHTTP/0.13"))
+      if not self.keep_alive:
+        headers = [(n, v) for n, v in headers if n != b"connection"]
+        headers.append((b"connection", b"close"))
+      data = _status_line(self.scope["http_version"], self.status)
+      data += b"".join(n + b": " + v + b"\r\n" for n, v in headers) + b"\r\n"
+      self.wire_started = True
+      await self.protocol.write(data)
+    if not no_body and body:
+      data = (b"%x\r\n" % len(body) + body + b"\r\n") if self.chunked else body
+      await self.protocol.write(data)
+    if not more:
+      if self.chunked:
+        await self.protocol.write(b"0\r\n\r\n")
+      self.closed = True
+      self.input.finish()
 
 
 def _error_response(status, message):
@@ -237,56 +365,150 @@ class _LifespanConnection:
   async def send(self, message):
     await self.send_queue.put(message)
 
+  async def _message(self):
+    waiter = asyncio.create_task(self.send_queue.get())
+    try:
+      done, _ = await asyncio.wait((waiter, self.task), timeout=10,
+                                   return_when=asyncio.FIRST_COMPLETED)
+      if waiter in done:
+        return waiter.result()
+      if self.task in done:
+        self.task.result()
+        raise ASGIProtocolError("Lifespan application exited without a message")
+      raise TimeoutError("ASGI lifespan timed out")
+    finally:
+      waiter.cancel()
+      await asyncio.gather(waiter, return_exceptions=True)
+
+  async def cancel(self):
+    if self.task:
+      self.task.cancel()
+      done, _ = await asyncio.wait((self.task,), timeout=1)
+      if done:
+        await asyncio.gather(self.task, return_exceptions=True)
+      else:
+        logging.getLogger('mrhttp.error').error('Lifespan application ignored cancellation')
+
   async def startup(self):
     if self.mode == "off":
       return
-
-    scope = {
-      "type": "lifespan",
-      "asgi": {"version": "3.0", "spec_version": "2.0"},
-      "state": self.state,
-    }
+    scope = {"type": "lifespan", "asgi": {"version": "3.0", "spec_version": "2.0"},
+             "state": self.state}
     self.task = asyncio.create_task(self.app(scope, self.receive, self.send))
     await self.receive_queue.put({"type": "lifespan.startup"})
-
     try:
-      message = await asyncio.wait_for(self.send_queue.get(), timeout=10)
+      message = await self._message()
     except Exception:
-      if self.mode == "auto" and self.task.done():
-        try:
-          self.task.result()
-        except Exception:
-          return
+      unsupported = self.task.done()
+      await self.cancel()
+      if self.mode == "auto" and unsupported:
+        return
       raise
-
     typ = message.get("type")
-    if typ == "lifespan.startup.complete":
-      self.supported = True
-      return
-    if typ == "lifespan.startup.failed":
-      raise RuntimeError(message.get("message", "ASGI lifespan startup failed"))
-    raise ASGIProtocolError("Unexpected lifespan startup message: {}".format(typ))
+    if typ != "lifespan.startup.complete":
+      await self.cancel()
+      if typ == "lifespan.startup.failed":
+        raise RuntimeError(message.get("message", "ASGI lifespan startup failed"))
+      raise ASGIProtocolError("Unexpected lifespan startup message: {}".format(typ))
+    self.supported = True
 
   async def shutdown(self):
-    if not self.supported or not self.task:
+    if not self.supported:
+      await self.cancel()
       return
-    await self.receive_queue.put({"type": "lifespan.shutdown"})
-    message = await asyncio.wait_for(self.send_queue.get(), timeout=10)
-    typ = message.get("type")
-    if typ == "lifespan.shutdown.failed":
-      raise RuntimeError(message.get("message", "ASGI lifespan shutdown failed"))
-    if typ != "lifespan.shutdown.complete":
-      raise ASGIProtocolError("Unexpected lifespan shutdown message: {}".format(typ))
-    await self.task
+    try:
+      await self.receive_queue.put({"type": "lifespan.shutdown"})
+      message = await self._message()
+      typ = message.get("type")
+      if typ == "lifespan.shutdown.failed":
+        raise RuntimeError(message.get("message", "ASGI lifespan shutdown failed"))
+      if typ != "lifespan.shutdown.complete":
+        raise ASGIProtocolError("Unexpected lifespan shutdown message: {}".format(typ))
+      done, _ = await asyncio.wait((self.task,), timeout=10)
+      if not done:
+        raise TimeoutError('Lifespan application did not exit after shutdown')
+      self.task.result()
+    finally:
+      await self.cancel()
 
 
 class ASGIServer(mrhttp.CApp):
-  def __init__(self, asgi_app, *, lifespan="auto", root_path="", scheme="http"):
+  def __init__(self, asgi_app, *, lifespan="auto", root_path="", scheme="http",
+               max_body_size=16*1024*1024, max_header_size=65536, max_connections=1000,
+               timeout_request=30, timeout_keep_alive=5, timeout_graceful_shutdown=10,
+               read_buffer_size=65536, max_pipeline_requests=1024, proxy_headers=False,
+               forwarded_allow_ips="127.0.0.1,::1", access_log=False, access_log_format="text",
+               request_id_header="x-request-id", metrics_path=None, health_check_path=None,
+               ws_max_size=16*1024*1024, ws_max_queue=32, ws_ping_interval=20,
+               ws_ping_timeout=20, ws_close_timeout=5,
+               timeout_worker_healthcheck=5, timeout_worker_startup=30,
+               limit_max_requests=0, limit_max_requests_jitter=0, backlog=2048, factory=False):
+    if scheme not in ('http', 'https'):
+      raise ValueError('scheme must be http or https')
+    if not isinstance(root_path, str) or (root_path and not root_path.startswith('/')):
+      raise ValueError('root_path must be empty or an absolute path')
+    self._configuration = {key: value for key, value in locals().items() if key not in ('self', 'asgi_app', '__class__')}
+    self._app_path = None
     self._loop = None
     self._connections = set()
-    self._protocol_factory = Protocol
+    self._tasks = set()
+    self._server = None
+    self._socket_cleanup = None
+    self.draining = False
+    self.metrics = Metrics()
+    self.proxy_headers = proxy_headers
+    self.trusted_proxies = TrustedProxies(forwarded_allow_ips)
+    self.access_log = access_log
+    if access_log_format not in ('text', 'json'):
+      raise ValueError('access_log_format must be text or json')
+    self.access_log_format = access_log_format
+    self.request_id_header = request_id_header.lower().encode('ascii')
+    _normalize_header((self.request_id_header, b'valid'))
+    if self.request_id_header in (b'content-length', b'transfer-encoding', b'connection', b'upgrade', b'host', b'trailer', b'te', b'keep-alive', b'sec-websocket-accept', b'sec-websocket-protocol'):
+      raise ValueError('request_id_header cannot be a protocol framing header')
+    configure_access_log(access_log)
+    for name, path in (('metrics_path', metrics_path), ('health_check_path', health_check_path)):
+      if path is not None and (not isinstance(path, str) or not path.startswith('/')):
+        raise ValueError(name + ' must be an absolute URL path')
+      setattr(self, name, path)
+    if metrics_path is not None and metrics_path == health_check_path:
+      raise ValueError('Metrics and health paths must differ')
+    for name, value in (('read_buffer_size', read_buffer_size), ('max_pipeline_requests', max_pipeline_requests),
+                        ('ws_max_size', ws_max_size), ('ws_max_queue', ws_max_queue), ('backlog', backlog)):
+      if type(value) is not int or value < 1 or value > 1024*1024*1024:
+        raise ValueError(name + ' must be a positive bounded integer')
+      setattr(self, name, value)
+    if max_pipeline_requests > 1024:
+      raise ValueError('max_pipeline_requests cannot exceed 1024')
+    for name, value in (('ws_ping_interval', ws_ping_interval), ('ws_ping_timeout', ws_ping_timeout),
+                        ('ws_close_timeout', ws_close_timeout), ('timeout_worker_healthcheck', timeout_worker_healthcheck),
+                        ('timeout_worker_startup', timeout_worker_startup)):
+      if type(value) not in (int, float) or not math.isfinite(value) or value < 0 or (name != 'ws_ping_interval' and not value):
+        raise ValueError(name + ' must be a valid positive duration')
+      setattr(self, name, value)
+    for name, value in (('limit_max_requests', limit_max_requests), ('limit_max_requests_jitter', limit_max_requests_jitter)):
+      if type(value) is not int or value < 0:
+        raise ValueError(name + ' must be a nonnegative integer')
+      setattr(self, name, value)
+    self.completed_requests = 0
+    self._recycle_requested = False
+    self._worker_pipe = None
+    self._worker_heartbeat = None
+    if lifespan not in ("auto", "on", "off"):
+      raise ValueError("lifespan must be auto, on, or off")
+    for name, value in (("max_body_size", max_body_size), ("max_header_size", max_header_size),
+                        ("max_connections", max_connections)):
+      if type(value) is not int or not 0 < value <= 1024*1024*1024:
+        raise ValueError(name + " must be a positive integer no greater than 1 GiB")
+      setattr(self, name, value)
+    for name, value in (("timeout_request", timeout_request), ("timeout_keep_alive", timeout_keep_alive),
+                        ("timeout_graceful_shutdown", timeout_graceful_shutdown)):
+      if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
+        raise ValueError(name + " must be positive")
+      setattr(self, name, value)
+    self._protocol_factory = ASGIProtocol
     self._asgi_app = asgi_app
-    self._asgi_handle = self._handle_asgi
+    self._asgi_handle = self._run_asgi
     self._asgi_root_path = root_path
     self._asgi_scheme = scheme
     self._asgi_state = {}
@@ -304,7 +526,7 @@ class ASGIServer(mrhttp.CApp):
   @property
   def loop(self):
     if not self._loop:
-      self._loop = asyncio.new_event_loop()
+      self._loop = uvloop.new_event_loop()
       asyncio.set_event_loop(self._loop)
     return self._loop
 
@@ -322,31 +544,131 @@ class ASGIServer(mrhttp.CApp):
     self._date_handle = self.loop.call_later(1, self._update_date_header)
 
   async def drain(self):
-    idle, busy = self._get_idle_and_busy_connections()
-    for c in idle:
-      c.transport.close()
-    for _ in range(5):
-      if not busy:
-        return
-      await asyncio.sleep(1)
+    for connection in list(self._connections):
+      if connection.websocket and connection.websocket.accepted and not connection.websocket.close_sent:
+        try:
+          await connection.websocket.send({'type': 'websocket.close', 'code': 1001, 'reason': 'Server shutdown'})
+        except ASGIConnectionClosed:
+          pass
+    deadline = self.loop.time() + self.timeout_graceful_shutdown
+    while self._connections:
       idle, busy = self._get_idle_and_busy_connections()
-      for c in idle:
-        c.transport.close()
-    for c in busy:
-      c.pipeline_cancel()
+      for connection in idle:
+        connection.transport.close()
+      if not busy or self.loop.time() >= deadline:
+        break
+      await asyncio.sleep(0.05)
+    for connection in list(self._connections):
+      connection.pipeline_cancel()
+      connection.transport.close()
+    if self._tasks:
+      for task in list(self._tasks):
+        task.cancel()
+      await asyncio.wait(self._tasks, timeout=1)
+    await asyncio.sleep(0)
 
-  async def _handle_asgi(self, scope, body, keep_alive):
-    responder = _ASGIResponder(scope, body, self._date_header_value)
+  async def shutdown(self):
+    self.draining = True
+    listener, self._server = self._server, None
+    if listener:
+      listener.close()
     try:
-      await self._asgi_app(scope, responder.receive, responder.send)
-    except Exception:
-      if not responder.started:
-        return _error_response(500, "The ASGI application raised before starting a response.")
+      await self.drain()
+      if listener:
+        await listener.wait_closed()
+      lifespan, self._lifespan = self._lifespan, None
+      if lifespan:
+        await lifespan.shutdown()
+    finally:
+      if self._date_handle:
+        self._date_handle.cancel()
+        self._date_handle = None
+      if self._worker_heartbeat:
+        self._worker_heartbeat.cancel()
+      self.cshutdown()
+      cleanup_socket(self._socket_cleanup)
+      self._socket_cleanup = None
+      if self.requests:
+        for request in self.requests:
+          request.cleanup()
+        self.requests = None
+
+  async def start_server(self, host="127.0.0.1", port=8080, *, uds=None, fd=None):
+    sock, self._socket_cleanup = bind_socket(host, port, uds=uds, fd=fd, backlog=self.backlog)
+    try:
+      return await self.serve(sock=sock, host=host, port=port,
+                              loop=asyncio.get_running_loop(), run_async=True)
+    except BaseException:
+      sock.close()
+      await self.shutdown()
       raise
 
-    if not responder.started:
-      return _error_response(500, "The ASGI application completed without starting a response.")
-    return responder.to_http(bool(keep_alive))
+  async def _run_asgi(self, scope, stream, keep_alive, protocol):
+    async with protocol.response_lock:
+      if protocol.disconnected.is_set():
+        return
+      protocol.request_running(stream)
+      websocket = isinstance(stream, WebSocketSession)
+      responder = stream if websocket else _ASGIResponder(scope, stream, self._date_header_value, protocol)
+      responder.keep_alive = bool(keep_alive)
+      protocol.active_response = responder
+      started = self.loop.time()
+      self.metrics.active(1)
+      try:
+        if stream.reject_for_shutdown:
+          if websocket:
+            await stream.send({'type': 'websocket.close'})
+          else:
+            await responder.send({'type': 'http.response.start', 'status': 503})
+            await responder.send({'type': 'http.response.body', 'body': b'Service unavailable'})
+        elif not websocket and scope['path'] in (self.health_check_path, self.metrics_path):
+          is_metrics = scope['path'] == self.metrics_path
+          body = self.metrics.render() if is_metrics else b'ok'
+          await responder.send({'type': 'http.response.start', 'status': 200,
+                                'headers': [(b'content-type', b'text/plain; version=0.0.4' if is_metrics else b'text/plain')]})
+          await responder.send({'type': 'http.response.body', 'body': body})
+        else:
+          await self._asgi_app(scope, responder.receive, responder.send)
+        if protocol.disconnected.is_set():
+          if not responder.wire_started:
+            responder.status = 499
+          return
+        if websocket:
+          if not stream.closed and not stream.close_sent:
+            await stream.send({'type': 'websocket.close', 'code': 1000})
+        elif not responder.closed:
+          raise ASGIProtocolError('ASGI application returned without completing its response')
+      except ASGIConnectionClosed:
+        protocol.transport.close()
+      except asyncio.CancelledError:
+        raise
+      except Exception:
+        logging.getLogger('mrhttp.error').exception('ASGI application error request_id=%s', scope['request_id'])
+        if websocket and stream.accepted:
+          stream.fail(1011, 'Application error')
+        else:
+          if not responder.wire_started:
+            responder.status = 500
+            try:
+              await protocol.write(_error_response(500, 'Internal Server Error'))
+            except ASGIConnectionClosed:
+              pass
+          protocol.transport.close()
+      finally:
+        if not websocket:
+          stream.finish()
+        self.metrics.active(-1)
+        duration = self.loop.time() - started
+        self.metrics.completed(responder.status, responder.sent_length, duration)
+        if self.access_log:
+          access_record(scope, responder.status, responder.sent_length, duration, self.access_log_format)
+        protocol.active_response = None
+        self.completed_requests += 1
+        if self._worker_pipe and self.limit_max_requests and self.completed_requests >= self.limit_max_requests and not self._recycle_requested:
+          self._recycle_requested = True
+          self._worker_pipe.send('recycle')
+      if not websocket and (not responder.keep_alive or (self.draining and len(protocol.request_tasks) == 1)):
+        protocol.transport.close()
 
   def serve(self, *, sock, host, port, loop, run_async=False):
     if not loop:
@@ -355,6 +677,7 @@ class ASGIServer(mrhttp.CApp):
       self._loop = loop
       asyncio.set_event_loop(loop)
 
+    self.draining = False
     self.requests = [Request() for _ in range(128)]
     self.cinit()
     self._lifespan = _LifespanConnection(self._asgi_app, self._asgi_state, self._lifespan_mode)
@@ -362,72 +685,42 @@ class ASGIServer(mrhttp.CApp):
 
     async def start():
       await self._lifespan.startup()
-      return await loop.create_server(lambda: self._protocol_factory(self), sock=sock)
+      self._server = await loop.create_server(lambda: self._protocol_factory(self), sock=sock, backlog=self.backlog)
+      if self._worker_pipe:
+        self._worker_pipe.send('ready')
+        self._heartbeat()
+      return self._server
 
     if run_async:
       return start()
 
-    server = loop.run_until_complete(start())
-    print("Accepting ASGI connections on http://{}:{}".format(host, port))
-    loop.add_signal_handler(signal.SIGTERM, loop.stop)
-
     try:
+      loop.run_until_complete(start())
+      print("Accepting ASGI connections on http://{}:{}".format(host, port), flush=True)
+      loop.add_signal_handler(signal.SIGTERM, loop.stop)
+      loop.add_signal_handler(signal.SIGINT, loop.stop)
       loop.run_forever()
     except KeyboardInterrupt:
       pass
     finally:
-      try:
-        loop.run_until_complete(self._lifespan.shutdown())
-      finally:
-        if self._date_handle is not None:
-          self._date_handle.cancel()
-          self._date_handle = None
-        loop.run_until_complete(loop.shutdown_asyncgens())
-        loop.run_until_complete(self.drain())
-        self._connections.clear()
-        server.close()
-        loop.run_until_complete(server.wait_closed())
-        for r in self.requests:
-          r.cleanup()
-        self.requests = None
-        loop.close()
-
-  def _run(self, *, host, port, num_workers=None):
-    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-    sock.bind((host, port))
-    os.set_inheritable(sock.fileno(), True)
-
-    workers = set()
-    terminating = False
-
-    def stop(sig, frame):
-      nonlocal terminating
-      terminating = True
-      for worker in workers:
-        worker.terminate()
-
-    signal.signal(signal.SIGTERM, stop)
-
-    for _ in range(num_workers or 1):
-      worker = multiprocessing.Process(
-        target=self.serve,
-        kwargs=dict(sock=sock, host=host, port=port, loop=None),
-      )
-      worker.daemon = True
-      worker.start()
-      workers.add(worker)
-
-    sock.close()
-    for worker in workers:
-      try:
-        worker.join()
-      except KeyboardInterrupt:
-        if not terminating:
-          worker.terminate()
+      loop.run_until_complete(self.shutdown())
+      loop.run_until_complete(loop.shutdown_asyncgens())
+      loop.close()
+
+  def _heartbeat(self):
+    try:
+      self._worker_pipe.send('heartbeat')
+    except (OSError, EOFError):
+      self.loop.stop()
+      return
+    self._worker_heartbeat = self.loop.call_later(min(1, self.timeout_worker_healthcheck / 3), self._heartbeat)
+
+  def _run(self, *, host, port, num_workers=None, uds=None, fd=None):
+    from .supervisor import supervise
+    supervise(self, host, port, 1 if num_workers is None else num_workers, uds=uds, fd=fd)
 
-  def run(self, host="0.0.0.0", port=8080, *, workers=None):
-    self._run(host=host, port=port, num_workers=workers)
+  def run(self, host="0.0.0.0", port=8080, *, workers=None, uds=None, fd=None):
+    self._run(host=host, port=port, num_workers=workers, uds=uds, fd=fd)
 
 
 def import_from_string(value):
@@ -441,11 +734,12 @@ def import_from_string(value):
   return obj
 
 
-def run(app, host="0.0.0.0", port=8080, *, workers=None, cores=None, lifespan="auto", root_path="", scheme="http"):
+def run(app, host="0.0.0.0", port=8080, *, workers=None, cores=None, lifespan="auto", root_path="", scheme="http", uds=None, fd=None, **server_options):
   if cores is not None and workers is None:
     workers = cores
-  server = ASGIServer(app, lifespan=lifespan, root_path=root_path, scheme=scheme)
-  return server.run(host=host, port=port, workers=workers)
+  server = ASGIServer(None if isinstance(app, str) else app, lifespan=lifespan, root_path=root_path, scheme=scheme, **server_options)
+  server._app_path = app if isinstance(app, str) else None
+  return server.run(host=host, port=port, workers=workers, uds=uds, fd=fd)
 
 
 def main(argv=None):
@@ -456,10 +750,34 @@ def main(argv=None):
   parser.add_argument("--workers", type=int, default=1)
   parser.add_argument("--lifespan", choices=("auto", "on", "off"), default="auto")
   parser.add_argument("--root-path", default="")
-  parser.add_argument("--scheme", default="http")
-  args = parser.parse_args(argv)
-  app = import_from_string(args.app)
-  run(app, host=args.host, port=args.port, workers=args.workers, lifespan=args.lifespan, root_path=args.root_path, scheme=args.scheme)
+  parser.add_argument("--scheme", choices=("http", "https"), default="http")
+  binding = parser.add_mutually_exclusive_group()
+  binding.add_argument("--uds", "--unix", dest="uds")
+  binding.add_argument("--fd", type=int)
+  parser.add_argument("--factory", action="store_true")
+  parser.add_argument("--proxy-headers", action="store_true")
+  parser.add_argument("--forwarded-allow-ips", default="127.0.0.1,::1")
+  parser.add_argument("--access-log", action="store_true")
+  parser.add_argument("--access-log-format", choices=("text", "json"), default="text")
+  parser.add_argument("--log-level", choices=("debug", "info", "warning", "error", "critical"), default="info")
+  parser.add_argument("--request-id-header", default="x-request-id")
+  parser.add_argument("--metrics-path")
+  parser.add_argument("--health-check-path")
+  for name, default in (("max-body-size", 16*1024*1024), ("max-header-size", 65536),
+                         ("max-connections", 1000), ("read-buffer-size", 65536),
+                         ("max-pipeline-requests", 1024), ("ws-max-size", 16*1024*1024),
+                         ("ws-max-queue", 32), ("backlog", 2048), ("limit-max-requests", 0),
+                         ("limit-max-requests-jitter", 0)):
+    parser.add_argument("--" + name, type=int, default=default)
+  for name, default in (("timeout-request", 30), ("timeout-keep-alive", 5),
+                         ("timeout-graceful-shutdown", 10), ("timeout-worker-healthcheck", 5),
+                         ("timeout-worker-startup", 30), ("ws-ping-interval", 20),
+                         ("ws-ping-timeout", 20), ("ws-close-timeout", 5)):
+    parser.add_argument("--" + name, type=float, default=default)
+  options = vars(parser.parse_args(argv))
+  logging.basicConfig(level=options.pop('log_level').upper())
+  app = options.pop('app')
+  run(app, **options)
 
 
 if __name__ == "__main__":
diff --git a/src/mrhttp/exceptions.py b/src/mrhttp/exceptions.py
new file mode 100644
index 0000000..eed28eb
--- /dev/null
+++ b/src/mrhttp/exceptions.py
@@ -0,0 +1,6 @@
+class ASGIConnectionClosed(OSError):
+  """The peer or server has closed this ASGI connection."""
+
+
+class ASGIProtocolError(RuntimeError):
+  """An application sent an invalid ASGI event."""
diff --git a/src/mrhttp/headers.py b/src/mrhttp/headers.py
new file mode 100644
index 0000000..b7bd65e
--- /dev/null
+++ b/src/mrhttp/headers.py
@@ -0,0 +1,18 @@
+import re
+from .exceptions import ASGIProtocolError
+
+_HEADER_NAME = re.compile(rb"[!#$%&'*+.^_`|~0-9a-z-]+\Z")
+
+
+def _normalize_header(header):
+  if not isinstance(header, (tuple, list)) or len(header) != 2:
+    raise ASGIProtocolError("ASGI headers must be two-item byte pairs")
+  name, value = header
+  if not isinstance(name, bytes) or not isinstance(value, bytes):
+    raise ASGIProtocolError("ASGI header names and values must be bytes")
+  name = name.lower()
+  if not _HEADER_NAME.fullmatch(name):
+    raise ASGIProtocolError("Invalid ASGI response header name")
+  if any(c < 32 and c != 9 or c == 127 for c in value):
+    raise ASGIProtocolError("Invalid ASGI response header value")
+  return name, value
diff --git a/src/mrhttp/internals/app.c b/src/mrhttp/internals/app.c
index cc8a9d0..b97ec02 100644
--- a/src/mrhttp/internals/app.c
+++ b/src/mrhttp/internals/app.c
@@ -3,6 +3,7 @@
 #include <Python.h>
 #include <stdbool.h>
 #include <math.h>
+#include <limits.h>
 
 #include "request.h"
 #include "common.h"
@@ -19,8 +20,27 @@ PyObject *MrhttpApp_new(PyTypeObject* type, PyObject *args, PyObject *kwargs) {
 }
 
 
-void MrhttpApp_dealloc(MrhttpApp* self) {
-  Py_XDECREF( self->check_interval ); 
+PyObject *MrhttpApp_cshutdown(MrhttpApp *self) {
+  if(self->check_idle_handle) {
+    PyObject *r=PyObject_CallMethod(self->check_idle_handle,"cancel",NULL);
+    if(!r) return NULL;
+    Py_DECREF(r);
+  }
+  Py_CLEAR(self->check_idle_handle);
+  Py_CLEAR(self->check_idle);
+  Py_CLEAR(self->check_interval);
+  Py_CLEAR(self->call_later);
+  Py_CLEAR(self->func_expand_requests);
+  Py_CLEAR(self->requests);
+  Py_CLEAR(self->connections);
+  Py_CLEAR(self->loop);
+  Py_CLEAR(self->err400);
+  Py_CLEAR(self->err404);
+  Py_RETURN_NONE;
+}
+
+void MrhttpApp_dealloc(MrhttpApp *self) {
+  Py_XDECREF(self->check_interval);
   Py_TYPE(self)->tp_free((PyObject*)self);
 }
 
@@ -30,8 +50,13 @@ int MrhttpApp_init(MrhttpApp* self, PyObject *args, PyObject *kwargs) {
 
 PyObject *MrhttpApp_cinit(MrhttpApp* self) {
   srand(time(0)); // TODO seed utils.randint
-  self->requests  = PyObject_GetAttrString((PyObject*)self, "requests");
+  self->requests = PyObject_GetAttrString((PyObject*)self, "requests");
+  if(!self->requests) return NULL;
   int l = PyList_Size(self->requests);
+  if(l<=0) {
+    if(!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError,"Request pool cannot be empty");
+    return NULL;
+  }
 
   self->numRequests = l;
   self->nextRequest = 0;
@@ -48,7 +73,8 @@ PyObject *MrhttpApp_cinit(MrhttpApp* self) {
 
   if(!(self->check_idle = PyObject_GetAttrString((PyObject*)self, "check_idle"))) goto error;
   self->check_interval = PyLong_FromLong(5);
-  self->check_idle_handle = PyObject_CallFunctionObjArgs( self->call_later, self->check_interval, self->check_idle, NULL);
+  if(!PyObject_HasAttrString((PyObject*)self, "_asgi_handle"))
+    self->check_idle_handle = PyObject_CallFunctionObjArgs(self->call_later, self->check_interval, self->check_idle, NULL);
 
   self->func_expand_requests = PyObject_GetAttrString((PyObject*)self, "expand_requests");
 
@@ -71,12 +97,8 @@ error:
 }
 
 void MrhttpApp_release_request(MrhttpApp* self, Request *r) {
-  if ( !(r->inprog) ) {
-    Request *z = r+10000;
-    z->inprog = false;
-  } else {
-    self->freeRequests++;
-  }
+  if (!r || !r->inprog) return;
+  self->freeRequests++;
   r->inprog = false;
   Request_reset(r);
   //self->numReleases++;
@@ -100,55 +122,34 @@ void MrhttpApp_release_request(MrhttpApp* self, Request *r) {
  */ 
 }
 
-void MrhttpApp_double_requests(MrhttpApp* self) {
-  PyObject *ret = PyObject_CallFunctionObjArgs(self->func_expand_requests, NULL);
-    
-  if ( ret == NULL ) { // TODO?
-    printf("ret null\n");
-    exit(1);
+PyObject *MrhttpApp_get_request(MrhttpApp *self) {
+  if(!self->requests || !PyList_Check(self->requests) || !self->numRequests) {
+    PyErr_SetString(PyExc_RuntimeError,"Request pool is not initialized");
+    return NULL;
   }
-  self->freeRequests += self->numRequests;
-  self->nextRequest = self->numRequests;
-  self->numRequests *= 2;
-  //printf("dbl req list sz %d num %d\n", PyList_GET_SIZE(self->requests), self->numRequests);
-}
-
-PyObject *MrhttpApp_get_request(MrhttpApp* self) {
-  Request *r = (Request*)PyList_GET_ITEM( self->requests, self->nextRequest );
-  //printf("get %p\n", r);
-  self->freeRequests--;
-  //self->numGets++;
-  DBG printf(" get request index %d\n", self->nextRequest ); 
-
-  // If we wrap and hit an in progress request double the number of requests and 
-  // start at the new ones. 
-  if ( r->inprog ) {
-    //printf("get req free %d num %d\n", self->freeRequests, self->numRequests); 
-    // Double the number of requests if necessary
-    if ( self->freeRequests < 10 ) {
-      MrhttpApp_double_requests(self);
-    }
-    // Loop until found a free request
-    int cnt;
-redo:
-    cnt = 0;
-    while (r->inprog) {
-      cnt++; 
-      if ( cnt > self->numRequests ) { 
-        //printf("ARGH %d > %d free %d!\n", cnt, self->numRequests,self->freeRequests); 
-        break; 
-      }
-      self->nextRequest = (self->nextRequest+1)%self->numRequests;
-      r = (Request*)PyList_GET_ITEM( self->requests, self->nextRequest );
-    }
-    if ( cnt > self->numRequests ) {
-      MrhttpApp_double_requests(self);
-      goto redo;
+  for(int count=0;count<self->numRequests;count++) {
+    int index=self->nextRequest;
+    self->nextRequest=(index+1)%self->numRequests;
+    Request *request=(Request*)PyList_GET_ITEM(self->requests,index);
+    if(!request->inprog) {
+      request->inprog=true;
+      self->freeRequests--;
+      return (PyObject*)request;
     }
   }
-  r->inprog = true;
-  self->nextRequest = (self->nextRequest+1)%self->numRequests;
-  return (PyObject*)r;
+  int old_size=self->numRequests;
+  PyObject *expanded=PyObject_CallFunctionObjArgs(self->func_expand_requests,NULL);
+  if(!expanded) return NULL;
+  Py_DECREF(expanded);
+  Py_ssize_t new_size=PyList_GET_SIZE(self->requests);
+  if(new_size<=old_size || new_size>INT_MAX) {
+    PyErr_SetString(PyExc_RuntimeError,"Request pool expansion failed");
+    return NULL;
+  }
+  self->numRequests=new_size;
+  self->freeRequests+=new_size-old_size;
+  self->nextRequest=old_size;
+  return MrhttpApp_get_request(self);
 }
 
 PyObject *MrhttpApp_updateDate(MrhttpApp *self, PyObject *date) {
@@ -219,6 +220,7 @@ void MrhttpApp_setup_error_pages(MrhttpApp* self) {
 
   self->err404 = PyBytes_FromStringAndSize( resp, (p-resp) + l );
   free(resp);
+  Py_DECREF(u);
   u = PyObject_GetAttrString((PyObject*)self, "err400");
   if ( !u ) return;
 
@@ -231,6 +233,7 @@ void MrhttpApp_setup_error_pages(MrhttpApp* self) {
 
   self->err400 = PyBytes_FromStringAndSize( resp, (p-resp) + l );
   free(resp);
+  Py_DECREF(u);
  
 }
 
diff --git a/src/mrhttp/internals/app.h b/src/mrhttp/internals/app.h
index 016acc5..115f4be 100644
--- a/src/mrhttp/internals/app.h
+++ b/src/mrhttp/internals/app.h
@@ -56,6 +56,7 @@ int       MrhttpApp_init   (MrhttpApp* self,    PyObject *args, PyObject *kwargs
 void      MrhttpApp_dealloc(MrhttpApp* self);
 
 PyObject *MrhttpApp_cinit(MrhttpApp* self);
+PyObject *MrhttpApp_cshutdown(MrhttpApp* self);
 
 void MrhttpApp_release_request(MrhttpApp* self, Request *r);
 PyObject *MrhttpApp_get_request(MrhttpApp* self);
diff --git a/src/mrhttp/internals/memprotocol.c b/src/mrhttp/internals/memprotocol.c
index 64721a8..0e76e6a 100644
--- a/src/mrhttp/internals/memprotocol.c
+++ b/src/mrhttp/internals/memprotocol.c
@@ -175,7 +175,7 @@ int MemcachedProtocol_asyncGet( MemcachedProtocol* self, char *key, void *fn, vo
   PyObject *bytes = PyBytes_FromString(self->get_cmd);
 
   // Queue up a callback for the response
-  self->queue[self->queue_end].cb = (tSessionCallback*)fn;
+  self->queue[self->queue_end].cb = (tSessionCallback)fn;
   self->queue[self->queue_end].connection = connection;
   self->queue_end = (self->queue_end+1)%self->queue_sz;
 
diff --git a/src/mrhttp/internals/module.h b/src/mrhttp/internals/module.h
index 9ff50d1..4c62be6 100644
--- a/src/mrhttp/internals/module.h
+++ b/src/mrhttp/internals/module.h
@@ -63,11 +63,12 @@ static PyMethodDef Protocol_methods[] = {
   {"connection_lost", (PyCFunction)Protocol_connection_lost, METH_VARARGS, ""},
   {"eof_received",    (PyCFunction)Protocol_eof_received,    METH_NOARGS,  ""},
   {"data_received",   (PyCFunction)Protocol_data_received,   METH_O,       ""},
-  {"pipeline_cancel", (PyCFunction)Protocol_pipeline_cancel, METH_NOARGS,  ""},
+  {"pipeline_cancel", (PyCFunction)Protocol_pipeline_cancel_method, METH_NOARGS,  ""},
   {"task_done",       (PyCFunction)protocol_task_done,       METH_O,       ""},
   {NULL}
 };
 static PyGetSetDef Protocol_getset[] = {
+  {"request_incomplete", (getter)Protocol_get_request_incomplete, NULL, "", NULL},
   {"pipeline_empty", (getter)Protocol_get_pipeline_empty, NULL, "", NULL},
   {"transport", (getter)Protocol_get_transport, NULL, "", NULL},
   {NULL}
@@ -79,6 +80,7 @@ static PyMethodDef Router_methods[] = {
   {NULL}
 };
 static PyMethodDef MrhttpApp_methods[] = {
+  {"cshutdown", (PyCFunction)MrhttpApp_cshutdown, METH_NOARGS, "Release server resources"},
   {"cinit",      (PyCFunction)MrhttpApp_cinit,       METH_NOARGS,  ""},
   {"updateDate", (PyCFunction)MrhttpApp_updateDate,  METH_O,       ""},
   {"check_idle", (PyCFunction)MrhttpApp_check_idle,  METH_NOARGS,  ""},
@@ -335,7 +337,7 @@ static PyTypeObject ProtocolType = {
   0,                         /* tp_getattro */
   0,                         /* tp_setattro */
   0,                         /* tp_as_buffer */
-  Py_TPFLAGS_DEFAULT,        /* tp_flags */
+  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,        /* tp_flags */
   "Protocol",                /* tp_doc */
   0,                         /* tp_traverse */
   0,                         /* tp_clear */
diff --git a/src/mrhttp/internals/mrcacheprotocol.c b/src/mrhttp/internals/mrcacheprotocol.c
index efa5ae5..8f5e284 100644
--- a/src/mrhttp/internals/mrcacheprotocol.c
+++ b/src/mrhttp/internals/mrcacheprotocol.c
@@ -185,7 +185,7 @@ int MrcacheProtocol_asyncGet( MrcacheProtocol* self, char *key, void *fn, void *
   PyObject *bytes = PyBytes_FromStringAndSize(self->get_cmd,36);
 
   // Queue up a callback for the response
-  self->queue[self->queue_end].cb = (tSessionCallback*)fn;
+  self->queue[self->queue_end].cb = (tSessionCallback)fn;
   self->queue[self->queue_end].connection = connection;
   self->queue_end = (self->queue_end+1)%self->queue_sz;
 
diff --git a/src/mrhttp/internals/mrqprotocol.c b/src/mrhttp/internals/mrqprotocol.c
index e3adba8..44a3de7 100644
--- a/src/mrhttp/internals/mrqprotocol.c
+++ b/src/mrhttp/internals/mrqprotocol.c
@@ -271,7 +271,7 @@ int MrqProtocol_getSession(MrqProtocol* self, char *key, void *fn, void *connect
   dsz = 32;
 
   // Queue up a callback for the response
-  self->queue[self->queue_end].cb = (tSessionCallback*)fn;
+  self->queue[self->queue_end].cb = (tSessionCallback)fn;
   self->queue[self->queue_end].connection = connection;
   self->queue_end = (self->queue_end+1)%self->queue_sz;
 
diff --git a/src/mrhttp/internals/mrqprotocol.h b/src/mrhttp/internals/mrqprotocol.h
index 2a056f0..73c0dd9 100644
--- a/src/mrhttp/internals/mrqprotocol.h
+++ b/src/mrhttp/internals/mrqprotocol.h
@@ -8,7 +8,7 @@ typedef void (*tSessionCallback)(void*, char*, int);
 //typedef void (*tMrqCallback)(void*);
 typedef struct {
   void *connection;
-  tSessionCallback *cb;
+  tSessionCallback cb;
 } MrqRequest;
 
 typedef struct {
diff --git a/src/mrhttp/internals/parser.c b/src/mrhttp/internals/parser.c
index cdebe6d..2ac1199 100644
--- a/src/mrhttp/internals/parser.c
+++ b/src/mrhttp/internals/parser.c
@@ -1,316 +1,347 @@
-
-
+#include <ctype.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
 #include <strings.h>
-#include <sys/param.h>
-#include <immintrin.h>
-
-#include "parser.h"
-#include "common.h"
 #include "module.h"
+#include "parser.h"
 #include "unpack.h"
-//#include "cpu_features.h"
-
-//#include "protocol.h"
-#include "faststrcmp.h"
-//int fast_compare(const unsigned char *s1, const unsigned char *s2, size_t len)
 
-// DELME
-static void print_buffer( char* b, int len ) {
-  for ( int z = 0; z < len; z++ ) {
-    printf( "%02x ",(int)b[z]);
+/* All reads are bounded by end. Incomplete messages remain intact so the next
+ * callback can reparse them, including headers and chunk framing. */
+static char *crlf(char *p, char *end) {
+  while (end - p >= 2) {
+    if (p[0] == '\r' && p[1] == '\n') return p;
+    p++;
   }
-  printf("\n");
+  return NULL;
 }
-
-static inline bool _isdigit(char c)  { return  c >= '0'  && c <= '9'; }
-static long my_strtol( char* s, int maxlen ) {
-  long l = 0;
-  int n = 0;
-  while (_isdigit(*s)) {
-
-    l = (l * 10) + (*s++ - '0');
-    n += 1;
-    if ( n >= maxlen ) return l;
+static int token(unsigned char c) {
+  return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
+    (c >= 'a' && c <= 'z') || (c && strchr("!#$%&'*+-.^_`|~", c) != NULL);
+}
+static int eq(const char *s, size_t n, const char *value) {
+  return n == strlen(value) && strncasecmp(s, value, n) == 0;
+}
+static int has_token(const char *s, size_t n, const char *value) {
+  const char *end = s + n;
+  while (s < end) {
+    while (s < end && (*s == ' ' || *s == '\t' || *s == ',')) s++;
+    const char *p = s;
+    while (s < end && *s != ',') s++;
+    const char *e = s;
+    while (e > p && (e[-1] == ' ' || e[-1] == '\t')) e--;
+    if (eq(p, e-p, value)) return 1;
+  }
+  return 0;
+}
+static int decimal(const char *s, size_t n, size_t limit, size_t *out) {
+  size_t v = 0;
+  if (!n) return 0;
+  for (size_t i=0; i<n; i++) {
+    if (s[i] < '0' || s[i] > '9') return 0;
+    size_t d = s[i]-'0';
+    if (d > limit || v > (limit-d)/10) return 0;
+    v = v*10+d;
   }
-  return l;
+  *out = v;
+  return 1;
 }
-
-static int scan_chunked(char *buf, size_t len, size_t *consumed_len) {
-  char *src = buf;
-  char *end = buf + len;
-
-  while (1) {
-    size_t chunk_len = 0;
-    int saw_digit = 0;
-
-    while (src < end) {
-      char c = *src;
-      if (c >= '0' && c <= '9') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - '0');
-        saw_digit = 1;
-        src++;
-      } else if (c >= 'a' && c <= 'f') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - 'a' + 10);
-        saw_digit = 1;
-        src++;
-      } else if (c >= 'A' && c <= 'F') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - 'A' + 10);
-        saw_digit = 1;
-        src++;
-      } else {
-        break;
-      }
-    }
-
-    if (!saw_digit) return -1;
-
-    while (src < end && *src != '\r') {
-      src++;
+static int hex(unsigned char c) {
+  if (c >= '0' && c <= '9') return c-'0';
+  if (c >= 'a' && c <= 'f') return c-'a'+10;
+  if (c >= 'A' && c <= 'F') return c-'A'+10;
+  return -1;
+}
+static int chunks(char *start, char *end, size_t limit, size_t *consumed,
+                  size_t *decoded, int decode) {
+  char *p=start, *dst=start;
+  size_t total=0;
+  for (;;) {
+    char *line=crlf(p,end);
+    if (!line) return end-p > 8192 ? -1 : -2;
+    size_t len=0;
+    char *q=p;
+    while (q<line && hex(*q)>=0) {
+      int digit=hex(*q++);
+      if ((size_t)digit > limit || len > (limit-digit)/16) return -1;
+      len=len*16+digit;
     }
-    if ((end - src) < 2) return -2;
-    if (src[0] != '\r' || src[1] != '\n') return -1;
-    src += 2;
-
-    if (chunk_len == 0) {
-      while (1) {
-        if ((end - src) < 2) return -2;
-        if (src[0] == '\r' && src[1] == '\n') {
-          src += 2;
-          *consumed_len = (size_t)(src - buf);
-          return 1;
-        }
-        while (src < end && *src != '\r') {
-          src++;
+    if (q==p || (q<line && *q!=';')) return -1;
+    for (;q<line;q++) if ((unsigned char)*q<32 || (unsigned char)*q==127) return -1;
+    p=line+2;
+    if (!len) {
+      char *trailers=p;
+      for (;;) {
+        line=crlf(p,end);
+        if (!line) return end-trailers > 65536 ? -1 : -2;
+        if (line-trailers > 65536) return -1;
+        if (line==p) {
+          *consumed=line+2-start; *decoded=total; return 1;
         }
-        if ((end - src) < 2) return -2;
-        if (src[0] != '\r' || src[1] != '\n') return -1;
-        src += 2;
+        q=p;
+        while(q<line && token(*q)) q++;
+        if(q==p || q==line || *q!=':') return -1;
+        for(q++;q<line;q++) if (((unsigned char)*q<32 && *q!='\t') || (unsigned char)*q==127) return -1;
+        p=line+2;
       }
     }
-
-    if ((size_t)(end - src) < chunk_len + 2) return -2;
-    src += chunk_len;
-    if (src[0] != '\r' || src[1] != '\n') return -1;
-    src += 2;
+    if (len>limit-total) return -1;
+    if ((size_t)(end-p)<len || (size_t)(end-p)-len<2) return -2;
+    if (p[len]!='\r' || p[len+1]!='\n') return -1;
+    if(decode) { memmove(dst,p,len); dst+=len; }
+    total+=len; p+=len+2;
   }
 }
 
-static int decode_chunked_inplace(char *buf, size_t len, size_t *decoded_len, size_t *consumed_len) {
-  int scan_rc = scan_chunked(buf, len, consumed_len);
-  if (scan_rc <= 0) return scan_rc;
-
-  char *src = buf;
-  char *dst = buf;
-  char *end = buf + *consumed_len;
-
-  while (src < end) {
-    size_t chunk_len = 0;
-    while (src < end) {
-      char c = *src;
-      if (c >= '0' && c <= '9') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - '0');
-      } else if (c >= 'a' && c <= 'f') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - 'a' + 10);
-      } else if (c >= 'A' && c <= 'F') {
-        chunk_len = (chunk_len << 4) + (size_t)(c - 'A' + 10);
-      } else {
-        break;
-      }
-      src++;
+/* ASGI bodies are delivered incrementally; the legacy router still receives
+ * a complete, owned request. The native buffer never owns an ASGI upload. */
+static int deliver(Parser *self, char *data, size_t length, int more) {
+  PyObject *body=PyBytes_FromStringAndSize(data,length);
+  if(!body) return -1;
+  PyObject *result=PyObject_CallMethod(self->stream,"feed","OO",body,more ? Py_True : Py_False);
+  Py_DECREF(body);
+  if(!result) return -1;
+  int ready=PyObject_IsTrue(result);
+  Py_DECREF(result);
+  return ready<0 ? -1 : ready ? 1 : 2;
+}
+static int stream_body(Parser *self) {
+  for(;;) {
+    size_t available=self->end-self->start;
+    if(self->stream_stage==6) {
+      if(!available) return -2;
+      int rc=deliver(self,self->start,available,1);
+      self->start=self->end;
+      return rc;
     }
-    while (src < end && *src != '\r') src++;
-    src += 2;
-    if (chunk_len == 0) {
-      *decoded_len = (size_t)(dst - buf);
-      return 1;
+    if(self->stream_stage==1 || self->stream_stage==3) {
+      if(!self->stream_remaining) {
+        if(self->stream_stage==3) { self->stream_stage=4; continue; }
+        int rc=deliver(self,"",0,0);
+        Py_CLEAR(self->stream); self->stream_stage=0;
+        if(self->stream_close) self->start=self->end;
+        return rc;
+      }
+      if(!available) return -2;
+      size_t length=self->stream_remaining<available ? self->stream_remaining : available;
+      if(length>16384) length=16384;
+      self->start+=length; self->stream_remaining-=length;
+      self->stream_decoded+=length;
+      int more=self->stream_chunked || self->stream_remaining!=0;
+      int rc=deliver(self,self->start-length,length,more);
+      if(!more) {
+        Py_CLEAR(self->stream); self->stream_stage=0;
+        if(self->stream_close) self->start=self->end;
+      }
+      if(rc!=1 || !self->stream_stage) return rc;
+    } else if(self->stream_stage==2) {
+      char *line=crlf(self->start,self->end);
+      if(!line) return available>8192 ? -1 : -2;
+      if(line-self->start>8192) return -1;
+      size_t length=0;
+      char *p=self->start;
+      while(p<line && hex(*p)>=0) {
+        size_t digit=hex(*p++);
+        if(digit>self->max_body_size || length>(self->max_body_size-digit)/16) return -1;
+        length=length*16+digit;
+      }
+      if(p==self->start || (p<line && *p!=';')) return -1;
+      for(;p<line;p++) if((unsigned char)*p<32 || (unsigned char)*p==127) return -1;
+      if(length>self->max_body_size-self->stream_decoded) return -1;
+      self->stream_remaining=length;
+      self->start=line+2;
+      self->stream_stage=length ? 3 : 5;
+    } else if(self->stream_stage==4) {
+      if(available<2) return -2;
+      if(memcmp(self->start,"\r\n",2)) return -1;
+      self->start+=2; self->stream_stage=2;
+    } else if(self->stream_stage==5) {
+      char *line=crlf(self->start,self->end);
+      if(!line) return available+self->trailer_bytes>self->max_header_size ? -1 : -2;
+      self->trailer_bytes+=line+2-self->start;
+      if(self->trailer_bytes>self->max_header_size) return -1;
+      if(line==self->start) {
+        self->start=line+2;
+        int rc=deliver(self,"",0,0);
+        Py_CLEAR(self->stream); self->stream_stage=0;
+        if(self->stream_close) self->start=self->end;
+        return rc;
+      }
+      char *p=self->start;
+      while(p<line && token(*p)) p++;
+      if(p==self->start || p==line || *p!=':') return -1;
+      for(p++;p<line;p++) if(((unsigned char)*p<32 && *p!='\t') || (unsigned char)*p==127) return -1;
+      self->start=line+2;
     }
-    memmove(dst, src, chunk_len);
-    dst += chunk_len;
-    src += chunk_len + 2;
-  }
-
-  return -1;
-}
-
-static void _reset(Parser* self, bool reset_buffer) {
-  self->body_length = 0;
-  if ( reset_buffer ) {
-    self->start = self->buf;
-    self->end = self->buf;
   }
 }
 
-
 int parser_init(Parser *self, void *protocol) {
-  DBG printf("parser_init\n");
-  self->protocol = protocol;
-  self->buf = malloc(8096); self->buf_size = 8096;
-  if ( !self->buf ) return 0;
-  _reset(self, true);
-
-  return 1;
-}
-
-// TODO Check we don't exceed a max request size.  Nginx does this for us though
-//      Sanic:  app.config.REQUEST_MAX_SIZE = 300_000_000
-int parser_data_received(Parser *self, PyObject *py_data, Request *request ) {
-  DBG printf("parser data\n");
-  char* data;
-  Py_ssize_t datalen;
-  size_t i;
-
-  if(PyBytes_AsStringAndSize(py_data, &data, &datalen) == -1) {
-    DBG printf("WARNING py bytes as string failed\n");
-    goto error;
-  }
-  DBG_PARSER printf("parser data\n%.*s\n",(int)datalen, data);
-
-  // If we need more space increase the size of the buffer
-  DBG_PARSER printf("parser datalen %zu buflen %ld buffer size %d\n", datalen, (self->end-self->start), self->buf_size);
-  if ( unlikely( (datalen+(self->end-self->start)) > self->buf_size) ) {
-    while ( (datalen+(self->end-self->start)) > self->buf_size )  self->buf_size *= 2;
-    int l = (self->end - self->buf);
-    self->buf = realloc( self->buf, self->buf_size );
-    self->end = self->buf + l;
-    self->start = self->buf;
-    DBG printf("Increasing buffer size %d end %p st %p\n", self->buf_size, self->end, self->start);
+  self->protocol=protocol;
+  self->buf_size=8096;
+  self->buf=malloc(self->buf_size);
+  self->start=self->end=self->buf;
+  self->body_length=0;
+  self->expect_sent=false;
+  self->max_body_size=16*1024*1024;
+  self->max_header_size=65536;
+  PyObject *app=(PyObject*)((Protocol*)protocol)->app;
+  const char *names[]={"max_body_size","max_header_size"};
+  size_t *limits[]={&self->max_body_size,&self->max_header_size};
+  for(int i=0;i<2;i++) {
+    PyObject *v=PyObject_GetAttrString(app,names[i]);
+    if(!v) { PyErr_Clear(); continue; }
+    size_t n=PyLong_AsSize_t(v); Py_DECREF(v);
+    if(PyErr_Occurred()) return 0;
+    *limits[i]=n;
   }
-  DBG_PARSER printf("buf    data\n%.*s\n",(int)(self->end-self->buf), self->buf);
-
-  DBG_PARSER printf("parser data startptr %p endptr %p dataptr %p\n",self->start, self->end, data);
-  memcpy(self->end, data, (size_t)datalen);
-  self->end += (size_t)datalen;
-
-parse_headers:
-
-  if (0) {}  
-
-  char *method, *path;
-  int rc, minor_version;
-  size_t method_len, path_len;
-  bool chunked = false;
-  size_t consumed_body_length = 0;
-
-  request->num_headers = 100; // Max allowed headers
-  DBG_PARSER printf("before parser requests\n");
-  //request->hreq.flags = 0; // TODO This isn't currently used in the parser
-  rc = mr_parse_request(self->start, self->end-self->start, (const char**)&method, &method_len, (const char**)&path, &path_len, &minor_version, request->headers, &(request->num_headers), &(request->hreq));
-
-  DBG_PARSER printf("parser requests rc %d\n",rc);
-  if ( rc < 0 ) return rc; // -2 incomplete, -1 error otherwise byte len of headers
+  return self->buf!=NULL;
+}
 
-  self->start += rc; 
-  
-  DBG_PARSER printf("request is %d bytes long\n", rc);
-  DBG_PARSER printf("method is %.*s\n", (int)method_len, method);
-  DBG_PARSER printf("path is %.*s\n", (int)path_len, path);
-  DBG_PARSER printf("HTTP version is 1.%d\n", minor_version);
-  DBG_PARSER printf("headers:\n");
-  DBG_PARSER for (i = 0; i != request->num_headers; ++i) {
-    printf("%.*s: %.*s\n", (int)request->headers[i].name_len, request->headers[i].name, (int)request->headers[i].value_len, request->headers[i].value);
+int parser_data_received(Parser *self, PyObject *py_data, Request *unused) {
+  char *data; Py_ssize_t datalen;
+  if(PyBytes_AsStringAndSize(py_data,&data,&datalen)<0) return -1;
+  if(((Protocol*)self->protocol)->asgi_handle && self->stream_close && !self->stream_stage) return 1;
+  size_t pending=self->end-self->start;
+  size_t max_buffer=((Protocol*)self->protocol)->asgi_handle ? self->max_header_size+1024*1024 : self->max_body_size+self->max_header_size+65536;
+  if ((size_t)datalen>max_buffer || pending>max_buffer-(size_t)datalen) return -1;
+  if(self->start!=self->buf) memmove(self->buf,self->start,pending);
+  self->start=self->buf; self->end=self->buf+pending;
+  size_t needed=pending+(size_t)datalen;
+  if(needed>(size_t)self->buf_size) {
+    size_t cap=self->buf_size;
+    while(cap<needed) cap=cap>max_buffer/2 ? max_buffer : cap*2;
+    char *newbuf=realloc(self->buf,cap);
+    if(!newbuf) { PyErr_NoMemory(); return -1; }
+    self->buf=newbuf; self->buf_size=cap;
+    self->start=newbuf; self->end=newbuf+pending;
   }
-
-  if(minor_version == 0) request->keep_alive = false;
-  else                   request->keep_alive = true;
- 
-  //self->body_length = request->hreq.body_length;
-
-#define name_compare(val) \
-  header->name_len == strlen(val) && fast_compare(header->name, val, header->name_len) == 0
-#define value_compare(val) \
-  header->value_len == strlen(val) && fast_compare(header->value, val, header->value_len) == 0
-
- for(struct mr_header* header = request->headers;
-      header < request->headers + request->num_headers;
-      header++) {
-
-    if(name_compare("Content-Type")) {
-      if ( header->value[0] == 'a' && header->value_len == 20 ) { //"application/mrpacker"
-        request->hreq.flags = 2;
-      } 
+  memcpy(self->end,data,datalen); self->end+=datalen;
+  Protocol *protocol=self->protocol;
+  while((self->start<self->end || self->stream_stage) && !protocol->closed) {
+    if(self->stream_stage) {
+      int rc=stream_body(self);
+      if(rc!=1) return rc;
+      continue;
     }
-    if(name_compare("Content-Length")) {
-      self->body_length = my_strtol(header->value, header->value_len);
-
-      // TODO If the request is too large.  I think we already checked
-
-      // Check for a bad 0 length - ie non digits for the length
-      if ( self->body_length == 0 && !( header->value_len == 1 && *(header->value) == '0') ) { 
-        goto error;
+    Request *request=protocol->request;
+    char *begin=self->start, *line=crlf(begin,self->end);
+    if(!line) return (size_t)(self->end-begin)>self->max_header_size ? -1 : -2;
+    char *method=begin, *p=begin;
+    while(p<line && token(*p)) p++;
+    size_t ml=p-method;
+    if(!ml || p==line || *p++!=' ') return -1;
+    char *path=p;
+    while(p<line && *p!=' ') {
+      if((unsigned char)*p<=32 || (unsigned char)*p==127) return -1;
+      p++;
+    }
+    size_t pl=p-path;
+    if(!pl || p==line || *p++!=' ' || line-p!=8) return -1;
+    int minor;
+    if(!memcmp(p,"HTTP/1.1",8)) minor=1;
+    else if(!memcmp(p,"HTTP/1.0",8)) minor=0;
+    else return -1;
+    if(path[0]!='/' && !(ml==7 && !memcmp(method,"OPTIONS",7) && pl==1 && *path=='*')) return -1;
+    p=line+2;
+    size_t nh=0, length=0;
+    int cl=0, te=0, host=0, expect=0, upgrade=0;
+    bool keep_alive=minor==1;
+    for(;;) {
+      line=crlf(p,self->end);
+      if(!line) return (size_t)(self->end-begin)>self->max_header_size ? -1 : -2;
+      if((size_t)(line+2-begin)>self->max_header_size) return -1;
+      if(line==p) { p+=2; break; }
+      if(nh>=100) return -1;
+      char *name=p;
+      while(p<line && token(*p)) p++;
+      size_t nl=p-name;
+      if(!nl || p==line || *p++!=':') return -1;
+      while(p<line && (*p==' ' || *p=='\t')) p++;
+      char *value=p, *value_end=line;
+      while(value_end>value && (value_end[-1]==' ' || value_end[-1]=='\t')) value_end--;
+      size_t vl=value_end-value;
+      for(;p<line;p++) if(((unsigned char)*p<32 && *p!='\t') || (unsigned char)*p==127) return -1;
+      request->headers[nh++]=(struct mr_header){.name=name,.name_len=nl,.value=value,.value_len=vl};
+      if(eq(name,nl,"content-length")) {
+        if(cl++ || !decimal(value,vl,self->max_body_size,&length)) return -1;
+      } else if(eq(name,nl,"transfer-encoding")) {
+        if(te++ || !eq(value,vl,"chunked") || !minor) return -1;
+      } else if(eq(name,nl,"upgrade") && eq(value,vl,"websocket")) {
+        upgrade=1;
+      } else if(eq(name,nl,"host")) {
+        if(host++ || !vl) return -1;
+      } else if(eq(name,nl,"connection")) {
+        if(has_token(value,vl,"close")) keep_alive=false;
+      } else if(eq(name,nl,"expect")) {
+        if(!eq(value,vl,"100-continue")) return -1;
+        expect=1;
       }
-
-    } else if(name_compare("Connection")) {
-      if      (value_compare("close"))      request->keep_alive = false;
-    } else if(name_compare("Transfer-Encoding")) {
-      if (header->value_len == 7 && strncasecmp(header->value, "chunked", 7) == 0) chunked = true;
+      p=line+2;
     }
-  } 
-
-  if(!Protocol_on_headers( self->protocol, method, method_len, path, path_len, minor_version, request->headers, request->num_headers)) goto error; 
-
-//body:
-
-  DBG_PARSER printf("body:\n%.*s\n", (int)(self->end-self->start),self->start);
-
-  if (chunked) {
-    size_t decoded_len = 0;
-    int chunked_rc = decode_chunked_inplace(self->start, self->end - self->start, &decoded_len, &consumed_body_length);
-    if (chunked_rc == -2) return -2;
-    if (chunked_rc < 0) goto error;
-    self->body_length = decoded_len;
-  } else {
-    consumed_body_length = self->body_length;
-  }
-
-  // Need more data
-  if ( consumed_body_length > ( self->end - self->start ) ) {
-    while ( (self->body_length+(self->end-self->start)) > self->buf_size )  self->buf_size *= 2;
-    int l = (self->end - self->buf);
-    self->buf = realloc( self->buf, self->buf_size );
-    self->end = self->buf + l;
-    self->start = self->buf;
-    DBG printf("Increasing buffer size %d end %p st %p\n", self->buf_size, self->end, self->start);
-    return -2;
-  }
-
-  if ( request->hreq.flags == 2 ) {
-    // TODO how to handle errors.  Have unpackc not do a python error? Or clear py error if null...  Return negative? 
-    request->py_mrpack = unpackc( self->start, self->body_length ); 
-    if ( request->py_mrpack == NULL ) {
-      printf("WARNING unpackc returned null in parser\n");
-      printf("WARNING data len %ld\n",self->body_length);
-      print_buffer(self->start, 16);
-      return -1;
+    if((minor && !host) || (cl && te)) return -1;
+    if(protocol->asgi_handle) {
+      if(upgrade && (!minor || ml!=3 || memcmp(method,"GET",3) || te || length)) return -1;
+      PyObject *raw=PyBytes_FromStringAndSize(begin,p-begin);
+      if(!raw) return -1;
+      char *copy=PyBytes_AS_STRING(raw);
+      for(size_t i=0;i<nh;i++) {
+        request->headers[i].name=copy+(request->headers[i].name-begin);
+        request->headers[i].value=copy+(request->headers[i].value-begin);
+      }
+      Py_XSETREF(request->raw_request,raw);
+      request->num_headers=nh; request->keep_alive=keep_alive;
+      if(!Protocol_on_headers(protocol,copy+(method-begin),ml,copy+(path-begin),pl,minor,request->headers,nh)) return -1;
+      self->start=p;
+      self->stream=Protocol_dispatch_asgi_headers(protocol,request);
+      Request_reset(request);
+      if(!self->stream) return -1;
+      self->stream_stage=upgrade ? 6 : te ? 2 : 1;
+      self->stream_remaining=length; self->stream_decoded=0; self->trailer_bytes=0;
+      self->stream_close=!keep_alive; self->stream_chunked=te;
+      continue;
     }
-
-  }
-
-  if(!Protocol_on_body(self->protocol, self->start, self->body_length)) return -1;
-
-  self->start += consumed_body_length; 
-
-  // If we still have data start parsing the next request
-  if ( self->start < self->end ) {
-    _reset(self, false);
-    goto parse_headers;
+    if(expect && !self->expect_sent && (te || length)) {
+      PyObject *b=PyBytes_FromString("HTTP/1.1 100 Continue\r\n\r\n");
+      if(!b) return -1;
+      PyObject *r=PyObject_CallFunctionObjArgs(protocol->write,b,NULL); Py_DECREF(b);
+      if(!r) return -1;
+      Py_DECREF(r); self->expect_sent=true;
+    }
+    size_t consumed=length, decoded=length;
+    if(te) {
+      int rc=chunks(p,self->end,self->max_body_size,&consumed,&decoded,0);
+      if(rc<0) return rc;
+      if(chunks(p,p+consumed,self->max_body_size,&consumed,&decoded,1)<0) return -1;
+    } else if((size_t)(self->end-p)<length) return -2;
+    /* Own request bytes across asynchronous handlers and future buffer growth. */
+    PyObject *raw=PyBytes_FromStringAndSize(begin,p+consumed-begin);
+    if(!raw) return -1;
+    char *copy=PyBytes_AS_STRING(raw);
+    for(size_t i=0;i<nh;i++) {
+      request->headers[i].name=copy+(request->headers[i].name-begin);
+      request->headers[i].value=copy+(request->headers[i].value-begin);
+    }
+    Py_XSETREF(request->raw_request,raw);
+    request->num_headers=nh; request->keep_alive=keep_alive;
+    if(!Protocol_on_headers(protocol,copy+(method-begin),ml,copy+(path-begin),pl,minor,request->headers,nh)) return -1;
+    self->start=p+consumed;
+    self->expect_sent=false;
+    if(!protocol->asgi_handle) {
+      for(size_t i=0;i<nh;i++) {
+        struct mr_header *h=request->headers+i;
+        if(eq(h->name,h->name_len,"content-type") && eq(h->value,h->value_len,"application/mrpacker")) {
+          request->py_mrpack=unpackc(copy+(p-begin),decoded);
+          if(!request->py_mrpack) return -1;
+        }
+      }
+    }
+    if(!Protocol_on_body(protocol,copy+(p-begin),decoded)) return -1;
+    if(!keep_alive) { self->start=self->end; break; }
   }
-  _reset(self, true);
-  
-// TODO CHUNKED body.  NGINX will never do chunked.
-  
-
-
-
+  if(self->start==self->end) self->start=self->end=self->buf;
   return 1;
-
-error:
-  DBG printf("ERROR in data recvd\n");
-  //if(!Protocol_on_error(self->protocol, error)) goto error;
-  return 0;
-}
-
-void parser_dealloc(Parser* self)
-{
-  //if(self->buffer != self->inline_buffer) free(self->buffer);
-  free(self->buf);
 }
+Parser* parser_disconnect(Parser *self) { Py_CLEAR(self->stream); self->stream_stage=0; return self; }
+void parser_dealloc(Parser *self) { parser_disconnect(self); free(self->buf); self->buf=NULL; }
diff --git a/src/mrhttp/internals/parser.h b/src/mrhttp/internals/parser.h
index d7db4d9..42d1b06 100644
--- a/src/mrhttp/internals/parser.h
+++ b/src/mrhttp/internals/parser.h
@@ -13,7 +13,13 @@ typedef struct {
   size_t chunked_offset;
 
   char *buf, *buf_end, *start, *end;
-  int buf_size;
+  size_t buf_size;
+  size_t max_body_size, max_header_size;
+  bool expect_sent;
+  int stream_stage;
+  size_t stream_remaining, stream_decoded, trailer_bytes;
+  bool stream_close, stream_chunked;
+  PyObject *stream;
 
   void* protocol;
 
diff --git a/src/mrhttp/internals/protocol.c b/src/mrhttp/internals/protocol.c
index 9778b56..592a1ef 100644
--- a/src/mrhttp/internals/protocol.c
+++ b/src/mrhttp/internals/protocol.c
@@ -46,6 +46,9 @@ PyObject * Protocol_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   self = (Protocol*)type->tp_alloc(type, 0);
   if(!self) goto finally;
 
+  self->queue_capacity = 64;
+  self->queue = PyMem_Calloc(self->queue_capacity, sizeof(PipelineRequest));
+  if(!self->queue) { Py_DECREF(self); return PyErr_NoMemory(); }
   self->app = NULL;
   self->transport = NULL;
   self->write = NULL;
@@ -77,11 +80,12 @@ void Protocol_dealloc(Protocol* self)
 {
   DBG printf("procotol dealloc\n");
   parser_dealloc(&self->parser);
+  PyMem_Free(self->queue);
   //Py_XDECREF(self->request);
   //Py_XDECREF(self->response);
   Py_XDECREF(self->router);
   Py_XDECREF(self->app);
-  //Py_XDECREF(self->transport);
+  Py_XDECREF(self->transport);
   Py_XDECREF(self->write);
   Py_XDECREF(self->writelines);
   Py_XDECREF(self->asgi_handle);
@@ -104,7 +108,8 @@ int Protocol_init(Protocol* self, PyObject *args, PyObject *kw)
   if(!PyArg_ParseTuple(args, "O", &self->app)) return -1;
   Py_INCREF(self->app);
 
-  self->request = (Request*)MrhttpApp_get_request( self->app );
+  self->request = (Request*)MrhttpApp_get_request(self->app);
+  if(!self->request) return -1;
   //if(!(self->request  = (Request*) PyObject_GetAttrString((PyObject*)self->app, "request" ))) return -1;
   //if(!(self->response = (Response*)PyObject_GetAttrString((PyObject*)self->app, "response"))) return -1;
   if(!(self->asgi_handle = PyObject_GetAttrString((PyObject*)self->app, "_asgi_handle"))) {
@@ -144,29 +149,12 @@ int Protocol_init(Protocol* self, PyObject *args, PyObject *kw)
   return 0;
 }
 
-// copied from Modules/socketmodule.h
-// TODO uvloop 0.9+ returns their own socket here
-typedef int SOCKET_T;
-typedef struct {
-    PyObject_HEAD
-    int sock_family;            /* Address family, e.g., AF_INET */
-    int sock_type;              /* Socket type, e.g., SOCK_STREAM */
-    int sock_proto;             /* Protocol type, usually 0 */
-    SOCKET_T sock_fd;           /* Socket file descriptor */
-    PyObject *(*errorhandler)(void); /* Error handler; checks
-                                        errno, returns NULL and
-                                        sets a Python exception */
-    _PyTime_t sock_timeout;     /* Operation timeout in seconds;
-                                        0.0 means non-blocking */
-} PySocketSockObject;
-
-
-
 PyObject* Protocol_connection_made(Protocol* self, PyObject* transport)
 {
 
   DBG printf("conn made %p\n",self);
-  self->transport = transport;
+  Py_INCREF(transport);
+  Py_XSETREF(self->transport, transport);
   self->closed = false;
 
   if(!(self->write      = PyObject_GetAttrString(transport, "write"))) return NULL;
@@ -207,11 +195,16 @@ PyObject* Protocol_connection_lost(Protocol* self, PyObject* args)
 {
   DBG printf("conn lost %p\n",self);
   self->closed = true;
-  MrhttpApp_release_request( self->app, self->request );
+  parser_disconnect(&self->parser);
+  MrhttpApp_release_request(self->app, self->request);
 
   PyObject* connections = NULL;
 
-  if(!Protocol_pipeline_cancel(self)) return NULL;
+  if(!self->asgi_handle && !Protocol_pipeline_cancel(self)) return NULL;
+  Py_CLEAR(self->task_done);
+  Py_CLEAR(self->create_task);
+  Py_CLEAR(self->write);
+  Py_CLEAR(self->writelines);
 
   Py_RETURN_NONE;
 }
@@ -221,8 +214,17 @@ PyObject* Protocol_data_received(Protocol* self, PyObject* data)
   self->num_data_received++;
   DBG printf("protocol data recvd %zu\n", Py_SIZE(data));
 
+  if(self->closed) Py_RETURN_NONE;
   if(parser_data_received(&self->parser, data, self->request) == -1) {
-    return protocol_write_error_response_bytes(self, self->app->err400);
+    PyErr_Clear();
+    if(self->asgi_handle) {
+      PyObject *result=PyObject_CallMethod((PyObject*)self,"parser_error",NULL);
+      if(!result) return NULL;
+      Py_DECREF(result);
+    } else {
+      if(!protocol_write_error_response_bytes(self,self->app->err400)) return NULL;
+      if(!Protocol_close(self)) return NULL;
+    }
   }
 
   Py_RETURN_NONE;
@@ -238,8 +240,31 @@ PyObject* pipeline_queue(Protocol* self, PipelineRequest r)
     self->queue_start = self->queue_end = 0;
   }
   
-  assert(self->queue_end < sizeof(self->queue) / sizeof(self->queue[0]));
+  if(self->queue_start) {
+    size_t pending = self->queue_end - self->queue_start;
+    memmove(self->queue, self->queue + self->queue_start, pending * sizeof(self->queue[0]));
+    self->queue_start = 0;
+    self->queue_end = pending;
+  }
+  if(self->queue_end == self->queue_capacity) {
+    if(self->queue_capacity >= 1024) {
+      PyErr_SetString(PyExc_OverflowError, "HTTP pipeline capacity exceeded");
+      return NULL;
+    }
+    size_t capacity = self->queue_capacity * 2;
+    PipelineRequest *queue = PyMem_Realloc(self->queue, capacity * sizeof(*queue));
+    if(!queue) return PyErr_NoMemory();
+    self->queue = queue;
+    self->queue_capacity = capacity;
+  }
   
+  size_t request_bytes = r.request->raw_request ? (size_t)PyBytes_GET_SIZE(r.request->raw_request) : 0;
+  size_t limit = self->parser.max_body_size + self->parser.max_header_size + 65536;
+  if(request_bytes > limit || self->queue_bytes > limit - request_bytes) {
+    PyErr_SetString(PyExc_OverflowError, "HTTP pipeline byte limit exceeded");
+    return NULL;
+  }
+  self->queue_bytes += request_bytes;
   PipelineRequest* end = self->queue + self->queue_end;
   *end = r;
   pipeline_INCREF(r);
@@ -263,11 +288,15 @@ PyObject* pipeline_queue(Protocol* self, PipelineRequest r)
   
   goto finally;
   
-error: 
+error:
+  self->queue_end--;
+  self->queue_bytes -= request_bytes;
+  pipeline_DECREF(r);
   result = NULL;
   
 finally:
   Py_XDECREF(add_done_callback);
+  Py_XINCREF(result);
   return result;
 } 
 
@@ -375,8 +404,8 @@ void Protocol_on_memcached_reply( SessionCallbackData *scd, char *data, int data
     Route *r = req->route;
     if ( r->mrq || r->mrq2 ) { 
       MrqClient *py_mrq;
-      if ( r->mrq ) py_mrq = self->app->py_mrq;
-      if ( r->mrq2) py_mrq = self->app->py_mrq2;
+      if ( r->mrq ) py_mrq = (MrqClient*)self->app->py_mrq;
+      if ( r->mrq2) py_mrq = (MrqClient*)self->app->py_mrq2;
       int slot = 0;
 
       // Pull slot from the first arg. Must be a number though a string won't break
@@ -471,27 +500,6 @@ void Protocol_on_memcached_reply( SessionCallbackData *scd, char *data, int data
   Py_DECREF(self); 
 }
 
-static inline bool request_header_name_eq(struct mr_header* header, const char* name) {
-  size_t name_len = strlen(name);
-  return header->name_len == name_len && strncasecmp(header->name, name, name_len) == 0;
-}
-
-static inline bool request_header_value_eq(struct mr_header* header, const char* value) {
-  size_t value_len = strlen(value);
-  return header->value_len == value_len && strncasecmp(header->value, value, value_len) == 0;
-}
-
-static bool request_is_websocket_upgrade(Request* request) {
-  for(struct mr_header* header = request->headers;
-      header < request->headers + request->num_headers;
-      header++) {
-    if(request_header_name_eq(header, "Upgrade") && request_header_value_eq(header, "websocket")) {
-      return true;
-    }
-  }
-  return false;
-}
-
 static PyObject* protocol_get_extra_info(Protocol* self, const char* name) {
   PyObject* get_extra_info = NULL;
   PyObject* py_name = NULL;
@@ -599,7 +607,7 @@ static PyObject* protocol_build_asgi_scope(Protocol* self, Request* request) {
   }
 
   request_decodePath(request);
-  if(dict_set_steal(scope, "path", PyUnicode_FromStringAndSize(request->path, request->path_len)) == -1) goto error;
+  if(dict_set_steal(scope, "path", PyUnicode_DecodeUTF8(request->path, request->path_len, "replace")) == -1) goto error;
 
   if(PyDict_SetItemString(scope, "root_path", self->asgi_root_path) == -1) goto error;
   if(PyDict_SetItemString(scope, "scheme", self->asgi_scheme) == -1) goto error;
@@ -628,73 +636,19 @@ error:
   return NULL;
 }
 
-Protocol* Protocol_handle_asgi_request(Protocol* self, Request* request) {
-  PyObject* scope = NULL;
-  PyObject* body = NULL;
-  PyObject* keep_alive = NULL;
-  PyObject* coro = NULL;
-  PyObject* task = NULL;
-  PyObject* ret = NULL;
-  static PyObject* empty_body = NULL;
-
-  if(request_is_websocket_upgrade(request)) {
-    PyObject* bytes = response_getErrorResponse(
-      501,
-      "Not Implemented",
-      "WebSocket ASGI is not implemented by this mrhttp build."
-    );
-    if(!bytes) return NULL;
-    Protocol* result = protocol_write_raw_response(self, request, bytes);
-    Py_DECREF(bytes);
-    return result;
-  }
-
-  if(self->request == request) {
-    self->request = (Request*)MrhttpApp_get_request(self->app);
-  }
-
-  if(!(scope = protocol_build_asgi_scope(self, request))) goto error;
-  if(request->body_len) {
-    if(!(body = PyBytes_FromStringAndSize(request->body, request->body_len))) goto error;
-  } else {
-    if(!empty_body && !(empty_body = PyBytes_FromStringAndSize("", 0))) goto error;
-    body = empty_body;
-    Py_INCREF(body);
-  }
-  keep_alive = request->keep_alive ? Py_True : Py_False;
-  Py_INCREF(keep_alive);
-
-  if(!(coro = PyObject_CallFunctionObjArgs(self->asgi_handle, scope, body, keep_alive, NULL))) goto error;
-  if(!(task = PyObject_CallFunctionObjArgs(self->create_task, coro, NULL))) goto error;
-
-  if(!(ret = pipeline_queue(self, (PipelineRequest){true, -1, request, task}))) goto error;
-
-  Py_DECREF(ret);
-  Py_DECREF(task);
-  Py_DECREF(coro);
-  Py_DECREF(keep_alive);
-  Py_DECREF(body);
+PyObject* Protocol_dispatch_asgi_headers(Protocol *self, Request *request) {
+  PyObject *scope=protocol_build_asgi_scope(self,request);
+  if(!scope) return NULL;
+  PyObject *stream=PyObject_CallMethod((PyObject*)self,"request_started","OO",
+                                     scope,request->keep_alive ? Py_True : Py_False);
   Py_DECREF(scope);
-  return self;
+  return stream;
+}
 
-error:
-  Py_XDECREF(ret);
-  Py_XDECREF(task);
-  Py_XDECREF(coro);
-  Py_XDECREF(keep_alive);
-  Py_XDECREF(body);
-  Py_XDECREF(scope);
-  PyErr_Print();
-
-  PyObject* bytes = response_getErrorResponse(
-    500,
-    "Internal Server Error",
-    "The ASGI server failed before the application could produce a response."
-  );
-  if(!bytes) return NULL;
-  Protocol* result = protocol_write_raw_response(self, request, bytes);
-  Py_DECREF(bytes);
-  return result;
+PyObject* Protocol_get_request_incomplete(Protocol *self) {
+  if(self->parser.stream_stage && self->parser.stream_stage!=6) Py_RETURN_TRUE;
+  if(self->parser.start<self->parser.end && self->parser.stream_stage!=6) Py_RETURN_TRUE;
+  Py_RETURN_FALSE;
 }
 
 Protocol* Protocol_on_body(Protocol* self, char* body, size_t body_len) {
@@ -708,10 +662,6 @@ Protocol* Protocol_on_body(Protocol* self, char* body, size_t body_len) {
   request->transport = self->transport;
   request->app = (PyObject*)self->app; //TODO need this?
 
-  if ( self->asgi_handle ) {
-    return Protocol_handle_asgi_request(self, request);
-  }
-
   // URL:  /  /json 
   Route *r = router_getRoute( self->router, self->request );
   if ( r == NULL ) {
@@ -773,8 +723,8 @@ Protocol* Protocol_on_body(Protocol* self, char* body, size_t body_len) {
   }
   if ( r->mrq || r->mrq2 ) { 
     MrqClient *py_mrq;
-    if ( r->mrq ) py_mrq = self->app->py_mrq;
-    if ( r->mrq2) py_mrq = self->app->py_mrq2;
+    if ( r->mrq ) py_mrq = (MrqClient*)self->app->py_mrq;
+    if ( r->mrq2) py_mrq = (MrqClient*)self->app->py_mrq2;
     DBG printf("Route uses mrq\n"); 
     int slot = 0;
     // Pull slot from the first arg. Must be a number
@@ -889,12 +839,15 @@ Protocol* Protocol_handle_request(Protocol* self, Request* request, Route* r) {
     Py_XDECREF(task);
     Py_DECREF(result);
     if ( !ret ) return NULL;
+    Py_DECREF(ret);
     return self;
   }
 
   if(!PIPELINE_EMPTY(self))
   {
-    if(!pipeline_queue(self, (PipelineRequest){false, r->mtype, request, result})) goto error;
+    PyObject *queued = pipeline_queue(self, (PipelineRequest){false, r->mtype, request, result});
+    if(!queued) goto error;
+    Py_DECREF(queued);
     Py_DECREF(result);
     return self;
   }
@@ -997,22 +950,6 @@ static inline Protocol* protocol_write_response(Protocol* self, Request *req, Py
   return self;
 }
 
-static inline Protocol* protocol_write_raw_response(Protocol* self, Request *req, PyObject *resp) {
-  if ( !resp || !PyBytes_Check(resp) ) return NULL;
-
-  PyObject *o;
-  if(!(o = PyObject_CallFunctionObjArgs(self->write, resp, NULL))) return NULL;
-  Py_DECREF(o);
-
-  if ( !req->keep_alive && !self->closed ) {
-    Protocol_close(self);
-  }
-
-  if ( req != self->request ) MrhttpApp_release_request( self->app, req );
-  else                        Request_reset(req);
-  return self;
-}
-
 static inline Protocol* protocol_write_redirect_response(Protocol* self, int code, char *url ) {
   PyObject *bytes = response_getRedirectResponse( code, url );
   if ( !bytes ) return NULL;
@@ -1073,6 +1010,7 @@ static void* protocol_pipeline_ready(Protocol* self, PipelineRequest r)
       PyErr_Fetch(&type, &value, &traceback);
       Py_XDECREF(traceback);
       Py_XDECREF(type);
+      type = NULL;
       if (value) {
 
         // Check for HTTPError ( if it has _message it is HTTPError )
@@ -1101,9 +1039,7 @@ static void* protocol_pipeline_ready(Protocol* self, PipelineRequest r)
       }
       PyErr_Clear();
 
-      printf("Unhandled exception in coro page handler:\n");
-      PyObject_Print( type, stdout, 0 ); printf("\n");
-      PyObject_Print( value, stdout, 0 ); printf("\n");
+      printf("Unhandled exception in coroutine page handler\n");
  
       self->num_requests_popped++; 
       if ( request != self->request ) MrhttpApp_release_request( self->app, request );
@@ -1117,21 +1053,6 @@ static void* protocol_pipeline_ready(Protocol* self, PipelineRequest r)
   }
   self->num_requests_popped++; 
 
-  if ( r.mtype == -1 ) {
-    if ( !PyBytes_Check(response) ) {
-      if ( request != self->request ) MrhttpApp_release_request( self->app, request );
-      protocol_write_error_response(self, 500,"Internal Server Error","The ASGI application did not return a raw HTTP response.");
-      return NULL;
-    }
-    if(!self->closed) {
-      if(!protocol_write_raw_response(self, request, response)) goto error;
-    } else {
-      DBG printf("Connection closed, ASGI response dropped prot %p\n",self);
-      if ( request != self->request ) MrhttpApp_release_request( self->app, request );
-    }
-    goto finally;
-  }
-
   //if ( PyBytes_Check( response ) ) {
     //response = PyUnicode_FromEncodedObject( response, "utf-8", "strict" );
     //printf("WARNING: Page handler should return a string. Bytes object returned from the page handler is being converted to unicode using utf-8\n");
@@ -1206,6 +1127,7 @@ PyObject* protocol_task_done(Protocol* self, PyObject* task)
       }
     } else {
     }
+    if(r->request->raw_request) self->queue_bytes -= (size_t)PyBytes_GET_SIZE(r->request->raw_request);
     if(!protocol_pipeline_ready(self, *r)) goto loop_error;
 
     pipeline_DECREF(*r);
@@ -1271,6 +1193,11 @@ void* Protocol_pipeline_cancel(Protocol* self)
   return result;
 }
 
+PyObject* Protocol_pipeline_cancel_method(Protocol *self) {
+  if(!Protocol_pipeline_cancel(self)) return NULL;
+  Py_RETURN_NONE;
+}
+
 PyObject* Protocol_get_pipeline_empty(Protocol* self)
 {
   if(PIPELINE_EMPTY(self)) {
diff --git a/src/mrhttp/internals/protocol.h b/src/mrhttp/internals/protocol.h
index b1b8fe6..4f0b184 100644
--- a/src/mrhttp/internals/protocol.h
+++ b/src/mrhttp/internals/protocol.h
@@ -28,8 +28,8 @@ struct Protocol {
   PyObject* writelines;
   double start_time;
 
-  // ASGI mode.  When asgi_handle is set the parser dispatches requests to
-  // app._asgi_handle(scope, body, keep_alive) instead of the mrhttp router.
+  // ASGI mode caches scope metadata. The native parser dispatches headers
+  // to protocol.request_started() and decoded chunks to its input stream.
   PyObject* asgi_handle;
   PyObject* asgi_root_path;
   PyObject* asgi_scheme;
@@ -41,7 +41,9 @@ struct Protocol {
   // Async Pipeline
   PyObject* create_task;
   PyObject* task_done; 
-  PipelineRequest queue[50];
+  PipelineRequest *queue;
+  size_t queue_capacity;
+  size_t queue_bytes;
   size_t queue_start;
   size_t queue_end;
 
@@ -84,12 +86,12 @@ Protocol* Protocol_on_body(Protocol* self, char* body, size_t body_len);
 Protocol* Protocol_on_error(Protocol* self, PyObject*);
 
 Protocol* Protocol_handle_request(Protocol* self, Request* request, Route* r);
-Protocol* Protocol_handle_asgi_request(Protocol* self, Request* request);
+PyObject* Protocol_dispatch_asgi_headers(Protocol* self, Request* request);
+PyObject* Protocol_get_request_incomplete(Protocol* self);
 void Protocol_timeout_request(Protocol* self);
 
 
 static inline Protocol* protocol_write_response(Protocol* self, Request *req, PyObject* resp);
-static inline Protocol* protocol_write_raw_response(Protocol* self, Request *req, PyObject* resp);
 static inline Protocol* protocol_write_redirect_response(Protocol* self, int code, char *url);
 static inline Protocol* protocol_write_error_response_bytes( Protocol* self, PyObject* bytes );
 static inline Protocol* protocol_write_error_response      ( Protocol* self, int code, char *reason, char *msg);
@@ -108,6 +110,7 @@ static inline void reverse(char* begin, char* end)
 
 PyObject* protocol_task_done(Protocol* self, PyObject* task);
 void* Protocol_pipeline_cancel(Protocol* self);
+PyObject* Protocol_pipeline_cancel_method(Protocol* self);
 
 static inline bool pipeline_is_task(PipelineRequest r)
 {
@@ -117,7 +120,7 @@ static inline bool pipeline_is_task(PipelineRequest r)
 static inline void pipeline_DECREF(PipelineRequest r)
 {
     Py_DECREF(r.request);
-    if(r.is_task) Py_XDECREF(r.task);
+    Py_XDECREF(r.task);
 }
 
 static inline void pipeline_INCREF(PipelineRequest r)
diff --git a/src/mrhttp/internals/request.c b/src/mrhttp/internals/request.c
index c8989ed..ed74f6d 100644
--- a/src/mrhttp/internals/request.c
+++ b/src/mrhttp/internals/request.c
@@ -89,7 +89,7 @@ void Request_dealloc(Request* self) {
   Py_XDECREF(self->py_files);
   Py_XDECREF(self->py_mrq_servers_down);
   Py_XDECREF(self->response);
-  Py_XDECREF(self->set_user);
+  Py_XDECREF(self->raw_request);
   Py_TYPE(self)->tp_free((PyObject*)self);
 }
 
@@ -97,7 +97,8 @@ void Request_dealloc(Request* self) {
 int Request_init(Request* self, PyObject *args, PyObject* kw)
 {
   //self->hreq.headers = malloc( sizeof(*(self->hreq.headers))*100 ); //TODO
-  self->headers = malloc( sizeof(*(self->headers))*100 ); //TODO
+  self->headers = malloc(sizeof(*(self->headers))*100);
+  if(!self->headers) { PyErr_NoMemory(); return -1; }
   if(!(self->response = (Response*)PyObject_GetAttrString((PyObject*)self, "response"))) return -1;
   if(!(self->set_user = PyObject_GetAttrString((PyObject*)self, "set_user"))) return -1;
   Request_reset(self);
@@ -108,7 +109,7 @@ int Request_init(Request* self, PyObject *args, PyObject* kw)
 
 // This only resets stuff that needs to be for reuse
 void Request_reset(Request *self) {
-  //self->inprog = false;
+  Py_CLEAR(self->raw_request);
   self->session_id = NULL;
   Py_XDECREF(self->py_headers); self->py_headers = NULL;
   Py_XDECREF(self->py_body);   self->py_body = NULL;
@@ -164,73 +165,27 @@ PyObject* Request_get_transport(Request* self, void* closure) {
   Py_RETURN_NONE;
 }
 
-static inline int path_decode(char* buf, int len, int *qs_len) {
-  unsigned long msk;
-  int i=0,tz; // 32B index
-  int cnt = 0;
-  unsigned int shifted;
-  char *sbuf = buf;
-  char *obuf = buf;
-  char *buf_end = buf+len;
-  char *wbuf;
-  int found = 0;
-
-  __m256i m37 = _mm256_set1_epi8(37);
-  __m256i m63 = _mm256_set1_epi8(63);
-
-  do {
-    const char *block_start = obuf+64*i;
-    __m256i b0 = _mm256_loadu_si256((const __m256i *) block_start);
-    __m256i b1 = _mm256_loadu_si256((const __m256i *) (block_start+32));
-    msk = (unsigned int) _mm256_movemask_epi8( _mm256_or_si256(_mm256_cmpeq_epi8(b0, m37), _mm256_cmpeq_epi8(b0, m63) ) )  |
-        ((unsigned long) _mm256_movemask_epi8( _mm256_or_si256(_mm256_cmpeq_epi8(b1, m37), _mm256_cmpeq_epi8(b1, m63) ) ) << 32);
-
-    while (1) {
-
-      //if ( buf >= buf_end ) { goto decdone; }
-      shifted = buf-block_start;
-      if ( shifted >= 64 ) break;
-      tz = TZCNT((msk >> shifted));
-      if ( tz < 64 ) {
-        buf += tz;
-        //printf( " fnd >%.*s<\n", (int)(buf-sbuf), sbuf );  
-        if ( buf >= buf_end ) { goto decdone; }
-        if ( *buf == '?' ) {
-          len -= buf_end-buf;
-          *qs_len = buf_end-buf;
-          //printf("path_decode len %d path >%.*s<\n", (int)len, (int)len, obuf);
-          goto decdone;
-        }
-        if ( *buf == '%' ) {
-          if ( found ) {
-            memcpy( wbuf, sbuf, buf-sbuf );
-            wbuf += buf-sbuf;
-            *wbuf = (hex_to_dec(buf[1]) << 4) + hex_to_dec(buf[2]);
-            wbuf++;
-          } else {
-            found = 1;
-            *buf = (hex_to_dec(buf[1]) << 4) + hex_to_dec(buf[2]);
-            wbuf = buf+1;
-          }
-          len -= 2;
-          buf += 3;
-        }
-        sbuf = buf;
-      } else {
-        buf += 64 - shifted;
-        break;
-      }
-
+static int hex_value(unsigned char c) {
+  if(c >= '0' && c <= '9') return c-'0';
+  if(c >= 'a' && c <= 'f') return c-'a'+10;
+  if(c >= 'A' && c <= 'F') return c-'A'+10;
+  return -1;
+}
+static inline int path_decode(char *buf, int len, int *qs_len) {
+  int read=0, write=0;
+  *qs_len=0;
+  while(read<len) {
+    if(buf[read]=='?') {
+      *qs_len=len-read;
+      memmove(buf+write,buf+read,len-read);
+      break;
     }
-    i+=1;
-    if ( buf >= buf_end ) { goto decdone; }
-  } while ( buf < buf_end ); // Why doesn't this work
-
-decdone:
-  if ( found ) {
-    memcpy( wbuf, sbuf, buf_end-sbuf );
+    if(buf[read]=='%' && len-read>=3 && hex_value(buf[read+1])>=0 && hex_value(buf[read+2])>=0) {
+      buf[write++]=(hex_value(buf[read+1])<<4)|hex_value(buf[read+2]);
+      read+=3;
+    } else buf[write++]=buf[read++];
   }
-  return len;
+  return write;
 }
 
 static inline PyObject* parse_query_args( char *buf, size_t len ) {
@@ -245,7 +200,7 @@ static inline PyObject* parse_query_args( char *buf, size_t len ) {
   PyObject* args = PyDict_New();
   PyObject* key = NULL; PyObject* value = NULL;
 
-  if ( len == 0 ) return;
+  if ( len == 0 ) return args;
   //len = path_decode( buf, len, &ignore_me );
   char *buf_end = buf+len;
 
@@ -314,7 +269,9 @@ pdone:
 
 void request_decodePath(Request* self) {
   if(!self->path_decoded) {
-    self->path_len = path_decode( self->path, self->path_len, &(self->qs_len) );
+    int qs_len = 0;
+    self->path_len = path_decode(self->path, self->path_len, &qs_len);
+    self->qs_len = qs_len;
     self->path_decoded = true;
   }
 }
diff --git a/src/mrhttp/internals/request.h b/src/mrhttp/internals/request.h
index b659096..99b3157 100644
--- a/src/mrhttp/internals/request.h
+++ b/src/mrhttp/internals/request.h
@@ -41,6 +41,7 @@ struct Request {
   //char* session_value;
   void *route;
 
+  PyObject* raw_request;
   PyObject* py_path;
   PyObject* py_method;
   PyObject* transport;
diff --git a/src/mrhttp/networking.py b/src/mrhttp/networking.py
new file mode 100644
index 0000000..8f24389
--- /dev/null
+++ b/src/mrhttp/networking.py
@@ -0,0 +1,57 @@
+import os
+import socket
+import stat
+
+
+def bind_socket(host, port, *, uds=None, fd=None, backlog=2048):
+  if uds is not None and fd is not None:
+    raise ValueError('uds and fd are mutually exclusive')
+  cleanup = None
+  sock = None
+  try:
+    if fd is not None:
+      sock = socket.socket(fileno=os.dup(fd))
+      if sock.type & socket.SOCK_STREAM != socket.SOCK_STREAM:
+        raise ValueError('Inherited socket must be a stream socket')
+    elif uds is not None:
+      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+      sock.bind(uds)
+      info = os.stat(uds)
+      cleanup = (uds, info.st_dev, info.st_ino)
+    else:
+      addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE)
+      last_error = None
+      for family, kind, proto, _, address in addresses:
+        candidate = socket.socket(family, kind, proto)
+        try:
+          candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+          if family == socket.AF_INET6:
+            candidate.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+          candidate.bind(address)
+          sock = candidate
+          break
+        except OSError as exc:
+          last_error = exc
+          candidate.close()
+      if sock is None:
+        raise last_error or OSError('No bindable address')
+    sock.listen(backlog)
+    sock.setblocking(False)
+    return sock, cleanup
+  except BaseException:
+    if sock is not None:
+      sock.close()
+    cleanup_socket(cleanup)
+    raise
+
+
+def cleanup_socket(identity):
+  if identity is None:
+    return
+  path, device, inode = identity
+  try:
+    info = os.stat(path, follow_symlinks=False)
+    if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == (device, inode):
+      os.unlink(path)
+  except FileNotFoundError:
+    pass
diff --git a/src/mrhttp/observability.py b/src/mrhttp/observability.py
new file mode 100644
index 0000000..2a8e06b
--- /dev/null
+++ b/src/mrhttp/observability.py
@@ -0,0 +1,88 @@
+"""Low-cardinality Prometheus metrics and structured access records."""
+import json
+import logging
+
+
+class Metrics:
+  buckets = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
+  width = 608 + len(buckets)
+
+  def __init__(self, store=None, slot=0):
+    self.store = store if store is not None else [0.0] * self.width
+    self.slot = slot
+
+  def add(self, column, value):
+    self.store[self.slot * self.width + column] += value
+
+  def connection(self, delta):
+    self.add(0, delta)
+
+  def active(self, delta):
+    self.add(1, delta)
+
+  def received(self, count):
+    self.add(2, count)
+
+  def protocol_error(self):
+    self.add(6, 1)
+
+  def completed(self, status, size, duration):
+    offset = self.slot * self.width
+    self.store[offset + 3] += size
+    self.store[offset + 4] += 1
+    self.store[offset + 5] += duration
+    self.store[offset + 8 + min(max(status, 0), 599)] += 1
+    for i, bound in enumerate(self.buckets):
+      if duration <= bound:
+        self.store[offset + 608 + i] += 1
+
+  def reset_gauges(self, slot):
+    self.store[slot * self.width] = 0
+    self.store[slot * self.width + 1] = 0
+
+  def render(self):
+    totals = [sum(self.store[i::self.width]) for i in range(self.width)]
+    rows = [
+      '# TYPE mrhttp_connections gauge', 'mrhttp_connections {}'.format(int(totals[0])),
+      '# TYPE mrhttp_active_requests gauge', 'mrhttp_active_requests {}'.format(int(totals[1])),
+      '# TYPE mrhttp_request_body_bytes_total counter', 'mrhttp_request_body_bytes_total {}'.format(int(totals[2])),
+      '# TYPE mrhttp_response_body_bytes_total counter', 'mrhttp_response_body_bytes_total {}'.format(int(totals[3])),
+      '# TYPE mrhttp_protocol_errors_total counter', 'mrhttp_protocol_errors_total {}'.format(int(totals[6])),
+      '# TYPE mrhttp_http_requests_total counter',
+    ]
+    for status in range(600):
+      count = totals[8 + status]
+      if count:
+        rows.append('mrhttp_http_requests_total{{status="{}"}} {}'.format(status, int(count)))
+    rows.append('# TYPE mrhttp_request_duration_seconds histogram')
+    for i, bound in enumerate(self.buckets):
+      rows.append('mrhttp_request_duration_seconds_bucket{{le="{}"}} {}'.format(bound, int(totals[608 + i])))
+    rows.extend([
+      'mrhttp_request_duration_seconds_bucket{{le="+Inf"}} {}'.format(int(totals[4])),
+      'mrhttp_request_duration_seconds_count {}'.format(int(totals[4])),
+      'mrhttp_request_duration_seconds_sum {}'.format(totals[5]),
+    ])
+    return ('\n'.join(rows) + '\n').encode('ascii')
+
+
+def configure_access_log(enabled):
+  logger = logging.getLogger('mrhttp.access')
+  if enabled:
+    logger.setLevel(logging.INFO)
+  if enabled and not logger.handlers and not logging.getLogger().handlers:
+    logger.addHandler(logging.StreamHandler())
+    logger.propagate = False
+    logger.setLevel(logging.INFO)
+
+
+def access_record(scope, status, size, duration, format):
+  record = dict(request_id=scope['request_id'], method=scope.get('method', 'WEBSOCKET'),
+                path=scope['path'], client=scope.get('client'), status=status,
+                bytes_sent=size, duration_ms=round(duration * 1000, 3))
+  if format == 'json':
+    message = json.dumps(record, ensure_ascii=True, separators=(',', ':'))
+  else:
+    message = '{} {} {} {} {} {:.3f}ms'.format(
+      record['request_id'], json.dumps(record['method']), json.dumps(record['path']),
+      status, size, duration * 1000)
+  logging.getLogger('mrhttp.access').info(message)
diff --git a/src/mrhttp/proxy.py b/src/mrhttp/proxy.py
new file mode 100644
index 0000000..54c0f91
--- /dev/null
+++ b/src/mrhttp/proxy.py
@@ -0,0 +1,50 @@
+"""Apply proxy metadata only for explicitly trusted immediate peers."""
+import ipaddress
+
+
+class TrustedProxies:
+  def __init__(self, allowed):
+    values = allowed.split(',') if isinstance(allowed, str) else allowed
+    self.networks = []
+    self.literals = set()
+    for value in values:
+      value = value.strip()
+      if value == '*':
+        self.literals.add('*')
+      else:
+        try:
+          self.networks.append(ipaddress.ip_network(value, strict=False))
+        except ValueError:
+          if not value.startswith('/'):
+            raise ValueError('Invalid trusted proxy address: ' + value)
+          self.literals.add(value)
+
+  def trusted(self, address):
+    if '*' in self.literals or address in self.literals:
+      return True
+    try:
+      ip = ipaddress.ip_address(address)
+      return any(ip in network for network in self.networks)
+    except (ValueError, TypeError):
+      return False
+
+  def apply(self, scope, peer):
+    address = peer[0] if isinstance(peer, tuple) else peer
+    if not self.trusted(address):
+      return
+    values = {}
+    for name, value in scope['headers']:
+      values.setdefault(name, []).append(value)
+    proto = b','.join(values.get(b'x-forwarded-proto', [])).split(b',')[-1].strip()
+    if proto in (b'http', b'https'):
+      scope['scheme'] = proto.decode('ascii')
+    forwarded = b','.join(values.get(b'x-forwarded-for', []))
+    if forwarded:
+      try:
+        chain = [str(ipaddress.ip_address(part.strip().decode('ascii'))) for part in forwarded.split(b',')]
+      except (ValueError, UnicodeError):
+        return
+      for address in reversed(chain):
+        if not self.trusted(address):
+          break
+      scope['client'] = (address, 0)
diff --git a/src/mrhttp/request.py b/src/mrhttp/request.py
index 2401d7a..b961223 100755
--- a/src/mrhttp/request.py
+++ b/src/mrhttp/request.py
@@ -1,5 +1,6 @@
 import urllib.parse
-import cgi, time
+from email.message import Message
+import time
 import encodings.idna
 import collections
 import mrhttp
@@ -31,7 +32,9 @@ class Request(mrhttp.CRequest):
     if not content_type: 
       content_type = self.headers.get('content-type')
       if not content_type: return None, {}
-    return cgi.parse_header(content_type)
+    message = Message()
+    message['content-type'] = content_type
+    return message.get_content_type(), dict(message.get_params()[1:])
 
   @property
   def mime_type(self):
diff --git a/src/mrhttp/streams.py b/src/mrhttp/streams.py
new file mode 100644
index 0000000..62635ec
--- /dev/null
+++ b/src/mrhttp/streams.py
@@ -0,0 +1,49 @@
+"""Bounded request-body queues fed by the native HTTP parser."""
+import asyncio
+from collections import deque
+
+
+class HTTPInput:
+  def __init__(self, protocol, scope, keep_alive):
+    self.protocol = protocol
+    self.scope = scope
+    self.keep_alive = keep_alive
+    self.messages = deque()
+    self.event = asyncio.Event()
+    self.complete = False
+    self.response_closed = False
+    self.expect_continue = any(n == b'expect' and v.lower() == b'100-continue'
+                               for n, v in scope['headers'])
+    self.header_bytes = len(scope['raw_path']) + sum(len(n) + len(v) + 4 for n, v in scope['headers'])
+
+  def feed(self, body, more):
+    if self.response_closed:
+      return False
+    self.messages.append({'type': 'http.request', 'body': body, 'more_body': more})
+    self.protocol.buffered_input += len(body)
+    self.protocol.server.metrics.received(len(body))
+    self.complete = not more
+    self.event.set()
+    return self.protocol.check_read_flow()
+
+  async def receive(self):
+    if self.expect_continue and not self.complete and not self.response_closed:
+      self.expect_continue = False
+      await self.protocol.write(b'HTTP/1.1 100 Continue\r\n\r\n')
+    while not self.messages:
+      if self.response_closed or self.protocol.disconnected.is_set():
+        return {'type': 'http.disconnect'}
+      await self.event.wait()
+      self.event.clear()
+    if self.response_closed or self.protocol.disconnected.is_set():
+      return {'type': 'http.disconnect'}
+    message = self.messages.popleft()
+    self.protocol.buffered_input -= len(message['body'])
+    self.protocol.schedule_resume()
+    return message
+
+  def finish(self):
+    self.response_closed = True
+    while self.messages:
+      self.protocol.buffered_input -= len(self.messages.popleft()['body'])
+    self.event.set()
diff --git a/src/mrhttp/supervisor.py b/src/mrhttp/supervisor.py
new file mode 100644
index 0000000..9045093
--- /dev/null
+++ b/src/mrhttp/supervisor.py
@@ -0,0 +1,183 @@
+"""Worker readiness, event-loop heartbeats, recovery, and rolling restarts."""
+import logging
+import multiprocessing
+from multiprocessing.connection import wait
+import random
+import signal
+import time
+from dataclasses import dataclass
+
+from .networking import bind_socket, cleanup_socket
+from .observability import Metrics
+
+
+@dataclass
+class Worker:
+  process: object
+  pipe: object
+  slot: int
+  started: float
+  seen: float
+  ready: bool = False
+  retiring: bool = False
+  deadline: float = 0
+  killed: bool = False
+
+
+def worker_entry(app, app_path, configuration, sock, pipe, metrics, slot, limit):
+  from .asgi import ASGIServer, import_from_string
+  try:
+    if app_path:
+      app = import_from_string(app_path)
+    if configuration['factory']:
+      app = app()
+    server = ASGIServer(app, **configuration)
+    server.metrics = Metrics(metrics.store, slot)
+    server._worker_pipe = pipe
+    server.limit_max_requests = limit
+    server.serve(sock=sock, host='', port=0, loop=None)
+  except BaseException:
+    logging.getLogger('mrhttp.error').exception('Worker startup or execution failed')
+    raise SystemExit(3)
+  finally:
+    pipe.close()
+
+
+def supervise(server, host, port, workers, *, uds=None, fd=None):
+  if type(workers) is not int or not 1 <= workers <= 1024:
+    raise ValueError('workers must be an integer from 1 to 1024')
+  sock, cleanup = bind_socket(host, port, uds=uds, fd=fd, backlog=server.backlog)
+  # Import strings use fresh interpreters, so rolling restarts load fresh code.
+  # Direct Python callables retain Unix fork support, including local functions.
+  context = multiprocessing.get_context('spawn' if server._app_path else 'fork')
+  # Each row has one worker writer. Lock-free rows keep SIGKILL from leaving
+  # a process-shared mutex locked; scrapes are approximate concurrent snapshots.
+  metrics = Metrics(context.RawArray('d', Metrics.width * workers * 2))
+  logger = logging.getLogger('mrhttp.error')
+  states = {}
+  active = {}
+  terminating = False
+  reload_requested = False
+  rolling = []
+  candidate = None
+  old_handlers = {}
+  failures = []
+
+  def signal_handler(sig, frame):
+    nonlocal terminating, reload_requested
+    if sig == signal.SIGHUP:
+      reload_requested = True
+    else:
+      terminating = True
+
+  def spawn(slot):
+    receiver, sender = context.Pipe(duplex=False)
+    limit = server.limit_max_requests
+    if limit:
+      limit += random.randint(0, server.limit_max_requests_jitter)
+    process = context.Process(target=worker_entry,
+      args=(server._asgi_app if not server._app_path else None, server._app_path,
+            server._configuration, sock, sender, metrics, slot, limit))
+    try:
+      process.start()
+    except BaseException:
+      receiver.close()
+      sender.close()
+      raise
+    sender.close()
+    now = time.monotonic()
+    states[slot] = Worker(process, receiver, slot, now, now)
+    return slot
+
+  def failure():
+    now = time.monotonic()
+    failures[:] = [stamp for stamp in failures if now - stamp < 60]
+    failures.append(now)
+    if len(failures) > max(5, workers * 3):
+      raise RuntimeError('Repeated worker failures; stopping to avoid a restart loop')
+
+  try:
+    for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
+      old_handlers[sig] = signal.signal(sig, signal_handler)
+    for index in range(workers):
+      active[index] = spawn(index)
+    while not terminating:
+      pipes = [worker.pipe for worker in states.values()]
+      for pipe in wait(pipes, timeout=0.05) if pipes else []:
+        worker = next((item for item in states.values() if item.pipe is pipe), None)
+        if worker is None:
+          continue
+        try:
+          while pipe.poll():
+            message = pipe.recv()
+            worker.seen = time.monotonic()
+            if message == 'ready':
+              worker.ready = True
+            elif message == 'recycle' and not worker.retiring:
+              index = next((index for index, slot in active.items() if slot == worker.slot), None)
+              if index is not None and index not in rolling and (candidate is None or candidate[0] != index):
+                rolling.append(index)
+        except (EOFError, OSError):
+          pass
+      now = time.monotonic()
+      for slot, worker in list(states.items()):
+        if worker.process.exitcode is not None:
+          worker.process.join()
+          worker.pipe.close()
+          metrics.reset_gauges(slot)
+          del states[slot]
+          if worker.retiring:
+            continue
+          if candidate is not None and candidate[1] == slot:
+            logger.error('Replacement worker failed; retaining the serving worker')
+            candidate = None
+            rolling.clear()
+            failure()
+            continue
+          if not worker.ready:
+            raise RuntimeError('Worker failed before becoming ready (exit {})'.format(worker.process.exitcode))
+          index = next(index for index, value in active.items() if value == slot)
+          if worker.process.exitcode:
+            failure()
+            logger.error('Worker %s exited (%s); restarting', worker.process.pid, worker.process.exitcode)
+          active[index] = spawn(slot)
+          continue
+        timeout = server.timeout_worker_healthcheck if worker.ready else server.timeout_worker_startup
+        expired = now - (worker.seen if worker.ready else worker.started) > timeout
+        if worker.retiring:
+          expired = now > worker.deadline
+        if expired and not worker.killed:
+          logger.error('Worker %s failed its deadline; killing it', worker.process.pid)
+          worker.process.kill()
+          worker.killed = True
+      if reload_requested and not rolling and candidate is None:
+        rolling = list(active)
+        reload_requested = False
+      if rolling and candidate is None and not any(worker.retiring for worker in states.values()):
+        index = rolling.pop(0)
+        free = next(slot for slot in range(workers * 2) if slot not in states)
+        candidate = (index, spawn(free))
+      if candidate is not None:
+        index, slot = candidate
+        if states[slot].ready:
+          previous = states[active[index]]
+          previous.retiring = True
+          previous.deadline = now + server.timeout_graceful_shutdown + 12
+          previous.process.terminate()
+          active[index] = slot
+          candidate = None
+  finally:
+    for worker in states.values():
+      if worker.process.is_alive():
+        worker.process.terminate()
+    deadline = time.monotonic() + server.timeout_graceful_shutdown + 12
+    for worker in states.values():
+      worker.process.join(timeout=max(0, deadline - time.monotonic()))
+      if worker.process.is_alive():
+        worker.process.kill()
+        worker.process.join()
+      worker.pipe.close()
+    sock.close()
+    cleanup_socket(cleanup)
+    for sig, handler in old_handlers.items():
+      signal.signal(sig, handler)
diff --git a/src/mrhttp/websocket.py b/src/mrhttp/websocket.py
new file mode 100644
index 0000000..3ed3f6e
--- /dev/null
+++ b/src/mrhttp/websocket.py
@@ -0,0 +1,214 @@
+"""ASGI WebSockets over the native HTTP upgrade path and wsproto framing."""
+import asyncio
+import base64
+import binascii
+from collections import deque
+
+from wsproto import WSConnection
+from wsproto.connection import ConnectionType
+from wsproto import events
+from wsproto.utilities import LocalProtocolError, RemoteProtocolError
+
+from .exceptions import ASGIConnectionClosed, ASGIProtocolError
+from .headers import _normalize_header
+
+
+class WebSocketSession:
+  def __init__(self, protocol, scope):
+    self.protocol = protocol
+    self.scope = scope
+    self.keep_alive = False
+    self.header_bytes = 0
+    self.ws = WSConnection(ConnectionType.SERVER)
+    keys = [value for name, value in scope['headers'] if name == b'sec-websocket-key']
+    try:
+      valid_key = len(keys) == 1 and len(base64.b64decode(keys[0], validate=True)) == 16
+    except (ValueError, binascii.Error):
+      valid_key = False
+    if not valid_key:
+      raise ASGIProtocolError('Invalid WebSocket key')
+    target = scope['raw_path'] + (b'?' + scope['query_string'] if scope['query_string'] else b'')
+    self.ws.initiate_upgrade_connection(scope['headers'], target)
+    request = next(self.ws.events())
+    scope.update(type='websocket', scheme='wss' if scope['scheme'] == 'https' else 'ws',
+                 subprotocols=request.subprotocols)
+    scope.pop('method', None)
+    self.messages = deque([{'type': 'websocket.connect'}])
+    self.event = asyncio.Event()
+    self.event.set()
+    self.accepted = False
+    self.closed = False
+    self.close_sent = False
+    self.status = 403
+    self.sent_length = 0
+    self.wire_started = False
+    self.partial = []
+    self.partial_size = 0
+    self.early_data = bytearray()
+    self.ping_task = None
+    self.close_handle = None
+    self.pong = asyncio.Event()
+    self.ping_payload = None
+    self.disconnect_message = {'type': 'websocket.disconnect', 'code': 1006, 'reason': ''}
+
+  def can_read(self):
+    return len(self.messages) < self.protocol.server.ws_max_queue and self.protocol.buffered_input < self.protocol.server.read_buffer_size
+
+  def feed(self, data, more=True):
+    if self.closed:
+      return False
+    if not self.accepted:
+      self.early_data.extend(data)
+      if len(self.early_data) > self.protocol.server.read_buffer_size:
+        self.protocol.transport.close()
+        return False
+      return True
+    try:
+      self.ws.receive_data(data)
+      self.drain_events()
+    except (RemoteProtocolError, LocalProtocolError, UnicodeError):
+      self.fail(1002, 'Invalid WebSocket frame')
+    return self.protocol.check_read_flow()
+
+  def drain_events(self):
+    if self.closed or not self.accepted:
+      return
+    for event in self.ws.events():
+      if isinstance(event, (events.TextMessage, events.BytesMessage)):
+        if self.close_sent:
+          continue
+        size = len(event.data.encode('utf-8')) if isinstance(event.data, str) else len(event.data)
+        self.partial_size += size
+        if self.partial_size > self.protocol.server.ws_max_size:
+          self.fail(1009, 'Message too large')
+          return
+        self.partial.append(event.data)
+        if event.message_finished:
+          is_text = isinstance(event, events.TextMessage)
+          data = ('' if is_text else b'').join(self.partial)
+          self.messages.append({'type': 'websocket.receive', 'text' if is_text else 'bytes': data})
+          self.protocol.buffered_input += self.partial_size
+          self.partial, self.partial_size = [], 0
+          self.event.set()
+          if not self.can_read():
+            return
+      elif isinstance(event, events.Ping):
+        if not self.close_sent:
+          self.protocol.transport.write(self.ws.send(event.response()))
+      elif isinstance(event, events.Pong):
+        if event.payload == self.ping_payload:
+          self.pong.set()
+      elif isinstance(event, events.CloseConnection):
+        if not self.close_sent:
+          self.protocol.transport.write(self.ws.send(event.response()))
+        self.disconnect(event.code, event.reason or '')
+        self.protocol.transport.close()
+        return
+
+  def fail(self, code, reason):
+    try:
+      self.protocol.transport.write(self.ws.send(events.CloseConnection(code=code, reason=reason)))
+    except LocalProtocolError:
+      pass
+    self.close_sent = True
+    self.disconnect(code, reason)
+    self.protocol.transport.close()
+
+  async def receive(self):
+    while not self.messages and not self.closed:
+      await self.event.wait()
+      self.event.clear()
+    if not self.messages:
+      return dict(self.disconnect_message)
+    message = self.messages.popleft()
+    if message['type'] == 'websocket.receive':
+      self.protocol.buffered_input -= len(message['text'].encode('utf-8')) if 'text' in message else len(message['bytes'])
+    self.protocol.schedule_resume()
+    return message
+
+  async def send(self, message):
+    if self.closed or self.protocol.disconnected.is_set() or self.close_sent:
+      raise ASGIConnectionClosed('WebSocket is closed')
+    if not isinstance(message, dict):
+      raise ASGIProtocolError('WebSocket events must be dictionaries')
+    typ = message.get('type')
+    try:
+      if typ == 'websocket.accept' and not self.accepted:
+        protocol = message.get('subprotocol')
+        if protocol is not None and protocol not in self.scope['subprotocols']:
+          raise ASGIProtocolError('Unrequested WebSocket subprotocol')
+        headers = [_normalize_header(header) for header in message.get('headers', [])]
+        if any(name in (b'sec-websocket-protocol', b'sec-websocket-accept', b'upgrade', b'connection') for name, _ in headers):
+          raise ASGIProtocolError('WebSocket handshake headers are server managed')
+        headers.append((self.protocol.server.request_id_header, self.scope['request_id'].encode('ascii')))
+        data = self.ws.send(events.AcceptConnection(subprotocol=protocol, extra_headers=headers))
+        self.accepted, self.wire_started, self.status = True, True, 101
+        if self.protocol.timeout_handle:
+          self.protocol.timeout_handle.cancel()
+        await self.protocol.write(data)
+        if self.early_data:
+          data = bytes(self.early_data)
+          self.early_data.clear()
+          self.feed(data)
+        if self.protocol.server.ws_ping_interval:
+          self.ping_task = asyncio.create_task(self.heartbeat())
+        return
+      if typ == 'websocket.close':
+        code, reason = message.get('code', 1000), message.get('reason', '')
+        if not self.accepted:
+          self.wire_started = True
+          await self.protocol.write(b'HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n' + self.protocol.server.request_id_header + b': ' + self.scope['request_id'].encode('ascii') + b'\r\n\r\n')
+          self.disconnect(1006, '')
+          self.protocol.transport.close()
+          return
+        if type(code) is not int or not (code in (1000, 1001, 1002, 1003, 1007, 1008, 1009, 1011, 1012, 1013, 1014) or 3000 <= code <= 4999):
+          raise ASGIProtocolError('Invalid WebSocket close code')
+        if not isinstance(reason, str) or len(reason.encode('utf-8')) > 123:
+          raise ASGIProtocolError('Invalid WebSocket close reason')
+        await self.protocol.write(self.ws.send(events.CloseConnection(code=code, reason=reason)))
+        self.close_sent = True
+        self.close_handle = self.protocol.server.loop.call_later(self.protocol.server.ws_close_timeout, self.protocol.transport.close)
+        return
+      if typ == 'websocket.send' and self.accepted:
+        text, binary = message.get('text'), message.get('bytes')
+        if (text is None) == (binary is None) or (text is not None and not isinstance(text, str)) or (binary is not None and not isinstance(binary, bytes)):
+          raise ASGIProtocolError('Send exactly one WebSocket text or bytes value')
+        payload = text if text is not None else binary
+        event = events.TextMessage(data=payload) if text is not None else events.BytesMessage(data=payload)
+        await self.protocol.write(self.ws.send(event))
+        self.sent_length += len(text.encode('utf-8')) if text is not None else len(binary)
+        return
+    except LocalProtocolError as exc:
+      raise ASGIProtocolError(str(exc)) from exc
+    raise ASGIProtocolError('Unexpected WebSocket event: {}'.format(typ))
+
+  async def heartbeat(self):
+    try:
+      while not self.closed and not self.close_sent:
+        await asyncio.sleep(self.protocol.server.ws_ping_interval)
+        self.pong.clear()
+        self.ping_payload = str(self.protocol.server.loop.time()).encode('ascii')
+        await self.protocol.write(self.ws.send(events.Ping(payload=self.ping_payload)))
+        await asyncio.wait_for(self.pong.wait(), self.protocol.server.ws_ping_timeout)
+    except asyncio.TimeoutError:
+      self.fail(1011, 'Ping timeout')
+    except (ASGIConnectionClosed, LocalProtocolError):
+      pass
+
+  def release_messages(self):
+    while self.messages:
+      message = self.messages.popleft()
+      if message['type'] == 'websocket.receive':
+        self.protocol.buffered_input -= len(message['text'].encode('utf-8')) if 'text' in message else len(message['bytes'])
+  def disconnect(self, code=1006, reason=''):
+    if self.closed:
+      return
+    self.closed = True
+    self.disconnect_message = {'type': 'websocket.disconnect', 'code': int(code), 'reason': reason}
+    self.partial.clear()
+    self.early_data.clear()
+    self.event.set()
+    if self.ping_task and self.ping_task is not asyncio.current_task():
+      self.ping_task.cancel()
+    if self.close_handle:
+      self.close_handle.cancel()
diff --git a/tests/common.py b/tests/common.py
index 6f7855a..5c152ee 100644
--- a/tests/common.py
+++ b/tests/common.py
@@ -1,44 +1,43 @@
 
-import sys, os, subprocess, signal
-#import ctypes.util
+import os
+import signal
+import subprocess
+import sys
 import time
-import psutil
-import inspect
 
-#num_fails = 0 
 
-#stdout=subprocess.PIPE
-def start_server( script, suppress_error=False ):
-  server = subprocess.Popen([sys.executable, script], stdout=subprocess.PIPE,stderr=subprocess.PIPE, start_new_session=True)
-  #(o, e) = server.communicate()
-  process = psutil.Process(server.pid)
-  try:
-    time.sleep(0.5)
-    # If server is not running fail
-    if not (server.poll() is None):
+def start_server(script, suppress_error=False):
+  import socket
+  server = subprocess.Popen([sys.executable, script], stdout=subprocess.PIPE,
+                            stderr=subprocess.PIPE, start_new_session=True)
+  deadline = time.monotonic() + 10
+  while time.monotonic() < deadline:
+    if server.poll() is not None:
+      stdout, stderr = server.communicate()
       if not suppress_error:
-        print("ERROR starting server",script)
+        print("ERROR starting server", script, stderr.decode(errors="replace"))
       return None
-    return server
-  except KeyboardInterrupt:
-    stop_server(server)
-
-def eq( a, b ):
-  #global num_fails
-  if a != b:
-    cf = inspect.currentframe()
-    print( "ERROR Line", cf.f_back.f_lineno, a, "!=", b )
-    #print( "ERROR Line", cf.f_back.f_code.co_filename, cf.f_back.f_lineno, a, "!=", b )
-    #num_fails += 1
-    return -1
-  return 0
-
-def contains( a, b ):
-  if not b in a:
-    cf = inspect.currentframe()
-    print( "ERROR Line", cf.f_back.f_lineno, "'"+b+"'", " not found in\n  " , a )
-   
+    try:
+      with socket.create_connection(("127.0.0.1", 8080), timeout=0.1):
+        return server
+    except OSError:
+      time.sleep(0.02)
+  stop_server(server)
+  server.communicate(timeout=15)
+  raise TimeoutError("Server did not become ready: " + script)
+
+
+def eq(a, b):
+  assert a == b, "{!r} != {!r}".format(a, b)
+
+
+def contains(a, b):
+  assert b in a, "{!r} not found in {!r}".format(b, a)
+
+
 def stop_server( s ):
   if s == None: return
-  os.killpg(os.getpgid(s.pid), signal.SIGTERM)  
-  s.terminate() 
+  try:
+    os.killpg(os.getpgid(s.pid), signal.SIGTERM)
+  except ProcessLookupError:
+    pass
diff --git a/tests/s_asgi.py b/tests/s_asgi.py
index 271c7b2..0574183 100644
--- a/tests/s_asgi.py
+++ b/tests/s_asgi.py
@@ -20,8 +20,12 @@ async def app(scope, receive, send):
         return
 
   assert scope["type"] == "http"
-  message = await receive()
-  body = message.get("body", b"")
+  body = b""
+  while True:
+    message = await receive()
+    body += message.get("body", b"")
+    if not message.get("more_body", False):
+      break
 
   if scope["path"] == "/":
     content = b"hello asgi"
diff --git a/tests/s_supervised.py b/tests/s_supervised.py
new file mode 100644
index 0000000..eeb2eee
--- /dev/null
+++ b/tests/s_supervised.py
@@ -0,0 +1,22 @@
+"""Real applications used by the supervisor process tests."""
+import asyncio
+import os
+import time
+
+
+async def app(scope, receive, send):
+  if scope['path'] == '/crash':
+    os._exit(71)
+  if scope['path'] == '/hang':
+    time.sleep(30)
+  if scope['path'] == '/slow':
+    await asyncio.sleep(0.6)
+  await send({'type': 'http.response.start', 'status': 200})
+  await send({'type': 'http.response.body', 'body': str(os.getpid()).encode()})
+
+
+def factory():
+  async def application(scope, receive, send):
+    await send({'type': 'http.response.start', 'status': 200})
+    await send({'type': 'http.response.body', 'body': ('factory:' + str(os.getpid())).encode()})
+  return application
diff --git a/tests/test_asgi.py b/tests/test_asgi.py
index 5a570eb..acf5b9c 100644
--- a/tests/test_asgi.py
+++ b/tests/test_asgi.py
@@ -1,4 +1,5 @@
 import socket
+import http.client
 
 import requests
 
@@ -40,8 +41,9 @@ def test_asgi_http():
       b"X-Dup: two\r\n"
       b"\r\n"
     )
-    data = sock.recv(4096)
-    assert b"\r\n\r\nGET|/scope|/scope|x=1|2|True" in data, data
+    response = http.client.HTTPResponse(sock)
+    response.begin()
+    assert response.read() == b"GET|/scope|/scope|x=1|2|True"
   finally:
     sock.close()
 
@@ -58,8 +60,9 @@ def test_chunked_request_body():
       b"5\r\npedia\r\n"
       b"0\r\n\r\n"
     )
-    data = sock.recv(4096)
-    assert b"\r\n\r\nWikipedia" in data, data
+    response = http.client.HTTPResponse(sock)
+    response.begin()
+    assert response.read() == b"Wikipedia"
   finally:
     sock.close()
 
diff --git a/tests/test_asgi_production.py b/tests/test_asgi_production.py
new file mode 100644
index 0000000..f5c3d47
--- /dev/null
+++ b/tests/test_asgi_production.py
@@ -0,0 +1,394 @@
+"""Production contracts at real socket and framework boundaries."""
+import asyncio
+import json
+import logging
+import os
+import socket
+
+import pytest
+from wsproto import WSConnection, events
+from wsproto.connection import ConnectionType
+
+import mrhttp
+from tests.test_asgi_regressions import running, connect, response, reply, request_body
+
+
+def test_dispatch_and_partial_body_arrive_before_upload_finishes():
+  async def scenario():
+    dispatched, partial = asyncio.Event(), asyncio.Event()
+    async def app(scope, receive, send):
+      dispatched.set()
+      first = await receive()
+      assert first == {'type': 'http.request', 'body': b'abc', 'more_body': True}
+      partial.set()
+      await reply(send, first['body'] + await request_body(receive))
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 6\r\n\r\n')
+        await writer.drain()
+        await asyncio.wait_for(dispatched.wait(), 1)
+        writer.write(b'abc')
+        await writer.drain()
+        await asyncio.wait_for(partial.wait(), 1)
+        writer.write(b'def')
+        await writer.drain()
+        assert (await response(reader))[2] == b'abcdef'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_early_rejection_does_not_read_upload_or_send_continue():
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, b'denied', 403)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 1000000\r\nExpect: 100-continue\r\n\r\n')
+        await writer.drain()
+        result = await response(reader)
+        assert result[0] == 403
+        assert result[1][b'connection'] == [b'close']
+        assert await asyncio.wait_for(reader.read(), 1) == b''
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_slow_upload_consumer_applies_read_backpressure_and_resumes_losslessly():
+  async def scenario():
+    started, consume, uploaded = asyncio.Event(), asyncio.Event(), asyncio.Event()
+    size = 8 * 1024 * 1024
+    async def app(scope, receive, send):
+      started.set()
+      await consume.wait()
+      body = await request_body(receive)
+      assert body == b'x' * size
+      await reply(send, str(len(body)).encode())
+    async with running(app, read_buffer_size=32768) as (_, port):
+      reader, writer = await connect(port)
+      async def upload():
+        writer.write(b'x' * size)
+        await writer.drain()
+        uploaded.set()
+      try:
+        writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %d\r\n\r\n' % size)
+        await writer.drain()
+        await asyncio.wait_for(started.wait(), 1)
+        task = asyncio.create_task(upload())
+        await asyncio.sleep(0.1)
+        assert not uploaded.is_set(), 'the producer must block while the application is not consuming'
+        consume.set()
+        await asyncio.wait_for(task, 3)
+        assert (await response(reader))[2] == str(size).encode()
+      finally:
+        consume.set()
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('trusted,expected', [('127.0.0.0/8', '203.0.113.7'), ('192.0.2.0/24', '127.0.0.1')])
+def test_proxy_metadata_is_applied_only_from_trusted_peers(trusted, expected):
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, json.dumps([scope['client'][0], scope['scheme']]).encode())
+    async with running(app, proxy_headers=True, forwarded_allow_ips=trusted) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\nX-Forwarded-For: 203.0.113.7, 127.0.0.2\r\nX-Forwarded-Proto: https\r\n\r\n')
+        await writer.drain()
+        assert json.loads((await response(reader))[2]) == [expected, 'https' if expected == '203.0.113.7' else 'http']
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_json_access_log_request_id_health_and_metrics(caplog):
+  caplog.set_level(logging.INFO, logger='mrhttp.access')
+  async def scenario():
+    calls = []
+    async def app(scope, receive, send):
+      calls.append(scope['path'])
+      await reply(send, b'created', 201)
+    async with running(app, access_log=True, access_log_format='json', metrics_path='/metrics', health_check_path='/healthz') as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET /created HTTP/1.1\r\nHost: localhost\r\nX-Request-Id: test-123\r\n\r\n')
+        await writer.drain()
+        result = await response(reader)
+        assert result[1][b'x-request-id'] == [b'test-123']
+        writer.write(b'GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[2] == b'ok'
+        writer.write(b'GET /metrics HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        metrics = (await response(reader))[2]
+        assert b'mrhttp_http_requests_total{status="201"} 1' in metrics
+        assert b'mrhttp_response_body_bytes_total 9' in metrics
+        assert b'mrhttp_request_duration_seconds_count 2' in metrics
+        assert calls == ['/created']
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+  records = [json.loads(record.message) for record in caplog.records if record.name == 'mrhttp.access']
+  assert any(record['request_id'] == 'test-123' and record['status'] == 201 and record['bytes_sent'] == 7 for record in records)
+
+
[email protected]('binding', ['unix', 'ipv6', 'fd'])
+def test_deployment_socket_binding(binding, tmp_path):
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, json.dumps(scope['server']).encode())
+    server = mrhttp.ASGIServer(app, lifespan='off')
+    inherited = None
+    path = str(tmp_path / 'server.sock')
+    try:
+      if binding == 'unix':
+        await server.start_server(uds=path)
+        reader, writer = await asyncio.open_unix_connection(path)
+      elif binding == 'ipv6':
+        if not socket.has_ipv6:
+          pytest.skip('IPv6 unavailable')
+        try:
+          listener = await server.start_server('::1', 0)
+        except OSError as exc:
+          if exc.errno in (97, 99):
+            pytest.skip('IPv6 loopback unavailable')
+          raise
+        reader, writer = await asyncio.open_connection('::1', listener.sockets[0].getsockname()[1])
+      else:
+        inherited = socket.socket()
+        inherited.bind(('127.0.0.1', 0))
+        inherited.listen()
+        listener = await server.start_server(fd=inherited.fileno())
+        reader, writer = await connect(listener.sockets[0].getsockname()[1])
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        address = json.loads((await response(reader))[2])
+        assert address[0] == (path if binding == 'unix' else '::1' if binding == 'ipv6' else '127.0.0.1')
+      finally:
+        writer.close()
+        await writer.wait_closed()
+      await server.shutdown()
+      if binding == 'unix':
+        assert not os.path.exists(path)
+      if inherited:
+        assert inherited.getsockname()[1] > 0
+    finally:
+      await server.shutdown()
+      if inherited:
+        inherited.close()
+  asyncio.run(scenario())
+
+
+async def ws_open(port, subprotocols=(), extensions=()):
+  reader, writer = await connect(port)
+  client = WSConnection(ConnectionType.CLIENT)
+  writer.write(client.send(events.Request(host='localhost', target='/ws', subprotocols=list(subprotocols), extensions=list(extensions))))
+  await writer.drain()
+  client.receive_data(await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1))
+  accepted = list(client.events())
+  assert len(accepted) == 1 and isinstance(accepted[0], events.AcceptConnection)
+  return client, reader, writer, accepted[0]
+
+
+async def ws_event(client, reader, kind):
+  while True:
+    for event in client.events():
+      if isinstance(event, kind):
+        return event
+    data = await asyncio.wait_for(reader.read(65536), 2)
+    assert data, 'WebSocket closed before expected event'
+    client.receive_data(data)
+
+
+def test_websocket_asgi_messages_subprotocol_fragmentation_ping_and_close():
+  async def scenario():
+    disconnected = asyncio.Event()
+    async def app(scope, receive, send):
+      assert scope['type'] == 'websocket'
+      assert scope['subprotocols'] == ['chat']
+      assert await receive() == {'type': 'websocket.connect'}
+      await send({'type': 'websocket.accept', 'subprotocol': 'chat'})
+      assert await receive() == {'type': 'websocket.receive', 'text': 'hello'}
+      await send({'type': 'websocket.send', 'text': 'HELLO'})
+      assert await receive() == {'type': 'websocket.receive', 'bytes': b'\x00\xff'}
+      await send({'type': 'websocket.send', 'bytes': b'\x00\xff'})
+      close = await receive()
+      assert close == {'type': 'websocket.disconnect', 'code': 1000, 'reason': 'done'}
+      disconnected.set()
+    async with running(app) as (_, port):
+      client, reader, writer, accepted = await ws_open(port, ['chat'])
+      try:
+        assert accepted.subprotocol == 'chat'
+        writer.write(client.send(events.TextMessage(data='hel', message_finished=False)))
+        writer.write(client.send(events.TextMessage(data='lo')))
+        await writer.drain()
+        assert (await ws_event(client, reader, events.TextMessage)).data == 'HELLO'
+        writer.write(client.send(events.Ping(payload=b'probe')))
+        await writer.drain()
+        assert (await ws_event(client, reader, events.Pong)).payload == b'probe'
+        writer.write(client.send(events.BytesMessage(data=b'\x00\xff')))
+        await writer.drain()
+        assert (await ws_event(client, reader, events.BytesMessage)).data == b'\x00\xff'
+        writer.write(client.send(events.CloseConnection(code=1000, reason='done')))
+        await writer.drain()
+        assert (await ws_event(client, reader, events.CloseConnection)).code == 1000
+        await asyncio.wait_for(disconnected.wait(), 1)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('attack,code', [('oversize', 1009), ('unmasked', 1002)])
+def test_websocket_limits_and_invalid_frames_close_safely(attack, code):
+  async def scenario():
+    async def app(scope, receive, send):
+      await receive()
+      await send({'type': 'websocket.accept'})
+      while (await receive())['type'] != 'websocket.disconnect':
+        pass
+    async with running(app, ws_max_size=8) as (_, port):
+      client, reader, writer, _ = await ws_open(port)
+      try:
+        data = client.send(events.BytesMessage(data=b'x' * 9)) if attack == 'oversize' else b'\x81\x01x'
+        writer.write(data)
+        await writer.drain()
+        assert (await ws_event(client, reader, events.CloseConnection)).code == code
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_websocket_handshake_can_be_denied():
+  async def scenario():
+    async def app(scope, receive, send):
+      assert await receive() == {'type': 'websocket.connect'}
+      await send({'type': 'websocket.close'})
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      client = WSConnection(ConnectionType.CLIENT)
+      try:
+        writer.write(client.send(events.Request(host='localhost', target='/ws')))
+        await writer.drain()
+        assert (await response(reader))[0] == 403
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_websocket_queue_resumes_without_losing_messages():
+  async def scenario():
+    consume = asyncio.Event()
+    async def app(scope, receive, send):
+      await receive()
+      await send({'type': 'websocket.accept'})
+      await consume.wait()
+      for i in range(40):
+        assert (await receive())['text'] == str(i)
+      await send({'type': 'websocket.send', 'text': 'all received'})
+      await send({'type': 'websocket.close'})
+    async with running(app, ws_max_queue=1) as (_, port):
+      client, reader, writer, _ = await ws_open(port)
+      try:
+        writer.write(b''.join(client.send(events.TextMessage(data=str(i))) for i in range(40)))
+        await writer.drain()
+        await asyncio.sleep(0.01)
+        consume.set()
+        assert (await ws_event(client, reader, events.TextMessage)).data == 'all received'
+      finally:
+        consume.set()
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_websocket_ping_timeout_closes_unresponsive_peer():
+  async def scenario():
+    async def app(scope, receive, send):
+      await receive()
+      await send({'type': 'websocket.accept'})
+      assert (await receive())['type'] == 'websocket.disconnect'
+    async with running(app, ws_ping_interval=0.02, ws_ping_timeout=0.03) as (_, port):
+      client, reader, writer, _ = await ws_open(port)
+      try:
+        assert isinstance(await ws_event(client, reader, events.Ping), events.Ping)
+        assert (await ws_event(client, reader, events.CloseConnection)).code == 1011
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('header', [b'invalid', b'not-base64', b'AAAAAAAAAAAAAAAAAAAA'])
+def test_invalid_websocket_keys_are_rejected(header):
+  async def scenario():
+    calls = []
+    async def app(scope, receive, send):
+      calls.append(scope)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET /ws HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: ' + header + b'\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[0] == 400
+        assert not calls
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_websocket_message_preceding_close_is_delivered_before_disconnect():
+  async def scenario():
+    done = asyncio.Event()
+    async def app(scope, receive, send):
+      await receive()
+      await send({'type': 'websocket.accept'})
+      assert await receive() == {'type': 'websocket.receive', 'text': 'last message'}
+      assert (await receive())['type'] == 'websocket.disconnect'
+      done.set()
+    async with running(app) as (_, port):
+      client, reader, writer, _ = await ws_open(port)
+      try:
+        writer.write(client.send(events.TextMessage(data='last message')) + client.send(events.CloseConnection(code=1000)))
+        await writer.drain()
+        await ws_event(client, reader, events.CloseConnection)
+        await asyncio.wait_for(done.wait(), 1)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_fastapi_websocket_json_roundtrip():
+  from fastapi import FastAPI, WebSocket
+  async def scenario():
+    app = FastAPI()
+    @app.websocket('/ws')
+    async def endpoint(websocket: WebSocket):
+      await websocket.accept()
+      message = await websocket.receive_json()
+      await websocket.send_json({'answer': message['number'] + 1})
+      await websocket.close()
+    async with running(app) as (_, port):
+      client, reader, writer, _ = await ws_open(port)
+      try:
+        writer.write(client.send(events.TextMessage(data='{"number":41}')))
+        await writer.drain()
+        assert json.loads((await ws_event(client, reader, events.TextMessage)).data) == {'answer': 42}
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
diff --git a/tests/test_asgi_regressions.py b/tests/test_asgi_regressions.py
new file mode 100644
index 0000000..df6c981
--- /dev/null
+++ b/tests/test_asgi_regressions.py
@@ -0,0 +1,511 @@
+"""ASGI regressions exercised through real TCP connections and the C parser."""
+import asyncio
+from contextlib import asynccontextmanager
+
+import pytest
+
+import mrhttp
+from tests.common import contains, eq
+
+
+@asynccontextmanager
+async def running(app, **options):
+  server = mrhttp.ASGIServer(app, lifespan=options.pop('lifespan', 'off'),
+                             timeout_graceful_shutdown=0.2, **options)
+  listener = await server.start_server(port=0)
+  port = listener.sockets[0].getsockname()[1]
+  try:
+    yield server, port
+  finally:
+    await server.shutdown()
+
+
+async def connect(port):
+  return await asyncio.open_connection('127.0.0.1', port)
+
+
+async def response(reader, head=False):
+  raw = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 2)
+  lines = raw.split(b'\r\n')
+  status = int(lines[0].split()[1])
+  headers = {}
+  for line in lines[1:-2]:
+    name, value = line.split(b':', 1)
+    headers.setdefault(name.lower(), []).append(value.strip())
+  body = b''
+  if not head and status not in (204, 304):
+    if headers.get(b'transfer-encoding') == [b'chunked']:
+      while True:
+        size = int(await asyncio.wait_for(reader.readline(), 2), 16)
+        if not size:
+          assert await reader.readexactly(2) == b'\r\n'
+          break
+        body += await reader.readexactly(size)
+        assert await reader.readexactly(2) == b'\r\n'
+    elif b'content-length' in headers:
+      body = await asyncio.wait_for(reader.readexactly(int(headers[b'content-length'][0])), 2)
+    else:
+      body = await asyncio.wait_for(reader.read(), 2)
+  return status, headers, body
+
+
+async def request_body(receive):
+  parts = []
+  while True:
+    message = await receive()
+    assert message['type'] == 'http.request'
+    parts.append(message.get('body', b''))
+    if not message.get('more_body', False):
+      return b''.join(parts)
+
+
+async def reply(send, body=b'ok', status=200, headers=()):
+  await send({'type': 'http.response.start', 'status': status, 'headers': list(headers)})
+  await send({'type': 'http.response.body', 'body': body})
+
+
[email protected]('header,encoded', [
+  (b'Content-Length: 6', b'abcdef'),
+  (b'content-length: 6', b'abcdef'),
+  (b'cOnTeNt-LeNgTh: 6', b'abcdef'),
+  (b'Transfer-Encoding: chunked', b'3;foo=bar\r\nabc\r\n3\r\ndef\r\n0\r\nX-Trailer: yes\r\n\r\n'),
+  (b'transfer-encoding: chunked', b'3\r\nabc\r\n3\r\ndef\r\n0\r\n\r\n'),
+])
+def test_fragmented_request_framing(header, encoded):
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, await request_body(receive))
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      data = b'POST /echo HTTP/1.1\r\nHost: localhost\r\n' + header + b'\r\n\r\n' + encoded
+      try:
+        for byte in data:
+          writer.write(bytes([byte]))
+          await writer.drain()
+          await asyncio.sleep(0.001)
+        assert (await response(reader))[2] == b'abcdef'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_pipeline_over_50_preserves_request_headers_and_bytes():
+  async def scenario():
+    async def app(scope, receive, send):
+      await asyncio.sleep(0)
+      body = scope['raw_path'] + b'|' + dict(scope['headers'])[b'x-id']
+      await reply(send, body)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b''.join(
+          b'GET /%d HTTP/1.1\r\nHost: localhost\r\nX-Id: %d\r\n\r\n' % (i, i)
+          for i in range(100)))
+        await writer.drain()
+        for i in range(100):
+          assert (await response(reader))[2] == b'/%d|%d' % (i, i)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_receive_waits_then_reports_response_completion():
+  async def scenario():
+    observed = asyncio.Event()
+    async def app(scope, receive, send):
+      assert (await receive())['more_body'] is False
+      waiting = asyncio.create_task(receive())
+      await asyncio.sleep(0.01)
+      assert not waiting.done()
+      await reply(send)
+      assert await waiting == {'type': 'http.disconnect'}
+      observed.set()
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[2] == b'ok'
+        await asyncio.wait_for(observed.wait(), 1)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_streaming_flushes_before_application_returns():
+  async def scenario():
+    finish = asyncio.Event()
+    async def app(scope, receive, send):
+      await send({'type': 'http.response.start', 'status': 200})
+      await send({'type': 'http.response.body', 'body': b'first', 'more_body': True})
+      await finish.wait()
+      await send({'type': 'http.response.body', 'body': b'last'})
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        headers = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1)
+        assert b'transfer-encoding: chunked' in headers
+        assert await asyncio.wait_for(reader.readexactly(10), 1) == b'5\r\nfirst\r\n'
+        finish.set()
+        assert await asyncio.wait_for(reader.readexactly(14), 1) == b'4\r\nlast\r\n0\r\n\r\n'
+      finally:
+        finish.set()
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('extra,body', [
+  (b'Content-Length: 1\r\nTransfer-Encoding: chunked\r\n', b'0\r\n\r\n'),
+  (b'Content-Length: 1\r\nContent-Length: 2\r\n', b'xx'),
+  (b'Content-Length: 2junk\r\n', b'xx'),
+  (b'Content-Length: -1\r\n', b''),
+  (b'Content-Length: 99999999999999999999999999999\r\n', b''),
+  (b'Host: duplicate\r\n', b''),
+  (b'Bad Header: value\r\n', b''),
+  (b'Transfer-Encoding: gzip, chunked\r\n', b''),
+  (b'Transfer-Encoding: chunked\r\n', b'ffffffffffffffffffffffffffffffff\r\n'),
+])
+def test_rejects_ambiguous_or_malformed_requests(extra, body):
+  async def scenario():
+    calls = []
+    async def app(scope, receive, send):
+      calls.append(scope)
+      await reply(send)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\n' + extra + b'\r\n' + body)
+        await writer.drain()
+        assert (await response(reader))[0] == 400
+        assert await asyncio.wait_for(reader.read(), 1) == b''
+        assert not calls
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('wire', [
+  b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 33\r\n\r\n',
+  b'POST / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n21\r\n',
+  b'GET / HTTP/1.1\r\nHost: localhost\r\nX-Large: ' + b'x'*1100 + b'\r\n\r\n',
+])
+def test_request_resource_limits(wire):
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send)
+    async with running(app, max_body_size=32, max_header_size=1024) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(wire)
+        await writer.drain()
+        assert (await response(reader))[0] == 400
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_assertion_helpers_raise_on_mismatch():
+  with pytest.raises(AssertionError):
+    eq(200, 500)
+  with pytest.raises(AssertionError):
+    contains('body', 'missing')
+
+
[email protected]('method,status,headers', [
+  (b'HEAD', 200, [(b'content-length', b'9')]),
+  (b'GET', 204, [(b'content-length', b'9')]),
+  (b'GET', 304, [(b'content-length', b'9')]),
+])
+def test_bodyless_responses_do_not_corrupt_next_response(method, status, headers):
+  async def scenario():
+    async def app(scope, receive, send):
+      if scope['path'] == '/first':
+        await reply(send, b'discarded', status, headers)
+      else:
+        await reply(send, b'next')
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(method + b' /first HTTP/1.1\r\nHost: localhost\r\n\r\n'
+                     b'GET /next HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        result = await response(reader, head=method == b'HEAD')
+        assert result[0] == status
+        if status == 204:
+          assert b'content-length' not in result[1]
+        assert (await response(reader))[2] == b'next'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('headers,body', [
+  ([(b'content-length', b'1')], b'too long'),
+  ([(b'content-length', b'10')], b'short'),
+  ([(b'content-length', b'1'), (b'content-length', b'1')], b'x'),
+  ([(b'bad name', b'value')], b'x'),
+  ([(b'x-test', b'value\r\ninjected: yes')], b'x'),
+])
+def test_invalid_application_response_returns_500_and_closes(headers, body):
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, body, headers=headers)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[0] == 500
+        assert await asyncio.wait_for(reader.read(), 1) == b''
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_client_disconnect_reaches_receive_and_releases_application():
+  async def scenario():
+    listening = asyncio.Event()
+    finished = asyncio.Event()
+    async def app(scope, receive, send):
+      await receive()
+      listening.set()
+      assert await receive() == {'type': 'http.disconnect'}
+      finished.set()
+    async with running(app) as (_, port):
+      _, writer = await connect(port)
+      writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+      await writer.drain()
+      await asyncio.wait_for(listening.wait(), 1)
+      writer.close()
+      await writer.wait_closed()
+      await asyncio.wait_for(finished.wait(), 1)
+  asyncio.run(scenario())
+
+
+def test_lifespan_state_and_shutdown_follow_inflight_requests():
+  async def scenario():
+    finish = asyncio.Event()
+    started = asyncio.Event()
+    events = []
+    resource = object()
+    async def app(scope, receive, send):
+      if scope['type'] == 'lifespan':
+        assert await receive() == {'type': 'lifespan.startup'}
+        scope['state']['resource'] = resource
+        await send({'type': 'lifespan.startup.complete'})
+        assert await receive() == {'type': 'lifespan.shutdown'}
+        events.append('shutdown')
+        await send({'type': 'lifespan.shutdown.complete'})
+      else:
+        assert scope['state']['resource'] is resource
+        scope['state']['local'] = True
+        started.set()
+        await finish.wait()
+        events.append('response')
+        await reply(send)
+    async with running(app, lifespan='on') as (server, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        await asyncio.wait_for(started.wait(), 1)
+        shutdown = asyncio.create_task(server.shutdown())
+        await asyncio.sleep(0.01)
+        assert not events
+        finish.set()
+        assert (await response(reader))[2] == b'ok'
+        await asyncio.wait_for(shutdown, 1)
+        assert events == ['response', 'shutdown']
+        assert 'local' not in server._asgi_state
+      finally:
+        finish.set()
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
[email protected]('mode', ['auto', 'on'])
+def test_unsupported_lifespan_is_detected_without_waiting_for_timeout(mode):
+  async def scenario():
+    async def app(scope, receive, send):
+      if scope['type'] == 'lifespan':
+        raise NotImplementedError('no lifespan')
+      await reply(send)
+    server = mrhttp.ASGIServer(app, lifespan=mode)
+    try:
+      if mode == 'on':
+        with pytest.raises(NotImplementedError):
+          await asyncio.wait_for(server.start_server(port=0), 1)
+      else:
+        listener = await asyncio.wait_for(server.start_server(port=0), 1)
+        reader, writer = await connect(listener.sockets[0].getsockname()[1])
+        try:
+          writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+          await writer.drain()
+          assert (await response(reader))[2] == b'ok'
+        finally:
+          writer.close()
+          await writer.wait_closed()
+    finally:
+      await server.shutdown()
+  asyncio.run(scenario())
+
+
+def test_expect_continue_allows_client_to_send_body():
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send, (await receive())['body'])
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 3\r\nExpect: 100-continue\r\n\r\n')
+        await writer.drain()
+        assert await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1) == b'HTTP/1.1 100 Continue\r\n\r\n'
+        writer.write(b'abc')
+        await writer.drain()
+        assert (await response(reader))[2] == b'abc'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_incomplete_request_deadline_closes_slow_client():
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send)
+    async with running(app, timeout_request=0.05) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost:')
+        await writer.drain()
+        assert await asyncio.wait_for(reader.read(), 1) == b''
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_slow_reader_applies_backpressure_and_disconnect_releases_sender():
+  async def scenario():
+    sent = asyncio.Event()
+    released = asyncio.Event()
+    async def app(scope, receive, send):
+      try:
+        await send({'type': 'http.response.start', 'status': 200})
+        for _ in range(64):
+          await send({'type': 'http.response.body', 'body': b'x' * 1024*1024, 'more_body': True})
+        sent.set()
+        await send({'type': 'http.response.body'})
+      finally:
+        released.set()
+    async with running(app) as (_, port):
+      reader, writer = await asyncio.open_connection('127.0.0.1', port, limit=1024)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), 1)
+        await asyncio.sleep(0.05)
+        assert not sent.is_set(), 'send must block when the client stops reading'
+        writer.transport.abort()
+        await asyncio.wait_for(released.wait(), 1)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_error_after_streaming_closes_without_second_response():
+  async def scenario():
+    async def app(scope, receive, send):
+      await send({'type': 'http.response.start', 'status': 200})
+      await send({'type': 'http.response.body', 'body': b'partial', 'more_body': True})
+      raise RuntimeError('late failure')
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        data = await asyncio.wait_for(reader.read(), 1)
+        assert data.startswith(b'HTTP/1.1 200')
+        assert data.count(b'HTTP/1.1') == 1
+        assert b'partial' in data
+        assert not data.endswith(b'0\r\n\r\n')
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_connection_admission_limit_preserves_existing_client():
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send)
+    async with running(app, max_connections=1) as (_, port):
+      reader, writer = await connect(port)
+      second_reader, second_writer = await connect(port)
+      try:
+        assert await asyncio.wait_for(second_reader.read(), 1) == b''
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[2] == b'ok'
+      finally:
+        writer.close()
+        second_writer.close()
+        await asyncio.gather(writer.wait_closed(), second_writer.wait_closed())
+  asyncio.run(scenario())
+
+
+def test_pipeline_capacity_is_bounded_without_worker_crash():
+  async def scenario():
+    async def app(scope, receive, send):
+      await reply(send)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n' * 1100)
+        await writer.drain()
+        await asyncio.wait_for(reader.read(), 2)
+      finally:
+        writer.close()
+        await writer.wait_closed()
+      # The same worker must remain usable after rejecting the connection.
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[2] == b'ok'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
+
+
+def test_encoded_path_and_duplicate_headers_are_preserved():
+  async def scenario():
+    async def app(scope, receive, send):
+      assert scope['path'] == '/café/%'
+      assert scope['raw_path'] == b'/caf%C3%A9/%'
+      assert scope['query_string'] == b'x=%2F'
+      assert [v for n, v in scope['headers'] if n == b'cookie'] == [b'a=1', b'b=2']
+      await reply(send)
+    async with running(app) as (_, port):
+      reader, writer = await connect(port)
+      try:
+        writer.write(b'GET /caf%C3%A9/%?x=%2F HTTP/1.1\r\nHost: localhost\r\nCookie: a=1\r\nCookie: b=2\r\n\r\n')
+        await writer.drain()
+        assert (await response(reader))[2] == b'ok'
+      finally:
+        writer.close()
+        await writer.wait_closed()
+  asyncio.run(scenario())
diff --git a/tests/test_supervisor.py b/tests/test_supervisor.py
new file mode 100644
index 0000000..25acd53
--- /dev/null
+++ b/tests/test_supervisor.py
@@ -0,0 +1,142 @@
+import contextlib
+import http.client
+import os
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+
+import pytest
+
+
[email protected]
+def managed(*options, app='tests.s_supervised:app', module_dir=None):
+  sock = socket.socket()
+  sock.bind(('127.0.0.1', 0))
+  sock.listen()
+  port = sock.getsockname()[1]
+  with tempfile.TemporaryFile() as logs:
+    env = dict(os.environ)
+    if module_dir:
+      env['PYTHONPATH'] = str(module_dir) + os.pathsep + env.get('PYTHONPATH', '')
+    process = subprocess.Popen([
+      sys.executable, '-m', 'mrhttp', app, '--fd', str(sock.fileno()), '--lifespan', 'off',
+      '--timeout-graceful-shutdown', '1', '--timeout-worker-startup', '5',
+      '--timeout-worker-healthcheck', '1', *options], pass_fds=(sock.fileno(),),
+      stdout=logs, stderr=logs, start_new_session=True, env=env)
+    try:
+      deadline = time.monotonic() + 10
+      while True:
+        if process.poll() is not None:
+          logs.seek(0)
+          raise AssertionError(logs.read().decode(errors='replace'))
+        try:
+          request(port)
+          break
+        except (OSError, http.client.HTTPException):
+          if time.monotonic() > deadline:
+            raise AssertionError('Supervisor did not become ready')
+          time.sleep(0.025)
+      yield process, port
+    finally:
+      sock.close()
+      if process.poll() is None:
+        process.send_signal(signal.SIGTERM)
+        try:
+          process.wait(timeout=5)
+        except subprocess.TimeoutExpired:
+          os.killpg(process.pid, signal.SIGKILL)
+          process.wait()
+      if process.returncode:
+        logs.seek(0)
+        print(logs.read().decode(errors='replace'))
+
+
+def request(port, path='/pid', timeout=0.3):
+  client = http.client.HTTPConnection('127.0.0.1', port, timeout=timeout)
+  try:
+    client.request('GET', path)
+    result = client.getresponse()
+    assert result.status == 200
+    return result.read()
+  finally:
+    client.close()
+
+
+def wait_for_new_pid(port, old, timeout=6):
+  deadline = time.monotonic() + timeout
+  while time.monotonic() < deadline:
+    try:
+      value = request(port)
+      if value != old:
+        return value
+    except (OSError, http.client.HTTPException):
+      pass
+    time.sleep(0.025)
+  raise AssertionError('Worker was not replaced')
+
+
[email protected]('failure', ['/crash', '/hang'])
+def test_worker_failure_is_recovered_without_stopping_supervisor(failure):
+  with managed('--workers', '1') as (process, port):
+    old = request(port)
+    with pytest.raises((OSError, http.client.HTTPException)):
+      request(port, failure, timeout=2)
+    assert wait_for_new_pid(port, old)
+    assert process.poll() is None
+
+
+def test_request_limit_recycles_worker():
+  with managed('--limit-max-requests', '3', '--limit-max-requests-jitter', '1') as (process, port):
+    old = request(port)
+    assert wait_for_new_pid(port, old)
+    assert process.poll() is None
+
+
+def test_rolling_restart_loads_fresh_code_and_finishes_inflight_request(tmp_path):
+  module = tmp_path / 'rolling_app.py'
+  template = '''import asyncio
+async def app(scope, receive, send):
+    if scope['path'] == '/slow':
+        await asyncio.sleep(0.8)
+    await send({{'type': 'http.response.start', 'status': 200}})
+    await send({{'type': 'http.response.body', 'body': {version!r}}})
+'''
+  module.write_text(template.format(version=b'old'))
+  with managed(app='rolling_app:app', module_dir=tmp_path) as (process, port):
+    old_client = http.client.HTTPConnection('127.0.0.1', port, timeout=3)
+    try:
+      old_client.request('GET', '/slow')
+      time.sleep(0.05)
+      module.write_text(template.format(version=b'new-version'))
+      process.send_signal(signal.SIGHUP)
+      deadline = time.monotonic() + 6
+      while request(port) != b'new-version':
+        assert time.monotonic() < deadline
+        time.sleep(0.025)
+      assert old_client.getresponse().read() == b'old'
+      assert process.poll() is None
+    finally:
+      old_client.close()
+
+
+def test_factory_and_shared_metrics_across_two_workers():
+  with managed('--workers', '2', '--factory', '--metrics-path', '/metrics', app='tests.s_supervised:factory') as (_, port):
+    seen = set()
+    deadline = time.monotonic() + 5
+    count = 0
+    while time.monotonic() < deadline:
+      body = request(port)
+      count += 1
+      assert body.startswith(b'factory:')
+      seen.add(body)
+      if len(seen) == 2:
+        break
+      time.sleep(0.01)
+    assert len(seen) == 2
+    metrics = request(port, '/metrics')
+    assert b'mrhttp_http_requests_total{status="200"}' in metrics
+    count_line = next(line for line in metrics.splitlines() if line.startswith(b'mrhttp_request_duration_seconds_count '))
+    assert int(count_line.split()[-1]) >= count + 1