SIGTERM Graceful Shutdown: Why In-Flight Requests Die on Deploy

Dark neon cover: three bars for the same twelve in-flight requests - the default signal answers 0 in 0.90 ms, a blind sleep answers 12 in 1,028 ms, the drain policy answers 12 in 435.6 ms, and chips reading 4,505 ms stuck with 20 idle keep-alive sockets against 181.4 ms once they are closed, 0 of 12 requests delivered when asyncio.run cancels them, and a 300 ms deadline that cut a 5,000 ms request off at 330.3 ms

A process can exit cleanly and still drop every request it was serving. On this host a server holding 12 requests of 400 ms each was sent SIGTERM; the process was gone 0.90 ms later with exit status -15, and 0 of the 12 clients ever received a reply. Handling the signal in Python does not fix it: when main() returns, asyncio.run cancels the tasks and the same 12 requests die at 27.4 ms with exit status zero.

What fixes it is a deadline that counts requests. A drain that closes the listening socket, counts the requests still in flight, closes the keep-alive connections that have carried nothing for their grace and holds the rest until an in-flight count of zero served 12 of 12 and exited 435.6 ms after the signal. Twenty sockets that were connected but idle moved the two obvious alternatives to 4,505 ms (the cap, with the process still running) and 1,030 ms (the whole window, with the listener still accepting); the same drain took 181.4 ms and closed all 20 of them.

The drain this page builds is a bare asyncio server’s. It is for a process that owns its listening socket, its connections and its request handlers – asyncio.start_server and the code around it, with no framework between the socket and the handler. One of the two problems below is already solved in the frameworks: uvicorn and gunicorn close the keep-alive connections that have gone idle, and section 11 measures both servers doing it. Waiting for the requests that are still running is not the half they lack either: a server that already owns the shutdown waits for them, and section 11 measures that too. What neither of them gives you is a cap that asks whether the wait is still buying anything – their only deadline is the number of seconds an operator passes in, or by default the orchestrator’s SIGKILL, and a request that was still being worked on when the deadline expired is cut off with nothing in the log to say the process had a choice. That question, and the line it writes, are the half worth carrying over.

TL;DR

  • SIGTERM’s default action is termination, not cleanup. Without a handler the kernel ends the process; here it exited in 0.90 ms with status -15 and 0% of the in-flight requests answered.
  • Exit status zero is not a clean shutdown. Returning from asyncio.run cancels the handlers: 36 requests were lost across 3 runs – all 12 in each – and every handler had seen CancelledError.
  • Count requests, not connections. Waiting for connections to close hit the cap at 4,505 ms with 20 idle keep-alive sockets open; counting requests finished in 181.4 ms.
  • The deadline is a cap, not a wait. Windows of 300 ms, 600 ms and 1,200 ms stopped a 5,000 ms request at 330.3 ms, 632.3 ms and 1,240 ms, while requests that ended in 150 ms closed a 1,200 ms window after 127.7 ms because the count reached zero.
  • The idle grace is a real cost, and a client that keeps its socket is what uncovers it. Every client in table 9 closes its connection when its reply arrives, so nothing is left to close; a client that holds the socket – as an HTTP client does – puts the exit floor at the last reply plus the grace: 686.8 ms against 435.9 ms for the same 12 requests, and waiting for connections never ends at all (4,510 ms, the cap).
  • On an asyncio stream, time is a guess and the socket is not. A 250 ms grace covers a 200 ms delay before the handler’s first read but not a 600 ms one, which lost every request again; asking the stream’s own buffer answered all 4 of them, at 809.6 ms.
  • What this runbook is not for. Every measurement here is a bare asyncio server’s – no framework and no ASGI layer – so check the server you already run before adding a drain to it: table 12 is uvicorn and gunicorn closing the idle connections themselves. Carry the count and the progress gate to a framework; carry this drain to a server you wrote.

The shape of the fix. One object owns the shutdown: it stops accepting, counts requests inside the connections it accepted, and applies a decision to each sample until nothing is in flight or the budget is spent. Section 6 is the decision as a state machine, section 7 the object that takes the samples, and section 8 the five shutdowns measured against the same twelve requests.

1. The deploy that ends requests

A rolling deploy sends SIGTERM to one pod at a time. The pod’s log ends with “shutting down”, the orchestrator sees exit status zero, and the load balancer logs a burst of server errors for the connections that were open when the process left. Nothing in the container’s log says a request was dropped, because nothing counted requests: the process counted connections, and the connections were closed by the kernel rather than by the application.

This page reproduces that shape on one host: a line-protocol server whose handler sleeps for a requested number of milliseconds and then writes OK, so a request in flight is a real coroutine waiting on a real timer. Clients are separate connections in the same process’s event loop; they send one request each and record the first thing the socket did back. Every arm below uses the same 12 clients, the same 400 ms request, the same signal at 120 ms after the first connection, and a fresh server process, so the difference between rows is the shutdown and nothing else. The host has 2 CPUs and no cgroup, so the container limit is an assumption this page does not measure (Table 1).

Every wall time in the tables below is a sample, so each one says how many runs it came from: the shutdowns that are compared with each other are the median of 5 runs, table 4’s cancellation is 3, and the one-observation readings – the four connection endings of table 2, the close in table 3, the host in table 1 – are one run each. Two things are held constant so the tables can be compared: the drain is given a 1,000 ms window, a 500 ms extension granted once, a 25 ms poll and a 250 ms idle grace unless a caption says otherwise, and each client closes its socket as soon as it has its reply unless a row says it keeps one. That second choice is not neutral – it hides the idle grace – so section 8 measures the other kind of client as well.

How the exit of a process is timed here

Every shutdown figure on this page is the moment the process left, measured by a watcher started the instant the signal is sent: it waits for the child in a thread of its own, so nothing the probe does afterwards can move the reading. That matters because the probe has work of its own after the signal – it opens 2 connections to ask whether the listener is still there, after a 30 ms pause – and a harness that checked poll() only after that work would charge the pause to the process. On the same runs of table 9 the two readings for the default arm were 0.90 ms from the watcher and 71.5 ms from a poll loop. The lag quoted for those runs is the median of the five per-run differences, 70.5 ms (the runs ranged 70.1 ms to 76.3 ms), and subtracting the two medians instead gives 70.6 ms: each of those is a median of its own five readings, and the median of five differences is not the difference of the two medians, so the 0.10 ms between the two answers is arithmetic rather than measurement. Both readings are in results/06_arms.json, for every arm.

ReadingValueWhere it comes from
Kernel6.12.8+uname, probe 00
Python3.12.16platform, probe 00
CPUs2os.cpu_count, probe 00
Page size4,096 bytessysconf, probe 00
Memory1,486.5 MiB/proc/meminfo, probe 00
SIGTERM to a process without a handlerstatus -15probe 09, a child process
SO_LINGER when nobody sets it0, 0 sgetsockopt, probe 09
TCP_NODELAY on an asyncio connection1getsockopt, probe 09
Server.close_clients() in this Pythonabsenthasattr, probe 09
FIN timeout60,000 ms/proc/sys, probe 00
Listen backlog ceiling4,096/proc/sys, probe 00
Table 1: the host and the constants these figures belong to. The last two rows are the kernel’s, not the application’s: a backlog an application asks for is capped at 4,096 here, and a half-closed socket waits out 60,000 ms before the kernel forgets it.

2. Three ways a connection ends

The client’s socket has only a few ways to learn that the server is gone, and a shutdown that wants to lose nothing has to know which one it is producing. Probe 03 runs four handlers, each ending a connection differently, and records what the client’s readline() returned (Table 2).

Handler’s last actClient sawBytesWhat it means
Read the request, wrote OK, closedcomplete3reply delivered, then FIN
Closed with the request still unreadreset0reset: the request was thrown away
Wrote OK and aborted the transportcomplete3the bytes had already reached the kernel
Wrote OK without its newline, closedpartial2half a reply: no way to tell it is half
Table 2: probe 03. close() sends a FIN after the bytes the handler wrote, because SO_LINGER is off (Table 1); abort() only becomes a reset when something is still unread.

Two lessons come out of that table. A reply cut in half is worse than an empty one – the client parsed something and cannot know whether the rest was coming – so a shutdown should either finish a handler’s write or make the connection unmistakably broken, never close between two writes. And a clean end of stream is not evidence that a request succeeded: in the first arm of Table 9 the client sees exactly the same end of stream after a lost request as after a reply it chose not to write. That is why the count of what was served has to come from the server.

Why an unread request is what turns a close into a reset

A close is a statement about the sender’s direction: the process has nothing more to write, and the kernel sends a FIN. It says nothing about the data the peer already sent. When a socket is closed with bytes still waiting in its receive queue, Linux answers with a reset instead, because the alternative would be to pretend the peer’s request was received and then ignore it. That is why probe 03’s second arm sees a reset without the handler raising anything, and why an application that wants a clean end of stream has to read the request before it closes the socket.

The drain prefers a finished write to a dropped connection. It waits for the handler, and drops only the connection whose handler has run out of time – the one case where there is nothing left to wait for.

3. close() stops the listener, not the server

The first instinct is to call server.close() in the signal handler. Probe 02 does exactly that against a server that is already serving one connection, and measures three things separately: whether new connections are refused, whether the connection accepted before the close still gets served, and what wait_closed() waits for (Table 3). The wait is measured by leaving wait_closed() as a task of its own and reading it later: a probe that wrapped the call in a timeout would record the timeout instead of the release.

ReadingValueWhat it shows
Connections refused after close()5 refusedthe listening socket is gone
Connections accepted after close()0no new work arrives
Request served on the connection opened before ityesexisting handlers keep running
Descriptors held by the process10 to 9one listener released
wait_closed() while that connection is openstill pendingthe close had not finished
wait_closed() releasing once the client closes0.20 msreleased by the client, not by the close
Table 3: probe 02. The server closed its listener, kept serving the connection it had accepted, and its wait_closed() had not returned 50.9 ms later – it returned 0.20 ms after the client ended the connection.

That last row is the trap this Python sets for a shutdown built on close(). Server.wait_closed() also waits for every accepted connection’s handler to finish, and a keep-alive connection with no request on it never finishes: the client keeps it open for the next request. A drain that awaits wait_closed() before it starts measuring is therefore waiting for something that has no deadline, and the deadline it wrote never applies. The drain in section 7 closes the listener, takes its first sample immediately, and never awaits wait_closed() before the sample.

Production SRE Note: In this Python the standard library cannot close the clients it accepted: Server.close_clients() and abort_clients() do not exist (Table 1), so the application has to keep the connections it accepted. That is one dictionary and two counters in section 7, and it is also what makes the request count possible – the same objects that let a shutdown close a socket can tell it whether a request is running on that socket.

4. asyncio.run cancels what is in flight

The second instinct is to handle the signal and return from main(). That looks like the cleanest possible shutdown – an exit status of zero, no traceback, no exception in the log – and it drops every request, because asyncio.run cancels the tasks it is still running when main() returns. Probe 05 sends the signal to 12 in-flight requests of 400 ms and records both the client’s view and the handler’s (Table 4).

ArmWall after signalReplies deliveredRequests lostExit status
Handler re-raises CancelledError27.4 ms0360
Handler swallows it and finishes the work430.5 ms3600
Table 4: probe 05, median of 3 runs of 12 clients. The same cancelled handlers are in both rows: 36 of them saw CancelledError in each run of the first row, and the second row’s handlers saw it and continued.

Cancellation is cooperative. asyncio.run cancels the tasks and then waits for them, so a handler that re-raises ends the process in 27.4 ms with nothing served, and a handler that ignores the cancellation keeps the process alive for as long as its work takes. That second row needs one figure read carefully. Its handler sleeps the whole 400 ms again when it is cancelled instead of what is left of it, so the arm’s 430.5 ms is about one request time after the cancellation – not two – and the ratio those two wall times make, 15.7 times, is a comparison between a fixture that re-sleeps its delay and one that stops at once, not a measurement of how much slower a swallowing handler is. It is 30.5 ms longer than a single request, which is the cancellation and the write on top of the sleep. What the row proves is the part that matters: every reply was delivered and the process stayed until the handlers had finished. A framework whose request handler catches CancelledError to finish a transaction is therefore not protected by the deadline either; it is protected by nothing except the orchestrator’s SIGKILL, and a killed process answers nothing at all.

5. Count requests, not connections

A load balancer’s connections outlive the requests on them. Probe 04 opens 20 keep-alive connections that send nothing, then 5 requests of 200 ms on five more, and sends the signal while those requests are running. Three shutdowns meet that shape (Table 5).

ShutdownWall after signalRequests answeredListener afterwardsEnded by
Close the listener, await every connection’s handler4,505 ms5refuses new connectionsthe cap
Close nothing, sleep the window1,030 ms5still accepts (2 of 2 accepted, refused none)the sleep
Close the listener, wait for in-flight requests181.4 ms5refuses new connections (2 of 2 refused)the count
Table 5: probe 04, median of 5 runs per arm (the third arm ranged 180.8 ms to 197.8 ms) with 20 idle keep-alive connections and 5 requests of 200 ms. The drain’s idle grace is 250 ms: a connection is closed only after it has carried nothing that long. Each of the five clients closes its socket as soon as its reply arrives, so none of them is still open when the drain looks – a client that keeps its socket is table 10’s subject. The first arm was killed at the 4,500 ms cap in 5 of 5 runs with its requests already answered; the third closed all 20 idle connections and left as soon as the last request it was counting had finished.

The requests in the first row were all answered, and the process still had to be killed: the twenty idle sockets had nothing left to do and no reason to close. That is the difference the second row cannot make and the third row is built on – a connection is finished when its handler returns, but a request is finished when the handler has written its reply, and only the server knows which one it is looking at.

None of this is a number the standard library gives an application. asyncio.Server knows how many connections it accepted and hands each one to a callback; it does not know whether a request is running inside that callback. The count has to be kept where the request starts and stops, which in an ASGI or WSGI framework is the first and last line of the handler rather than the connection’s whole lifetime.

A socket is not a request until a handler has read it. The count above is correct only about requests something is already serving. Between a request reaching the socket and the handler reading it there is a real interval in every server – a TLS handshake, a middleware stack, a loop busy with another task on the same worker – and in that interval the connection looks exactly like the idle sockets a load balancer left behind. Probe 11 puts a request on the socket and holds the handler back before its first read, then signals with 4 such connections open. It asks “is this socket idle?” three ways: from the count alone, from the clock, and from the socket itself (Table 6).

Delay before the handler readsReplies: close at onceReplies: wait 250 msReplies: ask the socket
none4 of 44 of 44 of 4
200 ms0 of 44 of 44 of 4
600 ms0 of 40 of 44 of 4
Table 6: probe 11, 5 runs per cell, with 4 connections holding a 300 ms request each and the signal at 150 ms. Each cell is how many of the 4 requests were answered – “0 of 4” means all four were lost in every run of that cell. The columns are three answers to the same question: the count alone (idle grace 0), the clock (idle grace 250 ms), and the socket (idle grace 0 with FIONREAD). Every request lost here was read by nobody and answered with nothing, and the client cannot tell that apart from a shutdown that forgot it: the connection in a failing cell ended with an ordinary end of stream – 0 resets across the runs, because the request had already arrived – which is what it would have seen if the server had simply dropped the request.

The first cell of the middle row is the defect a count alone cannot see. Closing on the sample that finds the connection idle dropped all 20 requests across the runs, and the drain left at 27.1 ms with its log saying no request in flight – true of the count it kept, and false about the four requests on the sockets it had just closed. The clock’s answer fixes that cell: with a 250 ms grace nothing is closed until a connection has carried nothing for that long, the handlers read at 200 ms, and all 4 are answered at 432.9 ms.

The bottom row is where the clock runs out of answers. A handler that takes 600 ms before it reads is still inside its own startup when the 250 ms grace expires, so the same policy closes the connection at 177.7 ms and loses all 20 requests of the runs, exactly as it did with no grace at all. No grace value can be right for every application: the interval it must cover is the one the framework spends before its first read, and that is a property of the framework, not of the drain.

The socket can answer instead. A connection that has bytes waiting on it is not idle, and the drain can ask before it closes one: FIONREAD for how much the kernel still holds, or recv(1, MSG_PEEK | MSG_DONTWAIT) for the first byte of it, neither of which consumes anything the handler will later read. The third column is the same 600 ms delay with the grace removed and that question asked: all 4 requests answered, none lost, and the process left at 809.6 ms once the last handler had written its reply, instead of at the window.

There is a trap in that, and probe 16 measures it. In an asyncio server the bytes of a request do not wait in the kernel for the handler: the transport reads them off the socket as they arrive and buffers them in the StreamReader. On 5 runs of the race shape, with the request sent and the handler held back, the kernel reported 0 unread bytes and MSG_PEEK returned nothing, while the stream’s buffer held 8 bytes: in all 5 runs only the reader knew. A kernel-only peek would therefore have called every one of those connections idle. The check below asks both – the reader’s buffer first, the kernel second, for the transports that have not read yet – and a plain TCP socket is the only thing it can see: behind TLS the socket holds ciphertext in records, so the check cannot tell a request from a handshake fragment, and there the grace or the framework’s own signal remains the answer.

from __future__ import annotations
from .probe import pending_bytes
def unread(self) -> bool:
    """Is something waiting on this socket that no handler has read yet?

    The grace is a time, and a time is a guess about how long an application takes
    between accepting a connection and reading from it. This is the same question
    asked of the socket itself, and it has two halves. The stream's own buffer is
    checked first: asyncio's transport moves arriving bytes out of the socket as soon
    as they land, so a request that arrived during a TLS handshake or a slow
    middleware stack is already in the reader and no longer in the kernel. The kernel
    is asked second, with ``FIONREAD``, for the bytes a transport has not read yet -
    a raw socket server, or a stream whose reading was paused. A kernel-only peek
    would report nothing for the first case, which is the one this page measured.

    This is a check on an asyncio stream and on nothing else. ``_buffer`` is a private
    attribute of ``StreamReader``, which a server built on ``asyncio.start_server``
    has and a ``Protocol``-based server such as uvicorn's does not: there is no stream
    to ask, and the protocol has already taken the bytes out of the kernel, so both
    halves answer nothing. A server that keeps its own buffer has to count the request
    where its protocol sees one - ``Protocol.data_received``, or the first line of the
    framework's request handler - which is the same moment the in-flight count opens.
    """
    buffered = getattr(self.reader, "_buffer", None)
    if buffered:
        return True
    return pending_bytes(self.writer) > 0
from __future__ import annotations
def _close_idle(self, ignore_grace: bool = False, sample: Sample | None = None) -> None:
    """Close the connections that have carried nothing for long enough.

    The grace is what keeps a request that has arrived but not been read yet from
    being closed out from under its handler: from the drain's side the socket looks
    idle, and only the clock can tell it apart from one a load balancer left behind.
    The clock is not the only witness: a socket with unread bytes is left alone
    whatever its grace says, because closing it would throw away a request the count
    has never seen. Both answers come from the walk the decision was taken on - the
    ``sample`` argument - so the closing pass asks no socket a second time; on an abort
    (the deadline reached, or a second signal) the grace and the peek are both given
    up: the drain is leaving, and what it could not count it does not keep.
    """
    sample = self._scan() if sample is None else sample
    for key, conn in list(self.conns.items()):
        if conn.active > 0:
            continue
        if ignore_grace:
            conn.close()
            self._remove(conn)
            self.counts.closed_idle += 1
            continue
        reading = sample.readings.get(key)
        if reading is None or reading[0] or reading[1]:
            continue
        conn.close()
        self._remove(conn)
        self.counts.closed_idle += 1

Two conditions instead of one, and a third witness. A connection is closed when nothing is running on it, it has been that way for the grace, and nothing is waiting on it; the grace still separates a socket the load balancer left behind from a request that is on its way, and the peek separates both from a request that has already arrived. Both answers come from the walk the decision was taken on – the sample argument – so the closing pass asks no socket a question the sample already asked, and the same clock decides all three: a drain that is already past its window closes what is left without waiting for a grace it no longer has.

That check belongs to an asyncio stream, and to nothing else. Conn.unread() reads reader._buffer, which is a private attribute of asyncio.StreamReader: a server built from asyncio.start_server has one, and a server built from Protocol objects – which is what uvicorn’s HTTP implementations are – does not. There the protocol has already taken the bytes out of the kernel into its own parser, so FIONREAD reports nothing either, and this check answers “idle” for a connection holding a whole request. A protocol-based server counts the request where its protocol sees the data instead – Protocol.data_received, or the framework’s own request-start hook, the first line of the handler or of a middleware – which is also where started_request goes, so the count and the peek close at the same moment. The table above is therefore a measurement of this server, not of every server, and section 10 lists the rest of what the check cannot see.

6. The policy: four states, eight transitions

The decision is a pure function of one sample: the state, the time since the signal, the number of requests in flight now, the number of connections still inside their idle grace, of those the number whose socket says it is holding bytes no handler has read, the number of requests that finished inside the progress window, and whether the one extension has been spent. It returns the next state, an action, and a reason that goes into the log line. Writing it as a function rather than as a loop is what lets the tests drive every gate with a fake clock instead of sleeping through a five-second window.

The order of the checks is the policy. Nothing in flight – and no connection that has only just stopped carrying something – is checked before any deadline, so an idle process exits at the first sample instead of sitting out a window it does not need, while a socket that was handed a request a moment ago is not closed in that same sample. The hard cap is checked before the progress gate, so an extension cannot carry a process past the budget its operator allowed. And the gate reads the number of requests that finished inside the last 500 ms, not the difference between two adjacent samples: a handler working through small writes can spend a sample or two inside one request, and a gate that looked only at the previous interval would call it stuck. Fifty milliseconds of silence is not a stuck handler; half a second of it is.

A stop and an abort are two different statements. A window that closes while a connection has merely carried nothing for its grace has nothing to give up: the count is zero, no socket is holding bytes, and closing those connections loses nothing, so the drain stops. The same window over a socket that is holding a request no handler read is a loss, and it is reported as an abort naming what it dropped. That is what makes the rule in section 8’s deploy order true rather than approximately true: an abort line always names a request that was lost, and a drain that logs no abort lost nothing.

The definitions below are drainage/policy.py verbatim – the states, the actions, Limits, Decision, decide and the four helpers it calls, _load, _waiting, _count and _decision, with the imports the module gives them – so the gates a reader checks are the gates the tests assert on, and the block can be pasted into the package as it stands. The helpers are in it because decide calls them: _load is what names what an abort gives up, _waiting is what names the two reasons a drain is still waiting, and _count is what puts a number and its noun in the line, so a drain with one straggler prints 1 connection rather than 1 connections. A block that printed only decide would raise NameError on the first hard cap it reached.

from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from .report import describe
class State(str, Enum):
    SERVING = "serving"
    DRAINING = "draining"
    OVERDUE = "overdue"
    STOPPED = "stopped"

class Action(str, Enum):
    KEEP = "keep"
    WAIT = "wait"
    EXTEND = "extend"
    STOP = "stop"
    ABORT = "abort"

class IllegalTransition(RuntimeError):
    """A decision tried to move the machine somewhere it cannot go."""

@dataclass(frozen=True)
class Limits:
    """The numbers a shutdown is allowed to spend, in milliseconds.

    ``grace_ms`` is the window in which in-flight requests are left alone.
    ``extension_ms`` is granted at most once, and only to a drain whose requests are
    still finishing; ``poll_ms`` is how often the sample is read, and it must fit twice
    inside the grace window or no decision can see progress at all. An extension no
    longer than one poll interval would be spent before it could ever be sampled, so it
    is refused rather than silently granted and ignored.

    ``progress_ms`` is how far back the progress gate looks: it reads the number of
    requests that finished inside that window, not the difference between two adjacent
    samples, so a handler that is getting work done slowly - one request every few
    samples, as a queue of small writes does - is not mistaken for one that is stuck.

    ``idle_grace_ms`` is how long a connection must have carried nothing before the
    drain closes it. A request can reach a socket whose handler has not read it yet -
    a TLS handshake, a middleware stack, a shared loop that was busy with another task -
    and a drain that closes every idle connection at its first sample throws that
    request away before the count could possibly see it. The grace is the time the
    application needs between accepting a connection and reading from it, and it is
    also why "nothing in flight" is not on its own a reason to leave: a socket that is
    still inside its grace may be holding a request that the count has never seen.
    """

    grace_ms: int = 5000
    extension_ms: int = 2000
    poll_ms: int = 25
    progress_ms: int = 500
    idle_grace_ms: int = 250

    def __post_init__(self) -> None:
        if self.grace_ms <= 0:
            raise ValueError("grace_ms must be positive")
        if self.extension_ms < 0:
            raise ValueError("extension_ms cannot be negative")
        if self.poll_ms <= 0:
            raise ValueError("poll_ms must be positive")
        if self.grace_ms < 2 * self.poll_ms:
            raise ValueError("grace_ms must fit two poll intervals")
        if 0 < self.extension_ms < self.poll_ms:
            raise ValueError("extension_ms must fit one poll interval")
        if self.progress_ms < self.poll_ms:
            raise ValueError("progress_ms must fit one poll interval")
        if self.progress_ms > self.grace_ms:
            raise ValueError("progress_ms cannot exceed the grace window")
        if self.idle_grace_ms < 0:
            raise ValueError("idle_grace_ms cannot be negative")
        if self.idle_grace_ms >= self.grace_ms:
            raise ValueError("idle_grace_ms must be shorter than the window")

    @property
    def hard_ms(self) -> int:
        """The longest a shutdown may take: the grace window plus one extension."""
        return self.grace_ms + self.extension_ms

@dataclass(frozen=True)
class Decision:
    """One sample's answer: where the machine goes, what to do, and why."""

    state: State
    action: Action
    reason: str
    elapsed_ms: float
    in_flight: int
    extended: bool

    def line(self) -> str:
        return describe(self)

