TL;DR: The Refusal, and the Four Ways It Is Hidden
BlockingIOError: [Errno 11] Resource temporarily unavailable is not a failure. A non-blocking socket that cannot take another byte accepts what fits, returns that count, and raises only when the count is zero. The message is accurate and carries no number, so the first thing a handler loses is how much of its buffer the peer already has.
Everything below comes from one host: Linux 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, loopback only, a client and a server in one process, and 5 repeats per arm. Buffer sizes are read back from the sockets rather than assumed, a count that was identical in all five runs is printed once, and every figure can be regenerated from a probe in the appendix.
Four findings, each one measured against a different expectation:
- A full socket refuses on its own queue, not on the reader’s window: a default socket took 99.6% of the buffer the kernel reports before its first refusal, while the peer’s window was still open (tables 2 and 4).
- A writer can have window to spare and still be refused. When the reader’s buffer holds no more than one segment, a sip of a read frees nothing at all, and the write that finally succeeds is allowed by the sender’s own retransmission timer, not by the read (tables 5 and 6).
POLLOUTis permission to try, never a capacity: it stayed silent while 9.0% of a 1 MiB send was accepted, and when it fired the same send took 90.5% and left the rest with the caller (table 9).sendallhides the count: it raised a timeout with 31.3% of an 8 MiB body already delivered, and nothing in the exception says how much (table 10).
If a service is stuck right now, the next section is the short answer. Section 4 is the one worth reading if a wait lasted longer than the timeout that was supposed to bound it.
Fix It First: Seven Changes, in the Order They Pay Off
Each row names the symptom, the change, and the measurement on this page that says why. Every figure in the last column is reproduced below with its conditions.
| What you see | What to change | Measured here |
|---|---|---|
sendall raised and the peer’s state is unknown | Keep the count: loop on send and add each return value | 31.3% of the body was delivered when the timeout fired |
POLLOUT is silent although a write would work | Treat writability as permission to try again, never as room | the poll was silent while 9.0% of the attempt was accepted |
| A writer stalls while the reader keeps reading | Read the whole buffer: drain the socket until a read would block, then parse | a 1,024-byte read left the window at zero for 2 s; the 32,768-byte read opened it and the wait ended |
| A writer waits far longer than its timeout | Put one absolute deadline on every wait – a ceiling on the wait, not a cure for it | the window reopened at once; the write was allowed only when the 204 ms retransmission timer fired |
| Memory grows when a client stops reading (asyncio) | Await drain with a deadline before writing the next chunk | 84.4% of a 16 MiB write stayed in the transport |
| A retried request arrives twice, or half | Make the retry recognisable: an idempotency key or a resumable offset | a timeout left 63.7% of an upload at the server |
| A small buffer refuses with nothing unsent | Size the buffer against one segment, not against the message | a buffer of 4,096 bytes held one 47,424-byte segment, 5.8× its accounting |
1. What Errno 11 Says, and What It Does Not
The accepting and the refusing happen in different calls, and only the first one is reported. send copies what the socket’s queue and the peer’s window allow, returns that number, and raises EAGAIN – CPython’s BlockingIOError – only in the call that fits nothing. A handler that treats the first short write as a failure throws away bytes it still owes the peer; a handler that treats EAGAIN as a broken connection closes one that is working.
The number that was accepted is the only evidence of where the peer’s copy ends, and it exists for exactly one moment: the return value of the call that took it. Every operation below that looks authoritative – a writable descriptor, a completed sendall, a drain that returned – is a statement about a different thing, and sections 5, 6 and 10 measure how far apart they can be.
The refusal itself is always one of two limits, whichever is smaller. The socket’s send buffer is a memory budget the kernel holds on the writer’s behalf; the advertised window is a promise the reader makes about the room it has left. A page that prints a single number for “the send buffer” cannot say which one refused, and the two are cleared by different events, which is why the wrong fix often changes nothing.
2. The Send Buffer Is a Budget, Not a Capacity
The first table asks for five send buffers and fills each socket until it refuses. The count is stable across the repeats – a loopback pair with a peer that never reads gives the same result every time – which is what makes it usable as a budget rather than a timing.
| Send buffer asked for | Reported by SO_SNDBUF | Accepted before EAGAIN | Repeats |
|---|---|---|---|
| default | 2,626,560 | 2,615,232 | 5 |
| 4,096 | 8,192 | 80,192 | 5 |
| 16,384 | 32,768 | 80,192 | 5 |
| 65,536 | 131,072 | 196,608 | 5 |
| 262,144 | 425,984 | 481,152 | 5 |
The small arms show the second limit plainly. A socket asked for 4,096 bytes reports 8,192 and took 80,192 before refusing – with 47,424 of them in flight, 5.8× the buffer it was charged against, and nothing left unsent. The socket did not hold that data; the connection did. Sizing an application write from the buffer alone therefore under-counts the first burst by whatever is in flight and over-counts the second, because a peer that stops reading closes the window that let the first burst out.
The requested value and the stored value differ twice: the kernel keeps its own bookkeeping in the same budget, so a value set with SO_SNDBUF reads back doubled, and the global ceiling net.core.wmem_max (212,992 bytes here) clamps the request before the doubling, which is why asking for a mebibyte gets the same buffer as asking for a quarter of it: both come back as 425,984 bytes.
| SO_SNDBUF requested | Stored and reported |
|---|---|
| 4,096 | 8,192 |
| 16,384 | 32,768 |
| 65,536 | 131,072 |
| 262,144 | 425,984 |
| 1,048,576 | 425,984 |
The doubling is worth internalising before reading a log line that says “sndbuf 2,626,560”: that figure is not the room a write has. The probe’s fill loop reached 2,615,232 bytes, and the kernel then reported a queue of 2,582,464 bytes, 95.7% of it never put on the wire, 32,768 already acknowledged into the reader’s buffer, and 2 segments in flight. Four numbers describe one socket, and none of them is the capacity the name suggests.
"""Shared helpers for the write-side probes: percentiles, a pair with chosen buffers, a fill.
Every probe writes one JSON file into ``results/``. The article reads only those files, so a
figure that is not in one of them cannot reach the page, and the file name fixes the order the
page's tables refer to.
The two limits this file keeps apart are the ones the article is about: how many bytes the
socket's own send queue will take (``fill``) and what the peer's advertised window says
(``sendback.window.stats``). A write waits on whichever is smaller, and a table that prints one
number cannot say which one it was.
"""
from __future__ import annotations
import socket
def fill(sock: socket.socket, chunk: int = CHUNK) -> int:
"""Write until the socket refuses once, and report how many bytes it took.
The socket is left non-blocking. The count is what a handler that writes "the response" and
moves on has actually queued: the send buffer plus whatever the peer's window absorbed.
"""
sock.setblocking(False)
sent = 0
while True:
try:
accepted = sock.send(b"R" * chunk)
except BlockingIOError:
break
if not accepted:
break
sent += accepted
return sent
The fill loop is the whole measurement and the whole mistake in one function: it writes until the socket refuses, keeps the sum, and never assumes that a short write is an error. A handler that calls send once and checks the return value for “truthy” has the same information, and most handlers throw it away.
3. Two Limits, One Refusal
The five arms refuse at five different totals, and they do not refuse for the same reason. TCP_INFO describes each socket at the moment the fill loop stops: the queue in bytes, the part of it never put on the wire, the segments in flight, the window the peer last advertised, and the segment size this socket sends.
| Send buffer | In the queue | Never sent | Peer window | Send MSS (writer) |
|---|---|---|---|---|
| default | 2,582,464 | 2,502,272 | 94,848 | 47,424 |
| 4,096 | 47,424 | 0 | 94,848 | 47,424 |
| 16,384 | 47,424 | 0 | 94,848 | 47,424 |
| 65,536 | 163,840 | 83,648 | 94,848 | 47,424 |
| 262,144 | 448,384 | 368,192 | 94,848 | 47,424 |
tcpi_snd_mss from TCP_INFO, read with the other fields at the refusal, on pairs whose reader kept the kernel’s default receive buffer.Two rows are the surprise. With the default buffer the socket refused holding megabytes it had never put on the wire: that is the budget the name promises, and the queue’s figure in table 4 is the accepted total minus what the reader had already acknowledged. With a buffer of 4,096 bytes it refused with nothing unsent at all: the whole queue was one 47,424-byte segment already in flight, 5.8× the buffer it was charged against.
Reading those fields is a getsockopt call, and the offsets are the part that needs a test rather than a comment: a field read at the wrong offset is still a number, and a number that is always zero looks exactly like a measurement. The test that pins the window is behavioural – fill a socket, drain the reader, assert that the window moves – and the module refuses to read a struct shorter than the fields it prints.
from __future__ import annotations
OFFSET_RTO = 8 # tcpi_rto: the retransmission timeout, in microseconds
OFFSET_MSS = 16 # tcpi_snd_mss: the segment size this socket sends
OFFSET_UNAKED = 24 # tcpi_unacked: segments in flight, not bytes
OFFSET_TOTAL_RETRANS = 100 # tcpi_total_retrans: segments resent since the connection opened
OFFSET_NOTSENT = 144 # tcpi_notsent_bytes: written by the app, not yet put on the wire
OFFSET_SND_WND = 228 # tcpi_snd_wnd: the window the peer last advertised
OFFSET_RCV_WND = 232 # tcpi_rcv_wnd: the window this socket advertises
SIZE_WITH_WINDOW = OFFSET_RCV_WND + 4
The practical consequence is a rule about EAGAIN: the exception does not say which limit refused, and the two limits are not cleared by the same event. A writer waiting on its own queue needs an acknowledgement; a writer waiting on the reader’s window needs a window update. The next section measures when each of those actually arrives, and the answer is not the same for both.
4. A Window Update Is Not a Retransmission
Both sockets are given 16 KiB after the handshake, so each reports a receive buffer of 32,768 bytes, and the queue that refused was one segment of the same size: the fill took two, and the second stayed whole in the sender’s queue – 32,768 bytes, nothing unsent, one segment in flight. A buffer that holds exactly one segment is filled by the first one to arrive: the window the reader advertises drops to zero, and the second has nowhere to go. The reader then takes bytes out, and the sender tries a one-byte write every two milliseconds until one succeeds or two seconds pass.
A buffer gets that small in two different ways, and the difference is visible in the connection. Set after the handshake, the 16 KiB shrinks a socket that opened with a 65,536-byte window and agreed a 32,741-byte segment: the first segment to arrive fills the new buffer, the window falls to zero, and the pair is in the state table 5 starts from. Set before listen() and before connect(), the same 16 KiB is what the handshake negotiates from – this host advertises an 8,192-byte segment for a 16 KiB receive buffer, four of which fit – and the pair never reaches a zero window: at the refusal the queue was full and the peer still had 16,384 bytes of window open (table 8). The stall below belongs to the first placement only: a receive buffer shrunk after the handshake to less than the segment the connection had already agreed, so the first segment fills it, the window shuts, and the next segment has nowhere to go. That is a condition of the order the buffers were set in – the change landed on a connection that had announced its window and settled its segment size – and not a property of TCP; the same request made before the handshake produces a pair that never stalls (table 8).
That state is the whole point of this section. A receive buffer that holds several segments does not produce it, and the section ends with the same read measured against the kernel’s default buffer (table 7) and against the other placement (table 8).
| Bytes read | Window after | Writable in 2 s | Resends counted |
|---|---|---|---|
| 0 | 0 | 0 of 5 | 4 |
| 1,024 | 0 | 0 of 5 | 4 |
| 16,384 | 0 | 0 of 5 | 4 |
| 32,768 | 31,872 | 5 of 5 | 1 |
Reading 16,384 bytes – half the receive buffer – left the advertised window at zero, and so did a kilobyte: the reader took data out of its buffer, and the sender was told nothing. A kilobyte at a time, the sender needed 32 reads – the whole buffer – before the first window update arrived. Reading all of it opened the window at once, but at 31,872 bytes, not the full buffer: 896 bytes stay charged to the socket after every byte has been handed to the application, and that gap is why “half a buffer” is not the boundary anyone expects.
So the window came back almost immediately, and the writer did not care. What the writer was waiting for was not the reader’s permission but an acknowledgement for the segment that had been dropped. The timeline below is that arm, five runs, with each field read from the socket as it moved.
| Event | Time after the read | What moved |
|---|---|---|
| the read returns | 0 | the reader’s buffer is empty; the advertised window is still 0 |
| the receiver advertises a window | 0.95 µs | the peer’s window goes from 0 to 31,872 |
| the sender resends the dropped segment | 210.5 ms | the socket’s own count goes from 0 to 1 |
| its acknowledgement empties the queue | 210.5 ms | 896 bytes stay queued, the rest is acknowledged |
| the write is allowed | 210.3 ms | a one-byte send is accepted in 5 of 5 runs |
The gap between the second row and the third is the finding: the wait ended at 1.03× the socket’s own retransmission timeout, with window to spare the whole time and no byte accepted. A window update tells the sender that room exists; it does not tell it to resend what the reader refused. Linux resends on three triggers – three duplicate acknowledgements, a SACK-based recovery, or the retransmission timer – and a window update is none of them. With one segment in flight there are no duplicate acknowledgements to count, so the only trigger left is the timer, and it started when the segment was sent, not when the reader freed space.
The arms that never recovered show the other half of the same mechanism. Their windows stayed at zero, so the timer fired into a shut window: 4 attempts in two seconds, each after a doubled wait (the socket’s backoff reached 3), and not one of them emptied the queue. No arm recorded a single zero-window probe either: the socket kept resending on its retransmission timer instead of asking the reader whether the window had moved.
A tail loss probe is the other candidate for that resend, and this host has one enabled – net.ipv4.tcp_early_retrans reads 3 – but the timing rules it out. A probe is armed at twice the retransmission timeout, and this socket’s timeout was already at the floor this host sets (204 ms against a 200 ms minimum), so the ordinary timer expired at 207.8 ms – partway to a probe’s due time – and the probe never had a turn. The socket counted the same single resend in the arm that recovered and the same doubling series in the arms that did not, which is the retransmission timer’s behaviour rather than a probe’s one-shot attempt.
Working: the three timers behind a stalled write
A retransmission timer is armed when data is sent and stopped when it is acknowledged. Its first value here is the socket’s minimum, which table 6 prints; every expiry without an acknowledgement doubles it, which is the backoff the last paragraph quotes. The timer does not know that the reader has drained its buffer – only an acknowledgement does that – so the fastest a blocked writer can learn about a window that reopened is the next expiry.
The zero-window probe is the other timer, and it belongs to a socket with bytes queued behind a shut window rather than bytes in flight. Both timers double on failure, and neither is a substitute for the other: one asks whether the window has moved, the other resends a segment the peer never took.
The reader’s buffer is what decides all of this. Three configurations, the same one-kilobyte read (table 7): the 16 KiB pair of table 5, the same 16 KiB send buffer against the kernel’s default receive buffer, and the kernel’s default on both ends. Only the first row fails to write inside the two seconds, and it is the only one whose receive buffer holds a single segment.
| Configuration | Receive buffer | Window when the queue filled | Window after 1 KiB | Writable in 2 s |
|---|---|---|---|---|
| 16 KiB, the pair of table 5 | 32,768 | 0 | 0 | 0 of 5 |
| 16 KiB send buffer, default receive buffer | 131,072 | 94,848 | 94,848 | 5 of 5, after 45.7 ms |
| default send and receive buffers | 131,072 | 94,848 | 14,720 | 5 of 5, after 4 µs |
| Buffers set | Window at the handshake | Reader’s MSS | Window at the fill | Writable after 1 KiB |
|---|---|---|---|---|
| after the handshake | 65,536 | 32,741 | 0 | 0 of 5 |
before listen() and connect() | 16,384 | 8,192 | 16,384 | 5 of 5 |
TCP_MAXSEG, read from its socket before the fill; the writer’s TCP_INFO reports 32,768 bytes for the same connection.The segment sizes in tables 4 and 8 come from opposite ends of their connections: table 4 reads the writer’s tcpi_snd_mss after the fill, table 8 the reader’s TCP_MAXSEG before it, on a pair shrunk after the handshake – two sockets, two interfaces, two connection histories, so the figures are not a like-for-like pair.
The two-second cap in this page’s title is a property of a pair shrunk after the handshake, whose receive buffer then holds one segment, not of TCP. The third row of table 7 is the kernel’s default on both ends (131,072 bytes on this host): the window stayed open at 14,720 bytes after the read and the write was accepted in 4 µs, with nothing resent. The second row is the case in between, and it is not free: its window never shut either – 94,848 bytes at the fill and the same after the read – but the write sat for 45.7 ms, because the 16 KiB send buffer was full with one 47,424-byte segment in flight, and the queue only freed when that segment was acknowledged at 45.6 ms. The reader had one segment and nothing behind it to acknowledge promptly, so that acknowledgement left on its delayed timer – the socket counted no retransmission, and this wait has nothing to do with the timer the first row waits on. With the 16 KiB set before the handshake the connection is a different one, and its segment is negotiated small enough that four of them fit (table 8). A server that wants the smaller buffer can have it – it should set it before it listens, and expect the smaller segments that come with it.
For an application, that turns “the client is slow” into “the client reads in the wrong size”. A line-oriented parser that reads a kilobyte at a time from a buffer this small keeps the writer at a zero window for the whole request while making steady progress, because the window only moves once the segment it is holding has been consumed. Reading in buffer-sized chunks – or reading until the read would block – costs nothing and removes the whole class of wait.
5. What a Writable Descriptor Promises
The obvious fix for all of this is to wait for POLLOUT and write when it arrives. The next probe fills a default socket, then runs two arms. In the first the peer reads one chunk and the descriptor is polled; in the second the peer keeps reading until the poll reports writable. Both arms then attempt a one-mebibyte send.
| Arm | Pollout reported | Peer had read | Accepted by the 1 MiB send |
|---|---|---|---|
| one chunk read (silent) | 0 of 5 | 65,536 | 94,848 |
| read until writable | 5 of 5 | 923,712 | 948,480 |
The first row is the finding. The poll reported nothing while the queue was still full, and the send immediately afterwards took 9.0% of the attempt. A server that waits for POLLOUT before writing its tail waits for a condition it does not need; a server that reads the poll as a capacity check gets the opposite error: when the poll does fire, the same send takes 90.5% of a one-mebibyte attempt and leaves the tail with the caller. Writable has never meant “your message fits”.
The delay has a shape: the peer had to read 35.3% of everything the socket had accepted before the poll fired, and the queue still held most of it at that moment (table 9). Linux marks a descriptor writable from sk_stream_is_writeable(), a low-water test against the send buffer rather than a one-byte test, so “writable” and “full” are not opposites. A handler that writes only on POLLOUT and reads it as “the buffer is drained” will find the next write partial and has to loop anyway.
from __future__ import annotations
import errno
import selectors
import socket
import time
def send_exact(sock: socket.socket, data, deadline_s: float,
poll: selectors.BaseSelector | None = None) -> Progress:
"""Send all of ``data``, waiting for writability, and return what the kernel took.
``poll`` lets a caller that already has a selector - an event loop, a test - register its
own descriptor; without one, a selector is created and closed around the call. The socket is
expected to be non-blocking: a blocking socket would park this thread inside ``send`` and
the deadline would only be checked after the whole buffer had gone.
"""
view = memoryview(data).cast("B")
total = len(view)
sent = 0
waits = 0
deadline = time.monotonic() + float(deadline_s)
selector = poll if poll is not None else selectors.DefaultSelector()
owned = poll is None
if owned:
selector.register(sock, selectors.EVENT_WRITE)
try:
while sent < total:
try:
took = sock.send(view[sent:])
except InterruptedError:
continue
except BlockingIOError:
took = None # nothing accepted: the queue is full
if took:
sent += took
continue
if took == 0:
# CPython raises BrokenPipeError here on Linux; the branch is kept so a
# platform that returns zero instead cannot turn the loop into a spin.
raise BrokenPipeError(errno.EPIPE, "the peer accepted no bytes")
left = deadline - time.monotonic()
if left <= 0:
return Progress(sent, total - sent, waits, True, True)
waits += 1
selector.select(left)
finally:
if owned:
selector.close()
return Progress(sent, total - sent, waits, False, False)
The loop above is the whole contract: send what fits, add the count, and when nothing fits, wait on the descriptor for the time that is left rather than for a fixed slice. The deadline is taken once, so a peer that accepts a little at a time cannot stretch the call, and the returned Progress says how much left the process – the number a retry policy needs and the number sendall does not give. The descriptor is permission to call send again, and nothing more.
6. sendall and the Bytes It Forgets
socket.sendall exists to hide exactly the loop above, and it hides the count with it. It returns None on success and raises when it cannot finish; what it does not tell the caller is how much of the buffer the kernel had already taken at the moment it gave up. The probe measures that gap directly: an 8 MiB body, a half-second socket timeout, a peer that never reads, and then the peer drains everything it has.
| Attempt | Outcome | Elapsed | Bytes the peer received | Share of the body |
|---|---|---|---|---|
| sendall | TimeoutError | 502.1 ms | 2,625,600 | 31.3% |
| send_exact | blocked after one wait | 502.2 ms | 2,720,448 | 32.4% |
In every run the exception was TimeoutError and the peer held 31.3% of the body the caller had asked to send; the rest was never written. A retry that sends the whole body again therefore sends the first part twice, and a server that checks the declared length sees a body longer than the header promised – or a stream that no longer parses.
The second row is the same attempt with the loop that keeps the count. It waited once, took 94,848 more bytes than sendall had managed in the same window, and returned the figure. The extra bytes are not a performance win; they are the difference between knowing the count and guessing it.
Python’s own docstrings describe the two methods without softening either. Of send: “Return the number of bytes sent; this may be less than len(data) if the network is busy.” Of sendall: “This calls send() repeatedly until all data is sent.” And then the sentence that turns a timeout into a decision: “If an error occurs, it’s impossible to tell how much data has been sent.” The probe measured that gap rather than assuming it, and table 10 is the measurement.
The four failures that reach a write handler look alike in a log line and call for four different decisions. The module this page ships classifies them, and the table is the classification without the code: the decision, not the exception name, is what the retry policy needs.
| Exception | errno | Same buffer again on this connection? | What it means |
|---|---|---|---|
BlockingIOError | 11 | yes, after a wait | the queue is full and nothing was accepted |
TimeoutError | – | only if the request is idempotent | the deadline passed; part of the buffer may be on the wire |
BrokenPipeError | 32 | no | the peer is gone; a retry needs a new connection |
ConnectionResetError | 104 | no, and the bytes in flight are lost | the peer reset the connection |
classify implements, and section 9 measures the two rows at the bottom, because they are the ones a handler gets wrong.7. The Half Request
The same failure at the HTTP layer is harder to see because the client library owns the socket. The probe runs an http.client connection against a server whose application reads the request line, stops for a second, and only then reads the body. The client’s socket timeout is 500 ms and the body is 4 MiB.
| Attempt | Outcome | Elapsed | Body the server had | Share of the upload |
|---|---|---|---|---|
| POST with a half-second timeout | TimeoutError | 502.0 ms | 2,672,619 | 63.7% |
The client raised TimeoutError in 5 of 5 runs, and the median run left the server with 63.7% of the body it was sending. From the server’s side an upload arrived and stopped; from the client’s side nothing was sent. A retry policy written from the client’s side is written from the wrong side.
The mitigation is not a longer timeout, because the next attempt meets the same application. It is a request the server can recognise as a repeat: an idempotency key in the header, a content hash, or a resumable offset. The client’s timeout is a statement about how long it will wait, and the server’s buffer is a statement about how much it has; the two are not the same fact, and only the second one is durable.
8. Pipes Are Not Sockets
The same code against a pipe gets a different budget and one extra rule. A pipe has a fixed capacity, no window, and a documented atomic unit: a write of at most PIPE_BUF bytes is delivered whole or not at all, and a longer write may be split. Both numbers are read from the kernel in the probe rather than written into the page.
| Medium | Budget | Write that fits | Relative to the pipe |
|---|---|---|---|
| pipe | 65,536 | 65,536 | baseline |
| Unix socket, 131,072 reported | 131,072 | 131,072 | 2.0× |
| TCP, default | 2,626,560 | 2,615,232 | 39.9× |
The pipe’s capacity is 16 pages of 4,096 bytes and a filled pipe refuses even one byte. Its room is released a page at a time, which is the part a logging path meets: with 1,024 bytes read out of a full pipe, a 1-byte write was refused in 5 of 5 runs. Free one whole page, though, and a 4,097-byte write goes in only as far as the page, 4,096 bytes, exactly PIPE_BUF. With two pages free, a 4,096-byte write fits whole, and the 8,192-byte write after it stops at 4,096.
That is why a single os.write of a multi-line log record can interleave with another process’s record at the PIPE_BUF boundary, and why the usual advice is to keep such a record under it or to write it into a file with O_APPEND. A socket has no such boundary: every send is a stream operation with no atomicity to offer at any size, so the same record needs a length prefix no matter how small it is.
from __future__ import annotations
import errno
import os
import select
import time
from .partial import Progress
def write_exact(fd: int, data, deadline_s: float) -> Progress:
"""Write all of ``data`` to a non-blocking pipe, waiting for room, and count the bytes.
The same shape as ``send_exact``: the deadline is absolute, each ``BlockingIOError`` is a
wait on the descriptor rather than a sleep, and a zero return is reported as a closed pipe
instead of being mistaken for progress. A pipe whose read end is closed raises
``BrokenPipeError`` here because Python ignores ``SIGPIPE``; a process that restores the
default disposition is killed instead, which is the other half of the story this package
exists to keep apart.
"""
view = memoryview(data).cast("B")
total = len(view)
sent = 0
waits = 0
deadline = time.monotonic() + float(deadline_s)
while sent < total:
try:
took = os.write(fd, view[sent:])
except InterruptedError:
continue
except BlockingIOError:
took = None # no room: the pipe is full
if took:
sent += took
continue
if took == 0:
raise BrokenPipeError(errno.EPIPE, "the pipe accepted no bytes")
left = deadline - time.monotonic()
if left <= 0:
return Progress(sent, total - sent, waits, True, True)
waits += 1
select.select([], [fd], [], left)
return Progress(sent, total - sent, waits, False, False)
The pipe loop is the socket loop with a different syscall and one extra constant, and it carries the same rule: count what was written, wait on the descriptor, and stop at the deadline rather than after a fixed number of retries.
9. SIGPIPE, EPIPE, and Which Write Fails
A write to a closed reader raises SIGPIPE, and the disposition of that signal decides whether the process dies or the call raises. CPython sets SIGPIPE to SIG_IGN before user code runs – the probe reads it back as 1 – so the write raises instead. A child that restores the default disposition is killed by the signal. The probe runs both.
| Writer | Disposition | Result | Runs |
|---|---|---|---|
| child writing to a closed pipe | SIG_DFL | killed by signal 13, return code -13 | 5 of 5 |
| child writing to a closed pipe | SIG_IGN (Python default) | BrokenPipeError 32 | 5 of 5 |
| socket whose peer has closed | SIG_IGN (Python default) | BrokenPipeError, errno 32 | 5 of 5 |
That table hides a difference the next one measures. A pipe with a closed read end and a socket with a closed peer are not the same event: the pipe has one reader and knows it is gone, while the socket’s kernel tells the peer nothing until the bytes arrive, and the peer’s answer is a reset. The probe writes twice to each and records what the two writes returned.
| Writer | What the peer did | First write | Second write |
|---|---|---|---|
| pipe | closed the read end | BrokenPipeError, errno 32 | BrokenPipeError, errno 32 |
| socket | called close(), which sends a FIN | accepted 4,096 bytes | BrokenPipeError, errno 32 |
| socket | called close() with SO_LINGER zero, which sends a reset | ConnectionResetError, errno 104 | BrokenPipeError, errno 32 |
| socket | called shutdown(SHUT_WR) and kept reading | accepted 4,096 bytes | accepted 4,096 bytes, 8,192 read by the peer |
CLOSE_WAIT before the first write and a closed connection after the reset that the write provoked; the pipe has no state to report.So the first write after a peer’s close can succeed on a socket, and it succeeds for the reason the whole page is about: the bytes fit in the local queue. They reach the peer’s kernel, whose socket is gone, and the reset comes back – which is why the error arrives on the write after that, and why a handler that logged “sent” from the first return value logged something untrue. When the peer’s reset is already in the socket, the same write raises ConnectionResetError instead, and only the one after it is EPIPE. Both mean the connection is over; neither is worth retrying on that connection.
The last row is the case a handler most often misreads in the other direction. A half-close is not a close: the peer said it will send no more, kept its end open for reading, and the connection carried every byte. Treating a FIN as a broken pipe hangs up on a client that was only telling the server its request was complete.
10. asyncio Keeps the Bytes in Your Own Memory
An event loop cannot return EAGAIN to the code that called transport.write, so it does the only other thing it can: it keeps the caller’s buffer in the transport’s own queue and returns. The backpressure appears later, as a buffer that grows and a coroutine that must await drain. The probe writes 16 mebibytes to a transport whose peer never reads, then measures what the transport admitted, what it held, and what the server’s application could read.
| Quantity | Value | Note |
|---|---|---|
| bytes transport.write accepted | 16,777,216 | 5 of 5 runs |
| held in the transport afterwards | 14,152,336 | 84.4% of what was written |
| process RSS growth | 13.9 MiB | 1.03× the buffered size |
| read by the server’s application | 2,624,880 | the rest never left this host’s kernel |
| drain timeouts at the half-second deadline | 5 of 5 | the backpressure signal |
| close() that had not completed a second later | 5 of 5 | the transport waits for bytes that cannot leave |
The transport accepted all of it without an exception and kept 84.4% of the write in this process. The process grew by 13.9 MiB, and the server’s application could read only the kernel’s share, not the caller’s. A handler that writes a response and never awaits drain has moved its backpressure into the heap, where a memory limit rather than a socket limit will end it.
Two waits report the problem, and neither is optional. drain timed out in 5 of 5 runs at the 500 ms deadline, which is the loop saying the buffer is above its high-water mark and has no way down. close then failed to complete within a second in 5 of 5 runs: the transport had 14,152,336 bytes queued and closes only after flushing them, so a shutdown path that awaits wait_closed hangs on a peer that will never read. abort discards the buffer and closes; it is the correct call at shutdown and a data-loss decision everywhere else.
Working: what drain actually waits for
transport.write appends to the transport’s buffer and tries to write to the socket immediately when the buffer was empty. When the buffer passes the high-water mark the protocol is asked to pause, and drain waits until the buffer falls below the low-water mark. The marks are sizes in bytes, not messages, so one large write pauses the protocol on its own and one small write may never pause it.
Because the wait is on the buffer rather than on the socket, a loop that writes in small pieces with a drain after each piece behaves well, while a loop that writes one large buffer and drains once waits for the socket to catch up with the whole thing. Both are correct; only the second has a deadline that a slow peer can miss.
The count lives in the transport, not in the exception: get_write_buffer_size() is the number to read before deciding that a response has been sent, and a drain without a deadline is a wait without a bound, exactly like the socket waits in section 4.
11. Monday Morning
The failure this page describes is not a slow network or a broken client. It is a caller that learned the wrong thing from a short write. The kernel told it how many bytes it took, the exception did not, and the operations that look authoritative disagreed with the count in both directions: the descriptor was silent while 9.0% of an attempt was accepted, and sendall raised after delivering 31.3% of a body.
Three habits cover every case on this page. Keep the count in the handler and log it on every failure, because that number is what tells a reader whether the peer saw a request, a fragment, or nothing – and a loop that adds the return value of each send is the only place it exists. Drain deliberately: a socket’s queue, a pipe’s capacity and an event loop’s buffer are three different places for the same bytes to wait, and each has its own signal that it is full. And put a deadline on every wait, absolute and taken once, including the waits that look instant – a wait without one turns a slow peer into an outage that looks like a hang.
None of the three needs a new library. The module this page ships is 379 lines with 47 tests, and the probes that produced every table are in the appendix, runnable against a host of your own. If your numbers differ, the tables should differ with them – which is the point of printing the conditions first, and of measuring the timer instead of guessing at it.
Frequently asked questions
Is BlockingIOError the same as EAGAIN or EWOULDBLOCK?
Yes. Both errno values are 11 on Linux, and CPython raises BlockingIOError for a non-blocking call that would have blocked. The socket is fine and nothing was sent by the call that raised.
Does a short send mean the connection is broken?
No. A return value below the buffer length means the kernel took that many bytes, and the rest is still the caller’s. In this container a default socket took 2,615,232 bytes in one loop, and a short write after a single read by the peer returned a positive count with no error at all.
Why did POLLOUT stay silent when send would have worked?
Linux marks a descriptor writable from a low-water test against the send buffer, not from a one-byte test, so a queue with room in it can still read as full to the poll. Waiting for the descriptor can therefore cost more than trying the write first.
How much did sendall send before its timeout?
2,625,600 bytes of the 8,388,608-byte body, 31.3%, measured by draining the peer after the exception. The call cannot report it; a loop that keeps the count can.
Is a longer timeout enough for an HTTP upload?
No timeout makes a truncated upload safe by itself. With a 500 ms timeout the server had 2,672,619 of 4,194,304 bytes, 63.7%; the fix is a request the server can recognise as a repeat, not a longer wait.
Does it matter whether the receive buffer is set before or after the connection opens?
It does. Set after the handshake, 16 KiB leaves a buffer that one segment fills, and the writer was refused for the whole 2 s cap; set before listen(), the same value is what the handshake negotiates from – an 8,192-byte segment, four to the buffer – and the same read was writable in every run, with no retransmission (table 8).
Why did the writer wait long after the reader drained its buffer?
Because the thing it was waiting for was not the reader’s buffer. The window update arrived in microseconds, but the segment the reader had refused could only be resent by the sender’s retransmission timer, and the acknowledgement for that resend is what emptied the queue. On this host the timer was 204 ms.
Why does my asyncio service grow when a client stops reading?
Because the transport buffers what the socket refused. Sixteen mebibytes written to a peer that did not read stayed in the process as 14,152,336 bytes; RSS grew by 13.9 MiB, 1.03× that buffer, and 5 of 5 drain calls timed out.
Should I raise SO_SNDBUF to make writes complete?
Only up to the ceiling. The host caps the stored value at 425,984 bytes whatever is requested, and a larger buffer delays the refusal without changing the count that must be kept; the write still ends in EAGAIN, just later, and the memory is held on the writer’s side.
How do I make a graceful shutdown when the peer is not reading?
Bound the drain and then abort. A transport with 14,152,336 bytes queued did not finish closing within a second in 5 of 5 runs, because close waits for the flush; call abort when the deadline passes and accept the loss of the unsent tail.
Appendix: every file this page ran
Seventeen files, printed whole: the five package modules, the probe helper, and the eleven probes that produced the tables. The package’s test files (5 files, 572 lines, 47 tests) are not printed because nothing imports them: probe 09 runs them and records the result, and the module they cover is above in full.
The package’s public surface. sendback/__init__.py
"""The write side of a stream socket: partial sends, a full buffer, and what the caller must do.
Three questions this package answers, each in its own module:
* ``partial.send_exact`` - how much of a buffer the kernel took, and whether the deadline or the
peer ended the attempt. A non-blocking ``send`` returns the bytes it accepted, which can be
fewer than asked for and can be zero with an exception; a loop that treats either as failure
loses data that was already on the wire.
* ``classify.classify`` - which of the write errors is a reason to wait, which is a reason to
give up on this connection, and which is a reason not to retry at all.
* ``window.stats`` - the kernel's own account of the queue: the bytes not yet sent, the segments
in flight, the peer's advertised window and the congestion window, read through ``TCP_INFO``
rather than inferred from timing, plus ``window.queued_bytes`` for the queue's byte count.
"""
from __future__ import annotations
from .classify import Fault, Kind, classify, retryable
from .partial import Progress, send_exact
from .pipes import pipe_capacity, write_exact
from .window import SocketStats, queued_bytes, send_buffer, stats
__all__ = [
"Fault",
"Kind",
"Progress",
"SocketStats",
"classify",
"pipe_capacity",
"queued_bytes",
"retryable",
"send_buffer",
"send_exact",
"stats",
"write_exact",
]
The loop that keeps the count. sendback/partial.py
"""Write a whole buffer to a non-blocking socket, and say exactly how far it got.
A non-blocking ``send`` does not fail when the queue is full: it returns the number of bytes it
accepted, and raises ``BlockingIOError`` only when it accepted none. A loop that treats the
return value as "all or nothing" either loses the tail or spins; a loop that calls ``sendall``
loses the count. This module keeps the count, waits on the descriptor instead of polling it, and
reports the two ways an attempt can end without finishing:
* the deadline passed while the queue stayed full - ``deadline_hit``;
* the peer closed, which a stream socket reports as ``BrokenPipeError`` on the write.
The wait is absolute, not per chunk: the deadline is taken once when the call starts, so a peer
that accepts a little at a time cannot extend the attempt indefinitely.
"""
from __future__ import annotations
import errno
import selectors
import socket
import time
from dataclasses import dataclass
@dataclass(frozen=True)
class Progress:
"""What one ``send_exact`` call achieved."""
sent: int
remaining: int
waits: int
blocked: bool
deadline_hit: bool
@property
def complete(self) -> bool:
"""True when every byte of the buffer was accepted by the kernel."""
return self.remaining == 0
def send_exact(sock: socket.socket, data, deadline_s: float,
poll: selectors.BaseSelector | None = None) -> Progress:
"""Send all of ``data``, waiting for writability, and return what the kernel took.
``poll`` lets a caller that already has a selector - an event loop, a test - register its
own descriptor; without one, a selector is created and closed around the call. The socket is
expected to be non-blocking: a blocking socket would park this thread inside ``send`` and
the deadline would only be checked after the whole buffer had gone.
"""
view = memoryview(data).cast("B")
total = len(view)
sent = 0
waits = 0
deadline = time.monotonic() + float(deadline_s)
selector = poll if poll is not None else selectors.DefaultSelector()
owned = poll is None
if owned:
selector.register(sock, selectors.EVENT_WRITE)
try:
while sent < total:
try:
took = sock.send(view[sent:])
except InterruptedError:
continue
except BlockingIOError:
took = None # nothing accepted: the queue is full
if took:
sent += took
continue
if took == 0:
# CPython raises BrokenPipeError here on Linux; the branch is kept so a
# platform that returns zero instead cannot turn the loop into a spin.
raise BrokenPipeError(errno.EPIPE, "the peer accepted no bytes")
left = deadline - time.monotonic()
if left <= 0:
return Progress(sent, total - sent, waits, True, True)
waits += 1
selector.select(left)
finally:
if owned:
selector.close()
return Progress(sent, total - sent, waits, False, False)
What a write failure means. sendback/classify.py
"""Name the write error, because the retry decision differs for each one.
A stream write fails in four ways that look alike in a log line and behave nothing alike:
``WOULD_BLOCK``
the socket's send queue is at its limit and nothing was accepted; the data is still the
caller's, and waiting is correct.
``TIMEOUT``
the deadline passed while some bytes may already have been accepted and delivered. The
buffer is now partly on the wire, so only a request that can be replayed belongs on a
retry of this connection.
``PIPE``
the peer is gone and the kernel will accept nothing more: ``EPIPE`` from a socket, or from
a pipe whose read end is closed. Python ignores ``SIGPIPE`` at startup, which is why this
arrives as an exception rather than as a signal that ends the process.
``RESET``
the peer answered with a reset; the connection is unusable and unacknowledged data in the
queue is discarded by the kernel.
The distinction that costs production time is ``WOULD_BLOCK`` against ``TIMEOUT``: one is a
reason to wait, the other is a reason to stop, and a handler that catches ``OSError`` and
retries the whole body gets the second one wrong.
"""
from __future__ import annotations
import enum
import errno
from dataclasses import dataclass
class Kind(enum.Enum):
"""What a write failure means for the caller's buffer."""
WOULD_BLOCK = "would_block"
TIMEOUT = "timeout"
PIPE = "pipe"
RESET = "reset"
OTHER = "other"
@dataclass(frozen=True)
class Fault:
"""One classified write failure, with the errno that produced it."""
kind: Kind
errno: int
detail: str
def classify(exc: BaseException) -> Fault:
"""Map the exception a ``send`` or ``os.write`` raised to the decision it implies.
The order matters: ``BrokenPipeError`` and ``ConnectionResetError`` are both ``OSError``
subclasses, and ``BlockingIOError`` is too, so the specific classes are tested before the
errno, and the errno before the catch-all.
"""
number = getattr(exc, "errno", None) or 0
if isinstance(exc, BlockingIOError) or number in (errno.EAGAIN, errno.EWOULDBLOCK):
return Fault(Kind.WOULD_BLOCK, number, "the send buffer is full; nothing was accepted")
if isinstance(exc, BrokenPipeError) or number == errno.EPIPE:
return Fault(Kind.PIPE, number,
"the peer is gone; nothing more can be written to this connection")
if isinstance(exc, ConnectionResetError) or number in (errno.ECONNRESET, errno.ECONNABORTED):
return Fault(Kind.RESET, number,
"the peer reset the connection; unacknowledged bytes are lost")
if isinstance(exc, TimeoutError) or number in (errno.ETIMEDOUT,):
return Fault(Kind.TIMEOUT, number,
"the deadline passed; bytes already accepted stay on the wire")
return Fault(Kind.OTHER, number, f"unclassified write failure: {type(exc).__name__}")
def retryable(fault: Fault, idempotent: bool = False) -> bool:
"""Whether the same buffer may be written again **on this connection**.
Only ``WOULD_BLOCK`` says the buffer is untouched. A timeout may have delivered part of
it, so replaying it is safe only when the other end can absorb a duplicate — the caller
says so with ``idempotent``. A pipe or a reset ends the connection: the next attempt needs
a new one, which is a decision this function does not make.
"""
if fault.kind is Kind.WOULD_BLOCK:
return True
if fault.kind is Kind.TIMEOUT:
return idempotent
return False
TCP_INFO read at named offsets. sendback/window.py
"""The kernel's own account of a socket's write side.
Timing tells you that a write waited; it does not tell you why. ``TCP_INFO`` does: the segment size
this socket sends, the bytes written and not yet put on the wire, the peer's advertised window and
the congestion window. ``TIOCOUTQ`` adds the byte count of the queue itself, which ``TCP_INFO``
does not carry in bytes.
Two fields are easy to mis-size if they are read by name alone, so this module names their unit:
``tcpi_unacked`` is a count of segments in flight, not a byte count - the same socket can hold two
megabytes it has never sent while one or two segments are unacknowledged - and ``tcpi_snd_wnd``
sits at offset 228 in the 6.12 layout, not at the end of the struct's first half.
A wait that does not end is a timer, and the timers have their own fields: ``tcpi_rto`` is the
retransmission timeout the socket would use right now, ``tcpi_probes`` counts zero-window probes
sent and ``tcpi_backoff`` the doublings applied to the probe timer. Reading all four beside the
queue tells a stall caused by a lost segment from one caused by a shut window.
The struct is a C layout, so the offsets are named here and checked against the length the kernel
returns rather than assumed: a kernel older than the field would otherwise be read as a number
taken from whatever follows it.
"""
from __future__ import annotations
import fcntl
import socket
import struct
from dataclasses import dataclass
TCP_INFO = getattr(socket, "TCP_INFO", 11)
# Linux's TIOCOUTQ/SIOCOUTQ: the write queue in bytes, the number ``/proc/net/tcp`` prints in its
# tx_queue column.
TIOCOUTQ = 0x5411
# Byte offsets into struct tcp_info, from include/uapi/linux/tcp.h. The first eight bytes are
# seven 8-bit fields; every field this module reads is a 32-bit integer after them.
OFFSET_RTO = 8 # tcpi_rto: the retransmission timeout, in microseconds
OFFSET_MSS = 16 # tcpi_snd_mss: the segment size this socket sends
OFFSET_UNAKED = 24 # tcpi_unacked: segments in flight, not bytes
OFFSET_CWND = 80 # tcpi_snd_cwnd
OFFSET_TOTAL_RETRANS = 100 # tcpi_total_retrans: segments resent since the connection opened
OFFSET_NOTSENT = 144 # tcpi_notsent_bytes: written by the app, not yet put on the wire
OFFSET_SND_WND = 228 # tcpi_snd_wnd: the window the peer last advertised
OFFSET_RCV_WND = 232 # tcpi_rcv_wnd: the window this socket advertises
SIZE_WITH_WINDOW = OFFSET_RCV_WND + 4
@dataclass(frozen=True)
class SocketStats:
"""One reading of ``TCP_INFO``: the queue, the windows, and the segment size."""
state: int
segments: int
not_sent: int
send_window: int
receive_window: int
cwnd: int
mss: int
rto_ms: int
probes: int
backoff: int
retransmitted: int
def stats(sock: socket.socket) -> SocketStats:
"""Read ``TCP_INFO`` from a TCP socket.
``segments`` counts what is in flight, ``not_sent`` counts bytes still in this process's
queue: the two are different units and adding them would be meaningless.
Raises ``ValueError`` when the kernel returns a struct too short to hold the fields this
package prints - better a named failure than a window read out of the following field.
"""
raw = sock.getsockopt(socket.IPPROTO_TCP, TCP_INFO, 256)
if len(raw) < SIZE_WITH_WINDOW:
raise ValueError(f"TCP_INFO returned {len(raw)} bytes, need {SIZE_WITH_WINDOW}")
state = raw[0]
mss = struct.unpack_from("@I", raw, OFFSET_MSS)[0]
segments = struct.unpack_from("@I", raw, OFFSET_UNAKED)[0]
cwnd = struct.unpack_from("@I", raw, OFFSET_CWND)[0]
not_sent = struct.unpack_from("@I", raw, OFFSET_NOTSENT)[0]
send_window = struct.unpack_from("@I", raw, OFFSET_SND_WND)[0]
receive_window = struct.unpack_from("@I", raw, OFFSET_RCV_WND)[0]
rto_us = struct.unpack_from("@I", raw, OFFSET_RTO)[0]
retransmitted = struct.unpack_from("@I", raw, OFFSET_TOTAL_RETRANS)[0]
return SocketStats(state=state, segments=segments, not_sent=not_sent,
send_window=send_window, receive_window=receive_window,
cwnd=cwnd, mss=mss,
rto_ms=round(rto_us / 1000), probes=raw[3], backoff=raw[4],
retransmitted=retransmitted)
def queued_bytes(sock: socket.socket) -> int:
"""Bytes in this socket's write queue: written by the app, not yet taken by the peer.
The count includes the bytes still waiting to be sent and the bytes in flight, so the
difference against ``stats(sock).not_sent`` is what has left this host's queue without being
acknowledged yet. It is the byte count ``/proc/net/tcp`` prints as tx_queue.
"""
return struct.unpack("i", fcntl.ioctl(sock.fileno(), TIOCOUTQ, struct.pack("i", 0)))[0]
def send_buffer(sock: socket.socket) -> int:
"""The send buffer the kernel reports for this socket, after any clamp it applied.
A value set with ``SO_SNDBUF`` reads back doubled: the kernel counts its own bookkeeping
overhead in the same budget, so it stores twice what was asked for and reports that stored
figure. A default buffer was never asked for and reads back as it is.
"""
return int(sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF))
The same loop against a pipe. sendback/pipes.py
"""``os.write`` on a non-blocking pipe: the same ``EAGAIN``, a much smaller budget.
A pipe is not a socket. It has no window, no congestion control and no ``TCP_INFO``; it has a
fixed capacity (65,536 bytes by default on Linux) and one rule a socket lacks: a write of at
most ``PIPE_BUF`` bytes is atomic, and a longer write may be split. Above that size a partial
write is normal even when the reader is keeping up, which is why a log line built with one
``os.write`` and no count can arrive cut in half.
The capacity is per pipe and readable with ``F_GETPIPE_SZ``; the atomic unit is
``PC_PIPE_BUF`` from ``fpathconf``. Both are read here rather than written down, because a
container can change the first and the second is not the same on every filesystem.
"""
from __future__ import annotations
import errno
import os
import select
import time
from .partial import Progress
# F_GETPIPE_SZ is Linux-specific and absent from Python's fcntl module.
F_GETPIPE_SZ = 1032
def pipe_capacity(fd: int) -> int:
"""The pipe's capacity in bytes, as the kernel holds it for this pipe."""
import fcntl
return int(fcntl.fcntl(fd, F_GETPIPE_SZ))
def atomic_write(fd: int) -> int:
"""The largest write the kernel guarantees to deliver unsplit: ``PC_PIPE_BUF``."""
return int(os.fpathconf(fd, "PC_PIPE_BUF"))
def write_exact(fd: int, data, deadline_s: float) -> Progress:
"""Write all of ``data`` to a non-blocking pipe, waiting for room, and count the bytes.
The same shape as ``send_exact``: the deadline is absolute, each ``BlockingIOError`` is a
wait on the descriptor rather than a sleep, and a zero return is reported as a closed pipe
instead of being mistaken for progress. A pipe whose read end is closed raises
``BrokenPipeError`` here because Python ignores ``SIGPIPE``; a process that restores the
default disposition is killed instead, which is the other half of the story this package
exists to keep apart.
"""
view = memoryview(data).cast("B")
total = len(view)
sent = 0
waits = 0
deadline = time.monotonic() + float(deadline_s)
while sent < total:
try:
took = os.write(fd, view[sent:])
except InterruptedError:
continue
except BlockingIOError:
took = None # no room: the pipe is full
if took:
sent += took
continue
if took == 0:
raise BrokenPipeError(errno.EPIPE, "the pipe accepted no bytes")
left = deadline - time.monotonic()
if left <= 0:
return Progress(sent, total - sent, waits, True, True)
waits += 1
select.select([], [fd], [], left)
return Progress(sent, total - sent, waits, False, False)
Shared helpers: pairs, fill, percentiles. probe.py
"""Shared helpers for the write-side probes: percentiles, a pair with chosen buffers, a fill.
Every probe writes one JSON file into ``results/``. The article reads only those files, so a
figure that is not in one of them cannot reach the page, and the file name fixes the order the
page's tables refer to.
The two limits this file keeps apart are the ones the article is about: how many bytes the
socket's own send queue will take (``fill``) and what the peer's advertised window says
(``sendback.window.stats``). A write waits on whichever is smaller, and a table that prints one
number cannot say which one it was.
"""
from __future__ import annotations
import errno
import json
import os
import pathlib
import platform
import resource
import socket
import statistics
import time
SANDBOX = pathlib.Path(__file__).resolve().parent
HERE = SANDBOX.parent
RESULTS = HERE / "results"
CHUNK = 65536
def percentiles(samples: list[float]) -> dict:
"""The numbers the article quotes, from one list of samples."""
ordered = sorted(samples)
if not ordered:
return {"count": 0}
def pick(fraction: float) -> float:
index = min(len(ordered) - 1, max(0, int(round(fraction * (len(ordered) - 1)))))
return ordered[index]
return {
"count": len(ordered),
"min": ordered[0],
"p50": pick(0.50),
"p90": pick(0.90),
"p95": pick(0.95),
"p99": pick(0.99),
"max": ordered[-1],
"mean": statistics.fmean(ordered),
}
def describe(name: str, samples: list[float]) -> dict:
"""One arm: its name, its samples and the summary the page reads."""
summary = percentiles(samples)
summary["samples"] = len(samples)
return {"name": name, **summary}
def tcp_pair(sndbuf: int = 0, rcvbuf: int = 0,
mode: str = "post") -> tuple[socket.socket, socket.socket]:
"""A connected loopback pair; 0 leaves the kernel's default buffer in place.
``mode`` says when the buffers are set, and the two are not the same connection. The
listen socket's buffers are inherited by the socket ``accept`` returns, and the client's
are fixed before the SYN leaves, so ``"pre"`` sets every buffer before the handshake and
the window and segment size are negotiated from it. ``"post"`` sets them on the connected
sockets: the handshake already happened, and the buffers change underneath a connection
whose window was advertised and whose segment size was agreed without them.
"""
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if mode == "pre":
if sndbuf:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
if rcvbuf:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if mode == "pre" and rcvbuf:
client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf)
client.settimeout(10)
client.connect(listener.getsockname())
server, _ = listener.accept()
listener.close()
if mode != "pre":
if sndbuf:
server.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
if rcvbuf:
client.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rcvbuf)
return client, server
def fill(sock: socket.socket, chunk: int = CHUNK) -> int:
"""Write until the socket refuses once, and report how many bytes it took.
The socket is left non-blocking. The count is what a handler that writes "the response" and
moves on has actually queued: the send buffer plus whatever the peer's window absorbed.
"""
sock.setblocking(False)
sent = 0
while True:
try:
accepted = sock.send(b"R" * chunk)
except BlockingIOError:
break
if not accepted:
break
sent += accepted
return sent
def drain(sock: socket.socket, limit: int = 64 * 1024 * 1024, timeout: float = 2.0) -> int:
"""Read whatever the peer has, until the buffer is empty or the timeout passes."""
sock.settimeout(timeout)
read = 0
while read < limit:
try:
chunk = sock.recv(CHUNK)
except (TimeoutError, socket.timeout):
break
except ConnectionResetError:
break
if not chunk:
break
read += len(chunk)
return read
def write_until_full(fd: int, chunk: int = 65536, limit: int = 8 * 1024 * 1024) -> int:
"""Fill a non-blocking pipe and return how many bytes it took."""
sent = 0
while sent < limit:
try:
sent += os.write(fd, b"P" * min(chunk, limit - sent))
except BlockingIOError:
break
return sent
def save(name: str, payload: dict) -> None:
RESULTS.mkdir(exist_ok=True)
(RESULTS / name).write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n",
encoding="utf-8")
def sysctl(path: str) -> str:
try:
return pathlib.Path(path).read_text().strip()
except OSError:
return ""
def host_facts() -> dict:
"""The conditions every probe ran under, read from the host rather than assumed."""
facts = {
"kernel": platform.release(),
"machine": platform.machine(),
"python": platform.python_version(),
"cpu_count": os.cpu_count(),
"affinity": len(os.sched_getaffinity(0)),
"page_size": os.sysconf("SC_PAGE_SIZE"),
"clock_resolution_ns": time.get_clock_info("monotonic").resolution * 1e9,
"wmem_max": sysctl("/proc/sys/net/core/wmem_max"),
"rmem_max": sysctl("/proc/sys/net/core/rmem_max"),
"tcp_wmem": sysctl("/proc/sys/net/ipv4/tcp_wmem"),
"tcp_rmem": sysctl("/proc/sys/net/ipv4/tcp_rmem"),
"tcp_fin_timeout": sysctl("/proc/sys/net/ipv4/tcp_fin_timeout"),
"rlimit_nofile": list(resource.getrlimit(resource.RLIMIT_NOFILE)),
"eagain": errno.EAGAIN,
"epipe": errno.EPIPE,
"pipe_buf": int(os.fpathconf(1, "PC_PIPE_BUF")),
"tcp_info": int(getattr(socket, "TCP_INFO", 11)),
"sol_socket": socket.SOL_SOCKET,
}
import fcntl
read_fd, write_fd = os.pipe()
try:
facts["pipe_capacity"] = int(fcntl.fcntl(write_fd, 1032))
finally:
os.close(read_fd)
os.close(write_fd)
return facts
Host limits and the buffer clamp. 01_conditions.py
"""Probe 01: the conditions - host limits, the buffer clamp, and the two pipe constants.
Nothing here is a result the article argues from; it is what every other probe ran under. The
clamp matters because a caller who asks for a 1 MiB send buffer gets a smaller one, and a page
that printed the requested value as if it were the working value would be wrong about its own
tables.
"""
from __future__ import annotations
import socket
import probe
def clamped(requested: int) -> dict:
"""Ask for a send buffer and read back what the kernel kept."""
left, right = probe.tcp_pair()
try:
left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, requested)
return {"requested": requested,
"reported": int(left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF))}
finally:
left.close()
right.close()
def main() -> None:
facts = probe.host_facts()
arms = {str(value): clamped(value)
for value in (4096, 16384, 65536, 262144, 1048576)}
left, right = probe.tcp_pair()
try:
defaults = {"sndbuf": int(left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)),
"rcvbuf": int(right.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)),
"tcp_info_bytes": len(left.getsockopt(socket.IPPROTO_TCP,
probe_host_tcp_info(), 256))}
finally:
left.close()
right.close()
payload = {"probe": 1, "facts": facts, "repeats": 5, "clamp": arms, "default": defaults}
probe.save("01_conditions.json", payload)
print("facts", facts["python"], facts["kernel"], "wmem_max", facts["wmem_max"])
print("clamp", {key: value["reported"] for key, value in arms.items()})
print("default", defaults)
def probe_host_tcp_info() -> int:
"""The TCP_INFO option number, read from the module the article ships."""
from sendback.window import TCP_INFO
return TCP_INFO
if __name__ == "__main__":
main()
The five arms behind tables 2 and 4. 02_sndbuf.py
"""Probe 02: how many bytes a non-blocking send takes before it refuses, by send buffer.
The receiver never reads. Five arms ask for five send buffers; the kernel clamps each to its own
limit, reports the stored value, and the fill loop writes 64 KiB chunks until the first refusal.
The count is the answer the article's first table prints: it is not the buffer the caller asked
for, and it is not the buffer the kernel reports either.
At the refusal the probe reads the kernel's account of the same socket: the queue in bytes
(``TIOCOUTQ``), how much of it was never put on the wire (``tcpi_notsent_bytes``), how many
segments were in flight (``tcpi_unacked``, a count, not a byte total), the peer's advertised
window and the segment size this socket sends. Those are the numbers table 4 prints, and they are
why the refusal is not the same limit in every arm.
"""
from __future__ import annotations
import socket
import time
import probe
from sendback.window import queued_bytes, stats
ARMS = (0, 4096, 16384, 65536, 262144)
REPEATS = 5
def one(requested: int) -> dict:
client, server = probe.tcp_pair(sndbuf=requested)
try:
started = time.monotonic()
accepted = probe.fill(server)
elapsed = (time.monotonic() - started) * 1000
reading = stats(server)
queued = queued_bytes(server)
return {"requested": requested,
"reported": int(server.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)),
"accepted": accepted,
"elapsed_ms": elapsed,
"queued": queued,
"not_sent": reading.not_sent,
"in_flight": queued - reading.not_sent,
"segments": reading.segments,
"window": reading.send_window,
"mss": reading.mss,
"rcvbuf": int(client.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF))}
finally:
client.close()
server.close()
def main() -> None:
arms: dict[str, dict] = {}
for requested in ARMS:
runs = [one(requested) for _ in range(REPEATS)]
accepted = probe.describe("accepted", [run["accepted"] for run in runs])
elapsed = probe.describe("elapsed_ms", [run["elapsed_ms"] for run in runs])
arms[str(requested)] = {
"requested": requested,
"reported": runs[0]["reported"],
"accepted": accepted,
"accepted_samples": [run["accepted"] for run in runs],
"elapsed_ms": elapsed,
"queued": probe.describe("queued", [run["queued"] for run in runs]),
"not_sent": probe.describe("not_sent", [run["not_sent"] for run in runs]),
"in_flight": probe.describe("in_flight", [run["in_flight"] for run in runs]),
"segments": probe.describe("segments", [run["segments"] for run in runs]),
"window": probe.describe("window", [run["window"] for run in runs]),
"window_zero": sum(1 for run in runs if run["window"] == 0),
"mss": runs[0]["mss"],
"rcvbuf": runs[0]["rcvbuf"],
}
print(requested, "reported", runs[0]["reported"], "accepted", accepted["p50"],
"queue", arms[str(requested)]["queued"]["p50"],
"not sent", arms[str(requested)]["not_sent"]["p50"],
"in flight", arms[str(requested)]["in_flight"]["p50"],
"window", arms[str(requested)]["window"]["p50"],
"ms", round(elapsed["p50"], 2))
probe.save("02_sndbuf.json", {"probe": 2, "repeats": REPEATS, "arms": arms})
if __name__ == "__main__":
main()
The read that frees nothing. 03_window.py
"""Probe 03: the peer reads, and the socket stays unwritable.
A pair with 16 KiB buffers is filled until the sender refuses. The reader then takes a stated
number of bytes and stops. Four clocks run from that moment:
* the sender's own loop tries a one-byte write every 2 ms and records when one succeeds - what an
application sees;
* a watcher thread reads this socket's transmit queue from ``/proc/net/tcp`` every millisecond and
records when the queue first falls below the value it held at the read;
* the same thread reads ``TCP_INFO`` beside it and records the first millisecond in which the
peer's advertised window is no longer zero, and the first in which the socket reports a
retransmission;
* the reader's own ``TCP_INFO`` records the window it advertises after the read.
Splitting them is the point. The window can reopen long before the writer is allowed: the window
is the reader's permission, and the dropped segment that fills the writer's queue is resent by the
sender's retransmission timer, not by the window update. If the clocks agree, the wait was one
event; if they do not, the article says which timer the writer was actually waiting for.
Two more arms keep the result from being read as a property of TCP. The control arm repeats the
shortest read against a pair whose receive buffer was left at the kernel's default, and the pre
arm sets the same 16 KiB before the handshake instead of after it - the handshake is where the
window is advertised and the segment size agreed, so the two placements are two different
connections and the probe records both.
"""
from __future__ import annotations
import pathlib
import socket
import threading
import time
import probe
from sendback.window import queued_bytes, stats
ARMS = (0, 1024, 16384, 32768)
DEFAULT_READ = 1024
PRE_ARMS = (1024, 32768)
TRICKLE = 1024
REPEATS = 5
CAP_MS = 2000
POLL_MS = 2
def transmit_queue(port: int) -> int | None:
"""This socket's tx_queue, in bytes, from the kernel's table; None if it is not listed."""
hexport = f"{port:04X}"
for line in pathlib.Path("/proc/net/tcp").read_text().splitlines()[1:]:
fields = line.split()
if len(fields) < 5:
continue
if fields[1].endswith(":" + hexport):
return int(fields[4].split(":")[0], 16)
return None
def one(read_bytes: int, sndbuf: int = 16384, rcvbuf: int = 16384,
mode: str = "post") -> dict:
client, server = probe.tcp_pair(sndbuf=sndbuf, rcvbuf=rcvbuf, mode=mode)
port = int(server.getsockname()[1])
try:
# Read before the fill: the window the handshake advertised and the segment size the
# connection agreed, which are what the two buffer placements differ in.
at_connect = stats(server)
peer_mss = int(client.getsockopt(socket.IPPROTO_TCP, socket.TCP_MAXSEG))
sent = probe.fill(server)
before = stats(server)
queued_before = queued_bytes(server)
initial = transmit_queue(port)
watch: dict = {"freed_ms": None, "window_ms": None, "retrans_ms": None, "samples": 0}
started = threading.Event()
def watcher() -> None:
started.set()
begin = time.monotonic()
while (time.monotonic() - begin) * 1000 < CAP_MS:
elapsed = (time.monotonic() - begin) * 1000
queue = transmit_queue(port)
reading = stats(server)
watch["samples"] += 1
if watch["freed_ms"] is None and initial is not None and queue is not None \
and queue < initial:
watch["freed_ms"] = elapsed
if watch["window_ms"] is None and reading.send_window > 0:
watch["window_ms"] = elapsed
if watch["retrans_ms"] is None and reading.retransmitted > 0:
watch["retrans_ms"] = elapsed
if None not in (watch["freed_ms"], watch["window_ms"], watch["retrans_ms"]):
return
time.sleep(0.001)
thread = threading.Thread(target=watcher, daemon=True)
thread.start()
started.wait(1)
client.settimeout(2)
taken = 0
while taken < read_bytes:
chunk = client.recv(min(65536, read_bytes - taken))
if not chunk:
break
taken += len(chunk)
after_read = stats(server)
peer_after_read = stats(client)
began = time.monotonic()
recovered = None
while (time.monotonic() - began) * 1000 < CAP_MS:
try:
server.send(b"x")
recovered = (time.monotonic() - began) * 1000
break
except BlockingIOError:
time.sleep(POLL_MS / 1000)
thread.join(CAP_MS / 1000 + 0.5)
end = stats(server)
return {"sent": sent,
"taken": taken,
"recovered_ms": recovered if recovered is not None else CAP_MS,
"recovered": recovered is not None,
"freed_ms": watch["freed_ms"],
"window_ms": watch["window_ms"],
"retrans_ms": watch["retrans_ms"],
"queue_at_read": initial,
"queued_before": queued_before,
"not_sent_before": before.not_sent,
"segments_before": before.segments,
"window_before": before.send_window,
"window_at_connect": at_connect.send_window,
"peer_advertised_mss": peer_mss,
"mss": before.mss,
"window_after_read": after_read.send_window,
"peer_window_after_read": peer_after_read.receive_window,
"rto_ms": before.rto_ms,
"probes_end": end.probes,
"backoff_end": end.backoff,
"retransmitted_end": end.retransmitted,
"sndbuf": server.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
"rcvbuf": client.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF),
"watcher_samples": watch["samples"],
"mode": mode}
finally:
client.close()
server.close()
def trickle() -> dict:
"""Read a kilobyte at a time and stop at the read that makes the window move.
The buffer is smaller than one segment, so the whole of it is one segment's worth of data and
the sender sits at a zero window. The reads are the only thing that can change that, and this
records how many of them - and how many bytes - the receiver needed before it advertised a
window again.
"""
client, server = probe.tcp_pair(sndbuf=16384, rcvbuf=16384)
try:
probe.fill(server)
client.settimeout(2)
read = 0
opens_at = None
window = 0
while read < 65536:
chunk = client.recv(TRICKLE)
if not chunk:
break
read += len(chunk)
window = stats(server).send_window
if window > 0:
opens_at = read
break
return {"read": read, "opens_at": opens_at, "window": window,
"reads": read // TRICKLE if opens_at else 0}
finally:
client.close()
server.close()
def optional(runs: list[dict], key: str, name: str) -> dict:
values = [run[key] for run in runs if run[key] is not None]
return probe.describe(name, values)
def arm_record(read_bytes: int, label: str, runs: list[dict]) -> dict:
recovered = probe.describe("recovered_ms", [run["recovered_ms"] for run in runs])
return {
"read": read_bytes,
"mode": runs[0]["mode"],
"sent": runs[0]["sent"],
"recovered": recovered,
"writable_runs": sum(1 for run in runs if run["recovered"]),
"recovered_samples": [run["recovered_ms"] for run in runs],
"freed": optional(runs, "freed_ms", "freed_ms"),
"freed_runs": sum(1 for run in runs if run["freed_ms"] is not None),
"window_update": optional(runs, "window_ms", "window_ms"),
"window_update_runs": sum(1 for run in runs if run["window_ms"] is not None),
"retransmission": optional(runs, "retrans_ms", "retrans_ms"),
"retransmission_runs": sum(1 for run in runs if run["retrans_ms"] is not None),
"queue_at_read": runs[0]["queue_at_read"],
"queued_before": runs[0]["queued_before"],
"not_sent_before": runs[0]["not_sent_before"],
"segments_before": runs[0]["segments_before"],
"window_at_connect": runs[0]["window_at_connect"],
"peer_advertised_mss": runs[0]["peer_advertised_mss"],
"mss": runs[0]["mss"],
"window_before": runs[0]["window_before"],
"window_after_read": runs[0]["window_after_read"],
"peer_window_after_read": runs[0]["peer_window_after_read"],
"rto_ms": runs[0]["rto_ms"],
"probes_end": runs[0]["probes_end"],
"backoff_end": runs[0]["backoff_end"],
"retransmitted_end": runs[0]["retransmitted_end"],
"sndbuf": runs[0]["sndbuf"],
"rcvbuf": runs[0]["rcvbuf"],
"watcher_samples": runs[0]["watcher_samples"],
"label": label,
}
def run_arm(read_bytes: int, label: str, **options) -> dict:
runs = [one(read_bytes, **options) for _ in range(REPEATS)]
record = arm_record(read_bytes, label, runs)
print(label, read_bytes, "sent", record["sent"], "queue", record["queue_at_read"],
"not sent", record["not_sent_before"], "segs", record["segments_before"],
"wnd@conn", record["window_at_connect"], "mss", record["mss"],
"adv", record["peer_advertised_mss"],
"| writable", record["writable_runs"], "/", REPEATS, "ms",
record["recovered"]["p50"], "| window", record["window_after_read"],
"| retrans", record["retransmitted_end"])
return record
def main() -> None:
arms: dict[str, dict] = {}
for read_bytes in ARMS:
arms[str(read_bytes)] = run_arm(read_bytes, "16k")
trickles = [trickle() for _ in range(REPEATS)]
arms["trickle"] = {
"read": TRICKLE,
"label": "16k",
"opens_at": probe.describe("opens_at", [run["opens_at"] or 0 for run in trickles]),
"opened_runs": sum(1 for run in trickles if run["opens_at"]),
"reads": trickles[0]["reads"],
"window_at_open": trickles[0]["window"],
}
print("trickle opens at", arms["trickle"]["opens_at"]["p50"], "bytes after",
arms["trickle"]["reads"], "reads; window", arms["trickle"]["window_at_open"])
arms["default_1024"] = run_arm(DEFAULT_READ, "default", sndbuf=0, rcvbuf=0)
arms["control_1024"] = run_arm(DEFAULT_READ, "control", sndbuf=16384, rcvbuf=0)
for read_bytes in PRE_ARMS:
arms[f"pre_{read_bytes}"] = run_arm(read_bytes, "pre", mode="pre")
probe.save("03_window.json", {"probe": 3, "repeats": REPEATS, "cap_ms": CAP_MS,
"poll_ms": POLL_MS, "arms": arms})
if __name__ == "__main__":
main()
What a writable descriptor grants. 04_pollout.py
"""Probe 04: what a writable descriptor grants, and how late ``POLLOUT`` is.
Two arms on a default pair whose reader has stopped:
``silent``
the peer reads one 64 KiB chunk and the descriptor is polled. The poll reports nothing, and
a one-mebibyte send immediately afterwards is accepted anyway - so "not writable" did not
mean "no room".
``wakeup``
the peer keeps reading 64 KiB chunks until the poll reports writable. The probe records how
much had to leave before that happened, what was queued at that moment, and how much of a
one-mebibyte send the socket took then.
The state is read before the send, not after it: the arm is about what the descriptor said of the
socket at the moment it fired, and a send of its own changes the queue.
Together they say what the low-water mark costs: the wakeup arrives after megabytes, not after a
byte, and waiting for it can outlast the work.
"""
from __future__ import annotations
import select
import probe
from sendback.window import queued_bytes, stats
REPEATS = 5
CHUNK = 65536
MAX_ROUNDS = 60
def reading(server) -> dict: # noqa: ANN001 - a socket
"""The socket's queue and window, taken in one go before anything writes to it."""
counted = stats(server)
return {"queued": queued_bytes(server), "not_sent": counted.not_sent,
"window": counted.send_window}
def silent() -> dict:
client, server = probe.tcp_pair(rcvbuf=65536)
try:
sent = probe.fill(server)
client.settimeout(2)
taken = len(client.recv(CHUNK))
poller = select.poll()
poller.register(server, select.POLLOUT)
ready = bool(poller.poll(0))
before = reading(server)
try:
took = server.send(b"R" * 1048576)
except BlockingIOError:
took = -1
return {"sent": sent, "read": taken, "ready": ready, "took": took, **before}
finally:
client.close()
server.close()
def wakeup() -> dict:
client, server = probe.tcp_pair(rcvbuf=65536)
try:
sent = probe.fill(server)
poller = select.poll()
poller.register(server, select.POLLOUT)
read = 0
rounds = 0
ready = False
while rounds < MAX_ROUNDS:
client.settimeout(2)
chunk = client.recv(CHUNK)
if not chunk:
break
read += len(chunk)
rounds += 1
if poller.poll(0):
ready = True
break
before = reading(server)
took = -1
if ready:
try:
took = server.send(b"R" * 1048576)
except BlockingIOError:
took = -1
return {"sent": sent, "read": read, "rounds": rounds, "ready": ready, "took": took,
**before}
finally:
client.close()
server.close()
def arm(name: str, runs: list[dict]) -> dict:
return {
"sent": runs[0]["sent"],
"read": probe.describe("read", [run["read"] for run in runs]),
"read_samples": [run["read"] for run in runs],
"rounds": probe.describe("rounds", [run["rounds"] for run in runs]) if "rounds" in runs[0]
else probe.describe("rounds", []),
"ready_count": sum(1 for run in runs if run["ready"]),
"took": probe.describe("took", [run["took"] for run in runs]),
"took_samples": [run["took"] for run in runs],
"queued": probe.describe(name + "_queued", [run["queued"] for run in runs]),
"not_sent": probe.describe(name + "_not_sent", [run["not_sent"] for run in runs]),
"window": probe.describe(name + "_window", [run["window"] for run in runs]),
}
def main() -> None:
silent_runs = [silent() for _ in range(REPEATS)]
wake_runs = [wakeup() for _ in range(REPEATS)]
payload = {
"probe": 4,
"repeats": REPEATS,
"chunk": CHUNK,
"silent": arm("silent", silent_runs),
"wakeup": arm("wakeup", wake_runs),
}
probe.save("04_pollout.json", payload)
print("silent: ready", payload["silent"]["ready_count"], "/", REPEATS,
"took", payload["silent"]["took"]["p50"], "queued", payload["silent"]["queued"]["p50"])
print("wakeup: read", payload["wakeup"]["read"]["p50"], "rounds",
payload["wakeup"]["rounds"]["p50"], "took", payload["wakeup"]["took"]["p50"],
"queued", payload["wakeup"]["queued"]["p50"])
if __name__ == "__main__":
main()
The bytes sendall forgets. 05_sendall.py
"""Probe 05: what ``sendall`` leaves behind when its timeout fires.
The reader never reads. ``sendall`` gets eight mebibytes and a half-second socket timeout, then
the peer drains everything it has. The two counts - how long the call took, and how much the peer
received - are the finding: the exception does not mean the body was not sent.
The second arm is the same attempt through ``sendback.send_exact``, which reports what the kernel
took and leaves the caller able to decide.
"""
from __future__ import annotations
import time
import probe
from sendback.partial import send_exact
REPEATS = 5
BODY = 8 * 1024 * 1024
TIMEOUT_S = 0.5
def one_sendall() -> dict:
client, server = probe.tcp_pair()
try:
server.settimeout(TIMEOUT_S)
started = time.monotonic()
outcome = "complete"
detail = ""
try:
server.sendall(b"R" * BODY)
except OSError as exc:
outcome = type(exc).__name__
detail = str(exc)
elapsed = (time.monotonic() - started) * 1000
delivered = probe.drain(client, limit=BODY, timeout=2.0)
return {"outcome": outcome, "detail": detail, "elapsed_ms": elapsed,
"delivered": delivered, "body": BODY}
finally:
client.close()
server.close()
def one_exact() -> dict:
client, server = probe.tcp_pair()
try:
server.setblocking(False)
started = time.monotonic()
progress = send_exact(server, b"R" * BODY, TIMEOUT_S)
elapsed = (time.monotonic() - started) * 1000
delivered = probe.drain(client, limit=BODY, timeout=2.0)
return {"elapsed_ms": elapsed, "sent": progress.sent, "remaining": progress.remaining,
"waits": progress.waits, "blocked": progress.blocked,
"delivered": delivered, "body": BODY}
finally:
client.close()
server.close()
def main() -> None:
alls = [one_sendall() for _ in range(REPEATS)]
exact = [one_exact() for _ in range(REPEATS)]
payload = {
"probe": 5,
"repeats": REPEATS,
"body": BODY,
"timeout_s": TIMEOUT_S,
"sendall": {
"outcome": alls[0]["outcome"],
"detail": alls[0]["detail"],
"outcome_count": sum(1 for run in alls if run["outcome"] != "complete"),
"elapsed_ms": probe.describe("elapsed_ms", [run["elapsed_ms"] for run in alls]),
"delivered": probe.describe("delivered", [run["delivered"] for run in alls]),
"delivered_samples": [run["delivered"] for run in alls],
},
"exact": {
"elapsed_ms": probe.describe("elapsed_ms", [run["elapsed_ms"] for run in exact]),
"sent": probe.describe("sent", [run["sent"] for run in exact]),
"sent_samples": [run["sent"] for run in exact],
"waits": probe.describe("waits", [run["waits"] for run in exact]),
"blocked_count": sum(1 for run in exact if run["blocked"]),
"delivered": probe.describe("delivered", [run["delivered"] for run in exact]),
},
}
probe.save("05_sendall.json", payload)
print("sendall", payload["sendall"]["outcome"], "after",
round(payload["sendall"]["elapsed_ms"]["p50"]), "ms, peer had",
payload["sendall"]["delivered"]["p50"])
print("send_exact sent", payload["exact"]["sent"]["p50"], "waits",
payload["exact"]["waits"]["p50"], "delivered", payload["exact"]["delivered"]["p50"])
if __name__ == "__main__":
main()
Three budgets, one loop. 06_pipe.py
"""Probe 06: the same partial write against three different budgets, and the PIPE_BUF boundary.
A pipe, a Unix socket pair and a TCP pair all return ``EAGAIN`` when full, and none of them holds
the same amount. The pipe's capacity and atomic unit are read from the kernel; the Unix socket
pair's send buffer is read back after it is set; the TCP figure comes from probe 02.
The second half is the rule a socket does not have. Three arms free a different amount from a
full pipe and then offer writes one after another:
``two_pages``
two pages freed, then ``PIPE_BUF`` and twice that: the first is accepted whole, the second
only to the page boundary that is left.
``one_page``
one page freed, then a single write one byte above ``PIPE_BUF``: it is cut at exactly
``PIPE_BUF``, which is the partial write a logging path does not expect.
``sub_page``
less than a page freed, then a single one-byte write: it is refused, because a pipe's room
is released a page at a time and a partial page buys nothing.
"""
from __future__ import annotations
import fcntl
import os
import socket
import probe
REPEATS = 5
ARMS = (
("two_pages", 2, ("pipe_buf", "twice")), # free 2 pages, then PIPE_BUF and 2xPIPE_BUF
("one_page", 1, ("pipe_buf_plus_one",)), # free 1 page, then PIPE_BUF + 1
("sub_page", 1 / 4, ("one",)), # free a quarter page, then one byte
)
def fill_pipe(write_fd: int) -> None:
while True:
try:
os.write(write_fd, b"F" * 65536)
except BlockingIOError:
return
def arm(pages: float, sizes: tuple[str, ...]) -> dict:
"""Fill a pipe, free ``pages`` pages, then offer each write in turn."""
read_fd, write_fd = os.pipe()
os.set_blocking(write_fd, False)
os.set_blocking(read_fd, False)
try:
capacity = int(fcntl.fcntl(write_fd, 1032))
atomic = int(os.fpathconf(write_fd, "PC_PIPE_BUF"))
wanted = int(atomic * pages)
fill_pipe(write_fd)
freed = 0
while freed < wanted:
chunk = os.read(read_fd, wanted - freed)
if not chunk:
break
freed += len(chunk)
writes = []
for name in sizes:
size = {"pipe_buf": atomic, "twice": atomic * 2,
"pipe_buf_plus_one": atomic + 1, "one": 1}[name]
try:
took = os.write(write_fd, b"A" * size)
except BlockingIOError:
took = -1
writes.append({"size": size, "took": took})
return {"capacity": capacity, "atomic": atomic, "free": freed, "writes": writes}
finally:
os.close(read_fd)
os.close(write_fd)
def pipe_arm() -> dict:
read_fd, write_fd = os.pipe()
os.set_blocking(write_fd, False)
try:
capacity = int(fcntl.fcntl(write_fd, 1032))
atomic = int(os.fpathconf(write_fd, "PC_PIPE_BUF"))
accepted = probe.write_until_full(write_fd, chunk=65536, limit=1024 * 1024)
return {"capacity": capacity, "atomic": atomic, "accepted": accepted}
finally:
os.close(read_fd)
os.close(write_fd)
def unix_arm() -> dict:
left, right = socket.socketpair()
try:
left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)
accepted = probe.fill(left)
return {"reported": int(left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)),
"accepted": accepted}
finally:
left.close()
right.close()
def main() -> None:
pipes = [pipe_arm() for _ in range(REPEATS)]
runs = {name: [arm(pages, sizes) for _ in range(REPEATS)]
for name, pages, sizes in ARMS}
unix = [unix_arm() for _ in range(REPEATS)]
payload = {
"probe": 6,
"repeats": REPEATS,
"pipe": {
"capacity": pipes[0]["capacity"],
"atomic": pipes[0]["atomic"],
"accepted": probe.describe("accepted", [run["accepted"] for run in pipes]),
"accepted_samples": [run["accepted"] for run in pipes],
},
"arms": {
name: {
"atomic": group[0]["atomic"],
"free": group[0]["free"],
"writes": [
{"size": group[0]["writes"][index]["size"],
"took": probe.describe(
"took", [run["writes"][index]["took"] for run in group])}
for index in range(len(group[0]["writes"]))
],
"refused": [
sum(1 for run in group if run["writes"][index]["took"] == -1)
for index in range(len(group[0]["writes"]))
],
}
for name, group in runs.items()
},
"unix": {
"reported": unix[0]["reported"],
"accepted": probe.describe("accepted", [run["accepted"] for run in unix]),
"accepted_samples": [run["accepted"] for run in unix],
},
}
probe.save("06_pipe.json", payload)
print("pipe capacity", payload["pipe"]["capacity"], "atomic", payload["pipe"]["atomic"],
"accepted", payload["pipe"]["accepted"]["p50"])
for name, record in payload["arms"].items():
print(name, "free", record["free"],
[(write["size"], write["took"]["p50"]) for write in record["writes"]],
"refused", record["refused"])
print("unix reported", payload["unix"]["reported"], "accepted",
payload["unix"]["accepted"]["p50"])
if __name__ == "__main__":
main()
Who dies when the reader is gone. 07_sigpipe.py
"""Probe 07: who dies when a pipe's reader is gone - the process or the call?
Python sets ``SIGPIPE`` to ``SIG_IGN`` before the first line of user code runs, so a write to a
closed pipe arrives as ``BrokenPipeError``. That is a property of the interpreter, not of the
kernel: a child that restores ``SIG_DFL`` is killed by the signal instead, and a service that
shares its pipes with a native helper can see either fate. The probe runs both children and
records the process return code, then checks the socket case in this process.
"""
from __future__ import annotations
import signal
import subprocess
import sys
import probe
REPEATS = 5
DEFAULT_SCRIPT = (
"import os, signal\n"
"read_fd, write_fd = os.pipe()\n"
"os.close(read_fd)\n"
"signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n"
"os.write(write_fd, b'x' * 65536)\n"
"print('survived')\n"
)
IGNORED_SCRIPT = (
"import os\n"
"read_fd, write_fd = os.pipe()\n"
"os.close(read_fd)\n"
"try:\n"
" os.write(write_fd, b'x' * 65536)\n"
"except OSError as exc:\n"
" print(type(exc).__name__, exc.errno)\n"
)
def child(script: str) -> dict:
result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True,
timeout=30)
return {"returncode": result.returncode,
"stdout": result.stdout.strip(),
"stderr": result.stderr.strip()[-120:]}
def socket_case() -> dict:
"""Close the peer, then write until the failure: how many writes got in first."""
client, server = probe.tcp_pair()
try:
client.close()
writes = 0
outcome = {"error": None, "errno": 0, "after": writes}
for _ in range(32):
try:
server.send(b"S" * 65536)
except OSError as exc:
outcome = {"error": type(exc).__name__, "errno": exc.errno, "after": writes}
break
writes += 1
return outcome
finally:
try:
server.close()
except OSError:
pass
def main() -> None:
defaults = [child(DEFAULT_SCRIPT) for _ in range(REPEATS)]
ignored = [child(IGNORED_SCRIPT) for _ in range(REPEATS)]
sockets = [socket_case() for _ in range(REPEATS)]
payload = {
"probe": 7,
"repeats": REPEATS,
"default": {
"returncode": defaults[0]["returncode"],
"killed": sum(1 for run in defaults if run["returncode"] < 0),
"signal": -defaults[0]["returncode"],
"stdout": defaults[0]["stdout"],
},
"ignored": {
"returncode": ignored[0]["returncode"],
"stdout": ignored[0]["stdout"],
"same": sum(1 for run in ignored if run["stdout"] == ignored[0]["stdout"]),
},
"socket": {
"error": sockets[0]["error"],
"errno": sockets[0]["errno"],
"after": sockets[0]["after"],
"same": sum(1 for run in sockets if run["error"] == sockets[0]["error"]),
},
"in_process": {
"sigpipe": int(signal.getsignal(signal.SIGPIPE)),
"sig_ign": int(signal.SIG_IGN),
"sig_dfl": int(signal.SIG_DFL),
},
}
probe.save("07_sigpipe.json", payload)
print("default child rc", payload["default"]["returncode"],
"ignored child", payload["ignored"]["stdout"],
"socket", payload["socket"]["error"], payload["socket"]["errno"])
if __name__ == "__main__":
main()
The buffer kept in process memory. 08_asyncio.py
"""Probe 08: asyncio accepts a write it cannot send, and puts the rest in this process's memory.
A client writes sixteen mebibytes to an ``asyncio`` transport connected to a server that does not
read until the client has given up. ``transport.write`` does not raise ``BlockingIOError`` and does
not return a count: it keeps the caller's buffer in the transport's write queue and returns. The
probe records what the transport admitted, what it was still holding, how much the process's
resident set grew, and what the server's application could read once the client closed.
``drain`` is the only place the backpressure shows, and a timeout there is the wiring's answer
that the peer is not keeping up.
"""
from __future__ import annotations
import asyncio
import pathlib
import socket
import probe
REPEATS = 5
CHUNKS = 16
CHUNK = 1024 * 1024
DRAIN_S = 0.5
def rss_mb() -> float:
"""Current resident set size in mebibytes, from /proc rather than a peak that never falls."""
for line in pathlib.Path("/proc/self/status").read_text().splitlines():
if line.startswith("VmRSS:"):
return int(line.split()[1]) / 1024
return 0.0
async def scenario() -> dict:
state: dict = {"read": 0, "done": asyncio.Event()}
release = asyncio.Event()
async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
await release.wait() # the application is busy: it does not read
while True:
chunk = await reader.read(65536)
if not chunk:
break
state["read"] += len(chunk)
finally:
state["done"].set()
writer.close()
# The listener's receive buffer is pinned so the server's kernel cannot absorb the whole
# write: otherwise autotuning decides the result and the arm is a race, not a measurement.
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
listener.bind(("127.0.0.1", 0))
listener.listen(100)
listener.setblocking(False)
server = await asyncio.start_server(handler, sock=listener)
port = listener.getsockname()[1]
reader, writer = await asyncio.open_connection("127.0.0.1", port)
await asyncio.sleep(0.05)
transport = writer.transport
before = rss_mb()
admitted = 0
for _ in range(CHUNKS):
transport.write(b"R" * CHUNK)
admitted += CHUNK
buffered = transport.get_write_buffer_size()
after = rss_mb()
outcome = "drained"
try:
await asyncio.wait_for(writer.drain(), DRAIN_S)
except asyncio.TimeoutError:
outcome = "timeout"
writer.close()
closed = "closed"
try:
await asyncio.wait_for(writer.wait_closed(), 1.0)
except asyncio.TimeoutError:
closed = "hung" # the transport waits for a buffer that cannot leave
except OSError:
closed = "error"
transport.abort()
release.set()
try:
await asyncio.wait_for(state["done"].wait(), 5.0)
except asyncio.TimeoutError:
pass
server.close()
await server.wait_closed()
return {"admitted": admitted, "buffered": buffered,
"rss_before_mb": before, "rss_after_mb": after,
"rss_delta_mib": after - before, "drain": outcome, "closed": closed,
"server_read": state["read"]}
def main() -> None:
runs = [asyncio.run(scenario()) for _ in range(REPEATS)]
payload = {
"probe": 8,
"repeats": REPEATS,
"chunks": CHUNKS,
"chunk": CHUNK,
"drain_s": DRAIN_S,
"admitted": probe.describe("admitted", [run["admitted"] for run in runs]),
"buffered": probe.describe("buffered", [run["buffered"] for run in runs]),
"rss_delta_mib": probe.describe("rss_delta_mib", [run["rss_delta_mib"] for run in runs]),
"server_read": probe.describe("server_read", [run["server_read"] for run in runs]),
"server_read_samples": [run["server_read"] for run in runs],
"timeouts": sum(1 for run in runs if run["drain"] == "timeout"),
"close_hung": sum(1 for run in runs if run["closed"] == "hung"),
}
probe.save("08_asyncio.json", payload)
print("admitted", payload["admitted"]["p50"], "buffered", payload["buffered"]["p50"],
"rss +", round(payload["rss_delta_mib"]["p50"], 1), "MiB", "server read",
payload["server_read"]["p50"], "timeouts", payload["timeouts"],
"close hung", payload["close_hung"])
if __name__ == "__main__":
main()
The test run this page cites. 09_tests.py
"""Probe 09: the counts the page prints about its own code, read from the tree.
The article says how many tests ran, how many lines the package is and how many probe files feed
the tables. Those are artefact counts rather than measurements, so they are collected here once
and cross-checked by build.py against the built page.
"""
from __future__ import annotations
import pathlib
import re
import subprocess
import sys
import probe
PACKAGE = probe.HERE / "module" / "sendback"
TESTS = PACKAGE / "tests"
def count_lines(paths: list[pathlib.Path]) -> int:
return sum(len(path.read_text(encoding="utf-8").splitlines()) for path in paths)
def main() -> None:
result = subprocess.run([sys.executable, "-m", "pytest", "sendback/tests", "-q",
"-p", "no:warnings"],
cwd=str(probe.HERE / "module"), capture_output=True, text=True)
tail = (result.stdout + result.stderr).strip().splitlines()
passed = 0
summary = ""
for line in tail:
match = re.search(r"(\d+) passed", line)
if match:
passed = int(match.group(1))
summary = line.strip()
package = sorted(path for path in PACKAGE.glob("*.py"))
tests = sorted(TESTS.glob("*.py"))
probes = sorted((probe.HERE / "sandbox").glob("[0-9][0-9]_*.py"))
payload = {
"probe": 9,
"pytest_rc": result.returncode,
"pytest_passed": passed,
"pytest_tail": summary,
"package_files": len(package),
"package_lines": count_lines(package),
"test_files": len(tests),
"test_lines": count_lines(tests),
"probe_files": len(probes),
"probes": [path.name for path in probes],
}
probe.save("09_tests.json", payload)
print(payload["pytest_tail"], "| package", payload["package_files"],
payload["package_lines"], "| tests", payload["test_files"],
payload["test_lines"], "| probes", payload["probe_files"])
if result.returncode != 0:
raise SystemExit(result.returncode)
if __name__ == "__main__":
main()
The half request. 10_http.py
"""Probe 10: an HTTP client that times out mid-body, and the server that keeps what arrived.
An ``http.client`` connection uploads four mebibytes to a server whose application reads the
request line and then stops. The client's socket timeout is half a second. The exception says
"timed out"; the server's count says how much of the body was already in its socket. That gap is
what a retry policy has to reason about, because the server has seen a truncated upload whether
or not the client considers the request sent.
"""
from __future__ import annotations
import http.client
import socket
import threading
import time
import probe
REPEATS = 5
BODY = 4 * 1024 * 1024
TIMEOUT_S = 0.5
STALL_S = 1.0
def one() -> dict:
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
port = listener.getsockname()[1]
result: dict = {"header": 0, "body": 0, "error": None}
def server() -> None:
try:
conn, _ = listener.accept()
except OSError:
return
try:
conn.settimeout(2.0)
head = b""
while b"\r\n\r\n" not in head:
chunk = conn.recv(65536)
if not chunk:
break
head += chunk
end = head.find(b"\r\n\r\n") + 4
result["header"] = end
result["body"] = len(head) - end
time.sleep(STALL_S) # the application has stopped reading
conn.settimeout(1.0)
while True:
try:
chunk = conn.recv(65536)
except (TimeoutError, socket.timeout):
break
if not chunk:
break
result["body"] += len(chunk)
finally:
conn.close()
thread = threading.Thread(target=server, daemon=True)
thread.start()
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=TIMEOUT_S)
started = time.monotonic()
outcome = "complete"
detail = ""
try:
connection.request("POST", "/upload", body=b"B" * BODY,
headers={"Content-Type": "application/octet-stream"})
connection.getresponse()
except OSError as exc:
outcome = type(exc).__name__
detail = str(exc)
elapsed = (time.monotonic() - started) * 1000
try:
connection.close()
except OSError:
pass
thread.join(6)
listener.close()
return {"outcome": outcome, "detail": detail, "elapsed_ms": elapsed,
"header": result["header"], "body": result["body"], "offered": BODY}
def main() -> None:
runs = [one() for _ in range(REPEATS)]
payload = {
"probe": 10,
"repeats": REPEATS,
"body": BODY,
"timeout_s": TIMEOUT_S,
"stall_s": STALL_S,
"outcome": runs[0]["outcome"],
"detail": runs[0]["detail"],
"outcome_count": sum(1 for run in runs if run["outcome"] != "complete"),
"elapsed_ms": probe.describe("elapsed_ms", [run["elapsed_ms"] for run in runs]),
"header": runs[0]["header"],
"received": probe.describe("received", [run["body"] for run in runs]),
"received_samples": [run["body"] for run in runs],
}
probe.save("10_http.json", payload)
print("outcome", payload["outcome"], "after",
round(payload["elapsed_ms"]["p50"]), "ms; server received",
payload["received"]["p50"], "of", BODY)
if __name__ == "__main__":
main()
Which write fails after the reader is gone. 11_epipe.py
"""Probe 11: which write raises EPIPE, and which one is accepted first.
A pipe and a TCP socket are both byte streams with a closed reader, and they report it at
different moments. A pipe has one reader: when its read end is closed, the next ``write`` fails
at once. A socket has a peer that can close its half and leave the connection usable, so the
kernel cannot refuse a write for a close it has not been told about - it accepts the bytes, they
reach the peer's kernel, and the reset that comes back turns the write after that into ``EPIPE``.
Four writers, five runs each: a pipe whose read end is closed, a socket whose peer called
``close()`` (a FIN), the same call with ``SO_LINGER`` zero (a reset), and a peer that called
``shutdown(SHUT_WR)`` and kept reading. The probe records what each write returned, the errno,
and the socket state the kernel reports between the two writes.
"""
from __future__ import annotations
import errno
import os
import socket
import struct
import time
import probe
REPEATS = 5
PAYLOAD = 4096
TCP_INFO = getattr(socket, "TCP_INFO", 11)
STATES = {1: "ESTABLISHED", 4: "FIN_WAIT1", 5: "FIN_WAIT2", 6: "TIME_WAIT", 7: "CLOSE",
8: "CLOSE_WAIT", 9: "LAST_ACK", 10: "LISTEN", 11: "CLOSING"}
SO_LINGER = getattr(socket, "SO_LINGER", 13)
def state(sock: socket.socket) -> str:
"""The connection state the kernel reports for this socket."""
return STATES.get(sock.getsockopt(socket.IPPROTO_TCP, TCP_INFO, 256)[0], "?")
def outcome(call) -> dict:
"""What one write did: the bytes it accepted, or the exception and its errno."""
try:
accepted = call()
return {"result": "accepted", "bytes": accepted, "errno": 0}
except OSError as exc:
return {"result": type(exc).__name__, "bytes": 0, "errno": exc.errno or 0}
def pipe_arm() -> dict:
"""A pipe whose read end is already closed."""
read_fd, write_fd = os.pipe()
os.close(read_fd)
try:
first = outcome(lambda: os.write(write_fd, b"P" * PAYLOAD))
second = outcome(lambda: os.write(write_fd, b"P" * PAYLOAD))
return {"first": first, "second": second, "state_before": "-", "state_between": "-",
"so_error": 0}
finally:
os.close(write_fd)
def socket_arm(how: str) -> dict:
"""A socket whose peer closed, or reset, or half-closed and kept reading."""
client, peer = probe.tcp_pair()
try:
if how == "reset":
peer.setsockopt(socket.SOL_SOCKET, SO_LINGER, struct.pack("ii", 1, 0))
peer.close()
elif how == "half_close":
peer.shutdown(socket.SHUT_WR)
else:
peer.close()
time.sleep(0.02) # let the FIN or RST reach this end
before = state(client)
first = outcome(lambda: client.send(b"S" * PAYLOAD))
time.sleep(0.005) # let the peer's answer reach this end
between = state(client)
so_error = client.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
second = outcome(lambda: client.send(b"S" * PAYLOAD))
delivered = 0
if how == "half_close":
peer.settimeout(1.0)
while delivered < PAYLOAD * 2:
try:
chunk = peer.recv(65536)
except TimeoutError:
break
if not chunk:
break
delivered += len(chunk)
return {"first": first, "second": second, "state_before": before,
"state_between": between, "so_error": so_error, "delivered": delivered}
finally:
client.close()
try:
peer.close()
except OSError:
pass
def summarise(runs: list[dict], key: str) -> dict:
"""One outcome column: the result that every run gave, and the errno behind it."""
results = [run[key]["result"] for run in runs]
errnos = [run[key]["errno"] for run in runs]
same = len(set(results)) == 1
record = {"result": results[0] if same else "mixed", "errnos": sorted(set(errnos)),
"same_runs": len(results) if same else 0, "runs": len(results)}
if record["result"] == "accepted":
record["bytes"] = runs[0][key]["bytes"]
record["bytes_all_same"] = len({run[key]["bytes"] for run in runs}) == 1
return record
def main() -> None:
arms: dict[str, dict] = {}
for name, runner in (("pipe", pipe_arm),
("fin", lambda: socket_arm("fin")),
("reset", lambda: socket_arm("reset")),
("half_close", lambda: socket_arm("half_close"))):
runs = [runner() for _ in range(REPEATS)]
record = {"first": summarise(runs, "first"), "second": summarise(runs, "second"),
"state_before": runs[0]["state_before"],
"state_between": runs[0]["state_between"],
"so_error": runs[0]["so_error"],
"delivered": runs[0].get("delivered", 0)}
arms[name] = record
print(f"{name:11s} first={record['first']} second={record['second']} "
f"state={record['state_before']}->{record['state_between']} "
f"so_error={record['so_error']} delivered={record['delivered']}")
probe.save("11_epipe.json", {"probe": 11, "repeats": REPEATS, "payload": PAYLOAD,
"epipe": errno.EPIPE, "econnreset": errno.ECONNRESET,
"arms": arms})
if __name__ == "__main__":
main()
Take the next step
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
