Answer requests cancelled at shutdown with 503 in the contract format

After the drain window uvicorn waits for accepted requests for three
seconds and then cancels their tasks. CancelledError is a BaseException,
so neither the pipeline nor ServerErrorMiddleware saw it and uvicorn
answered with its own text/plain 500 without X-Request-Id and
X-Instance-Id. The pipeline now handles the cancellation next to the
request timeout: it logs request.cancelled, sends 503 unavailable in the
common error format when the response has not started and re-raises,
so uvicorn only closes the transport after the buffered answer.

The declared Content-Length check joins the guard as a rejection to keep
the call within the statement limit; behaviour is unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-30 05:39:09 +03:00
co-authored by Claude Opus 5.5
parent 13e856ebd4
commit aa1485bd86
3 changed files with 33 additions and 15 deletions
+18 -3
View File
@@ -49,6 +49,17 @@ def status(port: int, path: str) -> int:
return 0
def answer_of(connection: socket.socket) -> tuple[str, dict[str, str], dict]:
data = b""
while chunk := connection.recv(4096):
data += chunk
connection.close()
head, _, body = data.partition(b"\r\n\r\n")
status, *lines = head.decode("latin-1").split("\r\n")
headers = dict(line.lower().split(": ", 1) for line in lines)
return status, headers, json.loads(body) if body else {}
def begin_registration(port: int) -> tuple[socket.socket, bytes]:
body = json.dumps(new_user("drain")).encode()
head = (
@@ -97,17 +108,21 @@ def test_sigterm_leaves_rotation_then_closes_and_cancels_stuck_requests() -> Non
pending.close()
code = server.wait(timeout=SHUTDOWN + 2)
exited = time.monotonic() - sent
cancelled = stuck.recv(64).split(b"\r\n")[0].decode()
stuck.close()
cancelled, headers, error = answer_of(stuck)
finally:
if server.poll() is None:
server.kill()
print(f"окно: ready/live {during}, порт закрыт через {closed:.2f} с, выход {exited:.2f} с")
print(f"запрос, принятый до SIGTERM и дописанный после закрытия порта: {answer}")
print(f"запрос, тело которого так и не пришло: {cancelled or 'соединение закрыто без ответа'}")
print(f" content-type {headers.get('content-type')}, тело {error}")
assert during == (503, 200)
assert answer == "HTTP/1.1 201 Created"
assert cancelled == "HTTP/1.1 500 Internal Server Error"
assert cancelled == "HTTP/1.1 503 Service Unavailable"
assert headers["content-type"] == "application/json"
assert headers["x-instance-id"]
assert error["error"]["code"] == "unavailable"
assert error["error"]["request_id"] == headers["x-request-id"]
assert DRAIN - 0.2 <= closed < SHUTDOWN
assert exited < SHUTDOWN
assert code == 0