def decide(
    *,
    state: State,
    elapsed_ms: float,
    in_flight: int,
    fresh_conns: int,
    progress_completed: int,
    extended: bool,
    limits: Limits,
    unread_conns: int = 0,
) -> Decision:
    """Decide one step of a shutdown from the sample the caller just read.

    The order of the checks is the policy. Nothing in flight - and no connection still
    inside its idle grace - is checked before every deadline, because a process with
    nothing left to serve should exit at once rather than sit out the window, while a
    socket that has just been handed a request its handler has not read yet must not be
    closed on that same sample. Past the window the same question is asked again with the
    two kinds of connection separated: a socket that has merely carried nothing for its
    grace has no request on it that the drain could name, so a window that closes on those
    stops without an abort, while a socket the drain's ``unread`` check says is holding
    bytes does have a request on it - one the count never saw - and closing it is an abort
    and is logged as one. That is what keeps one rule true: an abort line always names a
    request that was lost. The hard cap is checked before the progress gate, so an
    extension cannot carry a process past it. And the progress gate reads the number of
    requests that have *finished inside the last* ``progress_ms``, not the number in
    flight: on a keep-alive connection one request can end while the next one starts, and
    a net count would not move while the handler was plainly still working. A window
    rather than a single interval is what keeps a slow but working handler from being cut
    off for the sample it happened to spend inside one request.

    ``fresh_conns`` is the number of idle connections the drain is not yet willing to
    close: those that have carried nothing for less than ``idle_grace_ms``, plus any whose
    socket says it is holding bytes. From the count's side they are idle, and from the
    application's side they may be carrying a request that has not been read.
    ``unread_conns`` is how many of them the socket itself said are holding bytes - it is
    zero when the caller does not ask the socket, and never more than ``fresh_conns``.
    """
    if in_flight < 0:
        raise ValueError("in_flight cannot be negative")
    if fresh_conns < 0:
        raise ValueError("fresh_conns cannot be negative")
    if progress_completed < 0:
        raise ValueError("progress_completed cannot be negative")
    if unread_conns < 0:
        raise ValueError("unread_conns cannot be negative")
    if unread_conns > fresh_conns:
        raise ValueError("unread_conns must be a subset of fresh_conns")
    if state is State.STOPPED:
        return _decision(State.STOPPED, Action.KEEP, "already stopped", elapsed_ms,
                         in_flight, extended)
    if in_flight == 0 and fresh_conns == 0:
        return _decision(State.STOPPED, Action.STOP, "no request in flight", elapsed_ms,
                         in_flight, extended)
    if in_flight == 0 and unread_conns == 0 and elapsed_ms >= limits.grace_ms:
        # Every request has been answered, and no socket is holding one the count has not
        # seen. The connections still registered are inside their idle grace and nothing
        # else - closing them loses nothing, so this is a stop and not an abort.
        reached = (f"hard cap of {limits.hard_ms} ms" if elapsed_ms >= limits.hard_ms
                   else "window closed")
        return _decision(State.STOPPED, Action.STOP,
                         f"{reached} with {_count(fresh_conns, 'idle connection')} and no "
                         f"request counted", elapsed_ms, in_flight, extended)
    if elapsed_ms >= limits.hard_ms:
        return _decision(State.STOPPED, Action.ABORT,
                         f"hard cap of {limits.hard_ms} ms reached with "
                         f"{_load(in_flight, unread_conns)}", elapsed_ms, in_flight, extended)
    if elapsed_ms < limits.grace_ms:
        if in_flight == 0:
            return _decision(State.DRAINING, Action.WAIT,
                             f"no request in flight; {_waiting(fresh_conns, unread_conns)}",
                             elapsed_ms, in_flight, extended)
        return _decision(State.DRAINING, Action.WAIT,
                         f"within the grace window with {in_flight} in flight", elapsed_ms,
                         in_flight, extended)
    if extended:
        return _decision(State.OVERDUE, Action.WAIT,
                         f"past the window on the extension with {in_flight} in flight",
                         elapsed_ms, in_flight, extended)
    if in_flight == 0:
        # Only reachable with unread_conns > 0: a socket is holding bytes no handler has
        # read, so closing it drops a request even though the count is zero.
        return _decision(State.STOPPED, Action.ABORT,
                         f"window closed with {_count(unread_conns, 'socket')} holding unread "
                         f"bytes", elapsed_ms, in_flight, extended)
    if progress_completed <= 0:
        return _decision(State.STOPPED, Action.ABORT,
                         f"grace window closed and nothing finished in the last "
                         f"{limits.progress_ms} ms: {in_flight} in flight", elapsed_ms,
                         in_flight, extended)
    return _decision(State.OVERDUE, Action.EXTEND,
                     f"{in_flight} in flight and {progress_completed} finished in the last "
                     f"{limits.progress_ms} ms: one extension", elapsed_ms, in_flight, extended)

def _load(in_flight: int, unread_conns: int) -> str:
    """What an abort is giving up on, named the way the log line needs it."""
    parts = []
    if in_flight:
        parts.append(f"{in_flight} in flight")
    if unread_conns:
        parts.append(f"{_count(unread_conns, 'socket')} holding unread bytes")
    return " and ".join(parts)

def _waiting(fresh_conns: int, unread_conns: int) -> str:
    """What a wait is still giving time to, in the log line's own words.

    The two kinds of connection are named apart because they are different reasons to
    wait: one is inside its idle grace with nothing on it, and the other is holding bytes
    the count has never seen. A line that called both ``inside their idle grace`` would be
    describing a connection the drain can see a request on as one it is only guessing about.
    """
    inside = fresh_conns - unread_conns
    if not unread_conns:
        return f"{_count(inside, 'connection')} still inside the idle grace"
    if not inside:
        return f"{_count(unread_conns, 'connection')} holding unread bytes"
    return (f"{_count(inside, 'connection')} still inside the idle grace and "
            f"{_count(unread_conns, 'connection')} holding unread bytes")

def _count(n: int, noun: str) -> str:
    """One number and its noun, singular or plural, so a log line reads as a sentence.

    ``1 connection`` and ``2 connections`` are the same count and different English; a line
    an operator greps after a deploy should not read like a template, and the singular case
    is the one a drain with a single straggler prints.
    """
    return f"{n} {noun}" if n == 1 else f"{n} {noun}s"

def _decision(state: State, action: Action, reason: str, elapsed_ms: float,
              in_flight: int, extended: bool) -> Decision:
    if action is Action.EXTEND and extended:
        raise IllegalTransition("an extension is granted only once")
    return Decision(state=state, action=action, reason=reason, elapsed_ms=elapsed_ms,
                    in_flight=in_flight, extended=extended)
StateCondition at this sampleActionReason in the log line
draininginside the window, requests in flightwaitwithin the grace window with N in flight
drainingno request in flight, connections inside their idle gracewaitno request in flight; N connections still inside the idle grace
stoppedno request in flight and nothing inside its gracestopno request in flight
stoppedpast the window, nothing counted and nothing on a socketstopwindow closed with N idle connections and no request counted
overduewindow closed, requests finished inside the progress windowextendN in flight and M finished in the last 500 ms: one extension
overdueinside the extension, requests in flightwaitpast the window on the extension with N in flight
stoppedwindow closed, a socket holds bytes no handler readabortwindow closed with N sockets holding unread bytes
stoppedwindow closed, nothing finished inside the progress windowabortgrace window closed and nothing finished in the last 500 ms: N in flight
stoppedthe hard cap is reached with work the count could not finishaborthard cap of N ms reached with N in flight
stoppedalready stoppedkeepalready stopped
Table 7: the 10 decisions decide can return, out of 4 states and 8 transitions. The two stops are the ones that lose nothing: the first finds the count at zero with nothing waiting on a socket, and the second finds the same after the window (or at the hard cap, which uses the same branch and says so in its own words). The three aborts each name what they give up. The test files in the appendix run each row, including the guards that refuse: a second extension, a stopped machine draining again, and a negative count of any of the four numbers.

7. The drainer that applies it

The decision function knows nothing about sockets. drainage/drainer.py owns the part that does: the connections it accepted, the requests running inside them, the listener, and the loop that asks the policy what to do next. It takes two things from the application – a connection when one is accepted, and a start and an end around each request – and everything else it can read for itself.

The handler below is the whole contract, from the probe server the measurements ran against. attach registers the connection, the two counters bracket the work, and detach runs in the finally so a handler that raises still leaves the count correct.

"""The server under test: a line protocol, and the five shutdown behaviours compared here.

Clients send ``REQ <milliseconds>`` and get ``OK`` once the handler has slept that long,
so "in flight" is a real wait inside a real coroutine and a lost reply is a lost request.
The process is started by a probe with ``--ready-file`` and ``--stats-file`` rather than
over a pipe: a pipe would have to be drained while the server runs, and the point of the
exercise is what happens when the server stops.

``--mode default`` deliberately installs no signal handler, so the kernel's default
action for SIGTERM is what the probe measures. ``--read-delay-ms`` makes every handler
wait before its first read, which is the time a real framework spends between accepting
a connection and reading from it (a TLS handshake, a middleware stack); a request that
arrives inside it is on the socket but not yet in any count. ``--no-peek`` turns off the
socket's own answer to that question, so probe 11 can measure what the time-based grace
does on its own.
"""
from __future__ import annotations
import asyncio
from drainage import Drainer
async def handler(reader, writer, stats: dict, drainer: Drainer | None,
                  swallow: bool = False, read_delay_ms: int = 0):
    stats["accepted"] += 1
    conn = drainer.attach(reader, writer) if drainer is not None else None
    try:
        if read_delay_ms:
            await asyncio.sleep(read_delay_ms / 1000)
        while True:
            line = await reader.readline()
            if not line:
                break
            delay_ms = 0
            parts = line.split()
            if len(parts) > 1:
                delay_ms = int(parts[1])
            stats["requests"] += 1
            stats["in_flight"] += 1
            if conn is not None:
                drainer.started_request(conn)
            try:
                if delay_ms:
                    try:
                        await asyncio.sleep(delay_ms / 1000)
                    except asyncio.CancelledError:
                        stats["swallowed"] += 1
                        if not swallow:
                            raise
                        # A handler that refuses to stop: it finishes the work it began.
                        await asyncio.sleep(delay_ms / 1000)
                writer.write(b"OK\n")
                await writer.drain()
                stats["replied"] += 1
            finally:
                stats["in_flight"] -= 1
                if conn is not None:
                    drainer.finished_request(conn)
    except (ConnectionResetError, BrokenPipeError):
        stats["peer_gone"] += 1
    finally:
        stats["closed"] += 1
        if conn is not None:
            drainer.detach(conn)
        writer.close()

Counting per connection rather than in one global number is what makes the idle case in section 5 possible: the drainer can ask each connection whether anything is running on it, close the ones where nothing is, and keep the ones where something is – on the same sample. A single counter would leave a socket with no request on it indistinguishable from a socket in the middle of one.

The loop is short, and its order matters. If the policy says stop, every connection is closed, which flushes what the handlers wrote before the FIN; if it says abort, the connections with a request on them are dropped, their buffered bytes discarded, and the idle ones closed. Otherwise the connections that have been idle for their grace are closed, the finished total is written into a short history, and the samples continue after one poll interval – which is shorter than any request in the tables, so the count a decision sees is never stale by more than that interval. Each step begins with one walk over the table, and the decision and the closes it leads to read that one reading: a socket is asked whether it holds bytes once per sample, not once per question.

from __future__ import annotations
from .policy import Action, extended_after, transition
from .report import Summary
async def run(self) -> Summary:
    """Sample until the process may exit, closing idle connections on the way."""
    await self._signalled.wait()
    try:
        while True:
            # One walk over the table per step: the decision and the closes it leads to
            # read the same reading, so a socket is asked once and not again.
            sample = self._scan()
            decision = self._forced(sample) if self._force else self._sample(sample)
            self.counts.decisions += 1
            self.state = transition(self.state, decision)
            self.summary.add(decision)
            self.counts.samples.append(decision)
            if self.on_decision is not None:
                self.on_decision(decision)
            if decision.action is Action.STOP:
                self._close_all()
                return self.summary
            if decision.action is Action.ABORT:
                self._abort_active()
                self._close_idle(ignore_grace=True, sample=sample)
                return self.summary
            if decision.action is Action.KEEP:
                # The machine was already stopped: a second drain has nothing to
                # decide, and waiting for a window that was spent would never end.
                return self.summary
            self._close_idle(sample=sample)
            self.extended = extended_after(decision)
            self._remember()
            await self.sleep(self.limits.poll_ms / 1000)
    finally:
        self._finished = True

The history is what the progress gate reads. Each sample appends the finished total with the time it was read, and the oldest entries are dropped once they fall outside the progress window – except the first, which is the total at the moment of the signal and is the floor a sample reads when the window reaches back past every sample taken. So the gate’s question is “how many requests finished in the last 500 ms”, and its answer is a number that only rises: a keep-alive connection whose next request arrives as the last one ends keeps the in-flight count still, and a handler working slowly enough to spend two samples inside one request keeps finishing requests. A gate that compared adjacent samples would misread both. The extension flag is sticky once granted, so a second window cannot be opened by accident – and decide refuses to return extend twice even if it is asked.

When the signal arrives twice: A second SIGTERM is treated as an instruction, not as noise. The first call starts the clock and closes the listener; the second sets a flag, and the loop’s next sample aborts every connection that still has a request on it and writes one line saying so. Probe 12 measures it on a real policy server rather than in the unit tests: three requests of 5,000 ms against a 3,000 ms window, signalled once, left at 3,032 ms when the hard cap cut them off; signalled again at 300 ms, the same three were dropped at 332.6 ms and the log’s last line read second signal: aborting with 3 in flight. The signal has to reach the drainer for that: the server’s handler calls signal() on every SIGTERM, not only on the first, which is the wiring a callout in a unit test cannot check. An orchestrator sends the signal once, and a person who presses stop twice means it – a drain that ignored the second one would keep a pod in a rollout the operator has already given up on. A connection the listener accepts while it is closing is closed at once rather than registered: the loop that would have counted it has already returned.

A finished request on a connection that had none in flight raises ValueError (the test file asserts it), and so does detaching a connection that still has a request on it. Both are deliberate, from the two sides of the same count: a framework that calls the end of a request twice, or calls it after the connection was detached, would otherwise drive the count below zero, and a handler that detaches early would take its count with it. Either way the drainer would exit while a handler was still working – the first with a log that says a negative number is in flight, the second with a log that says zero.

Every sample goes through Summary in report.py, which counts waits, extensions and aborts and formats each sample as one line: state, action, in-flight count, elapsed milliseconds and reason. A deploy that lost nothing logs a run of wait lines ending in stop; a deploy that cut something off logs the abort line naming what it gave up – the requests still in flight, or the sockets still holding bytes no handler read – and each of those is what the load balancer’s error rate shows a minute later.

Field in the lineExample from a measured runWhy an operator needs it
statedraining then stoppedwhich half of the policy the process was in
actionwait, extend, abortwhether the last thing it did was wait or cut
inflightthe count at that samplehow much work the deadline was holding
elapsed_ms407.3 ms in section 8’s clean runhow much of the budget the shutdown spent
reasonno request in flightwhy the process was allowed to exit
Table 8: the fields of one decision line. The measured clean run in section 8 ended at 407.3 ms with a single stop after 16 waits, which is what a deploy that lost nothing looks like in a log.

Deploying it is four steps, and the first two are the ones that are usually missing:

  1. Register the handler for SIGTERM with loop.add_signal_handler, not signal.signal: the loop’s version runs the callback on the event loop, where closing a server and reading a dictionary are safe, and it is the same call that can count the signals – the drainer reads the second one as “stop now” (the callout above).
  2. Open the count where the request opens: attach the connection when it is accepted, and bracket the handler with started_request and finished_request. A framework’s middleware is the natural place for it; a bare server puts it at the top and bottom of the handler, as the excerpt above does.
  3. Give the policy a window shorter than the orchestrator’s grace period, and an extension only if the requests you serve sometimes outlive the window but still finish. Section 9 does the arithmetic with the figures measured here.
  4. After the drain returns, cancel what is left and exit. The drainer has already dropped the sockets it could not finish, so a handler still sleeping on a cancelled task cannot hold the process.

8. Five shutdowns, one table

Each row of Table 9 is a separate server process: 12 clients, each with one 400 ms request in flight, the signal at 120 ms after the first connection, 5 repeats per arm. The policy’s window is 1,000 ms with a 500 ms extension; every request ends well inside it, so this table is the easy case – and the one where four of the five shutdowns are distinguishable.

ShutdownRepliesWall after signalExitNew connections after signalLost
Nothing: the default action0 of 120.90 ms-152 of 2 refused60
Handle the signal, return from main()0 of 1226.3 ms02 of 2 refused60
Sleep the window, keep accepting12 of 121,028 ms02 accepted0
Close the listener, wait for every connection12 of 12417.5 ms02 of 2 refused0
Close the listener, wait for requests in flight12 of 12435.6 ms02 of 2 refused0
Table 9: probe 06, 5 runs per arm; the reply and loss columns are totals over those runs, the wall time is the median (the widest spread between an arm’s runs was 18.9 ms), and the refusal column is the median of 2 attempts made after the signal. Each client closes its socket as soon as its reply arrives, so no connection is left for the drain to close and the idle grace of 250 ms is never spent; table 10 is the same comparison with clients that keep their sockets. The last two rows are 18.1 ms apart here, and that gap is what a deadline costs when nothing needs it and nobody holds a socket open.

Two rows deserve their numbers in the text. The default action lost 60 requests across 5 runs, and every one of those clients saw a clean end of stream – the same bytes as a client whose reply the server chose to leave out – which is why an error rate, not a socket error, is how a lost request shows up. And the blind sleep answered everything while still accepting new connections: 2 connections made after the signal were accepted and served, because the listener was never closed. A load balancer that has not yet removed the pod sends its traffic to a process that is leaving.

That gap is small because the clients left. A client that keeps its connection – which is what an HTTP client does, and what the load balancer’s sockets in section 5 are – leaves the drain with twelve idle sockets at the end, and the graceful shutdown then costs whatever the drain spends before it closes them. Probe 15 measures both kinds of client on the same conditions, and the same policy at three graces (Table 10).

ShapeShutdownIdle graceWall after signalRepliesWhat ended it
12 requests, clients close their socketswait for every connectionnot spent418.4 ms12the last handler returning
12 requests, clients keep their socketswait for every connection250 ms4,510 ms, killed at the cap12the cap: the handlers never end
12 requests, clients close their socketswait for requests in flightnot spent435.9 ms12the count
12 requests, clients keep their socketswait for requests in flight250 ms686.8 ms12the last reply plus the grace
the same, idle grace 0wait for requests in flight0437.2 ms12the count, at once
the same, idle grace 500 mswait for requests in flight500 ms938.7 ms12the last reply plus the grace
5 requests and 20 idle sockets, clients keep themwait for every connection250 ms4,510 ms, killed at the cap5the cap: the handlers never end
5 requests and 20 idle sockets, clients keep themwait for requests in flight250 ms434 ms5the last reply plus the grace (25 sockets closed)
Table 10: probe 15, median of 5 runs per row, with requests of 400 ms and the signal at 120 ms; the last two rows are section 5’s shape (five requests of 200 ms). A client that keeps its socket changes the floor twice: waiting for connections stops ending at all, and the drain’s own exit moves by the grace – 250.9 ms to go from a socket the client closed to a 250 ms grace, and a further 251.9 ms to go from 250 ms to 500 ms.

The three policy rows read as one number: the last reply plus the grace. With the grace at 0 the drain leaves 437.2 ms after the signal – within 1.3 ms of the run whose clients closed, because there is nothing to wait for; at 250 ms it leaves 686.8 ms, and at 500 ms it leaves 938.7 ms. So the grace is not free and it is not hidden: it is the price of not cutting off a client that is about to send its next request on the connection it already has, and a deploy pays it once, at the end, after the last reply.

That price has a ceiling, and the policy already enforces it: Limits refuses an idle grace that does not fit inside the window, because a grace longer than the window would turn the exit floor into the window itself. In table 10 every policy row finishes inside the 1,000 ms window – the longest, at 938.7 ms, with 500 ms of grace and a 400 ms request – and a grace that pushed it past the window would abort the connections it was meant to spare.

The third row and the last row are 1.9 ms apart, and the reason is which part of each one is spent. The third row ends at its last answer: twelve requests of 400 ms and no grace at all, because those clients closed their sockets the moment they were answered. The last row ends one grace later: five requests of 200 ms that all end early in the window, then 250 ms on the sockets that stayed open. A shorter request with a grace after it lands near where a longer request with none does, so the two rows sit within a couple of milliseconds of each other – and the two runs’ own decision logs say which floor each one hit, though not in the line a reader looks at first: both rows end on the same one. The last line of either log is state=stopped action=stop inflight=0 ... reason=no request in flight, because by the time a drain stops there is nothing left to count and nothing holding a request. What differs is the line before it. The close row’s last wait reads within the grace window with N in flight: a request was still running at that sample, and the next sample found the count at zero. The pool row’s last wait reads no request in flight; N connections still inside the idle grace: its requests had all been answered, and what the drain was still waiting on was a socket that had carried nothing for less than its grace. One row ends because a request ended; the other because a grace did.

The same five strategies against one request that cannot finish inside the window – 5,000 ms – separate differently (Table 11).

ShutdownStalled requestWall with it in flightFast requests: answeredFast requests: wall
Close the listener, wait for every connectionnever answered4,507 ms, killed at the cap5 of 5167.9 ms
Sleep the window, keep acceptinglost at exit1,029 ms5 of 51,027 ms
Close the listener, wait for requests in flightdropped at the deadline: end of stream, no reply1,035 ms5 of 5178.7 ms
Table 11: probe 07, median of 5 runs per row (the policy’s stalled wall time ranged 1,034 ms to 1,039 ms). The stalled request is 5,000 ms against a 1,000 ms window; the fast requests are 200 ms. The blind sleep spent 848.5 ms more than the policy on requests that were done in 178.7 ms.

The stalled client in the last row saw the connection end without its reply, and the drainer’s log says why: one connection aborted at the deadline, with the fast requests already answered. The first row could not reach that decision at all – waiting for connections has no way to express “this one is not going to finish” – and the second row decided nothing, exiting on schedule with the request still running.

So the recommendation is the fifth row, with the fourth row’s simplicity as its fallback. Closing the listener and waiting for the requests in flight costs 18.1 ms over waiting for every connection when the connections all carry requests, and buys the idle connection case in section 5 and the deadline in table 9. The rest of this section is the order to deploy it in and the numbers to choose.

  1. Deploy the count first. Attach, start and finish around every request, with no shutdown changes at all; the counter is the new thing, and a request that ends twice raises rather than going negative.
  2. Add the signal handler and the listener close. From this point new connections are refused, existing requests keep running, and a deploy is already better than the default action – even if the window is wrong.
  3. Add the deadline, and set it below the orchestrator’s grace period. The window is a cap, not a wait: section 9 measured a process that used 10.6% of its window and left the other 89% unspent, because nothing was left to serve.
  4. Watch the abort line. A deploy with no abort line lost nothing; an abort line names what the window could not finish – the requests still in flight, or the sockets holding a request nobody read – and the next deploy should either raise the window or make the slow handler faster.

9. Choosing the numbers

Three numbers decide a drain: the window, the extension and the poll interval. The window is the only one that has to be right; the other two have defaults that are correct far more often than they are changed.

The window is a cap. Against a request that cannot finish, the process left at 330.3 ms for a 300 ms window, 632.3 ms for 600 ms, and 1,240 ms for 1,200 ms – the window plus the time it takes to notice, which averaged 34.2 ms over the three windows, each the median of 5 runs. Against requests that finished, the same policy with a 1,200 ms window left after 127.7 ms, because the count reached zero and nothing waited for the rest of the window. A rollout of ten replicas therefore spends 127.7 ms per replica on a quiet deploy, not 1,200 ms.

The arithmetic for the termination grace period, with the figures measured above

An orchestrator that waits 30,000 ms before SIGKILL, a preStop step that spends 5,000 ms, a window of 20,000 ms and the one extension it may grant of 2,000 ms leave 2,966 ms of headroom: the period, less the preStop step, less the window, less the extension, less the 34.2 ms measured to leave once the deadline is reached – because a drain that is still finishing requests at the window is allowed to spend the extension too. The headroom is not slack for the window – the window is a cap – it is slack for the process’s own teardown, which this page does not measure. Leaving the extension out of the subtraction is the mistake that turns a 20-second window into a 30-second period: the drain’s worst case is the window plus the extension, not the window.

Drop the preStop step and the same window leaves 7,966 ms. A window chosen from the period rather than from the request time is what makes the difference look like a policy question; it is a measurement question.

The extension is for a tail, not for a habit. If the slowest request is inside the window, an extension never applies and the policy aborts at the window with the count it could not finish. An extension is worth setting only when measured requests sometimes outlive the window and still complete – the falling count is what distinguishes those from a handler that is stuck.

The poll interval is a sample rate, and a sample is not free. The policy must see two samples inside the window or it can never observe progress, and Limits refuses a window shorter than two polls for that reason. At the default of 25 ms a one-second window gets 40 samples, and what a sample costs is not a walk over the table: every idle connection is asked whether it is holding a request, and on an asyncio stream that question is a dup, an ioctl(FIONREAD) and a close on the duplicate – three system calls per socket, per sample. Probe 17 registered real socket pairs in a real drain and timed the loop it runs. The drain asks each socket once per sample and takes both numbers it needs from that one answer – whether the connection is still inside its grace, and whether its socket says it holds bytes – so a walk over 2,000 idle sockets cost 6.6 ms and a whole sample cost 7.6 ms, 30% of the poll interval; at 1,000 sockets the sample cost 4 ms, and over an empty connection table 10 µs. Asking the same 2,000 sockets a second time – which is what two separate questions per socket did, one for freshness and one for the unread bytes – cost 12.9 ms: the sample is now one question per socket, and a drain’s first sample is no dearer than the ones after it – 6.9 ms on the zero-grace arm, which stops at that first sample and closes everything it found.

That cost still fits inside a 25 ms interval at this size, but 30% of that interval is spent asking sockets that have nothing to say, and the deciding is the rest of it. What bounds the cost is the idle grace rather than the poll – a connection is closed once it has carried nothing for its grace, so the population a sample walks is what arrived inside the grace, and a longer grace means more sockets to walk on every sample in between. It is a second reason, beside the exit floor of table 10, to keep the grace short. The walk also holds the loop it runs on: a sample is one coroutine that does not yield, so for its own length every handler that was ready to run waits. Probe 17 put a five-millisecond ticker beside the drain and recorded how much longer each nap took than it asked for: the longest gap while the drain was sampling was 7.4 ms at 2,000 sockets – the sample’s own work – and 17.3 ms in the worst of the five runs, which is the sample plus whatever else this host was doing at the time.

Closing that population is a lookup per connection. Probe 17’s zero-grace arm stops at its first sample and closes everything that sample found: 3.8 ms for 1,000 sockets and 7.9 ms for 2,000 – doubling the population moved the batch by 2.1 times, which is the population’s own growth and the linear cost the rest of the drain already had. It was not linear: Drainer._remove found each connection by scanning the table it was removing from, so closing N of them was N scans, and the batch grew faster than the population it closed. The table is now keyed by the number attach gave the connection, and the connection carries that number, so a removal is one pop – gone from the batch, and gone from the ordinary detach() that ends every request, which is the path every connection a deploy serves takes and not only the ones a shutdown closes.

  • Window: the measured p99 request time, or two thirds of the grace period when the request time is unknown – whichever is smaller.
  • Extension: zero unless a measured tail outlives the window and finishes; if it does, half the window is enough to see it.
  • Poll: the default, unless the window is under a few hundred milliseconds, in which case divide the window by the samples wanted and keep at least two.

10. What this does not fix

The drain decides when the process may leave. Everything that has to happen before the process is asked to leave, or after a request has already been answered, is outside it – and pretending otherwise is how a graceful shutdown ends up blamed for a rollout that was losing requests for another reason. The count of requests in flight, the deadline and the close of an idle connection decide only what the process does between the signal and its exit; the items below are the rest of the failure, and each of them is where a drain stops helping.

  1. Traffic that has not stopped arriving. The drain closes the listener, so connections that are already in the kernel’s accept queue are refused or reset rather than served; this page did not measure what the kernel does to a queued connection at close. A readiness probe that fails, and a load balancer that has observed the failure, are what stop traffic before the signal – the drain cannot do it.
  2. Protocol-level goodbye. The server here speaks a line protocol, so the measurements say nothing about an HTTP/2 GOAWAY or an HTTP/1.1 Connection: close; a framework that sends one needs its own measurement of how long clients take to notice.
  3. Streaming responses. A handler that is a stream has no moment when it finishes until the client stops reading, so the count stays above zero and the deadline aborts it. Those connections need a policy of their own – a maximum stream age, or a protocol goodbye – and this page did not measure one.
  4. Handlers that ignore cancellation. Section 4 measured the shape: 36 replies delivered after 430.5 ms, because the handlers kept working. A handler that never finishes holds the process until the orchestrator’s SIGKILL, whatever the policy decided.
  5. What a request was doing when it was cut off. Resetting a connection says nothing about a database transaction that was half-committed. Idempotency keys and an outbox are the answer to that, and neither is a shutdown concern; the drain only shortens the window in which they can be needed.
  6. TLS, and anything else that hides the request from the socket. The check in section 5 reads a plain TCP socket. Behind TLS the socket holds encrypted records, so neither FIONREAD nor MSG_PEEK can tell a request from a handshake fragment, and the honest answer there is the grace – measured for the framework the way table 6 measures it – or the framework’s own signal that a request has begun. The check is narrower in a second way as well: it reads the buffer of an asyncio StreamReader, so it exists only on a server built from streams. A Protocol-based server – uvicorn’s HTTP implementations, or one you wrote – has no stream to ask and holds the bytes in its own parser, where neither half of the check can see them; there the count opens at Protocol.data_received or at the framework’s request-start hook, and the window is what covers a request until its handler reads it.

11. The servers and entrypoints you already run

A drain is one way to shut down; most readers will deploy one of two servers that already own the listener and the signal handler, or an image whose entrypoint decides whether the application hears the signal at all. Both questions are measurable, and both answers change what is left for this page’s policy to do.

What uvicorn and gunicorn do with the same request

Probe 13 asks uvicorn and gunicorn the question table 9 asks: the same ASGI handler sleeping 2,500 ms, 3 requests in flight, the signal 200 ms after the first of them arrived. It asks it twice – once with nothing else on the server, and once with 20 keep-alive connections open and idle beside the requests, which is section 5’s shape (Table 12).

ServerIdle sockets beside itWall after signalRepliesLostWhat ended it
uvicorn, default shutdownnone2,494 ms90the last handler returning
uvicorn with a 1 s graceful timeoutnone1,185 ms09a 1,000 ms cap that never asked
gunicorn, one uvicorn workernone2,643 ms90the worker finishing, then the master
uvicorn, 20 idle keep-alive sockets20 closed in 72 ms2,485 ms90the idle sockets, then the last handler
gunicorn, 20 idle keep-alive sockets20 closed in 99.7 ms2,650 ms90the idle sockets, then the worker
Table 12: probe 13, 3 runs per server, each in a fresh process, with 3 requests of 2,500 ms and the signal at 200 ms. The wall time is the median of the runs; replies and losses are totals over them, and the idle column is the median number of keep-alive sockets the server closed before it left, with the median time it took to close them. These are the servers’ own shutdowns, not this page’s: the only thing added to them is the request that was in flight.

uvicorn already does the half this page’s table 5 is about. Told to stop, it closed all 20 idle keep-alive sockets 72 ms after the signal and then waited for the requests that were running, so the process left at 2,485 ms – within 9.2 ms of the run with no idle sockets at all. gunicorn, with one uvicorn worker, behaved the same way: 20 sockets closed in 99.7 ms, 9 replies delivered, 2,650 ms in total. Anyone reading this page for the idle-connection problem should know that a maintained server has already solved it, and writing a drain to re-solve it would be work for nothing.

What neither of them does is ask whether the requests are worth waiting for. The default rows wait because waiting is what they do, and the only cap they have is the orchestrator’s SIGKILL; the row told to give up after 1,000 ms is an unconditional deadline, and it dropped all 9 requests of the runs at 1,185 ms while every handler was still working. That is the gap this page’s policy fills: it leaves when the count reaches zero – the default rows’ behaviour without their risk – and reaches for a cap only when nothing finished inside the progress window, which is the timed row’s deadline with the question the timed row never asks. So the division of labour is: let the server close what is idle, and put the count and the progress gate where the request starts and stops. A bare asyncio server with neither behaviour is the case table 9 measures, and there this object is the whole shutdown.

The process that never hears the signal

Everything above assumes SIGTERM reaches the application. In a container it reaches whatever the image’s entrypoint is, and that is not always the application: shell form CMD runs /bin/sh -c "<cmd>", so the signal goes to the shell and what the shell does with it is a property of the shell. Probe 14 starts the same long-running child four ways as an ordinary child process – not as a container’s PID 1 – sends SIGTERM to the process the supervisor knows, and looks at what happened to the child (Table 13).

EntrypointProcesses the shell startedChildren that survivedWhat that means
sh -c, one command33 of 3the shell died; the app was never signalled
sh -c with execnone: the shell became the appthe shell itselfthe signal landed on the application
sh -c, a pipeline66 of 6nothing in the pipe was signalled
bash -c, one commandnone: bash replaced itselfthe shell itselfthe signal landed on the application
Table 13: probe 14, 3 runs per form, with the signal sent to the process the probe started – a child of the probe, not a container’s PID 1. The form that lists no child is the one the shell replaced itself with: there was nothing between the signal and the application, which is the outcome to want.

Read table 13 as the non-PID-1 case. /bin/sh on this host is not the shell that optimises a single command away – bash does, and sh does not – so the first row is the one that bites outside a container: the shell exits on SIGTERM, the application it started keeps running, and the process the supervisor signalled is gone while its child is not. The exec form and bash -c replace the shell, so the signal lands on the application, and a pipeline is worse than either: 6 processes across the runs, none of them signalled.

A container’s PID 1 is a second, different failure, and it runs the other way round. The kernel does not apply a signal’s default action to PID 1: a SIGTERM with no handler installed in PID 1 leaves it running, so a shell-form CMD in a container does not exit at the signal at all, and nothing passes the signal on to the application either. What ends the pod is the grace period expiring and the container runtime sending SIGKILL to PID 1, which takes the whole namespace with it. The application is not drained there, it is destroyed, and no log line records a request that was cut off. That is why table 13’s first row says the shell died and its child survived: that is what an ordinary child does, and a PID 1 shell would instead still be alive when the kill arrives.

The rule also covers the application itself at PID 1. An image whose entrypoint is the application, and whose application binds the socket without installing a handler, cannot be stopped by SIGTERM at all – it runs until the orchestrator’s SIGKILL, which is the exit that table 9’s default row recorded on a process that is not PID 1. This host does not let an unprivileged process create a PID namespace (probe 14 recorded the refusal), so the PID 1 rule is quoted from the kernel’s documentation rather than measured here, and it is the one claim in this section this page did not reproduce. The two failures are independent, which is why the fix has two halves.

Container entrypoints: Use the exec form (CMD ["python", "-m", "app"]) or an init shim such as tini or dumb-init as the entrypoint, and install the handler in the application as well. The shim fixes the shell – and reaps what PID 1 would otherwise leave behind – and the handler fixes PID 1. A pod that has both can be drained; a pod that has neither is stopped by SIGKILL and by nothing else.

The honest summary is one sentence long: count the requests in flight, close the listener, hold a deadline, and drop what the deadline could not save – and remember that an idle connection is not a request, that a socket with bytes on it is not idle whatever its grace says, and that the arithmetic of the deadline belongs inside the orchestrator’s grace period rather than on top of it.

Appendix: the package, its tests and every probe

The package is 5 files and 910 lines; the tests are 6 files and 1269 lines, 97 tests, all passing, with pyflakes reporting nothing on the package. Everything below is a whole file, and the order is the order a reader needs them in rather than alphabetical: the five files of the package first, then the three modules every probe stands on – harness.py, which drives the clients, arm_server.py, which is the server under test, and fw_app.py, the ASGI app the two production servers were asked to serve – then all 17 probes in the order the page takes them up, from the host readings of table 1 to the two servers and the shell of section 11, then the six test files, and last the gate run that produced the counts in this paragraph. Nothing is an excerpt, so nothing has a name its file does not define, and the tree is laid out as the probes expect it: module/drainage/ for the package, module/drainage/tests/ for the tests, sandbox/ for the probes and a results/ directory beside them. Copy them there and pytest drainage/tests runs the same 97 tests; run any probe and it writes its own numbers to results/.

The four states, the eight transitions, the limits and the decision function. policy.py
"""The shutdown decision, as a state machine over monotonic time.

Four states and eight transitions, and two rules that are easy to get wrong. The
deadline is not the only gate: a request that is still being served when the grace
window closes is either making progress or it is not, and the difference decides
whether the process gets one extension or is cut off. And progress is measured over a
window rather than between two adjacent samples, because a handler can spend a sample
or two finishing one request while it is plainly working. The decision is a pure
function of one sample, so the tests drive it with a fake clock instead of sleeping.

One distinction runs through it: an abort is a decision to lose a request, and a stop
is a decision that there is nothing left to lose. A window that closes on connections
that have merely been quiet is a stop, while the same window over a socket holding
bytes no handler has read is an abort, because those bytes are a request.
"""
from __future__ import annotations

from dataclasses import dataclass
from enum import Enum

from .report import describe


class State(str, Enum):
    SERVING = "serving"
    DRAINING = "draining"
    OVERDUE = "overdue"
    STOPPED = "stopped"


class Action(str, Enum):
    KEEP = "keep"
    WAIT = "wait"
    EXTEND = "extend"
    STOP = "stop"
    ABORT = "abort"


ALLOWED_TRANSITIONS = frozenset({
    (State.SERVING, State.DRAINING),
    (State.SERVING, State.STOPPED),
    (State.DRAINING, State.DRAINING),
    (State.DRAINING, State.OVERDUE),
    (State.DRAINING, State.STOPPED),
    (State.OVERDUE, State.OVERDUE),
    (State.OVERDUE, State.STOPPED),
    (State.STOPPED, State.STOPPED),
})


class IllegalTransition(RuntimeError):
    """A decision tried to move the machine somewhere it cannot go."""


@dataclass(frozen=True)
class Limits:
    """The numbers a shutdown is allowed to spend, in milliseconds.

    ``grace_ms`` is the window in which in-flight requests are left alone.
    ``extension_ms`` is granted at most once, and only to a drain whose requests are
    still finishing; ``poll_ms`` is how often the sample is read, and it must fit twice
    inside the grace window or no decision can see progress at all. An extension no
    longer than one poll interval would be spent before it could ever be sampled, so it
    is refused rather than silently granted and ignored.

    ``progress_ms`` is how far back the progress gate looks: it reads the number of
    requests that finished inside that window, not the difference between two adjacent
    samples, so a handler that is getting work done slowly - one request every few
    samples, as a queue of small writes does - is not mistaken for one that is stuck.

    ``idle_grace_ms`` is how long a connection must have carried nothing before the
    drain closes it. A request can reach a socket whose handler has not read it yet -
    a TLS handshake, a middleware stack, a shared loop that was busy with another task -
    and a drain that closes every idle connection at its first sample throws that
    request away before the count could possibly see it. The grace is the time the
    application needs between accepting a connection and reading from it, and it is
    also why "nothing in flight" is not on its own a reason to leave: a socket that is
    still inside its grace may be holding a request that the count has never seen.
    """

    grace_ms: int = 5000
    extension_ms: int = 2000
    poll_ms: int = 25
    progress_ms: int = 500
    idle_grace_ms: int = 250

    def __post_init__(self) -> None:
        if self.grace_ms <= 0:
            raise ValueError("grace_ms must be positive")
        if self.extension_ms < 0:
            raise ValueError("extension_ms cannot be negative")
        if self.poll_ms <= 0:
            raise ValueError("poll_ms must be positive")
        if self.grace_ms < 2 * self.poll_ms:
            raise ValueError("grace_ms must fit two poll intervals")
        if 0 < self.extension_ms < self.poll_ms:
            raise ValueError("extension_ms must fit one poll interval")
        if self.progress_ms < self.poll_ms:
            raise ValueError("progress_ms must fit one poll interval")
        if self.progress_ms > self.grace_ms:
            raise ValueError("progress_ms cannot exceed the grace window")
        if self.idle_grace_ms < 0:
            raise ValueError("idle_grace_ms cannot be negative")
        if self.idle_grace_ms >= self.grace_ms:
            raise ValueError("idle_grace_ms must be shorter than the window")

    @property
    def hard_ms(self) -> int:
        """The longest a shutdown may take: the grace window plus one extension."""
        return self.grace_ms + self.extension_ms


@dataclass(frozen=True)
class Decision:
    """One sample's answer: where the machine goes, what to do, and why."""

    state: State
    action: Action
    reason: str
    elapsed_ms: float
    in_flight: int
    extended: bool

    def line(self) -> str:
        return describe(self)


def decide(
    *,
    state: State,
    elapsed_ms: float,
    in_flight: int,
    fresh_conns: int,
    progress_completed: int,
    extended: bool,
    limits: Limits,
    unread_conns: int = 0,
) -> Decision:
    """Decide one step of a shutdown from the sample the caller just read.

    The order of the checks is the policy. Nothing in flight - and no connection still
    inside its idle grace - is checked before every deadline, because a process with
    nothing left to serve should exit at once rather than sit out the window, while a
    socket that has just been handed a request its handler has not read yet must not be
    closed on that same sample. Past the window the same question is asked again with the
    two kinds of connection separated: a socket that has merely carried nothing for its
    grace has no request on it that the drain could name, so a window that closes on those
    stops without an abort, while a socket the drain's ``unread`` check says is holding
    bytes does have a request on it - one the count never saw - and closing it is an abort
    and is logged as one. That is what keeps one rule true: an abort line always names a
    request that was lost. The hard cap is checked before the progress gate, so an
    extension cannot carry a process past it. And the progress gate reads the number of
    requests that have *finished inside the last* ``progress_ms``, not the number in
    flight: on a keep-alive connection one request can end while the next one starts, and
    a net count would not move while the handler was plainly still working. A window
    rather than a single interval is what keeps a slow but working handler from being cut
    off for the sample it happened to spend inside one request.

    ``fresh_conns`` is the number of idle connections the drain is not yet willing to
    close: those that have carried nothing for less than ``idle_grace_ms``, plus any whose
    socket says it is holding bytes. From the count's side they are idle, and from the
    application's side they may be carrying a request that has not been read.
    ``unread_conns`` is how many of them the socket itself said are holding bytes - it is
    zero when the caller does not ask the socket, and never more than ``fresh_conns``.
    """
    if in_flight < 0:
        raise ValueError("in_flight cannot be negative")
    if fresh_conns < 0:
        raise ValueError("fresh_conns cannot be negative")
    if progress_completed < 0:
        raise ValueError("progress_completed cannot be negative")
    if unread_conns < 0:
        raise ValueError("unread_conns cannot be negative")
    if unread_conns > fresh_conns:
        raise ValueError("unread_conns must be a subset of fresh_conns")
    if state is State.STOPPED:
        return _decision(State.STOPPED, Action.KEEP, "already stopped", elapsed_ms,
                         in_flight, extended)
    if in_flight == 0 and fresh_conns == 0:
        return _decision(State.STOPPED, Action.STOP, "no request in flight", elapsed_ms,
                         in_flight, extended)
    if in_flight == 0 and unread_conns == 0 and elapsed_ms >= limits.grace_ms:
        # Every request has been answered, and no socket is holding one the count has not
        # seen. The connections still registered are inside their idle grace and nothing
        # else - closing them loses nothing, so this is a stop and not an abort.
        reached = (f"hard cap of {limits.hard_ms} ms" if elapsed_ms >= limits.hard_ms
                   else "window closed")
        return _decision(State.STOPPED, Action.STOP,
                         f"{reached} with {_count(fresh_conns, 'idle connection')} and no "
                         f"request counted", elapsed_ms, in_flight, extended)
    if elapsed_ms >= limits.hard_ms:
        return _decision(State.STOPPED, Action.ABORT,
                         f"hard cap of {limits.hard_ms} ms reached with "
                         f"{_load(in_flight, unread_conns)}", elapsed_ms, in_flight, extended)
    if elapsed_ms < limits.grace_ms:
        if in_flight == 0:
            return _decision(State.DRAINING, Action.WAIT,
                             f"no request in flight; {_waiting(fresh_conns, unread_conns)}",
                             elapsed_ms, in_flight, extended)
        return _decision(State.DRAINING, Action.WAIT,
                         f"within the grace window with {in_flight} in flight", elapsed_ms,
                         in_flight, extended)
    if extended:
        return _decision(State.OVERDUE, Action.WAIT,
                         f"past the window on the extension with {in_flight} in flight",
                         elapsed_ms, in_flight, extended)
    if in_flight == 0:
        # Only reachable with unread_conns > 0: a socket is holding bytes no handler has
        # read, so closing it drops a request even though the count is zero.
        return _decision(State.STOPPED, Action.ABORT,
                         f"window closed with {_count(unread_conns, 'socket')} holding unread "
                         f"bytes", elapsed_ms, in_flight, extended)
    if progress_completed <= 0:
        return _decision(State.STOPPED, Action.ABORT,
                         f"grace window closed and nothing finished in the last "
                         f"{limits.progress_ms} ms: {in_flight} in flight", elapsed_ms,
                         in_flight, extended)
    return _decision(State.OVERDUE, Action.EXTEND,
                     f"{in_flight} in flight and {progress_completed} finished in the last "
                     f"{limits.progress_ms} ms: one extension", elapsed_ms, in_flight, extended)


def _load(in_flight: int, unread_conns: int) -> str:
    """What an abort is giving up on, named the way the log line needs it."""
    parts = []
    if in_flight:
        parts.append(f"{in_flight} in flight")
    if unread_conns:
        parts.append(f"{_count(unread_conns, 'socket')} holding unread bytes")
    return " and ".join(parts)


def _waiting(fresh_conns: int, unread_conns: int) -> str:
    """What a wait is still giving time to, in the log line's own words.

    The two kinds of connection are named apart because they are different reasons to
    wait: one is inside its idle grace with nothing on it, and the other is holding bytes
    the count has never seen. A line that called both ``inside their idle grace`` would be
    describing a connection the drain can see a request on as one it is only guessing about.
    """
    inside = fresh_conns - unread_conns
    if not unread_conns:
        return f"{_count(inside, 'connection')} still inside the idle grace"
    if not inside:
        return f"{_count(unread_conns, 'connection')} holding unread bytes"
    return (f"{_count(inside, 'connection')} still inside the idle grace and "
            f"{_count(unread_conns, 'connection')} holding unread bytes")


def _count(n: int, noun: str) -> str:
    """One number and its noun, singular or plural, so a log line reads as a sentence.

    ``1 connection`` and ``2 connections`` are the same count and different English; a line
    an operator greps after a deploy should not read like a template, and the singular case
    is the one a drain with a single straggler prints.
    """
    return f"{n} {noun}" if n == 1 else f"{n} {noun}s"


def _decision(state: State, action: Action, reason: str, elapsed_ms: float,
              in_flight: int, extended: bool) -> Decision:
    if action is Action.EXTEND and extended:
        raise IllegalTransition("an extension is granted only once")
    return Decision(state=state, action=action, reason=reason, elapsed_ms=elapsed_ms,
                    in_flight=in_flight, extended=extended)


def transition(current: State, decision: Decision) -> State:
    """Move the machine, refusing a move the table does not allow."""
    if (current, decision.state) not in ALLOWED_TRANSITIONS:
        raise IllegalTransition(f"{current.value} -> {decision.state.value} is not allowed")
    return decision.state


def extended_after(decision: Decision) -> bool:
    """The flag the next sample needs: an extension is spent the moment it is granted."""
    return decision.extended or decision.action is Action.EXTEND
The connections, the count, the unread check, the loop and what it closes or drops. drainer.py
"""The server-side half: stop accepting, count requests, hold the deadline.

``asyncio.Server.close()`` stops the listening socket and leaves every accepted
connection open; nothing in the standard library of this Python closes the clients
that are already connected, and nothing counts the requests inside them. So this
object keeps the count itself - per connection, because a keep-alive connection
with no request on it must be closed rather than waited for - and applies
:func:`drainage.policy.decide` on a fixed sample interval. It also keeps a running
total of finished requests and a short history of that total, which is the evidence
the policy uses for progress: a count in flight can stay flat while one request ends
and the next one starts, and a handler that finishes one request every few samples is
still working.

The clock and the sleep are injected so a test can run a five-second policy in
microseconds and assert on the same decision lines production would print.
"""
from __future__ import annotations

import asyncio
import time
from dataclasses import dataclass, field

from .policy import (
    Action,
    Decision,
    Limits,
    State,
    decide,
    extended_after,
    transition,
)
from .probe import pending_bytes
from .report import Summary


@dataclass
class Conn:
    """One accepted connection, the number of requests in flight on it, and its key.

    ``key`` is the number :meth:`Drainer.attach` registered the connection under. The drain
    keeps the connection in a dictionary keyed by it, so removing one - when a handler
    detaches, or when a sample closes an idle socket - is a lookup rather than a walk over
    every other connection: closing N of them costs N lookups, not N scans.
    """

    reader: object
    writer: object
    active: int = 0
    idle_since: float = 0.0
    key: int = 0

    def unread(self) -> bool:
        """Is something waiting on this socket that no handler has read yet?

        The grace is a time, and a time is a guess about how long an application takes
        between accepting a connection and reading from it. This is the same question
        asked of the socket itself, and it has two halves. The stream's own buffer is
        checked first: asyncio's transport moves arriving bytes out of the socket as soon
        as they land, so a request that arrived during a TLS handshake or a slow
        middleware stack is already in the reader and no longer in the kernel. The kernel
        is asked second, with ``FIONREAD``, for the bytes a transport has not read yet -
        a raw socket server, or a stream whose reading was paused. A kernel-only peek
        would report nothing for the first case, which is the one this page measured.

        This is a check on an asyncio stream and on nothing else. ``_buffer`` is a private
        attribute of ``StreamReader``, which a server built on ``asyncio.start_server``
        has and a ``Protocol``-based server such as uvicorn's does not: there is no stream
        to ask, and the protocol has already taken the bytes out of the kernel, so both
        halves answer nothing. A server that keeps its own buffer has to count the request
        where its protocol sees one - ``Protocol.data_received``, or the first line of the
        framework's request handler - which is the same moment the in-flight count opens.
        """
        buffered = getattr(self.reader, "_buffer", None)
        if buffered:
            return True
        return pending_bytes(self.writer) > 0

    def close(self) -> None:
        """Ask for a FIN: buffered writes are flushed, then the socket closes."""
        self.writer.close()

    def abort(self) -> None:
        """Drop the connection: buffered data is discarded and the socket is closed.

        What the client sees depends on what it had already sent. A request the handler
        never read is answered with a reset, while a connection with nothing unread ends
        with an ordinary FIN - an end of stream with no reply, which is what probe 07's
        stalled client recorded, and the same bytes the default action leaves.
        """
        transport = getattr(self.writer, "transport", None)
        if transport is not None:
            transport.abort()
        else:
            self.writer.close()


@dataclass(frozen=True)
class Sample:
    """One walk over the connection table: the count, and what each idle socket said.

    ``readings`` has an entry for every idle connection the walk met - whether it is still
    inside its idle grace, and whether its socket said it is holding bytes - so the answer
    to both questions is one ``Conn.unread()`` per socket per sample rather than one per
    question. It is what the decision is taken on and what the sample's closing pass reads,
    so a socket is asked once however many numbers are derived from its answer.
    """

    in_flight: int
    fresh: int
    unread: int
    readings: dict[int, tuple[bool, bool]]


@dataclass
class Counts:
    """What one shutdown did to the connections it held."""

    closed_idle: int = 0
    aborted: int = 0
    decisions: int = 0
    samples: list[Decision] = field(default_factory=list)

    def as_dict(self) -> dict:
        return {"closed_idle": self.closed_idle, "aborted": self.aborted,
                "decisions": self.decisions}


class Drainer:
    """Hold the shutdown of one listening server, and say why each step was taken."""

    def __init__(self, server, limits: Limits, *, clock=time.monotonic,
                 sleep=asyncio.sleep, on_decision=None, peek_unread: bool = True) -> None:
        self.server = server
        self.limits = limits
        self.clock = clock
        self.sleep = sleep
        self.on_decision = on_decision
        # Whether a socket with unread bytes counts as idle. Off only for the comparison in
        # probe 11 that shows what the time-based grace does without it.
        self.peek_unread = peek_unread
        self.state = State.SERVING
        self.conns: dict[int, Conn] = {}
        self.started = 0.0
        self.extended = False
        self.completed = 0
        self.progress: list[tuple[float, int]] = []
        self.summary = Summary()
        self.counts = Counts()
        self._signalled = asyncio.Event()
        self._next_id = 0
        self._force = False
        self._finished = False

    # -- what the request handler tells it -------------------------------------------
    def attach(self, reader, writer) -> Conn:
        self._next_id += 1
        conn = Conn(reader=reader, writer=writer, idle_since=self.clock(), key=self._next_id)
        if self._finished:
            # The drain already decided the process may leave. A connection the listener
            # accepted while it was closing has nobody left to serve it, so it is closed
            # here instead of being registered for a loop that has already returned.
            conn.close()
            return conn
        self.conns[self._next_id] = conn
        return conn

    def detach(self, conn: Conn) -> None:
        """The handler is done with this connection.

        Refusing a detach that still carries a request is the same guard as
        :meth:`finished_request`, from the other side: dropping the connection would drop
        its count with it, and the drain would see an idle process while a handler was
        still working on the socket it just forgot.
        """
        if conn.active > 0:
            raise ValueError("a connection was detached with a request still in flight")
        self._remove(conn)

    def _remove(self, conn: Conn) -> None:
        """Drop the connection from the table in one lookup.

        The table is keyed by the number ``attach`` gave the connection, and the connection
        carries that number, so nothing else in the table is looked at: closing every idle
        connection is one ``pop`` each instead of a scan each. A connection the drain never
        registered - one the listener accepted after it decided to leave - is not in the
        table at all, and the identity check makes that case a no-op rather than an error.
        """
        if self.conns.get(conn.key) is conn:
            del self.conns[conn.key]

    def started_request(self, conn: Conn) -> None:
        conn.active += 1

    def finished_request(self, conn: Conn) -> None:
        if conn.active <= 0:
            raise ValueError("a request finished on a connection that had none in flight")
        conn.active -= 1
        self.completed += 1
        if conn.active == 0:
            # The connection becomes a candidate for closing now, and the grace is
            # measured from here: a keep-alive socket that has just answered a request
            # may be about to carry the next one.
            conn.idle_since = self.clock()

    @property
    def in_flight(self) -> int:
        return sum(conn.active for conn in self.conns.values())

    @property
    def idle(self) -> int:
        return sum(1 for conn in self.conns.values() if conn.active == 0)

    @property
    def fresh(self) -> int:
        """Connections that may be holding a request nobody has counted yet.

        Two kinds: a socket that has carried nothing for less than its grace, and a socket
        with bytes waiting on it that no handler has read. The second is not a guess about
        time - it is the socket saying so - so it keeps the drain from leaving even when
        the grace has already expired.
        """
        return self._scan().fresh

    @property
    def unread(self) -> int:
        """Of those, the connections that say they are holding bytes right now.

        The policy needs the two apart at the end of a window: a socket that has been
        quiet for its grace has nothing on it, so closing it loses nothing and the drain
        stops, while a socket holding bytes has a request the count never saw and closing
        it is an abort that says so in the log. Zero when the drain was told not to ask.
        """
        if not self.peek_unread:
            return 0
        return self._scan().unread

    def _scan(self) -> Sample:
        """Walk the table once, asking each idle socket one question.

        Everything a decision needs comes out of this walk: the count in flight, the
        connections the drain is not yet willing to close, of those the ones whose socket
        says it holds bytes, and the per-connection answer the sample's closing pass reads
        instead of asking again. The freshness test is a comparison against the clock, so a
        connection past its grace still gets the socket's answer - the two are one reading,
        not two questions with the second one behind the first.
        """
        horizon = self.clock() - self.limits.idle_grace_ms / 1000
        in_flight = 0
        fresh = 0
        unread = 0
        readings: dict[int, tuple[bool, bool]] = {}
        for key, conn in self.conns.items():
            if conn.active > 0:
                in_flight += conn.active
                continue
            inside = conn.idle_since > horizon
            holding = bool(self.peek_unread) and conn.unread()
            readings[key] = (inside, holding)
            if inside or holding:
                fresh += 1
            if holding:
                unread += 1
        return Sample(in_flight=in_flight, fresh=fresh, unread=unread, readings=readings)

    # -- the shutdown ----------------------------------------------------------------
    def signal(self) -> None:
        """Stop accepting at once; the first sample is taken from this moment.

        A signal that arrives while a drain is already running is the operator asking
        again, and the drain honours it at its next sample: waiting out the rest of a
        window the operator has already given up on is the one thing this object must
        not do when it is told twice.
        """
        if self._signalled.is_set():
            self._force = True
            return
        self.started = self.clock()
        self.server.close()
        self.progress = [(self.started, self.completed)]
        self._signalled.set()

    async def wait_listener_closed(self) -> None:
        """Wait until the listening socket is really closed.

        Never before the first sample: on this Python ``Server.wait_closed()`` also
        waits for every accepted connection's handler to finish, so awaiting it at the
        start of a drain would turn the deadline into "however long the connections
        take" - which is the failure this object exists to prevent.
        """
        waiter = getattr(self.server, "wait_closed", None)
        if waiter is not None:
            await waiter()

    async def run(self) -> Summary:
        """Sample until the process may exit, closing idle connections on the way."""
        await self._signalled.wait()
        try:
            while True:
                # One walk over the table per step: the decision and the closes it leads to
                # read the same reading, so a socket is asked once and not again.
                sample = self._scan()
                decision = self._forced(sample) if self._force else self._sample(sample)
                self.counts.decisions += 1
                self.state = transition(self.state, decision)
                self.summary.add(decision)
                self.counts.samples.append(decision)
                if self.on_decision is not None:
                    self.on_decision(decision)
                if decision.action is Action.STOP:
                    self._close_all()
                    return self.summary
                if decision.action is Action.ABORT:
                    self._abort_active()
                    self._close_idle(ignore_grace=True, sample=sample)
                    return self.summary
                if decision.action is Action.KEEP:
                    # The machine was already stopped: a second drain has nothing to
                    # decide, and waiting for a window that was spent would never end.
                    return self.summary
                self._close_idle(sample=sample)
                self.extended = extended_after(decision)
                self._remember()
                await self.sleep(self.limits.poll_ms / 1000)
        finally:
            self._finished = True

    def _sample(self, sample: Sample | None = None) -> Decision:
        sample = self._scan() if sample is None else sample
        elapsed_ms = (self.clock() - self.started) * 1000.0
        return decide(state=self.state, elapsed_ms=elapsed_ms, in_flight=sample.in_flight,
                      fresh_conns=sample.fresh, unread_conns=sample.unread,
                      progress_completed=self.finished_in_progress(), extended=self.extended,
                      limits=self.limits)

    def _forced(self, sample: Sample | None = None) -> Decision:
        """The decision a second signal takes without asking the policy.

        The operator who signals twice means "now", so the window is given up - but only
        if there is something left to give up. A second signal that arrives with nothing in
        flight and nothing on a socket is the same stop any other sample would take, and
        logging it as an abort would put a loss in the log that never happened.
        """
        sample = self._scan() if sample is None else sample
        elapsed_ms = (self.clock() - self.started) * 1000.0
        if sample.in_flight == 0 and sample.unread == 0:
            return Decision(state=State.STOPPED, action=Action.STOP,
                            reason="second signal: nothing in flight",
                            elapsed_ms=elapsed_ms, in_flight=sample.in_flight,
                            extended=self.extended)
        held = (f"{sample.in_flight} in flight" if sample.in_flight
                else f"{sample.unread} sockets holding unread bytes")
        return Decision(state=State.STOPPED, action=Action.ABORT,
                        reason=f"second signal: aborting with {held}",
                        elapsed_ms=elapsed_ms, in_flight=sample.in_flight,
                        extended=self.extended)

    # -- progress, over a window rather than one interval ----------------------------
    def _remember(self) -> None:
        """Record the finished total, and keep only the entries the window can see.

        The first entry is the total at the moment of the signal and is never dropped:
        it is the baseline a sample reads when the window reaches back past every
        recorded sample, so a request that finished before the drain started can never
        be counted as progress made during it.
        """
        now = self.clock()
        self.progress.append((now, self.completed))
        horizon = now - self.limits.progress_ms / 1000
        while len(self.progress) > 2 and self.progress[1][0] <= horizon:
            del self.progress[1]

    def finished_in_progress(self) -> int:
        """How many requests finished inside the last ``progress_ms``."""
        horizon = self.clock() - self.limits.progress_ms / 1000
        base = self.progress[0][1] if self.progress else 0
        for recorded, total in self.progress:
            if recorded <= horizon:
                base = total
            else:
                break
        return self.completed - base

    def _close_idle(self, ignore_grace: bool = False, sample: Sample | None = None) -> None:
        """Close the connections that have carried nothing for long enough.

        The grace is what keeps a request that has arrived but not been read yet from
        being closed out from under its handler: from the drain's side the socket looks
        idle, and only the clock can tell it apart from one a load balancer left behind.
        The clock is not the only witness: a socket with unread bytes is left alone
        whatever its grace says, because closing it would throw away a request the count
        has never seen. Both answers come from the walk the decision was taken on - the
        ``sample`` argument - so the closing pass asks no socket a second time; on an abort
        (the deadline reached, or a second signal) the grace and the peek are both given
        up: the drain is leaving, and what it could not count it does not keep.
        """
        sample = self._scan() if sample is None else sample
        for key, conn in list(self.conns.items()):
            if conn.active > 0:
                continue
            if ignore_grace:
                conn.close()
                self._remove(conn)
                self.counts.closed_idle += 1
                continue
            reading = sample.readings.get(key)
            if reading is None or reading[0] or reading[1]:
                continue
            conn.close()
            self._remove(conn)
            self.counts.closed_idle += 1

    def _close_all(self) -> None:
        for conn in list(self.conns.values()):
            conn.close()
            self._remove(conn)
            self.counts.closed_idle += 1

    def _abort_active(self) -> None:
        for conn in list(self.conns.values()):
            if conn.active > 0:
                conn.abort()
                self._remove(conn)
                self.counts.aborted += 1
One line per decision, and a run’s totals. report.py
"""One line per decision, and a run's totals.

The line is the whole observability story of this page: an operator reading a log
after a deploy needs to know which state the process was in, how many requests were
still being served, and why the policy did what it did. Nothing here formats a
number differently from the policy's own sample, so a log line can be compared with
the probe's JSON without conversion.
"""
from __future__ import annotations

from dataclasses import dataclass, field


def describe(decision) -> str:
    """Format one decision as a single log line, in the policy's own units."""
    return (f"state={decision.state.value} action={decision.action.value} "
            f"inflight={decision.in_flight} elapsed_ms={decision.elapsed_ms:.0f} "
            f"reason={decision.reason}")


@dataclass
class Summary:
    """What one shutdown cost, counted the way the article's tables count it."""

    waits: int = 0
    extends: int = 0
    aborts: int = 0
    stops: int = 0
    max_in_flight: int = 0
    last_elapsed_ms: float = 0.0
    lines: list[str] = field(default_factory=list)

    def add(self, decision) -> None:
        self.lines.append(describe(decision))
        self.max_in_flight = max(self.max_in_flight, decision.in_flight)
        self.last_elapsed_ms = decision.elapsed_ms
        if decision.action.value == "wait":
            self.waits += 1
        elif decision.action.value == "extend":
            self.extends += 1
        elif decision.action.value == "abort":
            self.aborts += 1
        elif decision.action.value == "stop":
            self.stops += 1

    @property
    def outcome(self) -> str:
        """``clean`` when the last decision found nothing in flight, ``aborted`` otherwise."""
        if self.aborts:
            return "aborted"
        return "clean" if self.stops else "running"

    def as_dict(self) -> dict:
        return {
            "waits": self.waits,
            "extends": self.extends,
            "aborts": self.aborts,
            "stops": self.stops,
            "max_in_flight": self.max_in_flight,
            "last_elapsed_ms": round(self.last_elapsed_ms, 1),
            "outcome": self.outcome,
            "lines": list(self.lines),
        }
The readings that come from the kernel rather than the policy: descriptors, socket options, and the unread bytes. probe.py
"""The readings this page quotes about the host, rather than about the policy.

Each one is a file or a socket option the kernel owns: how many descriptors a
process holds, whether it is still running, the host's FIN timeout, the listen
backlog ceiling, and the two socket options a shutdown touches. They are read, not
assumed, because the article has to say which figures came from this host and which
came from documentation.
"""
from __future__ import annotations

import array
import fcntl
import pathlib
import socket
import struct
import termios

PROC = pathlib.Path("/proc")


def open_fds(pid: int) -> int:
    """How many descriptors the process holds right now, the listening socket included."""
    return len(list((PROC / str(pid) / "fd").iterdir()))


def proc_state(pid: int) -> str:
    """One letter from ``/proc/<pid>/stat``: ``R``, ``S``, ``Z`` or a gone process's error."""
    text = (PROC / str(pid) / "stat").read_text(encoding="ascii")
    tail = text.rsplit(")", 1)[1].split()
    return tail[0]


def sysctl(name: str) -> str:
    """One value under ``/proc/sys``, read as text so the article can quote it as is."""
    path = PROC / "sys" / name.replace(".", "/")
    return path.read_text(encoding="ascii").strip()


def tcp_fin_timeout_ms() -> int:
    """The host's FIN timeout in milliseconds; this is what a half-closed peer waits out."""
    return int(sysctl("net.ipv4.tcp_fin_timeout")) * 1000


def somaxconn() -> int:
    """The listen backlog ceiling the host enforces, not the value an application asks for."""
    return int(sysctl("net.core.somaxconn"))


def linger(writer) -> tuple[int, int]:
    """``SO_LINGER`` as ``(on, seconds)``: off means close() flushes and sends a FIN."""
    sock = writer.get_extra_info("socket")
    if sock is None:
        raise ValueError("the writer is not backed by a socket")
    raw = sock.getsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.calcsize("ii"))
    return struct.unpack("ii", raw)


def pending_bytes(writer) -> int:
    """Bytes the kernel still holds for this connection, without consuming any of them.

    ``FIONREAD`` answers "how many bytes are waiting to be read" straight from the socket
    buffer; the descriptor is duplicated first because a transport hands out a wrapper
    without ``recv`` on it, and a duplicate shares the file description, so the count is
    the connection's own and reading through the duplicate would not be a second read.
    This is the kernel half of the check: bytes asyncio's transport has already moved into
    a ``StreamReader`` are no longer here, which is why :meth:`drainage.Conn.unread`
    looks at the reader first.
    """
    sock = writer.get_extra_info("socket") if hasattr(writer, "get_extra_info") else None
    if sock is None:
        return 0
    duplicate = sock.dup()
    try:
        waiting = array.array("i", [0])
        fcntl.ioctl(duplicate.fileno(), termios.FIONREAD, waiting, True)
        return int(waiting[0])
    finally:
        duplicate.close()


def peek(writer, size: int = 1) -> bytes:
    """The first bytes of an unread request, left on the socket for its handler.

    ``MSG_PEEK`` reads without consuming, and ``MSG_DONTWAIT`` keeps the call from
    blocking: on an idle connection it raises ``BlockingIOError`` and returns nothing,
    which is the answer the drain wants. This is the kernel-level twin of
    :func:`pending_bytes` and reads the same buffer.
    """
    sock = writer.get_extra_info("socket") if hasattr(writer, "get_extra_info") else None
    if sock is None:
        return b""
    duplicate = sock.dup()
    try:
        return duplicate.recv(size, socket.MSG_PEEK | socket.MSG_DONTWAIT)
    except BlockingIOError:
        return b""
    finally:
        duplicate.close()


def nodelay(writer) -> int:
    """``TCP_NODELAY`` as the socket actually reports it, for the reader's comparison.

    ``IPPROTO_TCP``'s own default for the option is 0, but asyncio's transports set it,
    so the read on an asyncio connection is 1 (table 1) - a reply is not held back to
    share a segment with the next write.
    """
    sock = writer.get_extra_info("socket")
    if sock is None:
        raise ValueError("the writer is not backed by a socket")
    return struct.unpack("i", sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,
                                               struct.calcsize("i")))[0]
What the package exports. __init__.py
"""What a process needs to shut down without dropping the requests it is serving.

The package is small on purpose: a decision that is a pure function of one sample,
the object that takes the samples against a real server, the readings that come from
the kernel, and the log line that explains a decision afterwards.
"""
from __future__ import annotations

from .drainer import Conn, Drainer
from .policy import (
    Action,
    Decision,
    Limits,
    State,
    ALLOWED_TRANSITIONS,
    IllegalTransition,
    decide,
    transition,
)
from .report import Summary, describe

__all__ = [
    "ALLOWED_TRANSITIONS",
    "Action",
    "Conn",
    "Decision",
    "Drainer",
    "IllegalTransition",
    "Limits",
    "State",
    "Summary",
    "decide",
    "describe",
    "transition",
]
The clients – closing and keep-alive – the arm runner and the median with its range. harness.py
"""Start the server, drive real clients at it, and say how each request ended.

The client side is the honest witness: a reply that never arrived is classified by
what the socket actually did - a clean end of stream, a reset, or nothing at all
before the cap - rather than by what the server believed it had sent.

The moment the process leaves is measured by a watcher of its own, started the instant
the signal is sent. Nothing else the probe does afterwards can move that number: the
connections this harness makes to ask whether the listener is still there, and the
sleep between them, belong to the probe and not to the process's exit.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import signal
import statistics
import subprocess
import sys
import time

HERE = pathlib.Path(__file__).resolve().parent
SERVER = HERE / "arm_server.py"


class Client:
    def __init__(self, index: int, delay_ms: int, hold: bool = False) -> None:
        self.index = index
        self.delay_ms = delay_ms
        # A client that closes its socket as soon as it has its reply hides the idle grace:
        # the connection is detached at once and the drain has nothing left to wait for. A
        # hold client keeps the socket open for the next request, as an HTTP client does.
        self.hold = hold
        self.sent = False
        self.finished = False
        self.got = "not_started"
        self.elapsed_ms = 0.0


def summarize(runs: list[dict]) -> dict:
    """One arm's repeats, as a median with the range it came from.

    A wall time is a sample, not a constant: two runs of the same arm differ by a few
    milliseconds because the machine is doing other things. The median is what the
    tables quote and the range is what says how much the quote is worth; replies are a
    median over the runs, while losses are totalled because a loss in any run is a loss.
    ``server`` is the run nearest the median, so the decision log quoted beside a wall
    time belongs to the run that wall time came from. ``observed_median_ms`` is what a
    poll loop reading ``poll()`` after the probe would have reported for the same runs,
    kept beside the watched exit so the difference between the two is a measured fact
    rather than a claim about the harness.
    """
    walls = [run["exit_ms"] for run in runs]
    median = statistics.median(walls)
    nearest = min(range(len(runs)), key=lambda index: abs(runs[index]["exit_ms"] - median))
    tally = {key: (int(statistics.median(run["tally"].get(key, 0) for run in runs))
                   if key == "replied"
                   else sum(run["tally"].get(key, 0) for run in runs))
             for key in runs[0]["tally"]}
    return {
        "runs": runs,
        "repeats": len(runs),
        "wall_ms": round(median, 1),
        "wall_median_ms": round(median, 1),
        "wall_min_ms": min(walls),
        "wall_max_ms": max(walls),
        "observed_median_ms": round(statistics.median(run["observed_ms"] for run in runs), 1),
        "lag_median_ms": round(statistics.median(run["poll_lag_ms"] for run in runs), 1),
        "tally": tally,
        "replied_median": tally["replied"],
        "lost_eof_total": tally["lost_eof"],
        "reset_total": tally["reset"],
        "in_flight_median": statistics.median(run["in_flight_at_signal"] for run in runs),
        "refused_after_median": statistics.median(run["refused_after_signal"] for run in runs),
        "accepted_after_max": max(run["accepted_after_signal"] for run in runs),
        "hit_cap_count": sum(1 for run in runs if run["hit_cap"]),
        "exit_codes": sorted({run["exit_code"] for run in runs}),
        "server": runs[nearest]["server"],
    }


async def wait_ready(path: pathlib.Path, timeout: float = 10.0) -> dict:
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if path.exists() and path.stat().st_size:
            return json.loads(path.read_text(encoding="utf-8"))
        await asyncio.sleep(0.01)
    raise TimeoutError(f"server did not become ready: {path}")


async def drive(client: Client, port: int, results: dict,
                release: asyncio.Event | None = None) -> None:
    """Connect, send one request, and record the first thing the socket did back."""
    started = time.monotonic()
    try:
        reader, writer = await asyncio.wait_for(asyncio.open_connection("127.0.0.1", port), 1.0)
    except (ConnectionRefusedError, ConnectionResetError):
        client.got = "refused"
        client.finished = True
        results[client.index] = client
        return
    except asyncio.TimeoutError:
        client.got = "connect_timeout"
        client.finished = True
        results[client.index] = client
        return
    client.sent = True
    results[client.index] = client
    try:
        writer.write(f"REQ {client.delay_ms}\n".encode())
        await writer.drain()
        line = await asyncio.wait_for(reader.readline(), 30.0)
        client.got = "replied" if line.strip() == b"OK" else "lost_eof"
    except ConnectionResetError:
        client.got = "reset"
    except asyncio.TimeoutError:
        client.got = "timeout"
    finally:
        client.elapsed_ms = round((time.monotonic() - started) * 1000, 1)
        client.finished = True
        if client.hold and release is not None and client.got == "replied":
            # Keep-alive: the connection stays open after its reply, so on the server side
            # the handler is still attached and the socket is idle. This is the state a
            # load balancer's client leaves behind, and the one the idle grace is for.
            try:
                await release.wait()
            except asyncio.CancelledError:
                pass
        writer.close()


async def watch_exit(proc: subprocess.Popen, signalled: float) -> float:
    """Wait for the process to leave and report how long after the signal it did.

    ``Popen.wait`` blocks, so it is waited on in a thread: the event loop stays free for
    the clients, and the exit is timed from the kernel's own report rather than from a
    check the probe happens to make.
    """
    def wait() -> float:
        proc.wait()
        return time.monotonic()

    loop = asyncio.get_running_loop()
    return round((await loop.run_in_executor(None, wait) - signalled) * 1000, 1)


async def second_signal(proc: subprocess.Popen, signalled: float, after_ms: float) -> None:
    """Send the signal a second time, at a fixed offset from the first."""
    await asyncio.sleep(max(0.0, after_ms / 1000 - (time.monotonic() - signalled)))
    proc.send_signal(signal.SIGTERM)


async def run_arm(mode: str, *, clients: int = 12, delay_ms: int = 400,
                  stagger_ms: float = 10.0, signal_after_ms: float = 120.0,
                  grace_ms: int = 1000, extension_ms: int = 500, poll_ms: int = 25,
                  cap_ms: int | None = None, idle_conns: int = 0,
                  probe_new_conns: int = 0, probe_delay_ms: float = 30.0,
                  second_signal_after_ms: float | None = None,
                  read_delay_ms: int = 0, idle_grace_ms: int | None = None,
                  progress_ms: int | None = None, keep_alive: bool = False,
                  peek_unread: bool = True,
                  workdir: pathlib.Path | None = None) -> dict:
    # A short window gets a progress window and an idle grace that fit inside it: the
    # policy refuses both when they do not, rather than granting something it can never
    # sample.
    progress_ms = min(500, grace_ms) if progress_ms is None else progress_ms
    idle_grace_ms = min(250, grace_ms - poll_ms) if idle_grace_ms is None else idle_grace_ms
    workdir = workdir or HERE.parent / "scratch" / f"arm-{mode}"
    workdir.mkdir(parents=True, exist_ok=True)
    stamp = f"{mode}-{time.time_ns()}"
    ready = workdir / f"{stamp}.ready"
    stats_file = workdir / f"{stamp}.stats.json"
    proc = subprocess.Popen(
        [sys.executable, str(SERVER), "--mode", mode, "--ready-file", str(ready),
         "--stats-file", str(stats_file), "--grace-ms", str(grace_ms),
         "--extension-ms", str(extension_ms), "--poll-ms", str(poll_ms),
         "--progress-ms", str(progress_ms), "--idle-grace-ms", str(idle_grace_ms),
         "--read-delay-ms", str(read_delay_ms)]
        + ([] if peek_unread else ["--no-peek"]),
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    info = await wait_ready(ready, timeout=10.0)
    port = int(info["port"])
    results: dict[int, Client] = {}
    tasks: list[asyncio.Task] = []
    release = asyncio.Event()
    idle: list = []
    cap = cap_ms if cap_ms is not None else grace_ms + extension_ms + 3000

    # Keep-alive connections that send no request at all: they are what a load balancer
    # leaves behind, and they never end on their own.
    for _ in range(idle_conns):
        reader, writer = await asyncio.open_connection("127.0.0.1", port)
        idle.append((reader, writer))

    spawned = time.monotonic()
    for index in range(clients):
        client = Client(index, delay_ms, hold=keep_alive)
        tasks.append(asyncio.ensure_future(drive(client, port, results, release)))
        await asyncio.sleep(stagger_ms / 1000)

    # The signal lands a fixed time after the first client connected, not after the
    # stagger, or a slow spawn would move the experiment's start.
    await asyncio.sleep(max(0.0, signal_after_ms / 1000 - (time.monotonic() - spawned)))
    in_flight = sum(1 for client in results.values() if client.sent and not client.finished)
    proc.send_signal(signal.SIGTERM)
    signalled = time.monotonic()
    # Started before anything else the probe does: from here on, this is the process's
    # own exit being timed, not the probe's next look at it.
    exit_task = asyncio.ensure_future(watch_exit(proc, signalled))
    if second_signal_after_ms is not None:
        asyncio.ensure_future(second_signal(proc, signalled, second_signal_after_ms))

    accepted_after = 0
    refused_after = 0
    # Give the shutdown a moment to act before asking whether the listener is still
    # there: a connect that races the signal is not evidence either way.
    if probe_new_conns:
        await asyncio.sleep(probe_delay_ms / 1000)
    for _ in range(probe_new_conns):
        try:
            reader, writer = await asyncio.wait_for(
                asyncio.open_connection("127.0.0.1", port), 0.5)
            accepted_after += 1
            writer.close()
        except (ConnectionRefusedError, ConnectionResetError):
            refused_after += 1
        except asyncio.TimeoutError:
            refused_after += 1
        await asyncio.sleep(0.02)

    # The same question a poll loop asks, kept so the two ways of timing an exit can be
    # compared on the runs that produced the tables.
    observed_ms = None
    while (time.monotonic() - signalled) * 1000 < cap:
        if proc.poll() is not None:
            observed_ms = round((time.monotonic() - signalled) * 1000, 1)
            break
        await asyncio.sleep(0.01)
    hit_cap = observed_ms is None
    if hit_cap:
        proc.kill()
        observed_ms = round((time.monotonic() - signalled) * 1000, 1)
    exit_ms = await exit_task
    exit_code = proc.returncode if proc.returncode is not None else proc.wait(timeout=10)
    held = sum(1 for client in results.values() if client.hold and client.got == "replied")
    # Release the held sockets only after the process has gone, so nothing the probe does
    # can shorten the shutdown it is measuring.
    release.set()
    await asyncio.sleep(0.02)
    for task in tasks:
        if not task.done():
            task.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)
    for reader, writer in idle:
        writer.close()

    await asyncio.sleep(0.05)
    for path in (ready,):
        if path.exists():
            path.unlink()
    server_stats = None
    if stats_file.exists():
        server_stats = json.loads(stats_file.read_text(encoding="utf-8"))
        stats_file.unlink()

    tally = {"replied": 0, "lost_eof": 0, "reset": 0, "refused": 0, "timeout": 0,
             "connect_timeout": 0, "not_started": 0}
    for client in results.values():
        tally[client.got] = tally.get(client.got, 0) + 1
    return {
        "mode": mode,
        "clients": clients,
        "delay_ms": delay_ms,
        "grace_ms": grace_ms,
        "extension_ms": extension_ms,
        "poll_ms": poll_ms,
        "progress_ms": progress_ms,
        "idle_grace_ms": idle_grace_ms,
        "read_delay_ms": read_delay_ms,
        "idle_conns": idle_conns,
        "keep_alive": keep_alive,
        "peek_unread": peek_unread,
        "held_conns": held,
        "in_flight_at_signal": in_flight,
        "accepted_after_signal": accepted_after,
        "refused_after_signal": refused_after,
        "tally": tally,
        "wall_ms": exit_ms,
        "exit_ms": exit_ms,
        "observed_ms": observed_ms,
        "poll_lag_ms": round(observed_ms - exit_ms, 1),
        "hit_cap": hit_cap,
        "exit_code": exit_code,
        "server": server_stats,
    }
The server under test: a line protocol, the five shutdown behaviours, and the switch that turns the peek off. arm_server.py
"""The server under test: a line protocol, and the five shutdown behaviours compared here.

Clients send ``REQ <milliseconds>`` and get ``OK`` once the handler has slept that long,
so "in flight" is a real wait inside a real coroutine and a lost reply is a lost request.
The process is started by a probe with ``--ready-file`` and ``--stats-file`` rather than
over a pipe: a pipe would have to be drained while the server runs, and the point of the
exercise is what happens when the server stops.

``--mode default`` deliberately installs no signal handler, so the kernel's default
action for SIGTERM is what the probe measures. ``--read-delay-ms`` makes every handler
wait before its first read, which is the time a real framework spends between accepting
a connection and reading from it (a TLS handshake, a middleware stack); a request that
arrives inside it is on the socket but not yet in any count. ``--no-peek`` turns off the
socket's own answer to that question, so probe 11 can measure what the time-based grace
does on its own.
"""
from __future__ import annotations

import argparse
import asyncio
import json
import os
import pathlib
import signal
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "module"))

from drainage import Drainer, Limits  # noqa: E402


def stats_new() -> dict:
    return {"accepted": 0, "requests": 0, "replied": 0, "in_flight": 0, "peer_gone": 0,
            "closed": 0, "signalled_at": None, "exited_at": None, "mode": "",
            "decisions": None, "swallowed": 0, "signals": 0, "peek_unread": None}


async def handler(reader, writer, stats: dict, drainer: Drainer | None,
                  swallow: bool = False, read_delay_ms: int = 0):
    stats["accepted"] += 1
    conn = drainer.attach(reader, writer) if drainer is not None else None
    try:
        if read_delay_ms:
            await asyncio.sleep(read_delay_ms / 1000)
        while True:
            line = await reader.readline()
            if not line:
                break
            delay_ms = 0
            parts = line.split()
            if len(parts) > 1:
                delay_ms = int(parts[1])
            stats["requests"] += 1
            stats["in_flight"] += 1
            if conn is not None:
                drainer.started_request(conn)
            try:
                if delay_ms:
                    try:
                        await asyncio.sleep(delay_ms / 1000)
                    except asyncio.CancelledError:
                        stats["swallowed"] += 1
                        if not swallow:
                            raise
                        # A handler that refuses to stop: it finishes the work it began.
                        await asyncio.sleep(delay_ms / 1000)
                writer.write(b"OK\n")
                await writer.drain()
                stats["replied"] += 1
            finally:
                stats["in_flight"] -= 1
                if conn is not None:
                    drainer.finished_request(conn)
    except (ConnectionResetError, BrokenPipeError):
        stats["peer_gone"] += 1
    finally:
        stats["closed"] += 1
        if conn is not None:
            drainer.detach(conn)
        writer.close()


async def serve(args, stats: dict) -> None:
    limits = Limits(grace_ms=args.grace_ms, extension_ms=args.extension_ms,
                    poll_ms=args.poll_ms, progress_ms=args.progress_ms,
                    idle_grace_ms=args.idle_grace_ms)
    drainer = (Drainer(None, limits, peek_unread=not args.no_peek)
               if args.mode == "policy" else None)
    stats["peek_unread"] = not args.no_peek
    tasks: set[asyncio.Task] = set()

    def spawn(reader, writer):
        task = asyncio.ensure_future(handler(reader, writer, stats, drainer,
                                             swallow=args.mode == "cancel_swallow",
                                             read_delay_ms=args.read_delay_ms))
        tasks.add(task)
        task.add_done_callback(tasks.discard)
        return task

    server = await asyncio.start_server(spawn, "127.0.0.1", 0)
    if drainer is not None:
        drainer.server = server
    port = server.sockets[0].getsockname()[1]
    pathlib.Path(args.ready_file).write_text(
        json.dumps({"port": port, "pid": os.getpid()}), encoding="utf-8")

    stop = asyncio.Event()
    if args.mode != "default":
        def on_signal():
            # Every signal goes to the drainer, not only the first: a second SIGTERM is
            # the operator saying "now", and it can only be heard if this handler passes
            # it on. The first call starts the drain and closes the listener; the second
            # is what the loop turns into an abort at its next sample.
            stats["signals"] += 1
            if stats["signalled_at"] is None:
                stats["signalled_at"] = time.monotonic()
            if drainer is not None:
                drainer.signal()
            stop.set()

        asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, on_signal)

    if args.mode == "default":
        await asyncio.sleep(3600)
    elif args.mode == "blind":
        await stop.wait()
        await asyncio.sleep(args.grace_ms / 1000)
    elif args.mode == "wait_all":
        await stop.wait()
        server.close()
        await server.wait_closed()
        if tasks:
            await asyncio.gather(*list(tasks), return_exceptions=True)
    elif args.mode in ("cancel", "cancel_swallow"):
        await stop.wait()
    elif args.mode == "close_only":
        await stop.wait()
        server.close()
        await server.wait_closed()
        while True:
            await asyncio.sleep(0.05)
    elif args.mode == "policy":
        await stop.wait()
        summary = await drainer.run()
        stats["decisions"] = summary.as_dict()
        stats["counts"] = drainer.counts.as_dict()
    else:
        raise SystemExit(f"unknown mode {args.mode}")

    if args.mode == "policy":
        for task in list(tasks):
            task.cancel()
        await asyncio.gather(*list(tasks), return_exceptions=True)
    stats["exited_at"] = time.monotonic()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", default="default")
    parser.add_argument("--ready-file", required=True)
    parser.add_argument("--stats-file", required=True)
    parser.add_argument("--grace-ms", type=int, default=1000)
    parser.add_argument("--extension-ms", type=int, default=500)
    parser.add_argument("--poll-ms", type=int, default=25)
    parser.add_argument("--progress-ms", type=int, default=500)
    parser.add_argument("--idle-grace-ms", type=int, default=250)
    parser.add_argument("--read-delay-ms", type=int, default=0)
    parser.add_argument("--no-peek", action="store_true",
                        help="close idle connections on the clock alone (probe 11's comparison)")
    args = parser.parse_args()
    stats = stats_new()
    stats["mode"] = args.mode
    try:
        asyncio.run(serve(args, stats))
    finally:
        if stats["exited_at"] is None:
            stats["exited_at"] = time.monotonic()
        pathlib.Path(args.stats_file).write_text(json.dumps(stats, indent=1), encoding="utf-8")


if __name__ == "__main__":
    main()
The ASGI app the two production servers serve: one endpoint that sleeps. fw_app.py
"""The ASGI app probe 13 serves: one endpoint whose handler sleeps for a known time.

Nothing else is in it, so the only thing the probe's numbers can be about is the
server's shutdown: a request that arrives is a coroutine waiting on a timer, and a reply
that arrives is proof the server waited for it.
"""
from __future__ import annotations

import asyncio
import os

DELAY_MS = int(os.environ.get("FW_DELAY_MS", "2500"))


async def app(scope, receive, send) -> None:
    if scope["type"] != "http":
        return
    await asyncio.sleep(DELAY_MS / 1000)
    body = b"OK\n"
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-length", str(len(body)).encode())]})
    await send({"type": "http.response.body", "body": body})
The machine every figure belongs to (table 1). 00_host.py
"""Probe 00: the host these shutdown figures belong to.

Every number in the article is a property of one process on one machine, so the page
has to publish the machine: kernel, Python, CPU count, page size and the two kernel
timers a close touches. ``tcp_fin_timeout`` and ``somaxconn`` are read from /proc
because an application's request for a backlog is a wish and this file is the ceiling.
"""
from __future__ import annotations

import json
import os
import pathlib
import platform
import re
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "module"))

from drainage import probe  # noqa: E402


def os_release() -> str:
    path = pathlib.Path("/etc/os-release")
    if not path.exists():
        return "unknown"
    match = re.search(r'^PRETTY_NAME="(.*)"$', path.read_text(encoding="utf-8"), re.M)
    return match.group(1) if match else "unknown"


def meminfo() -> dict:
    values = {}
    with open("/proc/meminfo", encoding="ascii") as handle:
        for line in handle:
            key, _, rest = line.partition(":")
            values[key] = int(rest.split()[0])
    return values


def main() -> None:
    mem = meminfo()
    record = {
        "kernel": os.uname().release,
        "os": os_release(),
        "python": platform.python_version(),
        "python_build": " ".join(platform.python_implementation().split()) + " "
                        + sys_version(),
        "cpus": os.cpu_count(),
        "page_size": os.sysconf("SC_PAGE_SIZE"),
        "mem_total_kb": mem["MemTotal"],
        "mem_available_kb": mem["MemAvailable"],
        "cgroup_v2": pathlib.Path("/sys/fs/cgroup/cgroup.controllers").exists(),
        "tcp_fin_timeout_ms": probe.tcp_fin_timeout_ms(),
        "somaxconn": probe.somaxconn(),
        "identity": {"uid": os.getuid(), "hostname": os.uname().nodename},
    }
    out = pathlib.Path(__file__).resolve().parent.parent / "results" / "00_host.json"
    out.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(record, indent=1))


def sys_version() -> str:
    return " ".join(sys.version.split()[:3])


if __name__ == "__main__":
    main()
SIGTERM, SO_LINGER and the socket options (table 1). 09_constants.py
"""Probe 09: the constants a shutdown is built on, read from this host rather than quoted.

Four of them decide what an operator sees:

* what SIGTERM does to a process that never installed a handler;
* what ``SO_LINGER`` is set to when nobody sets it, which is why close() sends a FIN;
* whether this Python's ``asyncio.Server`` can close the clients it accepted;
* how long the kernel keeps a half-closed socket, and how deep a listen queue it allows.

The third is measured by looking for the method, because the article tells a reader on
3.12 they must track connections themselves, and a method that exists in a later version
would make that advice wrong for them.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import signal
import subprocess
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "module"))

from drainage import probe  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"


def default_action() -> dict:
    """A child process with no handler: the exit status says what the signal did."""
    child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    try:
        time.sleep(0.2)
        child.send_signal(signal.SIGTERM)
        code = child.wait(timeout=10)
    finally:
        if child.poll() is None:
            child.kill()
    handler = signal.getsignal(signal.SIGTERM)
    return {
        "exit_code": code,
        # Python's own default: SIG_DFL, the kernel's terminate action, before asyncio.
        "python_handler": "sig_dfl" if handler is signal.SIG_DFL else repr(handler),
        "signal_number": int(signal.SIGTERM),
    }


async def socket_defaults() -> dict:
    """SO_LINGER and TCP_NODELAY on a fresh asyncio connection, both unset by the app."""
    async def drop(reader, writer):
        writer.close()

    server = await asyncio.start_server(drop, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    try:
        on, seconds = probe.linger(writer)
        record = {"linger_on": on, "linger_seconds": seconds,
                  "tcp_nodelay": probe.nodelay(writer),
                  "close_clients": hasattr(asyncio.Server, "close_clients"),
                  "abort_clients": hasattr(asyncio.Server, "abort_clients")}
    finally:
        writer.close()
        server.close()
        del reader
    await asyncio.sleep(0.05)
    return record


def main() -> None:
    record = {
        "signal": default_action(),
        "sockets": asyncio.run(socket_defaults()),
        "tcp_fin_timeout_ms": probe.tcp_fin_timeout_ms(),
        "somaxconn": probe.somaxconn(),
        "open_fds_self": probe.open_fds(__import__("os").getpid()),
    }
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "09_constants.json").write_text(json.dumps(record, indent=1) + "\n",
                                              encoding="utf-8")
    print(json.dumps(record, indent=1))


if __name__ == "__main__":
    main()
What Server.close() stops and what it does not (table 3). 02_close.py
"""Probe 02: what ``Server.close()`` actually stops.

The listening socket is not the server. Closing it refuses new connections and leaves
every accepted one served - and in this Python it also leaves ``wait_closed()`` waiting
for those connections' handlers, which is why a shutdown built on ``close()`` alone
either serves requests during the deploy or never returns.

The wait is measured as a task that is left running: a probe that wrapped it in a
timeout would record the timeout, not the release, and the difference between those two
numbers is the whole claim that ``wait_closed()`` is not finished when ``close()`` is.
"""
from __future__ import annotations

import asyncio
import json
import os
import pathlib
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "module"))

from drainage import probe  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"


async def main() -> dict:
    served = 0

    async def handle(reader, writer):
        nonlocal served
        try:
            while True:
                line = await reader.readline()
                if not line:
                    break
                served += 1
                writer.write(b"OK\n")
                await writer.drain()
        finally:
            writer.close()

    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    writer.write(b"REQ 0\n")
    await writer.drain()
    first = (await asyncio.wait_for(reader.readline(), 1.0)).strip() == b"OK"
    fds_before = probe.open_fds(os.getpid())

    server.close()
    started = time.monotonic()
    # The waiter is created and then left alone: it is the thing being measured, so it
    # must not be cancelled by a timeout the probe chose.
    waiter = asyncio.ensure_future(server.wait_closed())
    fds_after = probe.open_fds(os.getpid())

    refused = 0
    accepted = 0
    for _ in range(5):
        try:
            late_reader, late_writer = await asyncio.wait_for(
                asyncio.open_connection("127.0.0.1", port), 1.0)
            accepted += 1
            late_writer.close()
        except (ConnectionRefusedError, ConnectionResetError):
            refused += 1

    # The connection accepted before close() still gets its request served.
    writer.write(b"REQ 0\n")
    await writer.drain()
    served_after_close = (await asyncio.wait_for(reader.readline(), 1.0)).strip() == b"OK"

    # Five round trips and a short sleep have passed; if wait_closed() were done when
    # close() returned, it would have reported by now.
    await asyncio.sleep(0.05)
    pending_while_open = not waiter.done()

    writer.close()
    client_closed = time.monotonic()
    released = True
    try:
        await asyncio.wait_for(waiter, 5.0)
    except asyncio.TimeoutError:
        released = False
    release_ms = round((time.monotonic() - client_closed) * 1000, 1)
    total_ms = round((time.monotonic() - started) * 1000, 1)

    return {
        "first_round_trip_before_close": first,
        "refused_after_close": refused,
        "accepted_after_close": accepted,
        "served_after_close": served_after_close,
        "served_total": served,
        "fds_before_close": fds_before,
        "fds_after_close": fds_after,
        "wait_closed_pending_while_a_connection_is_open": pending_while_open,
        "wait_closed_returns_after_the_connection_ends": released,
        "release_after_connection_end_ms": release_ms,
        "wait_closed_total_ms": total_ms,
    }


if __name__ == "__main__":
    record = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "02_close.json").write_text(json.dumps(record, indent=1) + "\n",
                                          encoding="utf-8")
    print(json.dumps(record, indent=1))
The four ways a connection can end (table 2). 03_abort.py
"""Probe 03: three ways to end a connection, and what the client sees for each.

A shutdown has to choose one. ``close()`` flushes what the handler wrote and sends a
FIN, so a reply already written still arrives. ``abort()`` drops the socket, and so does
closing with a request still unread: the client's next read raises
``ConnectionResetError`` instead of returning end-of-stream. A reply cut in half is the
worst case - the client read something and cannot tell whether more was coming.
"""
from __future__ import annotations

import asyncio
import json
import pathlib

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"


async def arm(kind: str) -> dict:
    async def handle(reader, writer):
        if kind == "close_after_reply":
            await reader.readline()
            writer.write(b"OK\n")
            await writer.drain()
            writer.close()
        elif kind == "close_unread":
            # The request stays in the receive queue; Linux answers its close with a reset.
            writer.close()
        elif kind == "abort_pending":
            await reader.readline()
            writer.write(b"OK\n")
            # No drain: the reply is buffered and abort() throws it away.
            writer.transport.abort()
        elif kind == "half_reply":
            await reader.readline()
            writer.write(b"OK")
            await writer.drain()
            writer.close()
        else:
            raise SystemExit(kind)

    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    writer.write(b"REQ 0\n")
    await writer.drain()
    outcome = "unknown"
    data = b""
    try:
        data = await asyncio.wait_for(reader.readline(), 1.0)
        if not data:
            outcome = "eof"
        elif data.endswith(b"\n"):
            outcome = "complete"
        else:
            outcome = "partial"
    except ConnectionResetError:
        outcome = "reset"
    except asyncio.TimeoutError:
        outcome = "timeout"
    writer.close()
    server.close()
    await asyncio.sleep(0.05)
    return {"kind": kind, "outcome": outcome, "bytes": len(data)}


async def main() -> dict:
    arms = []
    for kind in ("close_after_reply", "close_unread", "abort_pending", "half_reply"):
        arms.append(await arm(kind))
    return {"arms": arms}


if __name__ == "__main__":
    record = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "03_abort.json").write_text(json.dumps(record, indent=1) + "\n",
                                          encoding="utf-8")
    print(json.dumps(record, indent=1))
What asyncio.run cancels (table 4). 05_cancel.py
"""Probe 05: what ``asyncio.run`` does to the requests still in flight.

Returning from ``main()`` looks like a clean shutdown - exit code 0, no traceback - and
it drops every request, because ``asyncio.run`` cancels the tasks and closes the loop.
A handler that swallows ``CancelledError`` changes the picture again: its reply is
delivered, and the process exits when that handler is done rather than at a deadline.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import statistics
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
REPEATS = 3


async def main() -> dict:
    record: dict = {"conditions": {"clients": 12, "delay_ms": 400, "signal_after_ms": 120,
                                   "grace_ms": 1000, "repeats": REPEATS}, "arms": {}}
    for mode in ("cancel", "cancel_swallow"):
        runs = []
        for _ in range(REPEATS):
            run = await harness.run_arm(mode, clients=12, delay_ms=400,
                                        signal_after_ms=120, grace_ms=1000,
                                        extension_ms=500, probe_new_conns=1)
            runs.append(run)
            print(mode, run["wall_ms"], run["tally"], (run["server"] or {}).get("swallowed"),
                  flush=True)
        record["arms"][mode] = {
            "runs": runs,
            "wall_median_ms": round(statistics.median(r["wall_ms"] for r in runs), 1),
            "replied_total": sum(r["tally"]["replied"] for r in runs),
            "lost_eof_total": sum(r["tally"]["lost_eof"] for r in runs),
            "swallowed_total": sum((r["server"] or {}).get("swallowed", 0) for r in runs),
            "exit_codes": sorted({r["exit_code"] for r in runs}),
        }
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "05_cancel.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({mode: {key: value for key, value in arm.items() if key != "runs"}
                      for mode, arm in data["arms"].items()}, indent=1))
The five shutdowns of section 8, each in a fresh process (table 9). 06_arms.py
"""Probe 06: five shutdown behaviours against the same twelve in-flight requests.

Every arm runs in a fresh process with the same clients, the same request duration and
the same moment for the signal, so the difference in the table is the shutdown and
nothing else. The client side counts what arrived; the server side counts what it
decided. Repeats are recorded individually because a wall time is a sample, not a
constant.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
ARMS = ("default", "cancel", "blind", "wait_all", "policy")
REPEATS = 5
GRACE_MS = 1000
EXTENSION_MS = 500


async def main() -> dict:
    record: dict = {"conditions": {"clients": 12, "delay_ms": 400, "signal_after_ms": 120,
                                   "grace_ms": GRACE_MS, "extension_ms": EXTENSION_MS,
                                   "poll_ms": 25, "repeats": REPEATS},
                   "arms": {}}
    for mode in ARMS:
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm(
                mode, clients=12, delay_ms=400, signal_after_ms=120,
                grace_ms=GRACE_MS, extension_ms=EXTENSION_MS, poll_ms=25,
                probe_new_conns=2, cap_ms=GRACE_MS + EXTENSION_MS + 2500)
            runs.append(run)
            print(mode, repeat, run["wall_ms"], run["tally"], flush=True)
        record["arms"][mode] = harness.summarize(runs)
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "06_arms.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({mode: {key: value for key, value in arm.items() if key != "runs"}
                      for mode, arm in data["arms"].items()}, indent=1))
One request that cannot finish inside the window (table 11). 07_stalled.py
"""Probe 07: one request that will not finish inside the window.

A five-second handler against a one-second window is the case a drain policy exists
for. Waiting for connections waits forever; sleeping through the window exits with the
slow request still running; the policy serves the five that can finish and resets the
one that cannot, and the client learns which by the socket. Every arm is repeated, so
the wall time in the table is a median with a range.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
GRACE_MS = 1000
CAP_MS = 4500
REPEATS = 5


async def main() -> dict:
    record: dict = {"conditions": {"stalled_delay_ms": 5000, "fast_clients": 5,
                                   "fast_delay_ms": 200, "signal_after_ms": 100,
                                   "grace_ms": GRACE_MS, "extension_ms": 0,
                                   "cap_ms": CAP_MS, "repeats": REPEATS}, "arms": {}}
    for mode in ("wait_all", "blind", "policy"):
        stalled_runs = []
        fast_runs = []
        for repeat in range(REPEATS):
            stalled = await harness.run_arm(mode, clients=1, delay_ms=5000,
                                            signal_after_ms=100, grace_ms=GRACE_MS,
                                            extension_ms=0, poll_ms=25, cap_ms=CAP_MS,
                                            probe_new_conns=1)
            # The fast requests are a second run of the same arm, so the stalled client
            # and the ordinary ones are measured by the same code path.
            fast = await harness.run_arm(mode, clients=5, delay_ms=200,
                                         signal_after_ms=100, grace_ms=GRACE_MS,
                                         extension_ms=0, poll_ms=25, cap_ms=CAP_MS,
                                         probe_new_conns=1)
            stalled_runs.append(stalled)
            fast_runs.append(fast)
            print(mode, repeat, "stalled", stalled["wall_ms"], stalled["hit_cap"],
                  stalled["tally"], "fast", fast["wall_ms"], fast["tally"], flush=True)
        record["arms"][mode] = {"stalled": harness.summarize(stalled_runs),
                                "fast": harness.summarize(fast_runs)}
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "07_stalled.json").write_text(json.dumps(data, indent=1) + "\n",
                                            encoding="utf-8")
    print(json.dumps({mode: {"stalled_wall": arm["stalled"]["wall_ms"],
                             "stalled_range": [arm["stalled"]["wall_min_ms"],
                                               arm["stalled"]["wall_max_ms"]],
                             "stalled_hit_cap": arm["stalled"]["hit_cap_count"],
                             "stalled_tally": arm["stalled"]["tally"],
                             "fast_wall": arm["fast"]["wall_ms"],
                             "fast_tally": arm["fast"]["tally"]}
                      for mode, arm in data["arms"].items()}, indent=1))
Twenty idle keep-alive connections against the same three shutdowns (table 5). 04_idle.py
"""Probe 04: twenty idle keep-alive connections and five requests in flight.

This is the shape a load balancer leaves behind. Nothing is being served on most
sockets, and nothing on them will ever end by itself, so a shutdown that waits for
connections to close waits for the deadline - and the deadline is the whole grace
period, every deploy, whether or not a request needed it. Each arm is repeated so the
wall time quoted is a median with a range, not one run's luck.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
GRACE_MS = 1000
EXTENSION_MS = 500
CAP_MS = 4500
REPEATS = 5


async def main() -> dict:
    record: dict = {"conditions": {"idle_conns": 20, "clients": 5, "delay_ms": 200,
                                   "signal_after_ms": 100, "grace_ms": GRACE_MS,
                                   "extension_ms": EXTENSION_MS, "cap_ms": CAP_MS,
                                   "repeats": REPEATS},
                    "arms": {}}
    for mode in ("wait_all", "blind", "policy"):
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm(mode, clients=5, delay_ms=200, idle_conns=20,
                                        signal_after_ms=100, grace_ms=GRACE_MS,
                                        extension_ms=EXTENSION_MS, poll_ms=25,
                                        cap_ms=CAP_MS, probe_new_conns=2)
            runs.append(run)
            print(mode, repeat, run["wall_ms"], run["hit_cap"], run["tally"], flush=True)
        record["arms"][mode] = harness.summarize(runs)
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "04_idle.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({mode: {"wall_ms": arm["wall_ms"], "range_ms": [arm["wall_min_ms"],
                                                                   arm["wall_max_ms"]],
                             "hit_cap_count": arm["hit_cap_count"],
                             "tally": arm["tally"],
                             "closed_idle": (arm["server"] or {}).get("counts", {})
                             .get("closed_idle")}
                      for mode, arm in data["arms"].items()}, indent=1))
A request that arrived but was not read when the drain sampled, answered three ways (table 6). 11_race.py
"""Probe 11: the request that had arrived but not been read when the drain sampled.

A connection is not a request, and a request is not in the count until the handler that
owns it has read it. Between the two there is a real interval in every server - a TLS
handshake, a middleware stack, a shared loop busy with another task - and a drain that
closes every "idle" connection at its first sample closes sockets that are holding a
request nobody has looked at yet. ``--read-delay-ms`` puts a request on the socket and
holds the handler back from reading it, which is the same shape with a knob.

Three arms, each a different answer to "is this socket idle?":

``close_now``   the count alone - close it on the sample that finds nothing in flight;
``grace_250``   the clock - a connection is idle only after carrying nothing for 250 ms;
``peek``        the socket - a connection is idle only if nothing is waiting on it.

Three read delays: none, one the grace covers, and one it does not. The third is the cell
the clock fails: 600 ms is longer than the grace, so the connection is closed while its
handler is still in its own startup. The socket knows the whole time.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
GRACE_MS = 1000
EXTENSION_MS = 0
POLL_MS = 25
REPEATS = 5
CLIENTS = 4
REQUEST_MS = 300
SIGNAL_AFTER_MS = 150
# No read delay, a delay the 250 ms grace covers, and one it does not.
READ_DELAYS = (0, 200, 600)
# name: (idle grace, ask the socket as well)
ARMS = {"close_now": (0, False), "grace_250": (250, False), "peek": (0, True)}


async def main() -> dict:
    record: dict = {"conditions": {"clients": CLIENTS, "delay_ms": REQUEST_MS,
                                   "signal_after_ms": SIGNAL_AFTER_MS,
                                   "grace_ms": GRACE_MS, "extension_ms": EXTENSION_MS,
                                   "poll_ms": POLL_MS, "repeats": REPEATS,
                                   "idle_grace_ms": ARMS["grace_250"][0]},
                    "read_delays": {},
                    "arms": {name: {"idle_grace_ms": grace, "peek": peek}
                             for name, (grace, peek) in ARMS.items()}}
    for read_delay in READ_DELAYS:
        rows = {}
        for name, (idle_grace, peek) in ARMS.items():
            runs = []
            for repeat in range(REPEATS):
                run = await harness.run_arm(
                    "policy", clients=CLIENTS, delay_ms=REQUEST_MS,
                    signal_after_ms=SIGNAL_AFTER_MS, grace_ms=GRACE_MS,
                    extension_ms=EXTENSION_MS, poll_ms=POLL_MS,
                    cap_ms=GRACE_MS + 3000, read_delay_ms=read_delay,
                    idle_grace_ms=idle_grace, peek_unread=peek)
                runs.append(run)
                print(read_delay, name, repeat, run["exit_ms"], run["tally"], flush=True)
            rows[name] = harness.summarize(runs)
        record["read_delays"][str(read_delay)] = rows
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "11_race.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({delay: {name: {"replied": row["replied_median"],
                                     "lost_eof": row["lost_eof_total"],
                                     "reset": row["reset_total"],
                                     "wall_ms": row["wall_ms"],
                                     "closed_idle": (row["server"] or {})
                                     .get("counts", {}).get("closed_idle")}
                              for name, row in rows.items()}
                      for delay, rows in data["read_delays"].items()}, indent=1))
Where the bytes of that request are: the kernel’s socket or the stream’s buffer (section 5). 16_peek.py
"""Probe 16: where the bytes of an unread request actually are when a drain samples.

The deterministic check added to the drain has two halves - the stream's own buffer and the
kernel's socket buffer - and this probe measures why both are needed. A server holds its
handler back from its first read, as a TLS handshake or a middleware stack does, while the
client's request arrives; at a fixed checkpoint inside that interval the server asks each
half the same question:

  * ``FIONREAD`` and ``MSG_PEEK`` on the socket: is anything waiting in the kernel?
  * the ``StreamReader``'s buffer: has the transport already taken it?

The control is a connection that has sent nothing at all, which both halves should call
empty. The answer is the reason the check looks at the reader first.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "module"))

from drainage import probe  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
REPEATS = 5
CHECK_AT_MS = 100
READ_DELAY_MS = 200
REQUEST = b"REQ 300\n"


async def one(send: bool) -> dict:
    """One connection, one checkpoint: what each half says about the same socket."""
    seen: dict = {}
    ready = asyncio.Event()

    async def handle(reader, writer):
        await asyncio.sleep(CHECK_AT_MS / 1000)
        seen["kernel_bytes"] = probe.pending_bytes(writer)
        seen["kernel_peek"] = probe.peek(writer).decode(errors="replace")
        buffered = getattr(reader, "_buffer", b"")
        seen["buffered_bytes"] = len(buffered)
        await asyncio.sleep((READ_DELAY_MS - CHECK_AT_MS) / 1000)
        try:
            line = await asyncio.wait_for(reader.readline(), 0.5)
        except asyncio.TimeoutError:
            line = b""                     # the control sent nothing at all
        seen["read_line"] = line.decode(errors="replace").strip()
        writer.close()
        ready.set()

    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    if send:
        writer.write(REQUEST)
        await writer.drain()
    await asyncio.wait_for(ready.wait(), 5.0)
    writer.close()
    server.close()
    await server.wait_closed()
    seen["sent"] = send
    return seen


async def main() -> dict:
    with_request = [await one(True) for _ in range(REPEATS)]
    control = [await one(False) for _ in range(REPEATS)]
    return {
        "conditions": {"repeats": REPEATS, "check_at_ms": CHECK_AT_MS,
                       "read_delay_ms": READ_DELAY_MS, "request": REQUEST.decode().strip()},
        "with_request": with_request,
        "no_request": control,
        "totals": {
            "kernel_bytes_when_unread": [row["kernel_bytes"] for row in with_request],
            "buffered_when_unread": [row["buffered_bytes"] for row in with_request],
            "kernel_bytes_when_idle": [row["kernel_bytes"] for row in control],
            "runs_where_only_the_reader_knew": sum(
                1 for row in with_request
                if row["kernel_bytes"] == 0 and row["buffered_bytes"] > 0),
        },
    }


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "16_peek.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({"conditions": data["conditions"], "totals": data["totals"]}, indent=1))
    print(json.dumps(data["with_request"][0], indent=1))
Clients that keep their sockets: what the idle grace costs and why waiting for connections never ends (table 10). 15_keepalive.py
"""Probe 15: what the idle grace costs when the clients keep their connections open.

Every other arm of this page's client closes its socket as soon as it has its reply. That
is the easy case for a drain, and it hides a real cost: the socket is detached on the
handler's way out, so the drain has nothing left to close and no grace to spend. An HTTP
client does not do that. It keeps the connection for its next request, which is why a
server's connection outlives its request - and then the drain's exit floor is the last
reply plus ``idle_grace_ms``, because a socket that has just answered may be about to
carry the next request.

Two shapes, each measured with both kinds of client:

``arms``  the twelve-in-flight shape of table 9, with no idle sockets at all;
``pool``  the five-request, twenty-idle-socket shape of table 5.

and the same policy at three graces on the first shape, so the floor can be read off the
table instead of argued about: the exit time should move by exactly the grace.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
REPEATS = 5
CAP_MS = 4500

SHAPES = {
    # name: conditions
    "arms": {"clients": 12, "delay_ms": 400, "idle_conns": 0, "signal_after_ms": 120,
             "grace_ms": 1000, "extension_ms": 500},
    "pool": {"clients": 5, "delay_ms": 200, "idle_conns": 20, "signal_after_ms": 100,
             "grace_ms": 1000, "extension_ms": 500},
}

# name: (shape, mode, keep alive, idle grace)
ARMS = {
    "wait_all_close": ("arms", "wait_all", False, 250),
    "wait_all_hold": ("arms", "wait_all", True, 250),
    "policy_close": ("arms", "policy", False, 250),
    "policy_hold_250": ("arms", "policy", True, 250),
    "policy_hold_0": ("arms", "policy", True, 0),
    "policy_hold_500": ("arms", "policy", True, 500),
    "pool_wait_all_hold": ("pool", "wait_all", True, 250),
    "pool_policy_hold": ("pool", "policy", True, 250),
}


async def main() -> dict:
    record: dict = {"conditions": {"repeats": REPEATS, "cap_ms": CAP_MS,
                                   "idle_grace_ms": 250},
                    "shapes": SHAPES,
                    "arms": {name: {"shape": shape, "mode": mode, "keep_alive": hold,
                                    "idle_grace_ms": grace}
                             for name, (shape, mode, hold, grace) in ARMS.items()}}
    for name, (shape_key, mode, hold, grace) in ARMS.items():
        shape = SHAPES[shape_key]
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm(
                mode, clients=shape["clients"], delay_ms=shape["delay_ms"],
                idle_conns=shape["idle_conns"], signal_after_ms=shape["signal_after_ms"],
                grace_ms=shape["grace_ms"], extension_ms=shape["extension_ms"],
                poll_ms=25, cap_ms=CAP_MS, keep_alive=hold, idle_grace_ms=grace,
                probe_new_conns=0 if hold else 2)
            runs.append(run)
            print(name, repeat, run["exit_ms"], run["hit_cap"], run["held_conns"],
                  run["tally"], flush=True)
        summary = harness.summarize(runs)
        summary["keep_alive"] = hold
        summary["idle_grace_ms"] = grace
        summary["held_median"] = sorted(run["held_conns"] for run in runs)[len(runs) // 2]
        record["arms"][name].update(summary)
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "15_keepalive.json").write_text(json.dumps(data, indent=1) + "\n",
                                              encoding="utf-8")
    print(json.dumps({name: {"wall_ms": arm["wall_ms"],
                             "range_ms": [arm["wall_min_ms"], arm["wall_max_ms"]],
                             "replied": arm["replied_median"],
                             "lost": arm["lost_eof_total"],
                             "hit_cap": arm["hit_cap_count"],
                             "held": arm["held_median"],
                             "closed_idle": (arm["server"] or {}).get("counts", {})
                             .get("closed_idle")}
                      for name, arm in data["arms"].items()}, indent=1))
The second SIGTERM, delivered to a real policy server (section 7). 12_second.py
"""Probe 12: the second SIGTERM, delivered to the server rather than to the drainer's tests.

The drainer's own tests call ``signal()`` twice and watch the next sample abort. That
proves the object; it does not prove the server is wired to it. This probe signals a
real policy server twice and reads the process's exit and its own decision log, so the
number in the table is the operator's second press reaching the loop - through the
signal handler, not around it.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
GRACE_MS = 3000
EXTENSION_MS = 500
POLL_MS = 25
REPEATS = 5
CLIENTS = 3
REQUEST_MS = 5000
SECOND_AT_MS = 300
ARMS = {"one_signal": None, "two_signals": SECOND_AT_MS}


async def main() -> dict:
    record: dict = {"conditions": {"clients": CLIENTS, "delay_ms": REQUEST_MS,
                                   "grace_ms": GRACE_MS, "extension_ms": EXTENSION_MS,
                                   "poll_ms": POLL_MS, "second_signal_after_ms": SECOND_AT_MS,
                                   "repeats": REPEATS},
                    "arms": {}}
    for name, second in ARMS.items():
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm(
                "policy", clients=CLIENTS, delay_ms=REQUEST_MS, signal_after_ms=100,
                grace_ms=GRACE_MS, extension_ms=EXTENSION_MS, poll_ms=POLL_MS,
                cap_ms=GRACE_MS + EXTENSION_MS + 2500,
                second_signal_after_ms=second)
            runs.append(run)
            print(name, repeat, run["exit_ms"], run["tally"],
                  (run["server"] or {}).get("signals"),
                  (run["server"] or {}).get("decisions", {}).get("lines", [])[-1:], flush=True)
        record["arms"][name] = harness.summarize(runs)
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "12_second.json").write_text(json.dumps(data, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({name: {"wall_ms": arm["wall_ms"],
                             "range_ms": [arm["wall_min_ms"], arm["wall_max_ms"]],
                             "replied": arm["replied_median"],
                             "aborted": (arm["server"] or {}).get("counts", {}).get("aborted"),
                             "signals": (arm["server"] or {}).get("signals"),
                             "last_line": (arm["server"] or {}).get("decisions", {})
                             .get("lines", [""])[-1]}
                      for name, arm in data["arms"].items()}, indent=1))
The deadline as a cap, over three windows (section 9). 10_deadlines.py
"""Probe 10: the deadline is a cap, not a wait.

Three grace windows against one five-second request, and then the same policy against
requests that finish long before the window closes. The second measurement is the one
that matters on a quiet deploy: a shutdown that always sleeps the full grace period
holds a pod out of the pool for a second per replica, on every rollout. Each window is
repeated, so the cost of noticing is read as a median and a range.
"""
from __future__ import annotations

import asyncio
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

RESULTS = pathlib.Path(__file__).resolve().parent.parent / "results"
REPEATS = 5


def entry(grace: int, arm: dict) -> dict:
    """One window's repeats, flattened into the row the article quotes."""
    return {"grace_ms": grace,
            "repeats": arm["repeats"],
            "wall_ms": arm["wall_ms"],
            "wall_min_ms": arm["wall_min_ms"],
            "wall_max_ms": arm["wall_max_ms"],
            "tally": arm["tally"],
            "hit_cap_count": arm["hit_cap_count"],
            "decisions": (arm["server"] or {}).get("decisions")}


async def main() -> dict:
    record: dict = {"stalled": [], "quiet": []}
    for grace in (300, 600, 1200):
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm("policy", clients=1, delay_ms=5000,
                                        signal_after_ms=80, grace_ms=grace,
                                        extension_ms=0, poll_ms=25,
                                        cap_ms=grace + 2000, probe_new_conns=1)
            runs.append(run)
            print("stalled", grace, repeat, run["wall_ms"], run["tally"], flush=True)
        record["stalled"].append(entry(grace, harness.summarize(runs)))
    for grace in (1200,):
        runs = []
        for repeat in range(REPEATS):
            run = await harness.run_arm("policy", clients=3, delay_ms=150,
                                        signal_after_ms=80, grace_ms=grace,
                                        extension_ms=500, poll_ms=25,
                                        cap_ms=grace + 2500, probe_new_conns=1)
            runs.append(run)
            print("quiet", grace, repeat, run["wall_ms"], run["tally"], flush=True)
        record["quiet"].append(entry(grace, harness.summarize(runs)))
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "10_deadlines.json").write_text(json.dumps(data, indent=1) + "\n",
                                              encoding="utf-8")
    print(json.dumps({"stalled": [{"grace_ms": row["grace_ms"], "wall_ms": row["wall_ms"],
                                   "range_ms": [row["wall_min_ms"], row["wall_max_ms"]],
                                   "tally": row["tally"]} for row in data["stalled"]],
                      "quiet": [{"grace_ms": row["grace_ms"], "wall_ms": row["wall_ms"],
                                 "range_ms": [row["wall_min_ms"], row["wall_max_ms"]],
                                 "tally": row["tally"]} for row in data["quiet"]]},
                     indent=1))
What one sample costs when a thousand idle sockets are registered, how long its one walk holds the loop, and what closing them costs (section 9). 17_idle_cost.py
"""Probe 17: what one sample costs when a thousand idle sockets are registered.

Section 9 used to price a sample as "one dictionary walk", and only the walk is that
cheap. An idle connection is asked whether it is holding a request, and on an asyncio
stream that question costs a ``dup``, an ``ioctl(FIONREAD)`` and a ``close`` on the
duplicate. At a thousand sockets those syscalls are the sample; the dictionary is noise
beside them. The drain now asks each socket that question once per sample and takes the
freshness and the unread count from the one answer, so this probe measures the walk it
runs, the second walk the same loop used to make, and the batch of closes a sample can
end up carrying.

So this probe registers real sockets in a real :class:`drainage.Drainer` and times the
loop the drain actually runs: its first sample, every sample after it, and the batch of
closes a sample can end up carrying. The sockets are ``socket.socketpair()`` pairs
wrapped by ``asyncio.open_connection``, so each registered connection has a real
descriptor, a real transport and a real ``StreamReader`` - the three things
``Conn.unread()`` looks at - and the peer end is held open so nothing closes itself
behind the drain's back. The largest size is what ``RLIMIT_NOFILE`` allows: a pair costs
two descriptors, so it is half of what the process may hold.

Two costs are measured on the population itself, before the drain starts: one walk that
asks every socket once, and two walks that ask it twice, which is the shape a loop with a
separate ``fresh`` and ``unread`` pass produces. The sample's own work is then a third
measurement, taken from the timestamps the drain reports its decisions at.

The loop the sample runs on is single-threaded, so the sample is a pause for everything
else on it: a ticker naps for five milliseconds beside the drain and records how much
longer each nap took than it asked for, which is the longest a handler's own continuation
could have been made to wait.

Three shapes, because the idle grace decides what a sample does:

  * ``close_first`` - the grace is zero, so the first sample finds nothing to wait for,
    stops, and closes the whole population: one sample plus the batch it caused.
  * ``grace_250`` - the default grace, so the samples run with the population inside its
    grace and the loop keeps sampling until the grace expires and the batch is closed.
  * ``size_0`` - nothing registered at all, which is the floor the others are read
    against: a drain over an empty connection table.
"""
from __future__ import annotations

import asyncio
import json
import os
import pathlib
import resource
import socket
import statistics
import sys
import time

HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(ROOT / "module"))

from drainage import Drainer, Limits                      # noqa: E402
from drainage.policy import Action                        # noqa: E402
from drainage.probe import open_fds                       # noqa: E402

RESULTS = ROOT / "results"
REPEATS = 5
SIZES = (1000, 2000)
POLL_MS = 25
GRACE_MS = 1000
IDLE_GRACE_MS = 250
TICK_MS = 5
SHAPES = (("close_first", 0), ("grace_250", IDLE_GRACE_MS))
# Descriptors kept free for the loop's own use: its self-pipe, the result file, and what
# the interpreter holds before the probe starts.
RESERVE = 24


class Listener:
    """The drainer's server: both methods it calls do nothing."""

    def close(self) -> None:
        pass

    async def wait_closed(self) -> None:
        pass


def descriptors() -> dict:
    """The limits a size has to fit inside, and how many descriptors are already used."""
    soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
    if soft < hard:
        resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))
        soft = hard
    return {"soft": soft, "hard": hard, "in_use": open_fds(os.getpid())}


async def open_pairs(size: int) -> list:
    """``size`` real socket pairs, one end of each wrapped as an asyncio stream.

    The peer end is kept open: a closed peer would look like an unread request to the
    drain, and the population under test has to stay idle and open.
    """
    peers = []
    for _ in range(size):
        near, far = socket.socketpair()
        reader, writer = await asyncio.open_connection(sock=near)
        peers.append((reader, writer, far))
    return peers


def ask_ms(drainer: Drainer, walks: int) -> float:
    """Time ``walks`` walks that each ask every idle socket whether it holds bytes.

    One walk is what a sample makes now; two is what two separate questions made - the
    freshness test and the unread count - before they were answered from one reading.
    """
    started = time.perf_counter()
    for _ in range(walks):
        for conn in drainer.conns.values():
            if conn.active == 0:
                conn.unread()
    return (time.perf_counter() - started) * 1000


async def tick(stop: asyncio.Event, gaps: list[tuple[float, float]], interval: float) -> None:
    """Record how much longer each nap took than it asked for, until told to stop.

    Each gap is kept with the moment it ended, so the ones recorded while the drain was
    sampling can be read apart from the one the closing batch took at the end.
    """
    while not stop.is_set():
        started = time.monotonic()
        await asyncio.sleep(interval)
        gaps.append((time.monotonic(), (time.monotonic() - started - interval) * 1000))


async def one(size: int, idle_grace_ms: int) -> dict:
    """Run one real drain over ``size`` idle sockets and time each of its samples."""
    drainer = Drainer(Listener(), Limits(grace_ms=GRACE_MS, extension_ms=500,
                                         poll_ms=POLL_MS, progress_ms=500,
                                         idle_grace_ms=idle_grace_ms))
    before = open_fds(os.getpid())
    peers = await open_pairs(size)
    for reader, writer, _ in peers:
        drainer.attach(reader, writer)
    registered_fds = open_fds(os.getpid()) - before
    once_ms = ask_ms(drainer, 1) if size else 0.0
    twice_ms = ask_ms(drainer, 2) if size else 0.0

    stamps: list[tuple[float, object]] = []
    gaps: list[tuple[float, float]] = []
    stop = asyncio.Event()
    ticking = asyncio.ensure_future(tick(stop, gaps, TICK_MS / 1000))
    drainer.on_decision = lambda decision: stamps.append((time.monotonic(), decision))
    signalled = time.monotonic()
    drainer.signal()
    await drainer.run()
    ended = time.monotonic()
    stop.set()
    await ticking

    # The first sample starts at the signal. Every later one starts after the poll sleep
    # of the sample before it, so the work inside it is the gap minus that sleep: its own
    # sockets checked, plus any batch of closes the previous decision asked for. The
    # closes the last decision asked for are the tail of the run, after its last line.
    first_ms = (stamps[0][0] - signalled) * 1000
    later = [((stamps[index][0] - stamps[index - 1][0]) * 1000 - POLL_MS)
             for index in range(1, len(stamps))]
    close_ms = (ended - stamps[-1][0]) * 1000
    # A gap that ended before the last decision was recorded happened while the drain was
    # still sampling; the one after it is the batch of closes the last decision asked for.
    sampling_gaps = [lag for ended_at, lag in gaps if ended_at <= stamps[-1][0]]
    record = {
        "size": size,
        "idle_grace_ms": idle_grace_ms,
        "registered_fds": registered_fds,
        "decisions": len(stamps),
        "ask_once_ms": round(once_ms, 2),
        "ask_twice_ms": round(twice_ms, 2),
        "first_sample_ms": round(first_ms, 2),
        "later_sample_ms": [round(value, 2) for value in later],
        "sample_work_ms": round(statistics.median(later), 2) if later else 0.0,
        "batch_sample_ms": round(max(later), 2) if later else 0.0,
        "close_tail_ms": round(close_ms, 2),
        "loop_lag_max_ms": round(max(lag for _, lag in gaps), 2) if gaps else 0.0,
        "loop_lag_sample_max_ms": (round(max(sampling_gaps), 2) if sampling_gaps else 0.0),
        "loop_lag_median_ms": round(statistics.median(lag for _, lag in gaps), 3)
        if gaps else 0.0,
        "tick_samples": len(gaps),
        "wall_ms": round((ended - signalled) * 1000, 1),
        "closed_idle": drainer.counts.closed_idle,
        "last_action": stamps[-1][1].action.value,
        "last_reason": stamps[-1][1].reason,
        "max_elapsed_ms": round(max(decision.elapsed_ms for _, decision in stamps), 1),
    }
    assert stamps[-1][1].action in (Action.STOP, Action.ABORT), record["last_action"]
    for _, writer, far in peers:
        writer.close()
        far.close()
    await asyncio.sleep(0)
    return record


def summarise(runs: list[dict]) -> dict:
    """One shape's repeats: a median for each timing, the range behind it, the counts."""
    firsts = [run["first_sample_ms"] for run in runs]
    works = [run["sample_work_ms"] for run in runs]
    batches = [run["batch_sample_ms"] for run in runs]
    tails = [run["close_tail_ms"] for run in runs]
    once = [run["ask_once_ms"] for run in runs]
    twice = [run["ask_twice_ms"] for run in runs]
    lags = [run["loop_lag_max_ms"] for run in runs]
    sample_lags = [run["loop_lag_sample_max_ms"] for run in runs]
    later = [value for run in runs for value in run["later_sample_ms"]]
    return {
        "runs": runs,
        "repeats": len(runs),
        "size": runs[0]["size"],
        "idle_grace_ms": runs[0]["idle_grace_ms"],
        "registered_fds": runs[0]["registered_fds"],
        "decisions": int(statistics.median(run["decisions"] for run in runs)),
        "ask_once_ms": round(statistics.median(once), 2),
        "ask_twice_ms": round(statistics.median(twice), 2),
        "first_sample_ms": round(statistics.median(firsts), 2),
        "first_sample_min_ms": round(min(firsts), 2),
        "first_sample_max_ms": round(max(firsts), 2),
        "sample_work_ms": round(statistics.median(works), 2),
        "sample_work_min_ms": round(min(works), 2),
        "sample_work_max_ms": round(max(works), 2),
        "batch_sample_ms": round(statistics.median(batches), 2),
        "later_samples": len(later),
        "later_sample_max_ms": round(max(later), 2) if later else 0.0,
        "close_tail_ms": round(statistics.median(tails), 2),
        "close_tail_min_ms": round(min(tails), 2),
        "close_tail_max_ms": round(max(tails), 2),
        "loop_lag_max_ms": round(statistics.median(lags), 2),
        "loop_lag_worst_ms": round(max(lags), 2),
        "loop_lag_sample_max_ms": round(statistics.median(sample_lags), 2),
        "loop_lag_sample_worst_ms": round(max(sample_lags), 2),
        "tick_samples": int(statistics.median(run["tick_samples"] for run in runs)),
        "wall_ms": round(statistics.median(run["wall_ms"] for run in runs), 1),
        "closed_idle": int(statistics.median(run["closed_idle"] for run in runs)),
        "last_action": runs[0]["last_action"],
        "last_reason": runs[0]["last_reason"],
        "max_elapsed_ms": round(statistics.median(run["max_elapsed_ms"] for run in runs), 1),
    }


async def main() -> None:
    limits = descriptors()
    largest = (limits["soft"] - limits["in_use"] - RESERVE) // 2
    sizes = [size for size in SIZES if size <= largest]
    if not sizes:
        raise SystemExit(f"RLIMIT_NOFILE leaves room for only {largest} socket pairs")
    record = {
        "conditions": {"repeats": REPEATS, "poll_ms": POLL_MS, "grace_ms": GRACE_MS,
                       "idle_grace_ms": IDLE_GRACE_MS, "tick_ms": TICK_MS,
                       "requested_sizes": list(SIZES),
                       "largest_size": min(largest, max(SIZES)),
                       "cpu_count": os.cpu_count()},
        "file_limits": limits,
        "shapes": {"size_0": {"grace_250": summarise(
            [await one(0, IDLE_GRACE_MS) for _ in range(REPEATS)])}},
    }
    for size in sizes:
        record["shapes"][f"size_{size}"] = {}
        for name, grace in SHAPES:
            record["shapes"][f"size_{size}"][name] = summarise(
                [await one(size, grace) for _ in range(REPEATS)])
    for shape, arms in record["shapes"].items():
        for name, arm in arms.items():
            print(f"{shape:10s} {name:11s} " + json.dumps(
                {key: arm[key] for key in ("ask_once_ms", "ask_twice_ms", "first_sample_ms",
                                           "sample_work_ms", "batch_sample_ms", "close_tail_ms",
                                           "loop_lag_max_ms", "loop_lag_sample_max_ms",
                                           "wall_ms", "decisions", "closed_idle")}))
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "17_idle_cost.json").write_text(json.dumps(record, indent=1) + "\n",
                                               encoding="utf-8")
    print(f"wrote {RESULTS / '17_idle_cost.json'}")


if __name__ == "__main__":
    asyncio.run(main())
uvicorn and gunicorn asked the same question as the five shutdowns, with and without idle sockets (table 12). 13_frameworks.py
"""Probe 13: what two production servers do with the same request when the signal lands.

The drain in this page is a policy and a loop; uvicorn and gunicorn are servers that
already own both, so the question a reader deploying a framework actually asks is what
their shutdown does with a request that is still running. The same ASGI app, the same
request duration and the same signal, three ways: uvicorn with its default shutdown,
uvicorn told to give up after a second, and gunicorn with one uvicorn worker.

Two shapes, because a server can fail either half of the problem. In the first, the three
requests are all there is. In the second - the shape table 5 gives this page's own drain -
twenty keep-alive connections are open and idle beside them, which is what a load balancer
leaves behind; the probe watches those sockets too, so "the server closed the idle ones"
and "the server waited for them" are both measurable rather than assumed.

Every arm runs in a fresh process; the exit is timed by ``harness.watch_exit``, the same
watcher the other probes use, so the numbers are comparable across all of them.
"""
from __future__ import annotations

import asyncio
import json
import os
import pathlib
import signal
import socket
import statistics
import subprocess
import sys
import time

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))

import harness  # noqa: E402

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
REPEATS = 3
CLIENTS = 3
DELAY_MS = 2500
SIGNAL_AFTER_MS = 200
CAP_MS = 9000
GRACE_FLAG_MS = 1000
IDLE_CONNS = 20

ARMS = {
    "uvicorn": ("uvicorn, default shutdown", ["uvicorn", "fw_app:app"], "inflight"),
    "uvicorn_timeout": ("uvicorn with a 1 s graceful timeout",
                        ["uvicorn", "fw_app:app", "--timeout-graceful-shutdown",
                         str(GRACE_FLAG_MS // 1000)], "inflight"),
    "gunicorn": ("gunicorn, one uvicorn worker",
                 ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "-w", "1",
                  "fw_app:app"], "inflight"),
    "uvicorn_idle": ("uvicorn, 20 idle keep-alive sockets", ["uvicorn", "fw_app:app"],
                     "idle"),
    "gunicorn_idle": ("gunicorn, 20 idle keep-alive sockets",
                      ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "-w", "1",
                       "fw_app:app"], "idle"),
}


def free_port() -> int:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind(("127.0.0.1", 0))
        return sock.getsockname()[1]


async def wait_port(port: int, timeout: float = 20.0) -> None:
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        try:
            reader, writer = await asyncio.open_connection("127.0.0.1", port)
            writer.close()
            return
        except (ConnectionRefusedError, ConnectionResetError):
            await asyncio.sleep(0.05)
    raise TimeoutError(f"nothing listening on {port}")


async def get(index: int, port: int, results: dict, spawned: float,
              signal_after_ms: float, hold: asyncio.Event | None = None) -> None:
    """One request: sent before the signal, classified by what the socket did back."""
    await asyncio.sleep(max(0.0, spawned + signal_after_ms / 1000 - time.monotonic() - 0.05))
    try:
        reader, writer = await asyncio.open_connection("127.0.0.1", port)
    except (ConnectionRefusedError, ConnectionResetError):
        results[index] = "refused"
        return
    try:
        # A keep-alive request: HTTP/1.1 keeps the connection unless told otherwise, which
        # is the shape the idle sockets beside it are in.
        writer.write(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"
                     if hold is not None else
                     b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n")
        await writer.drain()
        if hold is None:
            data = await asyncio.wait_for(reader.read(), 30.0)
            results[index] = "replied" if b"OK" in data else "partial"
            return
        head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 30.0)
        length = 0
        for line in head.split(b"\r\n"):
            if line.lower().startswith(b"content-length:"):
                length = int(line.split(b":", 1)[1])
        body = await asyncio.wait_for(reader.readexactly(length), 30.0) if length else b""
        results[index] = "replied" if body.strip() == b"OK" else "partial"
        # Hold the connection open, as a client that intends to send another request does.
        try:
            await hold.wait()
        except asyncio.CancelledError:
            pass
    except (ConnectionResetError, BrokenPipeError):
        results[index] = "reset"
    except (asyncio.TimeoutError, asyncio.IncompleteReadError):
        results[index] = "timeout"
    finally:
        writer.close()


async def watch_idle(reader, signalled: dict, closes: list) -> None:
    """Wait for an idle socket to end and say how long after the signal it did."""
    try:
        while await reader.read(4096):
            pass
    except (ConnectionResetError, OSError):
        pass
    except asyncio.CancelledError:
        return
    if signalled.get("at") is not None:
        closes.append(round((time.monotonic() - signalled["at"]) * 1000, 1))


async def run_arm(name: str, label: str, command: list[str], shape: str) -> dict:
    port = free_port()
    env = {**os.environ, "FW_DELAY_MS": str(DELAY_MS), "PYTHONPATH": str(HERE),
           "PYTHONUNBUFFERED": "1"}
    if command[0] == "uvicorn":
        args = [sys.executable, "-m", "uvicorn", *command[1:], "--host", "127.0.0.1",
                "--port", str(port), "--lifespan", "off", "--log-level", "warning"]
    else:
        args = [sys.executable, "-m", "gunicorn", *command[1:], "-b",
                f"127.0.0.1:{port}", "--log-level", "error"]
    proc = subprocess.Popen(args, cwd=HERE, env=env,
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    try:
        await wait_port(port)
        results: dict[int, str] = {}
        hold = asyncio.Event() if shape == "idle" else None
        idle: list = []
        idle_tasks: list[asyncio.Task] = []
        signalled_at: dict = {"at": None}
        closes: list[float] = []
        for _ in range(IDLE_CONNS if shape == "idle" else 0):
            reader, writer = await asyncio.open_connection("127.0.0.1", port)
            idle.append(writer)
            idle_tasks.append(asyncio.ensure_future(watch_idle(reader, signalled_at, closes)))
        spawned = time.monotonic()
        tasks = [asyncio.ensure_future(get(index, port, results, spawned, SIGNAL_AFTER_MS,
                                          hold))
                 for index in range(CLIENTS)]
        await asyncio.sleep(max(0.0, SIGNAL_AFTER_MS / 1000))
        in_flight = CLIENTS - len(results)
        proc.send_signal(signal.SIGTERM)
        signalled = time.monotonic()
        signalled_at["at"] = signalled
        exit_task = asyncio.ensure_future(harness.watch_exit(proc, signalled))
        hit_cap = False
        while (time.monotonic() - signalled) * 1000 < CAP_MS:
            if exit_task.done():
                break
            await asyncio.sleep(0.01)
        if not exit_task.done():
            hit_cap = True
            proc.kill()
        exit_ms = await exit_task
        # The process is gone, so a socket still open is one the server left to the kernel.
        closed_before_exit = sum(1 for value in closes if value <= exit_ms)
        if hold is not None:
            hold.set()
        await asyncio.sleep(0.05)
        for task in tasks:
            if not task.done():
                task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
        for task in idle_tasks:
            if not task.done():
                task.cancel()
        await asyncio.gather(*idle_tasks, return_exceptions=True)
        for writer in idle:
            writer.close()
        await asyncio.sleep(0.05)
        tally = {kind: list(results.values()).count(kind)
                 for kind in ("replied", "partial", "reset", "refused", "timeout")}
        return {"arm": name, "label": label, "shape": shape, "exit_ms": exit_ms,
                "hit_cap": hit_cap, "exit_code": proc.returncode, "tally": tally,
                "in_flight_at_signal": in_flight, "idle_conns": len(idle),
                "idle_closed_before_exit": closed_before_exit,
                "idle_close_ms_median": (round(statistics.median(closes), 1) if closes else None),
                "idle_close_ms_max": (max(closes) if closes else None)}
    finally:
        if proc.poll() is None:
            proc.kill()
            proc.wait(timeout=10)


async def main() -> dict:
    record: dict = {"conditions": {"clients": CLIENTS, "delay_ms": DELAY_MS,
                                   "signal_after_ms": SIGNAL_AFTER_MS,
                                   "graceful_flag_ms": int(GRACE_FLAG_MS),
                                   "cap_ms": CAP_MS, "repeats": REPEATS,
                                   "idle_conns": IDLE_CONNS}, "arms": {}}
    for name, (label, command, shape) in ARMS.items():
        runs = []
        for repeat in range(REPEATS):
            run = await run_arm(name, label, command, shape)
            runs.append(run)
            print(name, repeat, run["exit_ms"], run["tally"], run["exit_code"],
                  run["idle_closed_before_exit"], run["idle_close_ms_median"], flush=True)
        record["arms"][name] = {
            "label": label,
            "shape": shape,
            "runs": runs,
            "wall_median_ms": round(statistics.median(r["exit_ms"] for r in runs), 1),
            "wall_min_ms": min(r["exit_ms"] for r in runs),
            "wall_max_ms": max(r["exit_ms"] for r in runs),
            "replied_total": sum(r["tally"]["replied"] for r in runs),
            "lost_total": sum(r["tally"]["timeout"] + r["tally"]["reset"] + r["tally"]["partial"]
                              for r in runs),
            "refused_total": sum(r["tally"]["refused"] for r in runs),
            "hit_cap_count": sum(1 for r in runs if r["hit_cap"]),
            "exit_codes": sorted({r["exit_code"] for r in runs}),
            "idle_closed_before_exit_median": statistics.median(
                r["idle_closed_before_exit"] for r in runs),
            "idle_close_ms_median": (statistics.median(
                r["idle_close_ms_median"] for r in runs if r["idle_close_ms_median"])
                if any(r["idle_close_ms_median"] for r in runs) else None),
        }
    return record


if __name__ == "__main__":
    data = asyncio.run(main())
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "13_frameworks.json").write_text(json.dumps(data, indent=1) + "\n",
                                               encoding="utf-8")
    print(json.dumps({name: {key: value for key, value in arm.items() if key != "runs"}
                      for name, arm in data["arms"].items()}, indent=1))
Four shell entrypoints, and the PID namespace this host would not give us (table 13). 14_container.py
"""Probe 14: the layer between the orchestrator and the application - a shell, and PID 1.

A container's ``CMD`` is not always the process that serves. In shell form Docker runs
``/bin/sh -c "<cmd>"``, and the signal goes to the shell: whether the application ever
hears it depends on what the shell does with the command it was given. This probe starts
the same long-running child four ways, sends SIGTERM to the process the orchestrator
knows, and looks at what happened to the child.

The other half of the same problem is PID 1, which the kernel treats differently from
every other process. This host does not let an unprivileged process create a PID
namespace, so the probe records that it could not be measured here rather than quoting
a number for it.
"""
from __future__ import annotations

import json
import os
import pathlib
import signal
import subprocess
import sys
import time

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
WORK = HERE.parent / "scratch" / "container"
CHILD = WORK / "idle_child.py"
CHILD_SOURCE = '''"""The process that would be the application: it holds the process open, and nothing else."""
import time

time.sleep(30)
'''
SETTLE_S = 0.6
AFTER_SIGNAL_S = 1.0
REPEATS = 3


def children_of(pid: int) -> list[int]:
    """The pids this process started, read from /proc rather than guessed."""
    path = pathlib.Path(f"/proc/{pid}/task/{pid}/children")
    if not path.exists():
        return []
    return [int(value) for value in path.read_text().split()]


def alive(pid: int) -> bool:
    return pathlib.Path(f"/proc/{pid}").exists()


def run_form(name: str, argv: list[str], workdir: pathlib.Path) -> dict:
    proc = subprocess.Popen(argv, cwd=workdir, stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)
    time.sleep(SETTLE_S)
    kids = children_of(proc.pid)
    proc.send_signal(signal.SIGTERM)
    time.sleep(AFTER_SIGNAL_S)
    shell_gone = proc.poll() is not None
    exit_code = proc.returncode
    survivors = [pid for pid in kids if alive(pid)]
    for pid in survivors:
        os.kill(pid, signal.SIGKILL)
    if not shell_gone:
        proc.kill()
    try:
        proc.wait(timeout=5)
    except subprocess.TimeoutExpired:
        pass
    return {"form": name, "argv": argv, "children": len(kids),
            "shell_exited": shell_gone, "shell_exit_code": exit_code,
            "children_survived": len(survivors)}


def pid_namespace() -> dict:
    """Can this host give us a PID 1 of our own? If not, say so and stop."""
    attempt = subprocess.run(["unshare", "--user", "--pid", "--fork", "--mount-proc",
                              "sh", "-c", "echo pid=$$"],
                             capture_output=True, text=True, check=False)
    return {"available": attempt.returncode == 0,
            "detail": (attempt.stdout + attempt.stderr).strip()[:200]}


def main() -> dict:
    WORK.mkdir(parents=True, exist_ok=True)
    CHILD.write_text(CHILD_SOURCE, encoding="utf-8")
    child = f"{sys.executable} {CHILD}"
    plain = subprocess.run(["sh", "-c", "echo ok"], capture_output=True, text=True)
    forms = {
        "sh_c": ("sh -c, one command", ["sh", "-c", child]),
        "sh_exec": ("sh -c with exec", ["sh", "-c", f"exec {child}"]),
        "sh_pipeline": ("sh -c, a pipeline", ["sh", "-c", f"{child} | cat"]),
        "bash_c": ("bash -c, one command", ["bash", "-c", child]),
    }
    runs = {name: [run_form(label, argv, WORK) for _ in range(REPEATS)]
            for name, (label, argv) in forms.items()}
    record = {
        "shell": {"path": subprocess.run(["sh", "-c", "command -v sh"],
                                        capture_output=True, text=True).stdout.strip(),
                  "probe": plain.stdout.strip(),
                  "repeats": REPEATS},
        "forms": {name: runs[name] for name in forms},
        "totals": {name: {"shell_exited": sum(1 for run in rows if run["shell_exited"]),
                          "children_survived": sum(run["children_survived"] for run in rows),
                          "children": sum(run["children"] for run in rows)}
                   for name, rows in runs.items()},
        "pid_namespace": pid_namespace(),
    }
    return record


if __name__ == "__main__":
    data = main()
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "14_container.json").write_text(json.dumps(data, indent=1) + "\n",
                                              encoding="utf-8")
    print(json.dumps({"totals": data["totals"], "pid_namespace": data["pid_namespace"]},
                     indent=1))
The fixtures the tests share: a clock that only moves, a server that records, a transport that says which end it got. conftest.py
"""Fixtures shared by every test: a clock that only moves when asked, a server that
records what was done to it, and a writer whose transport says whether it was flushed
or dropped."""
from __future__ import annotations

import pytest

from drainage import Limits


class FakeClock:
    """A monotonic clock the test advances; nothing here sleeps."""

    def __init__(self, start: float = 1000.0) -> None:
        self.now = start

    def __call__(self) -> float:
        return self.now

    def advance(self, seconds: float) -> None:
        self.now += seconds


class FakeTransport:
    def __init__(self) -> None:
        self.aborted = False

    def abort(self) -> None:
        self.aborted = True


class FakeWriter:
    def __init__(self) -> None:
        self.transport = FakeTransport()
        self.closed = False

    def close(self) -> None:
        self.closed = True

    def get_extra_info(self, name: str):
        return None


class FakeServer:
    """The two things the drainer asks of ``asyncio.Server``, and nothing else."""

    def __init__(self) -> None:
        self.closed = False
        self.waited = False

    def close(self) -> None:
        self.closed = True

    async def wait_closed(self) -> None:
        self.waited = True


@pytest.fixture
def clock() -> FakeClock:
    return FakeClock()


@pytest.fixture
def server() -> FakeServer:
    return FakeServer()


@pytest.fixture
def limits() -> Limits:
    """A one-second window in ten samples, with a half-second extension."""
    return Limits(grace_ms=1000, extension_ms=500, poll_ms=100)
Every state, every transition and every gate, including the two that must be refused. test_policy.py
"""Every state, every transition and every gate of the shutdown policy."""
from __future__ import annotations

import pytest

from drainage import Action, Decision, IllegalTransition, Limits, State, decide, transition
from drainage.policy import extended_after


def sample(state=State.DRAINING, elapsed=0.0, in_flight=3, progress=0, fresh=0,
           unread=0, extended=False, limits=None):
    limits = limits or Limits(grace_ms=1000, extension_ms=500, poll_ms=100,
                              progress_ms=500, idle_grace_ms=250)
    return decide(state=state, elapsed_ms=elapsed, in_flight=in_flight,
                  fresh_conns=fresh, unread_conns=unread, progress_completed=progress,
                  extended=extended, limits=limits)


def test_inside_the_window_waits():
    decision = sample(elapsed=200.0)
    assert decision.action is Action.WAIT
    assert decision.state is State.DRAINING


def test_a_server_with_nothing_in_flight_stops_at_the_first_sample():
    decision = sample(elapsed=0.0, in_flight=0)
    assert decision.action is Action.STOP
    assert "no request in flight" == decision.reason


def test_a_connection_inside_its_idle_grace_is_not_a_reason_to_leave():
    """Nothing is counted and a socket was handed a request a moment ago: closing every
    connection because the count is zero is how a drain loses the request it never saw."""
    decision = sample(elapsed=25.0, in_flight=0, fresh=4)
    assert decision.action is Action.WAIT
    assert "no request in flight; 4 connections still inside the idle grace" == decision.reason


def test_the_wait_line_names_an_unread_socket_apart_from_a_grace():
    """A connection past its grace with bytes on it is not "inside its grace": the line
    says which reason it is waiting for, so an operator reading it knows whether a close
    would lose a request or nothing."""
    decision = sample(elapsed=400.0, in_flight=0, fresh=3, unread=1)
    assert decision.action is Action.WAIT
    assert (decision.reason
            == "no request in flight; 2 connections still inside the idle grace and "
               "1 connection holding unread bytes")


def test_the_wait_line_reads_as_a_sentence_for_one_connection():
    """The count reaches the line with its noun: a drain with a single straggler prints
    ``1 connection``, because that is the line an operator greps for at three in the morning."""
    decision = sample(elapsed=25.0, in_flight=0, fresh=1)
    assert decision.action is Action.WAIT
    assert (decision.reason
            == "no request in flight; 1 connection still inside the idle grace")


def test_the_window_can_close_on_idle_connections_without_an_abort():
    """Nothing was counted and nothing is on the sockets: the window closed while a
    connection was still inside its grace, and closing it gives up no request. An abort
    line here would tell an operator that a deploy lost work it did not lose."""
    decision = sample(elapsed=1000.0, in_flight=0, fresh=2, progress=0)
    assert decision.action is Action.STOP
    assert decision.state is State.STOPPED
    assert "2 idle connections and no request counted" in decision.reason


def test_a_socket_holding_unread_bytes_still_aborts_at_the_window():
    """The same window, but the socket says a request is on it that no handler read:
    this one is a loss, and the log has to name it."""
    decision = sample(elapsed=1000.0, in_flight=0, fresh=2, unread=2, progress=0)
    assert decision.action is Action.ABORT
    assert "2 sockets holding unread bytes" in decision.reason


def test_the_hard_cap_with_nothing_in_flight_stops_instead_of_aborting():
    decision = sample(elapsed=1500.0, in_flight=0, fresh=1, progress=4)
    assert decision.action is Action.STOP
    assert "hard cap" in decision.reason
    assert "no request counted" in decision.reason


def test_an_extension_is_not_granted_to_a_drain_with_nothing_to_finish():
    """No request in flight and nothing on a socket means there is nothing an extension
    could save, whatever the finished total says."""
    decision = sample(elapsed=1200.0, in_flight=0, fresh=3, progress=2, extended=False)
    assert decision.action is Action.STOP


def test_every_abort_names_something_that_was_lost():
    """The rule the deploy order tells an operator to rely on: no abort line means
    nothing was lost, so an abort must never be returned for an empty drain."""
    cases = [
        dict(elapsed=1000.0, in_flight=1, progress=0),
        dict(elapsed=1500.0, in_flight=2, progress=4),
        dict(elapsed=1500.0, in_flight=1, progress=2, extended=True),
        dict(elapsed=1000.0, in_flight=0, fresh=1, unread=1),
    ]
    for case in cases:
        decision = sample(**case)
        assert decision.action is Action.ABORT, case
        assert decision.in_flight or case.get("unread"), case


def test_an_unread_count_that_is_not_a_subset_is_rejected():
    with pytest.raises(ValueError):
        sample(fresh=1, unread=2)


def test_zero_in_flight_is_checked_before_the_hard_cap():
    decision = sample(elapsed=10_000.0, in_flight=0, progress=4)
    assert decision.action is Action.STOP


def test_the_hard_cap_aborts_even_a_drain_that_is_finishing_requests():
    decision = sample(elapsed=1500.0, in_flight=2, progress=4)
    assert decision.action is Action.ABORT
    assert "hard cap" in decision.reason


def test_the_window_closing_without_progress_aborts():
    decision = sample(elapsed=1000.0, in_flight=3, progress=0)
    assert decision.action is Action.ABORT
    assert "nothing finished in the last 500 ms" in decision.reason


def test_a_first_sample_past_the_window_carries_no_progress_evidence():
    decision = sample(elapsed=1000.0, in_flight=1, progress=0)
    assert decision.action is Action.ABORT


def test_a_request_finishing_at_the_window_gets_one_extension():
    decision = sample(elapsed=1000.0, in_flight=2, progress=1)
    assert decision.action is Action.EXTEND
    assert decision.state is State.OVERDUE
    assert "1 finished in the last 500 ms" in decision.reason


def test_progress_is_a_finished_request_even_when_the_count_does_not_fall():
    """A keep-alive connection can end one request and start the next: the count in
    flight stays where it was while the handler is plainly working, so the gate reads
    the number that finished inside the progress window instead."""
    decision = sample(elapsed=1000.0, in_flight=3, progress=2)
    assert decision.action is Action.EXTEND


def test_the_extension_is_the_window_in_which_the_rest_finish():
    decision = sample(elapsed=1200.0, in_flight=1, progress=2, extended=True)
    assert decision.action is Action.WAIT
    assert decision.state is State.OVERDUE
    assert "on the extension" in decision.reason


def test_the_extension_cannot_outlive_the_hard_cap():
    decision = sample(elapsed=1500.0, in_flight=1, progress=2, extended=True)
    assert decision.action is Action.ABORT
    assert "hard cap" in decision.reason


def test_a_granted_extension_is_never_granted_twice():
    decision = sample(elapsed=1000.0, in_flight=2, progress=1, extended=True)
    assert decision.action is not Action.EXTEND
    assert decision.action is Action.WAIT


def test_a_stopped_machine_keeps_stopping():
    decision = sample(state=State.STOPPED, elapsed=5000.0)
    assert decision.action is Action.KEEP
    assert decision.reason == "already stopped"


def test_negative_in_flight_is_rejected():
    with pytest.raises(ValueError):
        sample(in_flight=-1)


def test_a_negative_progress_count_is_rejected():
    with pytest.raises(ValueError):
        sample(progress=-1)


def test_a_negative_fresh_count_is_rejected():
    with pytest.raises(ValueError):
        sample(fresh=-1)


def test_a_negative_unread_count_is_rejected():
    with pytest.raises(ValueError):
        sample(fresh=1, unread=-1)


def test_transitions_the_table_allows():
    current = State.DRAINING
    for decision in (sample(elapsed=100.0),
                     sample(elapsed=1000.0, in_flight=2, progress=1),
                     sample(state=State.OVERDUE, elapsed=1200.0, in_flight=2, progress=1,
                            extended=True),
                     sample(state=State.OVERDUE, elapsed=0.0, in_flight=0, progress=2,
                            extended=True)):
        current = transition(current, decision)
    assert current is State.STOPPED


def test_serving_goes_straight_to_stopped_when_idle():
    decision = sample(state=State.SERVING, in_flight=0)
    assert transition(State.SERVING, decision) is State.STOPPED


def test_a_stopped_machine_cannot_drain_again():
    decision = Decision(State.DRAINING, Action.WAIT, "wait", 0.0, 1, False)
    with pytest.raises(IllegalTransition):
        transition(State.STOPPED, decision)


def test_overdue_can_still_finish_cleanly():
    decision = sample(state=State.OVERDUE, elapsed=1100.0, in_flight=0, progress=1,
                      extended=True)
    assert transition(State.OVERDUE, decision) is State.STOPPED


def test_the_extension_flag_is_sticky():
    granted = sample(elapsed=1000.0, in_flight=2, progress=1)
    assert extended_after(granted) is True
    waiting = sample(elapsed=100.0)
    assert extended_after(waiting) is False


def test_the_hard_cap_is_the_window_plus_the_extension():
    assert Limits(grace_ms=1000, extension_ms=500, poll_ms=100).hard_ms == 1500


@pytest.mark.parametrize("grace", [0, -100])
def test_a_zero_or_negative_window_is_refused(grace):
    with pytest.raises(ValueError):
        Limits(grace_ms=grace, extension_ms=100, poll_ms=10)


def test_a_negative_extension_is_refused():
    with pytest.raises(ValueError):
        Limits(grace_ms=1000, extension_ms=-1, poll_ms=100)


def test_a_window_shorter_than_two_samples_is_refused():
    with pytest.raises(ValueError):
        Limits(grace_ms=150, extension_ms=0, poll_ms=100)


def test_an_extension_shorter_than_a_sample_is_refused():
    """It would be spent before the loop could sample it once, so the operator who
    asked for it would get an abort at the window and no extension at all."""
    with pytest.raises(ValueError):
        Limits(grace_ms=1000, extension_ms=40, poll_ms=100)


def test_a_progress_window_shorter_than_a_sample_is_refused():
    """The gate could then never see a second sample, so every drain whose requests
    outlive the window would abort whatever the handlers were doing."""
    with pytest.raises(ValueError):
        Limits(grace_ms=1000, extension_ms=500, poll_ms=100, progress_ms=50)


def test_a_progress_window_longer_than_the_grace_window_is_refused():
    with pytest.raises(ValueError):
        Limits(grace_ms=1000, extension_ms=500, poll_ms=100, progress_ms=1500)


def test_an_idle_grace_that_outlasts_the_window_is_refused():
    """An idle connection held longer than the whole window would never be closed by
    the grace, and the drain would spend the window on sockets with nothing on them."""
    with pytest.raises(ValueError):
        Limits(grace_ms=1000, extension_ms=500, poll_ms=100, idle_grace_ms=1000)


def test_zero_extension_means_one_window_and_no_more():
    limits = Limits(grace_ms=300, extension_ms=0, poll_ms=100, progress_ms=300,
                    idle_grace_ms=100)
    decision = sample(elapsed=300.0, in_flight=2, progress=1, limits=limits)
    assert decision.action is Action.ABORT


def test_the_reason_carries_the_count():
    decision = sample(elapsed=100.0, in_flight=7)
    assert "7 in flight" in decision.reason


def test_the_line_names_state_action_and_reason():
    line = sample(elapsed=100.0, in_flight=7).line()
    assert line.startswith("state=draining action=wait inflight=7 elapsed_ms=100 ")
    assert "reason=within the grace window with 7 in flight" in line
The samples, the abort paths, the guards on the count, and the second signal. test_drainer.py
"""The object that takes the samples: what it closes, what it waits for, what it aborts."""
from __future__ import annotations

import asyncio

import pytest

from drainage import Action, Conn, Drainer, Limits, State


def scenario(coro):
    return asyncio.run(coro)


class Writer:
    def __init__(self) -> None:
        self.closed = False
        self.aborted = False
        self.transport = self

    def close(self) -> None:
        self.closed = True

    def abort(self) -> None:
        self.aborted = True


def build(server, clock, limits, decisions=None):
    async def sleep(seconds):
        clock.advance(seconds)
        await asyncio.sleep(0)

    return Drainer(server, limits, clock=clock, sleep=sleep,
                   on_decision=None if decisions is None else decisions.append)


def _sleeper(clock):
    """A sleep that only moves the fake clock, for a drainer built inline."""
    async def sleep(seconds):
        clock.advance(seconds)
        await asyncio.sleep(0)

    return sleep


def test_signal_stops_accepting_and_starts_the_clock(server, clock, limits):
    drainer = build(server, clock, limits)
    drainer.signal()
    assert server.closed is True
    assert drainer.started == clock()
    assert drainer.state is State.SERVING


def test_an_idle_process_exits_at_the_first_sample(server, clock, limits):
    drainer = build(server, clock, limits)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.outcome == "clean"
    assert server.closed is True
    assert drainer.counts.decisions == 1


def test_idle_keep_alive_connections_are_closed_not_waited_for(server, clock, limits):
    drainer = build(server, clock, limits)
    writers = []
    for _ in range(3):
        writer = Writer()
        writers.append(writer)
        drainer.attach(None, writer)
    drainer.signal()
    scenario(drainer.run())
    assert all(writer.closed for writer in writers)
    assert drainer.counts.closed_idle == 3
    assert drainer.counts.aborted == 0


def test_a_connection_with_a_request_in_flight_is_not_closed_early(server, clock, limits):
    drainer = build(server, clock, limits)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.started_request(conn)
    assert drainer.in_flight == 2
    drainer.finished_request(conn)
    assert drainer.in_flight == 1
    assert drainer.completed == 1
    drainer.finished_request(conn)
    drainer.detach(conn)
    assert drainer.in_flight == 0
    assert drainer.completed == 2


def test_a_connection_detached_with_a_request_in_flight_is_refused(server, clock, limits):
    """Dropping the connection would drop its count, and the drain would then see an
    idle process while the handler was still working on the socket it forgot."""
    drainer = build(server, clock, limits)
    conn = drainer.attach(None, Writer())
    drainer.started_request(conn)
    with pytest.raises(ValueError):
        drainer.detach(conn)
    assert drainer.in_flight == 1


def test_a_handler_that_raises_still_finishes_its_request(server, clock, limits):
    """The count is the handler's bargain, not its success: the finally that ends the
    request runs on the exception path too, which is why a failed request cannot leak
    into the in-flight count."""
    drainer = build(server, clock, limits)
    conn = drainer.attach(None, Writer())
    drainer.started_request(conn)

    async def failing():
        try:
            raise RuntimeError("handler failed")
        finally:
            drainer.finished_request(conn)

    with pytest.raises(RuntimeError):
        scenario(failing())
    assert drainer.in_flight == 0
    assert drainer.completed == 1


def test_a_finished_request_on_an_idle_connection_is_refused(server, clock, limits):
    drainer = build(server, clock, limits)
    conn = drainer.attach(None, Writer())
    with pytest.raises(ValueError):
        drainer.finished_request(conn)


def test_requests_completing_inside_the_window_end_cleanly(server, clock, limits):
    drainer = build(server, clock, limits)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()

    async def finish_later():
        await asyncio.sleep(0)
        drainer.finished_request(conn)

    async def main():
        task = asyncio.ensure_future(finish_later())
        summary = await drainer.run()
        await task
        return summary

    summary = scenario(main())
    assert summary.outcome == "clean"
    assert writer.closed is True
    assert writer.aborted is False


def test_requests_finishing_after_the_window_earn_one_extension(server, clock, limits):
    """One request leaves on every sample after the ninth, so the finished total rises
    across the window's last interval and the policy has its evidence for an extension."""
    pending = []
    polls = {"n": 0}

    async def sleep(seconds):
        clock.advance(seconds)
        polls["n"] += 1
        if polls["n"] >= 10 and pending:
            finished = pending.pop(0)
            drainer.finished_request(finished)
            # The client closed its connection when the reply arrived, as the probe's
            # clients do; a socket nobody is holding cannot keep the drain open.
            drainer.detach(finished)
        await asyncio.sleep(0)

    drainer = Drainer(server, limits, clock=clock, sleep=sleep)
    for _ in range(4):
        conn = drainer.attach(None, Writer())
        drainer.started_request(conn)
        pending.append(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.extends == 1
    assert summary.outcome == "clean"
    assert summary.last_elapsed_ms >= limits.grace_ms


def test_progress_is_counted_in_finished_requests_not_the_net_count(server, clock, limits):
    """The request that ends on a keep-alive connection is replaced by the next one in
    the same sample, so the count in flight never falls. Counting what finished, rather
    than what is left, is what keeps the drain from aborting a working handler."""
    polls = {"n": 0}
    conns = []

    async def sleep(seconds):
        clock.advance(seconds)
        polls["n"] += 1
        if polls["n"] >= 10:
            drainer.finished_request(conns[0])
            drainer.started_request(conns[0])
        await asyncio.sleep(0)

    drainer = Drainer(server, limits, clock=clock, sleep=sleep)
    for _ in range(2):
        conn = drainer.attach(None, Writer())
        drainer.started_request(conn)
        conns.append(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.extends == 1
    assert summary.max_in_flight == 2


def test_a_count_that_does_not_fall_is_aborted_at_the_window(server, clock, limits):
    drainer = build(server, clock, limits)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.outcome == "aborted"
    assert writer.aborted is True
    assert drainer.counts.aborted == 1
    assert summary.last_elapsed_ms >= limits.grace_ms


def test_decisions_are_reported_as_they_are_taken(server, clock, limits):
    seen = []
    drainer = build(server, clock, limits, decisions=seen)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()
    scenario(drainer.run())
    assert seen and seen[0].action is Action.WAIT
    assert any(decision.action is Action.ABORT for decision in seen)


def test_signal_twice_does_not_move_the_deadline(server, clock, limits):
    drainer = build(server, clock, limits)
    drainer.signal()
    started = drainer.started
    clock.advance(1.0)
    drainer.signal()
    assert drainer.started == started


def test_a_second_signal_aborts_at_the_next_sample(server, clock, limits):
    """The operator who signals twice is not willing to wait for the window, so the
    drain gives up on the requests it is holding rather than spending the budget."""
    drainer = build(server, clock, limits)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()

    async def main():
        task = asyncio.ensure_future(drainer.run())
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        clock.advance(0.2)
        drainer.signal()
        return await task

    summary = scenario(main())
    assert summary.aborts == 1
    assert summary.outcome == "aborted"
    assert writer.aborted is True
    assert summary.last_elapsed_ms < limits.grace_ms
    assert "second signal" in drainer.counts.samples[-1].reason


def test_a_second_drain_returns_instead_of_waiting_again(server, clock, limits):
    """The stopped machine's decision is ``keep``, which is not an action to wait on:
    a second call has nothing to decide and must return, not loop until a clock moves."""
    drainer = build(server, clock, limits)
    drainer.signal()
    scenario(drainer.run())
    decisions = drainer.counts.decisions
    summary = scenario(drainer.run())
    assert summary.outcome == "clean"
    assert drainer.counts.decisions == decisions + 1


def test_a_connection_accepted_after_the_drain_is_closed_at_once(server, clock, limits):
    drainer = build(server, clock, limits)
    drainer.signal()
    scenario(drainer.run())
    writer = Writer()
    conn = drainer.attach(None, writer)
    assert writer.closed is True
    assert drainer.in_flight == 0
    assert conn.active == 0


def test_run_waits_for_the_signal(server, clock, limits):
    drainer = build(server, clock, limits)

    async def main():
        task = asyncio.ensure_future(drainer.run())
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        assert drainer.counts.decisions == 0
        drainer.signal()
        return await task

    summary = scenario(main())
    assert summary.outcome == "clean"


def test_a_poll_interval_sets_how_many_samples_a_window_gets(server, clock, limits):
    drainer = build(server, clock, limits)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()
    scenario(drainer.run())
    assert drainer.counts.decisions == limits.grace_ms // limits.poll_ms + 1


def test_the_summary_counts_what_the_run_did(server, clock, limits):
    drainer = build(server, clock, limits)
    for _ in range(2):
        writer = Writer()
        conn = drainer.attach(None, writer)
        drainer.started_request(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    payload = summary.as_dict()
    assert payload["aborts"] == 1
    assert payload["max_in_flight"] == 2
    assert payload["outcome"] == "aborted"
    assert drainer.counts.as_dict()["aborted"] == 2


def test_a_request_that_finished_before_the_progress_window_is_not_evidence(server, clock, limits):
    """One request ended early in the window and nothing after it: by the time the
    window closes, that finish is outside the progress window the gate reads, so the
    drain is looking at a handler that has done nothing for half a second."""
    polls = {"n": 0}

    async def sleep(seconds):
        clock.advance(seconds)
        polls["n"] += 1
        if polls["n"] == 2:
            drainer.finished_request(conn)
        await asyncio.sleep(0)

    drainer = Drainer(server, limits, clock=clock, sleep=sleep)
    conn = drainer.attach(None, Writer())
    drainer.started_request(conn)
    second = drainer.attach(None, Writer())
    drainer.started_request(second)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.extends == 0
    assert summary.outcome == "aborted"
    assert "nothing finished in the last 500 ms" in drainer.counts.samples[-1].reason


def test_a_slow_handler_that_keeps_finishing_is_still_progress(server, clock, limits):
    """A handler finishing one request every three samples never moves the count inside
    a single interval, and it is plainly working: the window the gate reads is what
    keeps it from being cut off as stuck."""
    polls = {"n": 0}
    pending: list = []

    async def sleep(seconds):
        clock.advance(seconds)
        polls["n"] += 1
        if polls["n"] % 3 == 0 and pending:
            finished = pending.pop(0)
            drainer.finished_request(finished)
            drainer.detach(finished)
        await asyncio.sleep(0)

    drainer = Drainer(server, limits, clock=clock, sleep=sleep)
    for _ in range(5):
        conn = drainer.attach(None, Writer())
        drainer.started_request(conn)
        pending.append(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.extends == 1
    assert summary.outcome == "clean"


def test_an_idle_connection_is_closed_only_after_its_grace(server, clock, limits):
    """A request can arrive on a socket whose handler has not read it yet, and from the
    drain's side that socket looks idle. The grace is the time the handler needs."""
    drainer = build(server, clock, limits)
    writer = Writer()
    drainer.attach(None, writer)
    drainer.signal()
    drainer._close_idle()
    assert writer.closed is False
    assert drainer.counts.closed_idle == 0
    clock.advance(limits.idle_grace_ms / 1000)
    drainer._close_idle()
    assert writer.closed is True
    assert drainer.counts.closed_idle == 1


def test_an_abort_closes_idle_connections_whatever_their_grace(server, clock, limits):
    drainer = build(server, clock, limits)
    writer = Writer()
    drainer.attach(None, writer)
    drainer.signal()
    drainer._close_idle(ignore_grace=True)
    assert writer.closed is True


def test_a_zero_extension_aborts_at_the_window(server, clock):
    limits = Limits(grace_ms=300, extension_ms=0, poll_ms=100, progress_ms=300,
                    idle_grace_ms=100)
    drainer = build(server, clock, limits)
    conn = drainer.attach(None, Writer())
    drainer.started_request(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.outcome == "aborted"
    assert summary.extends == 0


def test_a_window_closing_on_a_socket_that_just_went_idle_stops_without_an_abort(
        server, clock, limits):
    """The last request finishes and its keep-alive socket stays open inside its grace.
    The window then closes with the count at zero and no bytes on the socket: the drain
    closed a connection nobody was using, and there is no abort to log."""
    polls = {"n": 0}
    conn = None

    async def sleep(seconds):
        clock.advance(seconds)
        polls["n"] += 1
        if polls["n"] == 9:
            drainer.finished_request(conn)
        await asyncio.sleep(0)

    drainer = Drainer(server, limits, clock=clock, sleep=sleep)
    writer = Writer()
    conn = drainer.attach(None, writer)
    drainer.started_request(conn)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.aborts == 0
    assert summary.outcome == "clean"
    assert drainer.counts.aborted == 0
    assert drainer.counts.closed_idle == 1
    assert summary.last_elapsed_ms >= limits.grace_ms
    assert "idle connection and no request counted" in drainer.counts.samples[-1].reason
    assert writer.aborted is False


def test_a_window_closing_on_a_socket_holding_bytes_aborts(server, clock, limits):
    """A request that arrived but was never read keeps the drain waiting through the
    window; when the window closes the socket still holds it, and that is a loss."""
    class Reader:
        _buffer = b"REQ 300\n"

    drainer = build(server, clock, limits)
    writer = Writer()
    drainer.attach(Reader(), writer)
    drainer.signal()
    summary = scenario(drainer.run())
    assert summary.aborts == 1
    assert summary.outcome == "aborted"
    assert drainer.counts.aborted == 0
    assert drainer.counts.closed_idle == 1
    assert "1 socket holding unread bytes" in drainer.counts.samples[-1].reason


def test_a_socket_that_is_not_asked_does_not_report_unread_bytes(server, clock, limits):
    """With the peek switched off the drain has only the clock, so the same socket is
    just a quiet one - and it is closed when its grace expires, which is the comparison
    probe 11 makes."""
    class Reader:
        _buffer = b"REQ 300\n"

    drainer = Drainer(server, limits, clock=clock, sleep=_sleeper(clock),
                      peek_unread=False)
    writer = Writer()
    drainer.attach(Reader(), writer)
    assert drainer.unread == 0
    drainer.signal()
    scenario(drainer.run())
    assert writer.closed is True
    assert drainer.counts.aborted == 0


def test_a_second_signal_with_nothing_in_flight_stops_instead_of_aborting(server, clock,
                                                                          limits):
    """The operator pressing stop twice wants the process gone, but a drain with nothing
    on it has nothing to abort, and the log must not claim otherwise."""
    drainer = build(server, clock, limits)
    drainer.attach(None, Writer())
    drainer.signal()

    async def main():
        task = asyncio.ensure_future(drainer.run())
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        clock.advance(0.2)
        drainer.signal()
        return await task

    summary = scenario(main())
    assert summary.aborts == 0
    assert summary.stops == 1
    assert summary.outcome == "clean"
    assert "second signal: nothing in flight" == drainer.counts.samples[-1].reason


# -- the table, the key and the single walk -------------------------------------------
class Holding:
    """A reader that says it holds a request, the way a StreamReader with buffered bytes does."""

    _buffer = b"GET / HTTP/1.1\r\n"


class KeyedTable(dict):
    """A connection table that fails if anything walks it.

    Removing one connection has to be a lookup: the table is keyed by the number the
    connection was registered under, and a removal that scans is the O(N²) the article's
    section 9 measured. This subclass turns that scan into a failed test rather than a
    slower deploy.
    """

    def items(self):
        raise AssertionError("the table was walked to remove one connection")

    def values(self):
        raise AssertionError("the table was walked to remove one connection")

    def __iter__(self):
        raise AssertionError("the table was walked to remove one connection")


def _counting_unread(monkeypatch):
    """Every call to ``Conn.unread`` recorded by the key of the connection it asked."""
    asked: list[int] = []
    original = Conn.unread

    def counting(self):
        asked.append(self.key)
        return original(self)

    monkeypatch.setattr(Conn, "unread", counting)
    return asked


def test_each_connection_carries_the_key_it_is_registered_under(server, clock, limits):
    drainer = build(server, clock, limits)
    first = drainer.attach(None, Writer())
    second = drainer.attach(None, Writer())
    assert first.key != second.key
    assert drainer.conns[first.key] is first
    assert drainer.conns[second.key] is second
    drainer.detach(first)
    assert first.key not in drainer.conns
    assert drainer.conns[second.key] is second      # the neighbour was not disturbed


def test_detaching_a_connection_does_not_walk_the_table(server, clock, limits):
    """Closing N connections is N lookups: a removal that scans the table is what made the
    closing batch grow faster than the population it closed."""
    drainer = build(server, clock, limits)
    conn = drainer.attach(None, Writer())
    other = drainer.attach(None, Writer())
    drainer.conns = KeyedTable(drainer.conns)
    drainer.detach(conn)
    assert drainer.conns.get(other.key) is other
    assert drainer.conns.get(conn.key) is None


def test_removing_a_connection_the_drain_never_registered_is_a_no_op(server, clock, limits):
    """A connection accepted while the drain was finishing is closed, not registered; the
    removal must not fail on the one connection the table does not hold."""
    drainer = build(server, clock, limits)
    drainer.signal()
    scenario(drainer.run())
    conn = drainer.attach(None, Writer())
    assert conn.key not in drainer.conns
    drainer._remove(conn)
    assert drainer.conns == {}


def test_one_sample_asks_each_idle_socket_once(server, clock, limits, monkeypatch):
    """Freshness and unread bytes come from one reading.

    The freshness test is a comparison against the clock, so it cannot answer for a socket
    past its grace; the socket has to be asked either way. Asking it once and deriving both
    numbers is what halves a sample that used to make two walks over the same sockets.
    """
    drainer = build(server, clock, limits)
    for _ in range(4):
        drainer.attach(Holding(), Writer())
    clock.advance((limits.idle_grace_ms + 100) / 1000)
    asked = _counting_unread(monkeypatch)
    sample = drainer._scan()
    assert asked == [1, 2, 3, 4]                    # one question per socket
    assert (sample.fresh, sample.unread) == (4, 4)  # both numbers from that one answer
    assert len(sample.readings) == 4


def test_the_closing_pass_reads_the_sample_it_was_taken_on(server, clock, limits, monkeypatch):
    """The decision and the closes it leads to share one walk: the closing pass asks no
    socket what the sample already asked."""
    drainer = build(server, clock, limits)
    held, quiet = Writer(), Writer()
    drainer.attach(Holding(), held)
    drainer.attach(None, quiet)
    clock.advance((limits.idle_grace_ms + 100) / 1000)
    asked = _counting_unread(monkeypatch)
    sample = drainer._scan()
    assert len(asked) == 2
    drainer._close_idle(sample=sample)
    assert len(asked) == 2                          # nothing asked twice
    assert quiet.closed is True
    assert held.closed is False
    assert drainer.counts.closed_idle == 1
The socket’s own answer, on a real socket pair, and the gate it adds to the drain. test_peek.py
"""The socket's own answer to "is a request waiting here?" - and what it is blind to.

Two halves, and the page's measurement is the reason both exist: a ``StreamReader`` has
already taken the bytes out of the kernel by the time a drain samples, so ``FIONREAD`` and
``MSG_PEEK`` see nothing on exactly the connection the race is about. The reader's buffer
is the half that answers it; the kernel is asked for the transports that have not read yet.
The socket-level tests use a real socket pair rather than a fake, because the question is
what the kernel reports.
"""
from __future__ import annotations

import asyncio
import socket

import pytest

from drainage import Conn, Drainer, Limits
from drainage import probe


class FakeReader:
    """The one attribute of ``StreamReader`` the check reads: what it has buffered."""

    def __init__(self, buffered: bytes = b"") -> None:
        self._buffer = buffered


class FakeWriter:
    def __init__(self) -> None:
        self.closed = False
        self.aborted = False
        self.transport = self

    def close(self) -> None:
        self.closed = True

    def abort(self) -> None:
        self.aborted = True


class SocketWriter(FakeWriter):
    """A writer backed by a real socket, as asyncio's is."""

    def __init__(self, sock: socket.socket) -> None:
        super().__init__()
        self.sock = sock

    def get_extra_info(self, name: str):
        return self.sock if name == "socket" else None


class FakeServer:
    def __init__(self) -> None:
        self.closed = False

    def close(self) -> None:
        self.closed = True

    async def wait_closed(self) -> None:
        return None


@pytest.fixture
def pair():
    left, right = socket.socketpair()
    yield left, right
    left.close()
    right.close()


def sleeper(clock):
    async def sleep(seconds):
        clock.advance(seconds)

    return sleep


def test_bytes_in_the_kernel_are_counted_and_left_alone(pair, clock):
    server_side, client_side = pair
    client_side.sendall(b"REQ 100\n")
    writer = SocketWriter(server_side)
    assert probe.pending_bytes(writer) == 8
    assert Conn(reader=FakeReader(b""), writer=writer).unread() is True
    assert server_side.recv(8) == b"REQ 100\n"


def test_a_buffered_request_is_unread_after_the_transport_emptied_the_socket(pair, clock):
    """The case this page measured: asyncio reads the socket before any handler looks, so
    a kernel-only peek reports an idle connection holding an unread request."""
    server_side, client_side = pair
    client_side.sendall(b"REQ 100\n")
    server_side.recv(8)                       # the transport's own read
    writer = SocketWriter(server_side)
    assert probe.pending_bytes(writer) == 0
    assert Conn(reader=FakeReader(b""), writer=writer).unread() is False
    assert Conn(reader=FakeReader(b"REQ 100\n"), writer=writer).unread() is True


def test_peek_leaves_the_bytes_for_the_handler(pair):
    server_side, client_side = pair
    client_side.sendall(b"REQ 100\n")
    writer = SocketWriter(server_side)
    assert probe.peek(writer) == b"R"
    assert probe.peek(writer) == b"R"
    assert server_side.recv(8) == b"REQ 100\n"


def test_an_idle_socket_reports_nothing_and_does_not_block(pair):
    server_side, _ = pair
    writer = SocketWriter(server_side)
    assert probe.peek(writer) == b""
    assert probe.pending_bytes(writer) == 0


def test_a_writer_without_a_socket_reports_nothing():
    conn = Conn(reader=FakeReader(b""), writer=FakeWriter())
    assert conn.unread() is False


def test_an_unread_request_keeps_the_drain_from_leaving(server, clock, limits):
    """The gate the time-based grace cannot express: the socket says a request is there,
    so the drain waits through the window - and when the window closes on bytes nobody
    read, that is a loss the log names."""
    drainer = Drainer(FakeServer(), limits, clock=clock, sleep=sleeper(clock))
    drainer.attach(FakeReader(b"REQ 300\n"), FakeWriter())
    drainer.signal()
    assert drainer.in_flight == 0
    assert drainer.fresh == 1
    summary = asyncio.run(drainer.run())
    assert summary.waits >= 1
    assert summary.outcome == "aborted"
    assert "socket holding unread bytes" in summary.lines[-1]


def test_the_peek_can_be_turned_off_for_the_comparison(server, clock, limits):
    """With the witness removed, the grace is all that stands between an unread request
    and a close - which is probe 11's 600 ms cell."""
    drainer = Drainer(FakeServer(), limits, clock=clock, sleep=sleeper(clock),
                      peek_unread=False)
    writer = FakeWriter()
    drainer.attach(FakeReader(b"REQ 300\n"), writer)
    drainer.signal()
    assert drainer.fresh == 1                  # still inside its grace
    clock.advance((limits.idle_grace_ms + 100) / 1000)
    assert drainer.fresh == 0                  # past the grace, and nothing else to ask
    drainer._close_idle()
    assert writer.closed is True


def test_close_idle_leaves_a_connection_with_unread_bytes_alone(server, clock, limits):
    drainer = Drainer(FakeServer(), limits, clock=clock, sleep=sleeper(clock))
    writer = FakeWriter()
    drainer.attach(FakeReader(b"REQ 300\n"), writer)
    drainer.signal()
    clock.advance((limits.idle_grace_ms + 100) / 1000)
    drainer._close_idle()
    assert writer.closed is False
    assert drainer.counts.closed_idle == 0


def test_an_abort_gives_up_the_peek_too(server, clock, limits):
    drainer = Drainer(FakeServer(), limits, clock=clock, sleep=sleeper(clock))
    writer = FakeWriter()
    drainer.attach(FakeReader(b"REQ 300\n"), writer)
    drainer.signal()
    drainer._close_idle(ignore_grace=True)
    assert writer.closed is True
    assert drainer.counts.closed_idle == 1


def test_the_grace_still_closes_a_socket_with_nothing_on_it(server, clock, limits):
    drainer = Drainer(FakeServer(), limits, clock=clock, sleep=sleeper(clock))
    writer = FakeWriter()
    drainer.attach(FakeReader(b""), writer)
    drainer.signal()
    drainer._close_idle()
    assert writer.closed is False
    clock.advance((limits.idle_grace_ms + 100) / 1000)
    drainer._close_idle()
    assert writer.closed is True


def test_the_peek_adds_no_limit_to_the_window():
    """The peek is a witness, not a number: a drain with and without it shares a window."""
    assert Limits(grace_ms=1000).idle_grace_ms == 250
The log line and the totals of a run. test_report.py
"""The decision line and the run's totals."""
from __future__ import annotations

from dataclasses import dataclass
from enum import Enum

from drainage import describe
from drainage.report import Summary


class State(str, Enum):
    DRAINING = "draining"
    STOPPED = "stopped"


class Action(str, Enum):
    WAIT = "wait"
    STOP = "stop"
    ABORT = "abort"
    EXTEND = "extend"


@dataclass
class FakeDecision:
    state: State
    action: Action
    reason: str
    elapsed_ms: float
    in_flight: int
    extended: bool = False


def test_the_line_is_one_line_of_key_value_pairs():
    line = describe(FakeDecision(State.DRAINING, Action.WAIT, "within the window", 132.4, 7))
    assert line == "state=draining action=wait inflight=7 elapsed_ms=132 reason=within the window"


def test_an_empty_summary_is_still_running():
    assert Summary().outcome == "running"


def test_the_summary_counts_each_action():
    summary = Summary()
    summary.add(FakeDecision(State.DRAINING, Action.WAIT, "wait", 100.0, 4))
    summary.add(FakeDecision(State.DRAINING, Action.EXTEND, "extend", 1000.0, 3))
    summary.add(FakeDecision(State.STOPPED, Action.ABORT, "abort", 1500.0, 1))
    payload = summary.as_dict()
    assert payload["waits"] == 1
    assert payload["extends"] == 1
    assert payload["aborts"] == 1
    assert payload["stops"] == 0
    assert payload["outcome"] == "aborted"


def test_a_clean_run_reports_clean():
    summary = Summary()
    summary.add(FakeDecision(State.DRAINING, Action.WAIT, "wait", 100.0, 2))
    summary.add(FakeDecision(State.STOPPED, Action.STOP, "none left", 400.0, 0))
    assert summary.outcome == "clean"
    assert summary.as_dict()["last_elapsed_ms"] == 400.0


def test_one_line_is_kept_per_decision():
    summary = Summary()
    for index in range(4):
        summary.add(FakeDecision(State.DRAINING, Action.WAIT, "wait", 10.0 * index, 1))
    assert len(summary.lines) == 4
    assert "inflight=1 elapsed_ms=30" in summary.as_dict()["lines"][3]
The readings from /proc and from a socket. test_probe.py
"""The readings: descriptor counts, process state, and the host's own socket knobs."""
from __future__ import annotations

import os

import pytest

from drainage import probe


def test_open_descriptors_counts_this_process():
    assert probe.open_fds(os.getpid()) >= 3


def test_process_state_is_one_letter():
    assert probe.proc_state(os.getpid()) in {"R", "S", "D", "T", "t", "Z"}


def test_a_missing_process_raises():
    with pytest.raises(FileNotFoundError):
        probe.proc_state(2 ** 22 + 7)


def test_the_fin_timeout_is_positive_milliseconds():
    assert probe.tcp_fin_timeout_ms() > 0


def test_somaxconn_is_at_least_the_default_backlog():
    assert probe.somaxconn() >= 128


def test_a_writer_without_a_socket_is_refused():
    class Bare:
        def get_extra_info(self, name):
            return None

    with pytest.raises(ValueError):
        probe.linger(Bare())
The gate run: the linter, the tests, and the counts the prose quotes. 08_tests.py
"""Probe 08: the package's own numbers - files, lines, tests, and the linter.

The article quotes these as its proof that the code in the appendix is the code that
ran: the same tree is linted and tested here, and the counts printed in the prose are
read from this record rather than typed.
"""
from __future__ import annotations

import json
import pathlib
import re
import subprocess
import sys

HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
MODULE = ROOT / "module" / "drainage"
TESTS = MODULE / "tests"
RESULTS = ROOT / "results"


def lines(path: pathlib.Path) -> int:
    return len(path.read_text(encoding="utf-8").splitlines())


def main() -> None:
    lint = subprocess.run([sys.executable, "-m", "pyflakes", str(MODULE)],
                          capture_output=True, text=True, cwd=ROOT / "module")
    test = subprocess.run([sys.executable, "-m", "pytest", "drainage/tests", "-q"],
                          capture_output=True, text=True, cwd=ROOT / "module")
    tail = test.stdout.strip().splitlines()[-1] if test.stdout.strip() else ""
    passed = re.search(r"(\d+) passed", tail)
    package = sorted(path for path in MODULE.glob("*.py"))
    tests = sorted(path for path in TESTS.glob("*.py"))
    record = {
        "pyflakes": {
            "clean": not (lint.stdout.strip() + lint.stderr.strip()),
            "output": (lint.stdout + lint.stderr).strip()[:400],
        },
        "pytest": {
            "passed": int(passed.group(1)) if passed else 0,
            "failed": len(re.findall(r"(\d+) failed", tail)),
            "summary": tail,
        },
        "package_files": len(package),
        "package_lines": sum(lines(path) for path in package),
        "test_files": len(tests),
        "test_lines": sum(lines(path) for path in tests),
        "test_modules": len([path for path in tests if path.name.startswith("test_")]),
        "probe_files": len(list(HERE.glob("[0-9][0-9]_*.py"))),
        "package_names": [path.name for path in package],
        "test_names": [path.name for path in tests],
    }
    RESULTS.mkdir(exist_ok=True)
    (RESULTS / "08_tests.json").write_text(json.dumps(record, indent=1) + "\n",
                                          encoding="utf-8")
    print(json.dumps(record, indent=1))


if __name__ == "__main__":
    main()

Frequently asked questions

Why did my service exit with status 0 and still drop requests?

Because returning from asyncio.run cancels the tasks it was running. Probe 05 lost 36 requests in 3 runs that way, each handler having seen CancelledError, with exit status zero and no traceback.

Is server.close() not enough?

It stops the listener and nothing else. Probe 02 refused 5 new connections after the close, served another request on the connection it had already accepted, and wait_closed() was still pending 50.9 ms later – it returned 0.20 ms after the client closed that connection, not after the close.

How long should the grace window be?

The measured p99 request time, or two thirds of the orchestrator’s grace period when that time is unknown. The window is a cap, not a wait: a 300 ms window stopped a 5,000 ms request at 330.3 ms, and the same policy against requests that finished left at 127.7 ms, having used 10.6% of its 1,200 ms window and left the rest unspent.

Why do idle keep-alive connections matter so much?

Because they never end, and a shutdown that waits for connections waits for them. Twenty idle connections turned a 1,000 ms window into 4,505 ms and a kill, while the drain that counted requests closed all 20 of them and left at 181.4 ms, as soon as the last request it was counting had finished.

What happens to a request that cannot finish before the deadline?

Its connection is dropped and its reply is lost, and the client sees the connection end without an answer – an ordinary end of stream, not a reset, because the request it sent had already been read: probe 07 recorded 5 lost replies and 0 resets. It cut one 5,000 ms request off at 1,035 ms with a 1,000 ms window, having answered all 5 fast requests in 178.7 ms. Setting SO_LINGER to 0 before the close is what turns that end of stream into a reset, and this page did not measure that.

Why would a drain close a request that had arrived?

Because a connection is closed when it looks idle, and a request the handler has not read yet looks idle. Probe 11 held the handlers back from reading for 200 ms and dropped all 20 requests across its runs by closing on the first sample, with the log saying no request was in flight. A connection gets its grace of 250 ms before it counts as idle for this reason, and that grace has to be longer than the interval between accepting a connection and reading from it: at 600 ms the same grace is too short and the requests are lost again – unless the drain asks the socket, which answered all 4 of them.

Does a drain that counts requests still pay for the idle grace?

Only when a client keeps its connection. Every client in table 9 closed its socket as its reply arrived, so there was nothing to close and the grace was never spent; with clients that held their sockets the same policy left 686.8 ms after the signal rather than 435.9 ms, which is the grace plus the last reply, and at a 500 ms grace it left at 938.7 ms. The floor is real and predictable; what it is not is optional, because closing a socket the moment its reply is written is how a client that was about to reuse it loses its connection.

Why not just peek at the socket instead of waiting?

Half of the answer is yes, and that half is the accurate one: probe 11’s third column answered every request at a 600 ms delay by asking the socket instead of the clock. The other half is where it goes wrong on its own. In an asyncio server the transport has already read the bytes into the stream’s buffer, so the kernel reports nothing: probe 16 found the kernel holding 0 bytes while the reader held 8 in every run. Ask the reader first, the kernel second, and keep the grace for the bytes that have not left the client yet – and remember that on TLS the socket holds ciphertext. The reader this check asks is asyncio.StreamReader‘s, a private buffer that only a stream server has: on uvicorn or any Protocol-based server there is no stream, the protocol has already consumed the bytes, and the place to count the request is Protocol.data_received or the framework’s request-start hook.

Does a shell CMD break this?

It can. With sh -c the shell is the process the supervisor signals, and on this host it exited while the application it started kept running (3 of 3 children survived). The exec form and bash -c replaced the shell with the application, which is what lets the signal land; an init shim such as tini does the same and also reaps orphans. A container adds the PID 1 rule on top: a signal whose default action is to terminate is not applied to PID 1 without a handler, so a shell at PID 1 does not exit at all and the pod ends at SIGKILL instead.

Does this apply to FastAPI, uvicorn or gunicorn?

Partly, and the measurements say which part. Probe 13 gave both servers the same requests: uvicorn waited for the last handler with no deadline of its own (2,494 ms for a 2,500 ms request), and its 1,000 ms graceful timeout is an unconditional cap that lost all 9 requests of the run. Both of them closed the 20 idle keep-alive sockets they were holding within 72 ms of the signal, so the idle-connection problem is already handled. What is left is the decision at the deadline – take the count in the middleware’s first and last line, and gate the window on progress instead of on the clock alone.

Why does a closed connection sometimes reset instead of ending cleanly?

SO_LINGER is off by default (Table 1), so a close sends a FIN after buffered bytes – unless the peer has sent something the process never read, in which case the kernel answers with a reset. Probe 03 saw reset for the unread arm and complete for the one that had read first.

Does a second SIGTERM change anything?

It ends the drain at once. The first signal closes the listener and starts the window; the second makes the loop abort every connection that still has a request on it at its next sample, and the log line says second signal with the number it gave up on. An orchestrator sends the signal once, and a person who presses stop twice means it – a drain that ignored the second one would keep a pod that the operator has already written off.

The path from a deploy that loses requests to one that does not is four steps: count the requests where they start and stop, close the listener on the signal, hold the requests in flight under a deadline that is shorter than the orchestrator’s grace period, and drop only what the deadline could not finish. Each of those steps has a number in the tables above, and the probes that produced them are in the appendix.

TechBobby Engineering writes measured infrastructure runbooks: one failure, its probes, and the code that survives it. Every figure here was produced on a single Linux host with the probes printed in the appendix, and the tests of the package run in the same tree.

Take the next step


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.