EAGAIN errno 11: Resource Temporarily Unavailable – The Bytes That Fit

Dark cover headed 'Resource temporarily unavailable': errno 11, 65,536 bytes in a pipe, 180,224 in a socket before the refusal, and 33 passing tests

Updated December 2, 2026 · every figure below was measured on the host described in Section 1, and a table that counts runs says how many it used.

  • errno 11 is a pause, and five different things write it. In this page’s matrix of 20 calls, 9 answered 11: a buffer with no room, nothing to read or accept, a held lock, a spent task count and an expired kernel timeout. One more answered 115 in the same exception class.
  • A pipe holds 65,536 bytes on this host and hands them out by the page. Writing three bytes at a time spent 65,520 – one byte left over in each of the 16 pages. A write larger than a page starts only when a whole page is free; a write of 4,096 bytes or fewer can still take what is left of the last page.
  • A socket is charged per send, not per byte. The same 212,992-byte buffer took 44 sends of 4 KiB and only 278 sends of one byte, because each call is charged a whole kernel bucket and the floor is 768 bytes on this host: one byte is charged 768, and a 4 KiB send 4,864, its payload plus that floor.
  • Readiness is a hint, not a reservation. On this host poll refused this socket at 53,504 bytes charged while direct sends reached 180,224, so a writer that waits for POLLOUT before every send stops with 135,168 bytes of room left.

Fix It First: Ten Changes, Matched to What You Saw

What you sawWhat it usually isFirst move
BlockingIOError: [Errno 11] on a pipe write, with a reader that is merely slowThe pipe’s page budget is spent, not brokenRead the budget with F_GETPIPE_SZ, then either drain faster or raise it with F_SETPIPE_SZ, up to the pipe ceiling
The same number on an AF_UNIX socket send, although SO_SNDBUF looks largeOn this host an AF_UNIX socket charges every send in whole sk_buff buckets, with a floor of 768 bytes, so many small sends spend a large buffer quicklySend page-sized pieces; check TIOCOUTQ before sizing a worker pool
poll said writable and the send still answered 11Readiness is answered before the room is claimed, and another worker may take itTreat 11 as a pause: wait again on the descriptor and retry only what is left
A sender that waits for POLLOUT before every send stalls at a fraction of the bufferThe readiness threshold and the send path disagree on this kernel: it stops calling the socket writable at a quarter of SO_SNDBUFSend until 11 first, and use POLLOUT only after a refusal has been seen
sendall raised, yet the peer received part of the messageOn a non-blocking socket sendall is not all-or-nothing, and it carries no countLoop on send yourself, move your own offset, and retry only the remainder; never the whole buffer
A blocking socket answers 11 even though you never set O_NONBLOCKA kernel-side timeout (SO_SNDTIMEO, SO_RCVTIMEO) expires as EAGAIN, not as a timeout exceptionDecide which timeout you meant: the socket option, or Python’s settimeout
settimeout raises TimeoutError with no byte countPython’s timeout discards the partial progress the kernel reportedUse a non-blocking descriptor and a timeout that carries the count it sent
11 from fork or a new threadRLIMIT_NPROC: a count of the uid’s tasks, threads included, compared with the limitCount the uid’s tasks and compare with the limit before blaming memory
11 from flock with LOCK_NBAnother process holds the lock; nothing is wrong with the fileRetry with a backoff, or wait on a descriptor rather than spinning on the call
A reader loop that burns a core while the peer is idle11 used as a loop condition instead of a pauseWait in poll; after the event, read until 11 again
Table 1: ten symptoms and the shortest reliable move for each, as measured on the host of Section 1. The per-call charge and the readiness threshold are that kernel’s accounting, not a constant of the interface; the move in each row is what travels, and the section behind it measures the figure.

1. What This Page Measures

Everything below comes from one machine: Linux 6.12.118-guest-1.2, x86_64, 2 CPUs, 1,487 MiB of RAM, running Python 3.12.16 as uid 1000. The system page size is 4,096 bytes, and the numbers that decide an EAGAIN were read before any arm ran: a default pipe reports 65,536 bytes and the kernel’s pipe ceiling is 1,048,576 bytes; net.core.wmem_default is 212,992, which is what a fresh socketpair reports as SO_SNDBUF; RLIMIT_NOFILE is 1,024 and RLIMIT_NPROC is 256.

The matrix in Section 2 runs each arm in its own interpreter, five times, and the parent reads one JSON line per run: a limit lowered by one arm cannot reach the next. The budget sections build their own pipes and socketpairs, each five times, and record what the kernel charged as well as what it accepted. Nothing in this page was measured through a mock: the pipe is a pipe and the refusal is the kernel’s. The probes themselves are printed in Appendix B, so the runs can be repeated on another host rather than taken on trust.

One method note matters for the socket numbers, and for how far they travel. SO_SNDBUF is not the number of bytes that will fit: the kernel doubles a value you set, and it charges each send call for the bucket it allocates rather than for the payload. Section 4 measures the gap instead of assuming it, which is why the same buffer appears as 212,992 reported and 214,016 charged. The size of that gap belongs to this kernel: it follows the socket’s sk_buff accounting and the net.core.wmem_default and SO_SNDBUF settings in force. Another kernel version or a tuned host will produce a different charge and a different readiness threshold. What travels is the shape – a charge per call, a budget read from the descriptor, a threshold that is conservative rather than exact – and the pages below name the host wherever a figure is its measure rather than the interface’s rule.

QuestionMeasured hereHow
How many bytes a pipe holdsYesA non-blocking write loop fills a fresh pipe in each of the five runs
Whether the chunk size changes thatYesThe same fill with 1-, 2-, 3-, 100-, 4 KiB and 64 KiB writes
What a write finds when a page is free and when it is notYesEight fill levels against an 8 KiB write, three against 4 KiB, and six small writes into the last page, with poll asked before each
What a pipe size change is allowed to beYesFour sizes requested, refused with EPERM above the ceiling
How much an AF_UNIX socket takes, by send sizeYesThree chunk sizes against three send buffers
Where AF_UNIX readiness stops saying writableYesPage-by-page sends until poll refuses, then direct sends to the refusal
How TCP differs at both endsYesA pinned send buffer, a peer that never reads, then a peer that reads
What a timeout answers, and what it hidesYesFour timeouts: SO_SNDTIMEO, SO_RCVTIMEO, Python’s settimeout, and a blocking write
What level and edge-triggered readiness reportYesOne 8 KiB write, one 4 KiB read, then poll and epoll asked again
What a full accept queue tells the clientYesFour concurrent connects against four backlog sizes
UDP, TLS and io_uring refusalsNoOnly stream sockets were measured; the page says so wherever it matters
cgroup memory pressure as a source of 11NoThis host has no cgroup v2 mount, so it is described, not measured
Table 2: twelve questions, ten answered by a run on this host. The two that are not are marked as described wherever they appear.
Is a pipe write atomic, or can it be split?

A write of PIPE_BUF bytes or fewer is atomic by POSIX, and fpathconf reports PIPE_BUF as 4,096 on this host. Above that, a blocking write may be split. This page measured the non-blocking case instead: a request larger than a page comes back in whole pages, a request of 4,096 bytes or fewer comes back whole or is refused whole, and either is refused with 11 when no page is free. A caller that writes more than a page must still advance its offset by the count it was given (Section 3).

2. One Number, Twenty Calls

The matrix is the argument in one place: 20 arms, five repeats each, 100 runs, and every arm answered the same way in all five. 9 answered errno 11, 1 answered 115, 1 answered 32 and 1 raised TimeoutError; 8 raised nothing, and what they returned is the trap in Section 7: three answered None, two answered b'', one answered '' and two answered a count.

ArmWhat was arrangedWhat came backRunsWhat the caller learns
pipe_full_writeA pipe filled to its budget, then one 4 KiB writeBlockingIOError, 115/5the buffer has no page to give
pipe_empty_readA non-blocking read on a pipe with nothing in itBlockingIOError, 115/5nothing has arrived yet
pipe_oversize_write65,537 bytes into an empty 65,536-byte pipeok5/565,536 of the 65,537 went in; the last byte had no page
unix_recv_emptyA non-blocking recv on an empty socketpairBlockingIOError, 115/5nothing has arrived yet
unix_recv_dontwaitThe same recv with MSG_DONTWAITBlockingIOError, 115/5the flag and the mode agree
unix_send_when_fullA 4 KiB send loop on a socketpair whose peer never readsBlockingIOError, 115/5the send side is charged to its limit
accept_emptyA non-blocking accept with no connection waitingBlockingIOError, 115/5no handshake has completed
connect_in_progressA non-blocking connect to a listening portBlockingIOError, 1155/5the handshake is not finished
flock_contendedflock LOCK_EX|LOCK_NB on a file another process holdsBlockingIOError, 115/5the lock is held elsewhere
fork_at_nprocfork with RLIMIT_NPROC set to the uid’s task countBlockingIOError, 115/5the task count is spent
socket_send_timeoutA blocking socket with SO_SNDTIMEO 50 ms, filledBlockingIOError, 115/5the kernel timeout expired
python_settimeoutThe same fill with socket.settimeout(0.05)TimeoutError5/5Python’s own timeout expired
send_after_shutdownsend after shutdown(SHUT_WR)BrokenPipeError, 325/5the pipe is closed, not busy
read_at_eofread on a pipe whose writer closedok5/5the end of the stream
send_zero_bytessend of a zero-length bufferok5/5nothing was asked for
fileio_read_emptyio.FileIO.read on an empty non-blocking pipeok5/5no bytes, no exception
buffered_read_emptyBufferedReader.read on the same pipeok5/5no bytes, no exception
buffered_read1_emptyBufferedReader.read1 on the same pipeok5/5an empty bytes object
makefile_read_emptysocket.makefile(‘rb’).read on an empty socketok5/5no bytes, no exception
textio_read_emptyTextIOWrapper.read on an empty non-blocking pipeok5/5an empty string, not None
Table 3: 20 calls and the same answer five times each. Where the arm raised nothing the answer is shown as ok; the empty answers are described in the text.

Three results in that table are easy to misread. connect answered 115, not 11, and Python raised the same BlockingIOError class: the number is the only thing that tells a connection in progress from a buffer with no room. send after shutdown(SHUT_WR) answered 32: a closed peer is a failure, not a pause, and a retry loop that treats every refusal alike will retry it forever. And five reads answered nothing at all: FileIO.read and BufferedReader.read returned None, os.read at end of file and read1 returned b'', and a text-mode file object’s read() returned an empty string – three different empty answers for the same idle pipe, which is the trap in Section 7. read1 is the worst of them: it answers b'' both when nothing has arrived and at end of file, so only a read() that is allowed to block tells the two apart.

The helper below is all the matrix needed: call, catch, record the type and the number. It is printed as it ran, so every answer in the table above was recorded by this code rather than copied from a summary of it.

"""Helpers shared by the probes: read what the kernel reports, and record it.

Every probe writes one JSON file under results/ with the shape

    {"probe": "...", "when": "...", "repeats": 5,
     "arms": [{"label": ..., "runs": [...], "summary": {...}}],
     "notes": {...}}

so a number that reaches the article can be traced to the run that wrote it.
"""


def outcome(exc: BaseException | None = None, value=None) -> dict:
    if exc is None:
        return {"outcome": "ok", "type": None, "errno": None, "message": "",
                "value": value}
    return {"outcome": "error", "type": type(exc).__name__,
            "errno": getattr(exc, "errno", None), "message": str(exc), "value": value}


def try_call(fn, *args, **kwargs) -> dict:
    try:
        return outcome(None, fn(*args, **kwargs))
    except BaseException as exc:  # noqa: BLE001 - the answer is the record
        return outcome(exc)
python3 -c "import fcntl, os; r, w = os.pipe(); print(fcntl.fcntl(w, 1032))"

That one-liner is the cheapest question to ask of any pipe: the budget is a number the kernel will hand over without filling anything. On this host it prints 65,536, and Section 3 shows what that number means when a writer spends it.

3. The Pipe Counts Pages

A pipe’s budget is not a guess. F_GETPIPE_SZ reports 65,536 bytes, and a non-blocking writer that keeps asking for 4 KiB receives exactly that much before the kernel answers 11: 16 pages of 4,096 bytes, in 16 calls. The number is stable across five runs, and it is the same number the shell one-liner in Section 2 printed.

The interesting part is what changes when the chunk size does. The table below is the same pipe, the same five repeats, and six write sizes. A page is spent whole: a three-byte write needs a page, and the byte that is left in the page cannot be used by the next three-byte write. The arithmetic closes exactly – 16 pages of 4,096 bytes are 65,536 bytes, and 16 pages holding 1,365 three-byte writes each are 65,520 bytes.

Write sizeBytes writtenCallsLeft over in each page
1 byte65,53665,536none
2 bytes65,53632,768none
3 bytes65,52021,8401 byte
100 bytes64,00064096 bytes
4 KiB65,53616none
64 KiB65,5361none
Table 4: one pipe, six write sizes, five runs each. The fill is the same 65,536-byte budget every time; what changes is how much of each page the chunk size can use.

A size the kernel will not honour is refused with a different number. Asking for a 4 KiB or 8 KiB pipe works, and so does the full mebibyte the host allows; asking for two mebibytes is refused with EPERM, which is a permission answer, not a pause, and the pipe keeps the size it had. A retry loop around that call would spin on the wrong errno forever.

Requested pipe sizeGrantedRefusalBudget after the call
4,096 bytes4,096none4,096
8,192 bytes8,192none8,192
1,048,576 bytes1,048,576none1,048,576
2,097,152 bytesno changeEPERM (1)65,536
Table 5: four sizes asked of the same pipe. The ceiling these requests run into is the host’s pipe ceiling, not the pipe’s own budget.

The edge of the budget is where the page rule becomes visible. With 4,095 bytes free a write of 8 KiB is refused outright; with 4,096 free the same call writes 4,096 and returns that count. With 5,000 free it still writes 4,096, not 5,000. For a write larger than a page, poll agrees with the refusal exactly: it calls the pipe writable when a whole page is free and not one byte earlier.

Free roomRequestedWritten11 raisedpoll said writable before the write
65,536 bytes (empty pipe)8 KiB8,192noyes
1 byte8 KiB0yesno
1,000 bytes8 KiB0yesno
4,095 bytes8 KiB0yesno
4,096 bytes8 KiB4,096noyes
5,000 bytes8 KiB4,096noyes
8,192 bytes8 KiB8,192noyes
1,000 bytes3 bytes3nono
1,000 bytes1,000 bytes1,000nono
1,000 bytes1,001 bytes0yesno
1 byte1 byte1nono
1 byte2 bytes0yesno
96 bytes100 bytes0yesno
Table 6: thirteen rows from one pipe. The top half asks for 8 KiB at seven fill levels and changes answer only at a page boundary; the bottom half asks for what is left of the last page, where a request of 4,096 bytes or fewer is stored whole even though poll said no.

Two rules follow, and the bottom half of the table is the second one. First, for a request larger than a page, a partial write is a page multiple: the caller must add the count it was given to its offset and offer the rest, which is exactly what the module in Section 7 does. Second, a request of 4,096 bytes or fewer is placed whole into whatever is left of the last page: at 1,000 bytes of room a 3-byte write and a 1,000-byte write both succeeded while poll was saying no, and a 1,001-byte write was refused whole with 11. The room left in the last page is a budget for a small write, not for a multi-page one.

getconf PIPE_BUF /
cat /proc/sys/fs/pipe-max-size

The kernel’s own page and atomicity numbers are printed by that block: 4,096 bytes for PIPE_BUF and 1,048,576 bytes for the largest pipe an unprivileged process may create. The reading below asks for the budget and then spends it, so the number and the fill can be compared in one place.

import fcntl
import os

PAGE = os.sysconf("SC_PAGE_SIZE")
F_GETPIPE_SZ = 1032


def pipe_budget(fd: int) -> int:
    """The size of the pipe this descriptor belongs to, in bytes."""
    return int(fcntl.fcntl(fd, F_GETPIPE_SZ))


def pipe_pages(fd: int) -> int:
    """How many whole pages a pipe can hand out."""
    return pipe_budget(fd) // PAGE


def fill_pipe(reader: int, writer: int, chunk: int = PAGE) -> dict:
    """Write ``chunk`` bytes until the pipe refuses, and report what went in.

    ``reader`` is accepted so the pair is named at the call site; nothing is read from it. The
    pipe is left full, so the caller must drain it before using it for anything else.
    """
    flags = fcntl.fcntl(writer, fcntl.F_GETFL)
    fcntl.fcntl(writer, fcntl.F_SETFL, flags | os.O_NONBLOCK)
    payload = b"x" * chunk
    written = 0
    calls = 0
    errno_value = None
    while True:
        try:
            written += os.write(writer, payload)
            calls += 1
        except BlockingIOError as exc:
            errno_value = exc.errno
            break
    return {"written": written, "calls": calls, "budget": pipe_budget(writer),
            "pages": written // PAGE, "errno": errno_value}
Is a partial pipe write a bug?

No. A non-blocking pipe write returns the bytes it stored: whole pages when the request is larger than a page, and the whole request when it is 4,096 bytes or fewer and fits in what is left of the last page. A request that does not fit is refused whole with 11. Code that treats a short count as an error will fail on a busy pipe; code that advances its offset and calls again gets the rest.

4. The Socket Counts Sends

An AF_UNIX stream socketpair on this host reports 212,992 bytes of send buffer, and that number is not what it will take. Filling it in 4 KiB sends accepted 180,224 bytes; filling the same socket one byte at a time accepted 278. Same buffer, two very different capacities, and the difference is the size of the call.

Send sizeAcceptedCallsCharged at refusalCharge per call
1 byte278278213,504768
192 bytes53,376278213,504768
193 bytes32,231167213,7601,280
512 bytes85,504167213,7601,280
3,776 bytes185,02449213,2484,352
3,777 bytes166,18844214,0164,864
4 KiB180,22444214,0164,864
Table 7: one socketpair, seven send sizes, five runs each. The charge is what the kernel reports through TIOCOUTQ, divided by the calls that were accepted; 192 bytes is the largest send that still pays the same floor as one byte, and the two rows before 4 KiB put the last bucket’s edge between them.

The charge column is the whole story, but the rule behind it is a bucket with a floor, not a fixed sum added to every payload. The kernel charges each send for the sk_buff it builds – the data buffer rounded up to the next allocation, plus the bookkeeping that travels with it – so the charge steps as the send grows. On this host the smallest unit is 768 bytes, and every send of 192 bytes or fewer is charged exactly that: one byte pays 768, the floor itself rather than the floor plus its byte. Above the floor the charge steps four times, and each step is a flat price for a range of send sizes rather than a sum added to each payload: a send of 193 to 704 bytes is charged 1,280, 705 to 1,728 bytes is charged 2,304, and 1,729 to 3,776 bytes is charged 4,352. The fourth step begins one byte past that last range, at 3,777: from there the charge is 4,864 through a page, which at 4,096 bytes is exactly the payload plus the same floor. Page-aligned sends above it keep that relation: 8,960 for 8 KiB, 17,152 for 16 KiB. Because the charge follows the call rather than the byte, a protocol that writes a status byte at a time spends 278 bytes of a 212,992-byte buffer, while the same buffer carries 180,224 bytes in page-sized writes. Those buckets are this kernel’s, and a host with a different sk_buff layout or buffer tuning will charge a different amount per call; what holds everywhere is that the charge follows the call, not the byte.

The charged total also explains why the buffer can look over its own limit. 44 calls at 4,864 each is 214,016 bytes charged against a 212,992-byte budget: the check that refuses the next call runs before that call’s charge is added, so the last send lands just past the line. Any arithmetic that assumes the reported buffer is the number of bytes that will fit is wrong by the size of one charge.

Send buffer set toReported4 KiB sends acceptedBytes accepted1-byte sends accepted
unset212,99244180,224278
65,536131,07227110,592171
131,072262,14454221,184342
Table 8: three send buffers, the same socketpair. A value set through SO_SNDBUF is reported doubled, and the page rule of the send path applies to each of them.

The second column is worth a second look: setting 65,536 bytes makes the socket report 131,072, because the kernel doubles what it is given. Sizing a pool from the number you set rather than the number reported is a quiet way to be wrong by a factor of two.

python3 -c "import socket; a, b = socket.socketpair(); print(a.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF))"

That block prints 212,992, the same number the table’s first row carries. The reading below is the fill loop the table was built from – from the same probe library as the helper in Section 2 – and it sends until the kernel refuses, then reports what was accepted, how many calls it took, and what the kernel charges.

import fcntl
import socket
import struct

TIOCOUTQ = 0x5411


def queued_bytes(sock: socket.socket) -> int:
    """Bytes the kernel says are still held by this socket's send side."""
    return struct.unpack("i", fcntl.ioctl(sock.fileno(), TIOCOUTQ, b"\0\0\0\0"))[0]


def unix_fill(chunk: int, sndbuf: int | None = None) -> dict:
    """Send ``chunk`` bytes into an AF_UNIX socketpair until the send side refuses."""
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        if sndbuf is not None:
            left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        left.setblocking(False)
        reported = left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        peer = right.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        payload = b"x" * chunk
        total = 0
        calls = 0
        code = None
        while True:
            try:
                total += left.send(payload)
                calls += 1
            except BlockingIOError as exc:
                code = exc.errno
                break
        queued = queued_bytes(left)
        return {"chunk": chunk, "sndbuf_set": sndbuf, "sndbuf_reported": reported,
                "peer_rcvbuf": peer, "accepted": total, "calls": calls, "errno": code,
                "queued": queued, "charge_per_call": (queued / calls) if calls else None}
    finally:
        left.close()
        right.close()

5. TCP: The Buffer You Measured Is Not the Buffer That Fills

TCP is the case where a single number is least trustworthy. A socket that has not connected reports 16,384 bytes of send buffer; the same socket a moment after it connects reports 2,626,560, before a byte has been sent, because the stack sizes the buffer for the connection it now has. A sizing rule that reads the value at startup is reading a different socket from the one that runs.

With the send buffer set to 65,536, which the socket reports as 131,072, a sender whose peer never reads gets 159,744 bytes out before errno 11. Of those, 131,072 is still held by the sender and 28,672 is not: it is already in the peer’s receive queue, whose buffer is 131,072 bytes. Reading the peer afterwards returned all 159,744 bytes, so the two numbers account for every byte the sender was allowed to write.

Send sizeSend bufferAcceptedStill in the senderSent before the refusal
4 KiB131,072159,744131,07228,672
1 byte131,072239,735 (238,344–267,987)141,120coalesced
64 KiB131,072196,608163,867split by the stack
4 KiB2,626,5602,647,1682,618,496the window drains the rest
Table 9: four TCP fills on loopback. The first three pin the send buffer to the same value; the last leaves the stack to size it, and the accepted total follows the buffer it chose.

One-byte sends are where TCP and AF_UNIX part company. The AF_UNIX socket accepted 278 one-byte sends into 212,992 bytes, because each call was charged the 768-byte floor whatever it carried. The TCP socket accepted 239,735 (238,344–267,987) one-byte sends into the same buffer size, because the stack coalesces them before it charges anything. The variation between runs is real and is reported as a range: the number depends on when the sender is descheduled, so a test that asserts one exact count here is asserting the scheduler’s mood.

The fourth row is the practical warning. Left alone, this stack grew the buffer to 2,626,560 bytes and let the sender write 2,647,168 bytes before refusing. A pool sized from the 16,384 bytes a fresh socket reports would under-size itself by two orders of magnitude – or, if it sized itself from the pinned value, would misjudge a socket that had grown.

import fcntl
import socket
import struct

TIOCOUTQ = 0x5411


def queued_bytes(sock: socket.socket) -> int:
    """Bytes the kernel says are still held by this socket's send side."""
    return struct.unpack("i", fcntl.ioctl(sock.fileno(), TIOCOUTQ, b"\0\0\0\0"))[0]


def tcp_fill(chunk: int, sndbuf: int | None = None) -> dict:
    """Fill a loopback TCP send buffer whose peer never reads."""
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(1)
    client = socket.create_connection(server.getsockname())
    conn, _ = server.accept()
    try:
        before = client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        if sndbuf is not None:
            client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        reported = client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        peer = conn.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        client.setblocking(False)
        payload = b"x" * chunk
        total = 0
        calls = 0
        code = None
        while True:
            try:
                total += client.send(payload)
                calls += 1
            except BlockingIOError as exc:
                code = exc.errno
                break
        return {"chunk": chunk, "sndbuf_set": sndbuf, "sndbuf_before": before,
                "sndbuf_reported": reported, "peer_rcvbuf": peer, "accepted": total,
                "calls": calls, "errno": code, "queued": queued_bytes(client)}
    finally:
        client.close()
        conn.close()
        server.close()

Two details of that loop are worth copying. The peer is accepted and then left alone, which is what makes the sender’s buffer fill; and the record includes the peer’s receive buffer, because on loopback the bytes that leave the sender arrive immediately and the two buffers together are what the caller sees.

6. Readiness Is a Hint, Not a Reservation

The first failure of readiness is the one every multi-threaded reader meets. poll reports a readable pipe, another worker reads the one byte that made it readable, and the read that follows answers 11. The probe does exactly that, deterministically, and gets the same answer in all five runs: one event, then an empty poll, then the refusal. Nothing is broken; the answer was true when it was given.

The second failure is quieter, and it costs capacity. An AF_UNIX socket stops being called writable long before its send buffer is full: filling it until poll refuses stops at 53,504 bytes charged against 212,992, while direct sends continue to 180,224. In sends, that is 11 against 44. The threshold sits at 25% of the buffer on this kernel; the send path uses all of it.

DescriptorReadiness stopped atShare of the budgetThe send path reached
Pipe4,096 bytes freeone page of 4,09665,536 bytes
AF_UNIX socket53,504 charged25%180,224 bytes
TCP socket86,016 queued66%159,744 bytes
Table 10: where each descriptor stops being called writable, and how far its send path actually goes. The pipe is exact for a request larger than a page; the two socket thresholds are this kernel’s own and move with the send buffer and the memory settings behind it.

Level-triggered and edge-triggered readiness then differ in what they say after a partial read. With 8 KiB in a pipe and one 4 KiB read taken, poll reports the pipe readable again, because data remains; epoll registered with EPOLLET reports nothing, because no new data arrived. The remaining 4,096 bytes are still there, and a reader that stops at the missing event leaves them until the next write.

Question askedLevel-triggered pollEdge-triggered epoll
First event after an 8 KiB write11
Events after one 4 KiB read10
Bytes still readable without a new eventnot asked4,096
Events after a second 4 KiB readnot asked0
Table 11: the same pipe read under both disciplines. The counts are events reported, so zero means the API stayed silent, not that the pipe is empty.

The cost of getting this wrong is measurable in both directions. A writer that waits for POLLOUT before every send and gives up when the wait times out sent 45,056 bytes in 11 waits, because the poll after the eleventh send never became ready; the same socket, written directly, took 180,224 bytes. The poll-gated writer left 135,168 bytes of room unused. At the other extreme, a reader that spins on the refusal burns a core: more than a million refused reads a second, nearly 200 ms of CPU in the 200 ms window, against a tenth of a millisecond in poll for the same window.

Way of waitingCalls or waits in the windowCPU spentTime to notice a byte
Read in a loop, catch 111,118,120 (1,085,117–1,128,062) per second199.5 (198.4–199.9) msone call
poll with no timeout1 wait0.1 (0.1–0.3) ms125.6 (57.0–130.6) µs after the write
Table 12: the same idle descriptor, two ways. The window is the same in both rows, so the CPU column is the price of the loop, not of the wait.

The rule that follows is small. Use readiness to decide when to look, never how much fits: after an event, read or write until the descriptor answers 11 again, and use the count the call returned to move the offset. That single rule covers the stale event, the conservative threshold and the edge-triggered drain, which is why the module’s readiness helper is used only as a wait.

"""Waiting on a descriptor, and retrying only what is left.

errno 11 is a pause. The three rules this module implements:

  * **pause, do not fail**: a ``BlockingIOError`` means try again later, not that the peer is gone;
  * **wait on the descriptor**: ``readiness`` blocks in ``poll`` instead of calling in a loop, so a
    waiting process costs no CPU;
  * **retry the remainder**: a partial write moves the offset, and the next attempt sends what is
    left - never the whole buffer again.

Readiness is used here only to decide *when to look*, never *how much fits*: on this kernel a
poll-gated AF_UNIX writer stops being told writable at a quarter of the send buffer, four times
earlier than the send path refuses, so the amount is asked of the write call itself.
"""

import select
import time


def readiness(fd: int, mask: int, timeout: float | None = None) -> bool:
    """True when poll says the descriptor is ready for ``mask`` within ``timeout`` seconds."""
    poller = select.poll()
    poller.register(fd, mask)
    milliseconds = -1 if timeout is None else max(0, int(timeout * 1000))
    return bool(poller.poll(milliseconds))


def _deadline(timeout: float | None) -> float | None:
    return None if timeout is None else time.monotonic() + timeout


def _remaining(deadline: float | None) -> float | None:
    return None if deadline is None else max(0.0, deadline - time.monotonic())

7. The Retry That Does Not Spin

Everything measured so far points at one small contract. A refusal is a pause, so the caller waits instead of failing. The wait is a readiness question, asked of the descriptor rather than answered by a loop, so an idle process costs no CPU. And the retry moves by the remainder the kernel reports, so no byte is written twice or dropped. Those three rules are the module below; the rest is bookkeeping around them. The module does not catch InterruptedError: CPython retries a call that a signal interrupted (PEP 475), so EINTR never reaches these loops and 11 is the only refusal they pause for.

The timeout is where most implementations lose the contract. A kernel timeout set with SO_SNDTIMEO answers errno 11 after 180,224 bytes – the error, not a TimeoutError, and no count of what was sent. Python’s settimeout answers TimeoutError instead, after 45,056 bytes, and the exception carries no count either. The module’s own RetryTimeout carries sent, because a caller that retries from zero after a timeout sends the buffer twice.

Way of limiting a sendWhat it raisedBytes sent before itWhat it told the caller
SO_SNDTIMEO 50 msBlockingIOError, 11180,224the errno, and nothing else
SO_RCVTIMEO 50 msBlockingIOError, 11n/a (a receive)the errno after 55.8 (55.7–56.0) ms
settimeout(0.05)TimeoutError45,056no count, no errno
A blocking write into a full pipenothing4,096 after 50.3 (50.2–50.6) msthe wait itself
Table 13: four limits on the same kind of call. Only the last one is what code that never asked for a timeout usually gets.
NameWhat it answersWhat it never does
pipe_budget, pipe_pagesThe size the kernel reports for a pipe, in bytes and in pagesFill the pipe to find out
socket_capacity, queued_bytesThe reported send buffer and what is charged against it nowAssume the reported number is the payload that fits
fill_pipeThe bytes a pipe accepts and the count of callsDrain the pipe it filled
write_all, send_allEvery byte of a payload, retrying only the remainderChange the descriptor’s flags
read_exactlyThe bytes asked for, or fewer at end of fileReturn None for an empty non-blocking pipe
drainEverything readable, ending at the refusalStop at the first event’s worth of bytes
readinessWhether poll reported the mask within the timeoutDecide how much fits
Table 14: seven names, one contract each. The package is printed whole below, its test files in Appendix A, and the probes behind every figure in Appendix B.

nbio/__init__.py – the exports, so a caller imports the contract rather than the internals.

"""Non-blocking I/O with the two mistakes errno 11 invites left out.

``write_all`` waits on the descriptor and retries only the remainder, so a partial write is not
lost. The readers in ``buffers`` report the budget a descriptor really has - the pipe size the
kernel reports, the bytes already charged against a socket - instead of a number guessed from a
buffer size the API doubled.
"""
from nbio.buffers import PAGE, Capacity, fill_pipe, pipe_budget, pipe_pages, queued_bytes, socket_capacity
from nbio.retry import RetryTimeout, drain, read_exactly, readiness, send_all, write_all

__all__ = [
    "PAGE",
    "Capacity",
    "RetryTimeout",
    "drain",
    "fill_pipe",
    "pipe_budget",
    "pipe_pages",
    "queued_bytes",
    "read_exactly",
    "readiness",
    "send_all",
    "socket_capacity",
    "write_all",
]

nbio/buffers.py – the readers of the kernel’s own accounting. Every number it returns is read from the descriptor, never inferred from what a caller thinks it wrote.

"""What a descriptor's buffer really is: a reported number and a charge against it.

The kernel counts a pipe in pages and a socket in charges per send call, so neither is the
number a caller would guess:

  * ``pipe_budget`` asks the kernel for the pipe's size (16 pages on a default pipe of the
    kernel measured here), and a non-blocking write can spend all of it but not one byte of a
    page it has not been given;
  * ``queued_bytes`` reads how much is charged against a socket's send side right now, which for
    an AF_UNIX socket is a whole sk_buff bucket per send call rather than the payload: the
    charge steps with the size of the send and never falls below 768 bytes on the host measured
    here, and a page-sized send there is charged its payload plus that floor. Another kernel or
    different socket memory settings change those figures.

``fill_pipe`` is a diagnostic: it writes until the kernel refuses and reports what went in, so
the caller's own pipe must be drained afterwards.
"""
from __future__ import annotations

import fcntl
import os
import socket
import struct
from dataclasses import dataclass

PAGE = os.sysconf("SC_PAGE_SIZE")
F_GETPIPE_SZ = 1032
TIOCOUTQ = 0x5411


@dataclass(frozen=True)
class Capacity:
    """A send side as the kernel sees it: what it reports, and what is charged against it."""

    reported: int
    queued: int

    @property
    def free(self) -> int:
        """Never negative: a charge can sit just past the reported number when it lands."""
        return max(0, self.reported - self.queued)

    @property
    def share_queued(self) -> float:
        return self.queued / self.reported if self.reported else 0.0


def pipe_budget(fd: int) -> int:
    """The size of the pipe this descriptor belongs to, in bytes."""
    return int(fcntl.fcntl(fd, F_GETPIPE_SZ))


def pipe_pages(fd: int) -> int:
    """How many whole pages a pipe can hand out."""
    return pipe_budget(fd) // PAGE


def queued_bytes(sock: socket.socket) -> int:
    """What the kernel charges against this socket's send side, in its own accounting."""
    return struct.unpack("i", fcntl.ioctl(sock.fileno(), TIOCOUTQ, b"\0\0\0\0"))[0]


def socket_capacity(sock: socket.socket) -> Capacity:
    return Capacity(reported=sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
                    queued=queued_bytes(sock))


def fill_pipe(reader: int, writer: int, chunk: int = PAGE) -> dict:
    """Write ``chunk`` bytes until the pipe refuses, and report what went in.

    ``reader`` is accepted so the pair is named at the call site; nothing is read from it. The
    pipe is left full, so the caller must drain it before using it for anything else.
    """
    flags = fcntl.fcntl(writer, fcntl.F_GETFL)
    fcntl.fcntl(writer, fcntl.F_SETFL, flags | os.O_NONBLOCK)
    payload = b"x" * chunk
    written = 0
    calls = 0
    errno_value = None
    while True:
        try:
            written += os.write(writer, payload)
            calls += 1
        except BlockingIOError as exc:
            errno_value = exc.errno
            break
    return {"written": written, "calls": calls, "budget": pipe_budget(writer),
            "pages": written // PAGE, "errno": errno_value}

nbio/retry.py – the writers and readers. The wait uses poll with the remaining time, and the offset moves by what the kernel returned. Its drain accepts EWOULDBLOCK as well as EAGAIN: on this host the two names are the same number (11), and on a platform where they differ the loop must pause for either.

"""Waiting on a descriptor, and retrying only what is left.

errno 11 is a pause. The three rules this module implements:

  * **pause, do not fail**: a ``BlockingIOError`` means try again later, not that the peer is gone;
  * **wait on the descriptor**: ``readiness`` blocks in ``poll`` instead of calling in a loop, so a
    waiting process costs no CPU;
  * **retry the remainder**: a partial write moves the offset, and the next attempt sends what is
    left - never the whole buffer again.

Readiness is used here only to decide *when to look*, never *how much fits*: on this kernel a
poll-gated AF_UNIX writer stops being told writable at a quarter of the send buffer, four times
earlier than the send path refuses, so the amount is asked of the write call itself.
"""
from __future__ import annotations

import errno
import os
import select
import socket
import time


class RetryTimeout(TimeoutError):
    """A deadline passed while the descriptor was still not ready.

    ``sent`` carries the bytes the caller no longer owns: a timeout is not an all-or-nothing
    answer, and a retry that starts from zero would send them twice.
    """

    def __init__(self, message: str, sent: int = 0, data: bytes = b"") -> None:
        super().__init__(message)
        self.sent = sent
        self.data = data


def readiness(fd: int, mask: int, timeout: float | None = None) -> bool:
    """True when poll says the descriptor is ready for ``mask`` within ``timeout`` seconds."""
    poller = select.poll()
    poller.register(fd, mask)
    milliseconds = -1 if timeout is None else max(0, int(timeout * 1000))
    return bool(poller.poll(milliseconds))


def _deadline(timeout: float | None) -> float | None:
    return None if timeout is None else time.monotonic() + timeout


def _remaining(deadline: float | None) -> float | None:
    return None if deadline is None else max(0.0, deadline - time.monotonic())


def write_all(fd: int, data: bytes, timeout: float | None = None) -> int:
    """Write every byte, waiting for room when the kernel says there is none yet.

    The descriptor must already be non-blocking; this function never changes its flags.
    """
    view = memoryview(data)
    deadline = _deadline(timeout)
    sent = 0
    while sent < len(view):
        try:
            sent += os.write(fd, view[sent:])
        except BlockingIOError:
            wait = _remaining(deadline)
            if wait is not None and wait <= 0:
                raise RetryTimeout(f"only {sent} of {len(view)} bytes sent", sent=sent) from None
            if not readiness(fd, select.POLLOUT, wait):
                raise RetryTimeout(f"only {sent} of {len(view)} bytes sent", sent=sent) from None
    return sent


def send_all(sock: socket.socket, data: bytes, timeout: float | None = None) -> int:
    """``write_all`` for a socket: ``send`` may take less than asked, so the offset moves.

    The socket must already be non-blocking; this function never changes its mode.
    """
    view = memoryview(data)
    deadline = _deadline(timeout)
    sent = 0
    while sent < len(view):
        try:
            sent += sock.send(view[sent:])
        except BlockingIOError:
            wait = _remaining(deadline)
            if wait is not None and wait <= 0:
                raise RetryTimeout(f"only {sent} of {len(view)} bytes sent", sent=sent) from None
            if not readiness(sock.fileno(), select.POLLOUT, wait):
                raise RetryTimeout(f"only {sent} of {len(view)} bytes sent", sent=sent) from None
    return sent


def read_exactly(fd: int, count: int, timeout: float | None = None) -> bytes:
    """Read ``count`` bytes; return fewer only when the peer closed the pipe.

    The descriptor must already be non-blocking; this function never changes its flags.
    """
    deadline = _deadline(timeout)
    pieces: list[bytes] = []
    got = 0
    while got < count:
        try:
            piece = os.read(fd, count - got)
        except BlockingIOError:
            wait = _remaining(deadline)
            if wait is not None and wait <= 0:
                raise RetryTimeout(f"only {got} of {count} bytes read",
                                   data=b"".join(pieces)) from None
            if not readiness(fd, select.POLLIN, wait):
                raise RetryTimeout(f"only {got} of {count} bytes read",
                                   data=b"".join(pieces)) from None
            continue
        if not piece:
            break
        pieces.append(piece)
        got += len(piece)
    return b"".join(pieces)


def drain(fd: int, chunk: int = 65536) -> int:
    """Read until the kernel answers 11: the loop an edge-triggered reader has to run.

    The descriptor must already be non-blocking. End of file ends the drain too: ``os.read``
    answers ``b""`` there, which is not a pause, and reading it again would spin forever.
    """
    total = 0
    while True:
        try:
            piece = os.read(fd, chunk)
        except BlockingIOError as exc:
            if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK):
                raise
            return total
        if not piece:
            return total
        total += len(piece)
"""One line per question this page answers, measured on the host that runs it.

    python3 examples/eagain_demo.py

Nothing here is a mock: the pipe is a pipe, the socketpair is a socketpair, and the numbers are
read from the kernel that served them.
"""
from __future__ import annotations

import os
import select
import socket
import threading

from nbio.buffers import PAGE, fill_pipe, pipe_budget, queued_bytes
from nbio.retry import write_all


def main() -> int:
    reader, writer = os.pipe()
    try:
        budget = pipe_budget(writer)
        print(f"budget: a default pipe reports {budget} bytes, {budget // PAGE} pages")
        # Non-blocking, so write_all does the waiting: the kernel would otherwise block inside
        # one os.write and the retry path this page is about would never run.
        os.set_blocking(writer, False)
        payload = b"p" * 204_800
        received = bytearray()

        def drain() -> None:
            while len(received) < len(payload):
                received.extend(os.read(reader, 8192))

        thread = threading.Thread(target=drain)
        thread.start()
        try:
            sent = write_all(writer, payload, timeout=5)
        finally:
            thread.join(timeout=5)
        print(f"wrote: {sent} bytes through a {budget}-byte pipe, {len(received)} read back")
    finally:
        os.close(reader)
        os.close(writer)

    reader, writer = os.pipe()
    try:
        fill = fill_pipe(reader, writer, chunk=3)
        print(f"pages: a three-byte writer spent {fill['written']} of {fill['budget']} bytes "
              f"in {fill['calls']} calls")
    finally:
        os.close(reader)
        os.close(writer)

    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        reported = left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        pages_ready = 0
        while select.select([], [left], [], 0)[1]:
            left.send(b"x" * PAGE)
            pages_ready += 1
        charged = queued_bytes(left)
        pages_total = pages_ready
        while True:
            try:
                left.send(b"x" * PAGE)
                pages_total += 1
            except BlockingIOError:
                break
        print(f"readiness: {reported} reported, {charged} charged when poll refused at "
              f"{pages_ready} pages, {pages_total} pages accepted in all")
    finally:
        left.close()
        right.close()

    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        poller = select.poll()
        poller.register(left, select.POLLOUT)
        gated = 0
        while poller.poll(0):
            gated += left.send(b"x" * PAGE)
        direct = gated
        while True:
            try:
                direct += left.send(b"x" * PAGE)
            except BlockingIOError:
                break
        print(f"gated: a poll-gated writer sent {gated} bytes, direct sends reached {direct}")
    finally:
        left.close()
        right.close()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Run on this host, the example prints 65,536 bytes for the pipe, 204,800 bytes written through it and 204,800 read back, 65,520 bytes from the three-byte writer in 21,840 calls, a readiness refusal at 11 pages against 44 accepted, and 45,056 bytes from a poll-gated writer against 180,224 from direct sends. The 5 lines are the five claims of this page, measured again on whatever machine runs it.

Why 768 bytes, and can I avoid it?

The 768-byte charge is the smallest sk_buff accounting unit this kernel bills a send call, not a protocol header. Any send of 192 bytes or less is charged exactly that, and above it the charge steps in buckets – 1,280, 2,304, 4,352, then 4,864 from 3,777 bytes up to a page; at a page that is exactly the payload plus the same floor: 4,864 for 4 KiB and 8,960 for 8 KiB. That is why 44 calls of 4 KiB land at 214,016 charged against a 212,992-byte budget. The figure is not portable – it follows the kernel’s sk_buff size and the socket’s memory settings – but the per-call shape is: a caller avoids paying it per call by sending page-sized pieces, and a message format that writes one status byte at a time pays the floor once per byte.

8. What This Page Does Not Cover, and the Checklist

  • UDP. A datagram socket answers a full send queue with ENOBUFS or drops, not with a partial write; none of that was measured here.
  • TLS. A TLS layer re-chunks what it is given, so the byte count a socket returns is not the count a caller’s record boundary expects; the retry contract belongs to the TLS implementation.
  • cgroup pressure. This host has no cgroup v2 mount, so memory pressure as a source of refusals is described, not measured.
  • Namespace and sysctl tuning. net.core.wmem_default and the pipe ceiling were read, not changed; a host with different values will produce different capacities with the same shape.
  • Windows and other kernels. The pipe-page rule and the readiness thresholds are this Linux kernel’s; the contract in Section 7 is portable, the numbers are not.

The checklist below is the page in the order it should be used. Each line is a decision that was measured, and each is cheap to apply before the first refusal rather than after it.

  • Set O_NONBLOCK once, where the descriptor is created, and leave the flag alone: the module never changes it, and code that toggles it races with every other user of the fd.
  • When a call answers 11, treat it as a pause: wait on the descriptor with a deadline, and only then call again.
  • Move the offset by the count the call returned. A pipe write larger than a page returns a page multiple; a request of 4,096 bytes or fewer is stored whole or refused whole; a socket send can take less than asked.
  • Send page-sized pieces on AF_UNIX. The charge is per call, so a status-byte protocol spends a 212,992-byte buffer on 278 bytes.
  • Read F_GETPIPE_SZ or TIOCOUTQ before sizing a pool from a buffer, and expect a value set through SO_SNDBUF to be reported doubled.
  • With edge-triggered readiness, read until the descriptor answers 11. An event is not a promise that one read empties it.
  • Distinguish None, '', b'' and 11: the first three come from file objects that never raise, and 11 is the only one that is a pause. None is a raw or buffered read with nothing yet; '' is a text mode read with nothing yet or at the end; b'' is the end from read(), while read1 answers it in both cases.

Three sibling runbooks cover the refusals this page does not: errno 12, where a mapping ceiling and three limits answer with one number; errno 9, where three families of bug arrive as a bad descriptor; and errno 28, where the space a deleted file still holds is the space you cannot use. Each has the same shape: one number, several writers, and a measurement that tells them apart.

None of this needs a new library. It needs one number read instead of guessed, one pause instead of a failure, and one offset that moves with the remainder. The 20 calls in Section 2 are the evidence that the same number arrives from five different situations; the tables are the evidence that the amount that fits is a budget you can read. The rest is a retry that does not spin.

One failure per issue, with the probe behind it: Zero-Crash Python, free.

TechBobby Engineering writes runbooks from failures it has seen. The package is printed in Section 7, its 33 tests in Appendix A, and every probe that produced a figure in Appendix B, so each number on this page can be re-run rather than taken on trust. The host that produced them is described in Section 1, and a table that counts runs says how many each row used.

Questions This Page Answers

What does errno 11 actually mean?

Resource temporarily unavailable: the call could not proceed now, and retrying later is expected to work. This page measured it from five situations – a pipe with no page free or a socket send side charged to its limit, nothing to read or accept, a held flock, a task count at RLIMIT_NPROC, and an expired SO_SNDTIMEO. The right response is a pause: wait on the descriptor, then retry the remainder.

My pipe write failed with errno 11 although the pipe should be empty. Why?

A pipe spends whole pages. With 4,095 bytes free an 8 KiB write is refused, because a page is not free; with 4,096 bytes free the same call writes 4,096 and returns it, and with 8,192 bytes free it writes all 8,192. A request of 4,096 bytes or fewer is different: it is stored whole in what is left of the last page, so it can succeed with 1,000 bytes of room while poll says no. Read F_GETPIPE_SZ for the budget and expect a refusal for a multi-page request whenever a whole page is not free.

How many bytes fit in a socket before EAGAIN?

It depends on the send size, not only the buffer. The same 212,992-byte AF_UNIX buffer took 180,224 bytes in 4 KiB sends and only 278 bytes in one-byte sends, because on this host each call is charged a whole sk_buff bucket: one byte paid the 768-byte floor, and a 4 KiB send paid 4,864, its payload plus the same floor.

Why does SO_SNDBUF not match the bytes that fit?

Three reasons, all measured: the kernel reports a value you set doubled; on this host each send is charged in a bucket with a 768-byte floor, so a 4 KiB send pays its payload plus that floor while a one-byte send pays the floor alone; and the check that refuses a call runs before that call’s charge is added, so the last send lands just past the reported line – 214,016 charged against 212,992.

Why did poll say writable and the send still return 11?

Readiness is a hint, not a reservation. It was true when it was given; another worker can take the room before the send arrives. Treat 11 as a pause and wait again rather than treating POLLOUT as permission to send a fixed count.

Why does my poll-gated sender stall with room left in the buffer?

The readiness threshold and the send path disagree on this kernel. AF_UNIX stops being called writable at 53,504 charged, a quarter of the buffer, while sends continue to 180,224; a writer that waits before every send sent 45,056 bytes and left 135,168 unused. Send until 11 first; wait only after a refusal.

Is sendall atomic on a non-blocking socket?

No. It can queue part of the buffer and then raise BlockingIOError, and the exception carries no count of what it queued, so a handler that retries the whole buffer sends some bytes twice and a handler that treats the exception as ‘nothing was sent’ loses the rest. Send the pieces yourself with send() and move your offset by each return.

Why does a blocking socket raise errno 11 when I never set O_NONBLOCK?

A kernel timeout does it. With SO_SNDTIMEO set, a full socket answered 11 after 180,224 bytes, and SO_RCVTIMEO on an empty socket answered it after 55.8 ms. The number is the kernel’s timeout, not a non-blocking flag.

Why does settimeout raise TimeoutError instead of errno 11?

Python implements its own timeout over a non-blocking socket, so it converts the kernel’s refusal into TimeoutError after 45,056 bytes here. The exception carries no count, which is why a retry needs its own deadline and its own record of what was sent – the module’s RetryTimeout does that.

Why does FileIO.read return None on an empty pipe?

A raw or buffered file object in non-blocking mode returns None when no data is available and b” at end of file. read1 returns b” for both, and a text-mode TextIOWrapper.read returns ” for both, so neither of those can tell an idle pipe from a closed one by the value alone. None of these is an error: 11 is the only pause, and a loop that treats the empty value as end of file stops reading a pipe that is merely idle.

How do I wait without burning a core?

Wait on the descriptor with poll and the remaining deadline; a window spent in poll cost a tenth of a millisecond of CPU against nearly 200 ms for the loop above, which called read a million times in the same window. After the event, read or write until 11 again, so the remainder is handled and the pause is short.

Does a full accept queue give the client EAGAIN?

No. With four concurrent connects, a backlog of 0, 1 and 2 completed 1, 2 and 3 connections – one more than the argument – and the rest stayed in progress with 115. The server’s accept is the call that answers 11 while the queue is empty.

Appendix A: the tests, printed whole

The budget readers against the kernel’s accounting nbio/tests/test_buffers.py
"""The budget readers, against the kernel's own accounting."""
from __future__ import annotations

import os
import socket

from nbio.buffers import (PAGE, Capacity, fill_pipe, pipe_budget, pipe_pages, queued_bytes,
                          socket_capacity)


def test_a_default_pipe_is_sixteen_pages():
    reader, writer = os.pipe()
    try:
        assert pipe_budget(writer) == 65536
        assert pipe_pages(writer) == 16
    finally:
        os.close(reader)
        os.close(writer)


def test_a_page_sized_fill_spends_the_whole_pipe():
    reader, writer = os.pipe()
    try:
        fill = fill_pipe(reader, writer)
        assert fill["written"] == pipe_budget(writer) == 65536
        assert fill["calls"] == 16
        assert fill["pages"] == 16
    finally:
        os.close(reader)
        os.close(writer)


def test_a_three_byte_fill_leaves_a_byte_in_every_page():
    reader, writer = os.pipe()
    try:
        fill = fill_pipe(reader, writer, chunk=3)
        assert fill["written"] == 65520
        assert fill["written"] == 16 * (4096 // 3) * 3
    finally:
        os.close(reader)
        os.close(writer)


def test_fill_reports_the_refusal_not_a_zero_byte_success():
    reader, writer = os.pipe()
    try:
        fill = fill_pipe(reader, writer)
        assert fill["errno"] == 11
    finally:
        os.close(reader)
        os.close(writer)


def test_free_room_never_goes_negative():
    assert Capacity(reported=100, queued=140).free == 0
    assert Capacity(reported=100, queued=25).free == 75


def test_the_queued_share_is_of_the_reported_number():
    capacity = Capacity(reported=212992, queued=53504)
    assert abs(capacity.share_queued - 53504 / 212992) < 1e-9


def test_queued_bytes_grows_by_more_than_the_payload():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        before = queued_bytes(left)
        left.send(b"x" * 4096)
        after = queued_bytes(left)
        assert before == 0
        assert after == 4864
    finally:
        left.close()
        right.close()


def test_a_pinned_send_buffer_is_reported_doubled():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65536)
        assert left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) == 131072
        assert socket_capacity(left).reported == 131072
    finally:
        left.close()
        right.close()


def test_the_capacity_free_room_is_reported_minus_charged():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.send(b"x" * PAGE)
        capacity = socket_capacity(left)
        assert capacity.free == capacity.reported - capacity.queued
        assert capacity.queued == 4864
    finally:
        left.close()
        right.close()
The retrying writers and readers nbio/tests/test_retry.py
"""The retrying readers and writers: pause, wait, and retry the remainder."""
from __future__ import annotations

import fcntl
import os
import select
import socket
import threading
import time

import pytest

from nbio.buffers import PAGE, pipe_budget
from nbio.retry import RetryTimeout, drain, read_exactly, readiness, send_all, write_all


def nonblock(fd: int) -> None:
    fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)


def test_write_all_sends_a_payload_larger_than_the_pipe():
    reader, writer = os.pipe()
    nonblock(writer)
    payload = bytes(range(256)) * 800            # 204,800 bytes through a 65,536-byte pipe
    received = bytearray()

    def drain_reader() -> None:
        while len(received) < len(payload):
            received.extend(os.read(reader, 8192))

    thread = threading.Thread(target=drain_reader)
    thread.start()
    try:
        sent = write_all(writer, payload, timeout=5)
    finally:
        thread.join(timeout=5)
        os.close(reader)
        os.close(writer)
    assert sent == len(payload)
    assert bytes(received) == payload


def test_write_all_reports_the_bytes_it_sent_when_the_deadline_passes():
    reader, writer = os.pipe()
    nonblock(writer)
    try:
        with pytest.raises(RetryTimeout) as caught:
            write_all(writer, b"x" * (pipe_budget(writer) * 2), timeout=0.05)
        assert caught.value.sent == pipe_budget(writer)
    finally:
        os.close(reader)
        os.close(writer)


def test_write_all_retries_only_the_remainder():
    reader, writer = os.pipe()
    nonblock(writer)
    nonblock(reader)
    os.write(writer, b"x" * (pipe_budget(writer) - 1024))
    payload = b"y" * 1024 + b"z" * 1024
    freed: dict[str, int] = {}

    def free_one_page() -> None:
        time.sleep(0.02)
        freed["bytes"] = len(os.read(reader, PAGE))

    thread = threading.Thread(target=free_one_page)
    thread.start()
    try:
        sent = write_all(writer, payload, timeout=5)
    finally:
        thread.join(timeout=5)
        rest = b""
        while True:
            try:
                rest += os.read(reader, 65536)
            except BlockingIOError:
                break
        os.close(reader)
        os.close(writer)
    assert sent == len(payload)
    assert rest.endswith(payload)
    assert freed["bytes"] == PAGE


def test_send_all_uses_the_partial_counts_send_returns():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    payload = b"q" * 400_000
    received = bytearray()

    def read_peer() -> None:
        while len(received) < len(payload):
            received.extend(right.recv(16384))

    thread = threading.Thread(target=read_peer)
    thread.start()
    try:
        sent = send_all(left, payload, timeout=5)
    finally:
        thread.join(timeout=5)
        left.close()
        right.close()
    assert sent == len(payload)
    assert bytes(received) == payload


def test_read_exactly_returns_the_count_it_was_asked_for():
    reader, writer = os.pipe()
    nonblock(reader)
    try:
        os.write(writer, b"abcdefgh")
        assert read_exactly(reader, 4, timeout=1) == b"abcd"
        assert read_exactly(reader, 4, timeout=1) == b"efgh"
    finally:
        os.close(reader)
        os.close(writer)


def test_read_exactly_stops_at_end_of_file():
    reader, writer = os.pipe()
    nonblock(reader)
    os.close(writer)
    try:
        assert read_exactly(reader, 16, timeout=1) == b""
    finally:
        os.close(reader)


def test_read_exactly_keeps_what_it_read_when_the_deadline_passes():
    reader, writer = os.pipe()
    nonblock(reader)
    try:
        os.write(writer, b"r" * 100)
        with pytest.raises(RetryTimeout) as caught:
            read_exactly(reader, 200, timeout=0.05)
        assert caught.value.data == b"r" * 100
    finally:
        os.close(reader)
        os.close(writer)


def test_drain_returns_everything_and_then_zero():
    reader, writer = os.pipe()
    nonblock(reader)
    try:
        os.write(writer, b"x" * 16384)
        assert drain(reader) == 16384
        assert drain(reader) == 0
    finally:
        os.close(reader)
        os.close(writer)


def test_drain_stops_at_end_of_file_instead_of_spinning():
    reader, writer = os.pipe()
    nonblock(reader)
    try:
        os.write(writer, b"x" * 1024)
        os.close(writer)
        assert drain(reader) == 1024
        assert drain(reader) == 0
    finally:
        os.close(reader)


def test_readiness_waits_for_the_timeout_and_answers_false():
    reader, writer = os.pipe()
    try:
        started = time.perf_counter()
        assert readiness(reader, select.POLLIN, 0.05) is False
        waited = time.perf_counter() - started
    finally:
        os.close(reader)
        os.close(writer)
    assert waited >= 0.04
The walls behind errno 11, forced with real descriptors nbio/tests/test_walls.py
"""The walls behind errno 11, forced with real descriptors rather than injected numbers."""
from __future__ import annotations

import fcntl
import os
import select
import socket
import struct
import tempfile

import pytest


def nonblock(fd: int) -> None:
    fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)


def test_a_full_pipe_refuses_a_write():
    reader, writer = os.pipe()
    try:
        nonblock(writer)
        os.write(writer, b"x" * 65536)
        with pytest.raises(BlockingIOError) as caught:
            os.write(writer, b"y")
        assert caught.value.errno == 11
    finally:
        os.close(reader)
        os.close(writer)


def test_a_small_write_uses_what_is_left_of_the_last_page():
    """poll says no when no page is free, yet a request of PIPE_BUF bytes or fewer can still fit."""
    reader, writer = os.pipe()
    try:
        os.write(writer, b"x" * 65535)
        nonblock(writer)
        assert select.select([], [writer], [], 0)[1] == []
        assert os.write(writer, b"y") == 1
        with pytest.raises(BlockingIOError) as caught:
            os.write(writer, b"y")
        assert caught.value.errno == 11
    finally:
        os.close(reader)
        os.close(writer)


def test_an_empty_pipe_refuses_a_read():
    reader, writer = os.pipe()
    try:
        nonblock(reader)
        with pytest.raises(BlockingIOError) as caught:
            os.read(reader, 1)
        assert caught.value.errno == 11
    finally:
        os.close(reader)
        os.close(writer)


def test_an_empty_socket_refuses_a_receive():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        with pytest.raises(BlockingIOError) as caught:
            left.recv(1)
        assert caught.value.errno == 11
    finally:
        left.close()
        right.close()


def test_an_empty_accept_queue_refuses_an_accept():
    server = socket.socket()
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    server.setblocking(False)
    try:
        with pytest.raises(BlockingIOError) as caught:
            server.accept()
        assert caught.value.errno == 11
    finally:
        server.close()


def test_a_connection_in_progress_is_a_different_number_in_the_same_class():
    server = socket.socket()
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    client = socket.socket()
    client.setblocking(False)
    try:
        with pytest.raises(BlockingIOError) as caught:
            client.connect(server.getsockname())
        assert caught.value.errno == 115
        assert caught.value.errno != 11
    finally:
        client.close()
        server.close()


def test_a_held_lock_answers_the_same_number():
    directory = tempfile.mkdtemp(prefix="nbio-lock-")
    path = os.path.join(directory, "lock")
    first = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
    second = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
    try:
        fcntl.flock(first, fcntl.LOCK_EX)
        with pytest.raises(BlockingIOError) as caught:
            fcntl.flock(second, fcntl.LOCK_EX | fcntl.LOCK_NB)
        assert caught.value.errno == 11
    finally:
        os.close(first)
        os.close(second)
        os.unlink(path)
        os.rmdir(directory)


def test_a_kernel_send_timeout_answers_eleven_on_a_blocking_socket():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", 0, 20_000))
        with pytest.raises(BlockingIOError) as caught:
            while True:
                left.send(b"x" * 4096)
        assert caught.value.errno == 11
    finally:
        left.close()
        right.close()


def test_a_python_timeout_answers_a_timeout_instead():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.settimeout(0.02)
        with pytest.raises(TimeoutError):
            while True:
                left.send(b"x" * 4096)
    finally:
        left.close()
        right.close()


def test_a_raw_file_read_answers_none_rather_than_raising():
    reader, writer = os.pipe()
    try:
        nonblock(reader)
        stream = os.fdopen(reader, "rb", buffering=0)
        try:
            assert stream.read(16) is None
        finally:
            stream.close()
    finally:
        os.close(writer)


def test_a_buffered_read1_answers_empty_bytes_not_none():
    reader, writer = os.pipe()
    try:
        nonblock(reader)
        stream = os.fdopen(reader, "rb", buffering=4096)
        try:
            assert stream.read1(16) == b""
        finally:
            stream.close()
    finally:
        os.close(writer)


def test_end_of_file_is_empty_bytes_and_not_a_refusal():
    reader, writer = os.pipe()
    nonblock(reader)
    os.close(writer)
    try:
        assert os.read(reader, 16) == b""
    finally:
        os.close(reader)


def test_readiness_stops_calling_a_socket_writable_before_it_refuses():
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        pages_looked_ready = 0
        while select.select([], [left], [], 0)[1]:
            left.send(b"x" * 4096)
            pages_looked_ready += 1
        pages_actually_accepted = pages_looked_ready
        while True:
            try:
                left.send(b"x" * 4096)
                pages_actually_accepted += 1
            except BlockingIOError:
                break
        assert pages_looked_ready == 11
        assert pages_actually_accepted == 44
    finally:
        left.close()
        right.close()


def test_data_can_be_taken_between_the_answer_and_the_read():
    reader, writer = os.pipe()
    try:
        nonblock(reader)
        os.write(writer, b"x")
        poller = select.poll()
        poller.register(reader, select.POLLIN)
        assert poller.poll(0)
        os.read(reader, 1)                       # another worker drains the byte
        with pytest.raises(BlockingIOError) as caught:
            os.read(reader, 1)
        assert caught.value.errno == 11
    finally:
        os.close(reader)
        os.close(writer)

Appendix B: the probes, printed whole

Every figure in the tables came from one of these files. Each probe runs from the sandbox directory, writes one JSON record under results/ with its own name, the time, the number of repeats, every run and a summary, and the tables were rendered from those records; probelib.py is the library they all import. Run one on your own kernel and the same code answers with your figures, which is the point of printing them: the shape should hold, and the constants may not.

The library every probe imports: records, limits, fills, JSON sandbox/probelib.py
"""Helpers shared by the probes: read what the kernel reports, and record it.

Every probe writes one JSON file under results/ with the shape

    {"probe": "...", "when": "...", "repeats": 5,
     "arms": [{"label": ..., "runs": [...], "summary": {...}}],
     "notes": {...}}

so a number that reaches the article can be traced to the run that wrote it.
"""
from __future__ import annotations

import datetime
import fcntl
import json
import os
import pathlib
import resource
import socket
import statistics
import struct
import sys

HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
PAGE = os.sysconf("SC_PAGE_SIZE")
PIPE_BUF = 4096
F_GETPIPE_SZ = 1032
F_SETPIPE_SZ = 1031
TIOCOUTQ = 0x5411


def when() -> str:
    return datetime.datetime.now().astimezone().isoformat(timespec="seconds")


def meminfo() -> dict[str, int]:
    out: dict[str, int] = {}
    for line in pathlib.Path("/proc/meminfo").read_text().splitlines():
        key, _, rest = line.partition(":")
        out[key] = int(rest.split()[0]) if rest.strip() else 0
    return out


def sysctl(name: str) -> str:
    return pathlib.Path("/proc/sys/" + name.replace(".", "/")).read_text().strip()


def limits() -> dict[str, list[int]]:
    names = {"AS": resource.RLIMIT_AS, "DATA": resource.RLIMIT_DATA,
             "NPROC": resource.RLIMIT_NPROC, "NOFILE": resource.RLIMIT_NOFILE,
             "STACK": resource.RLIMIT_STACK}
    out = {}
    for name, which in names.items():
        soft, hard = resource.getrlimit(which)
        out[name] = [int(soft), int(hard)]
    return out


def task_count(uid: int | None = None) -> int:
    """How many tasks the uid owns, threads included: what RLIMIT_NPROC counts.

    The limit is compared with the number of tasks for the real uid, and a task is a thread,
    so a process running four threads spends four of the limit. Counting only the /proc
    entries that carry the uid would under-count exactly the processes that hit the limit by
    starting a thread. Each process is counted through its own task directory, and a process
    that exits between the two reads is skipped, because its threads went with it.
    """
    wanted = os.getuid() if uid is None else uid
    count = 0
    for entry in pathlib.Path("/proc").iterdir():
        if not entry.name.isdigit():
            continue
        try:
            status = (entry / "status").read_text()
        except OSError:
            continue
        owner = None
        for line in status.splitlines():
            if line.startswith("Uid:"):
                owner = int(line.split()[1])
                break
        if owner != wanted:
            continue
        try:
            count += sum(1 for _ in (entry / "task").iterdir())
        except OSError:
            continue
    return count


def facts() -> dict:
    reader, writer = os.pipe()
    try:
        pipe_buf = os.fpathconf(writer, "PC_PIPE_BUF")
        get_size = fcntl.fcntl(writer, F_GETPIPE_SZ)
    finally:
        os.close(reader)
        os.close(writer)
    return {
        "python": ".".join(str(part) for part in sys.version_info[:3]),
        "kernel": os.uname().release,
        "machine": os.uname().machine,
        "uid": os.getuid(),
        "gid": os.getgid(),
        "cpus": os.cpu_count(),
        "page_bytes": PAGE,
        "pipe_buf": pipe_buf,
        "pipe_size_default": get_size,
        "pipe_max_size": int(sysctl("fs.pipe-max-size")),
        "wmem_default": int(sysctl("net.core.wmem_default")),
        "rmem_default": int(sysctl("net.core.rmem_default")),
        "wmem_max": int(sysctl("net.core.wmem_max")),
        "rmem_max": int(sysctl("net.core.rmem_max")),
        "tcp_wmem": sysctl("net.ipv4.tcp_wmem"),
        "tcp_rmem": sysctl("net.ipv4.tcp_rmem"),
        "mem_total_kb": meminfo()["MemTotal"],
        "mem_available_kb": meminfo()["MemAvailable"],
        "limits": limits(),
        "cgroup_v2": pathlib.Path("/sys/fs/cgroup/cgroup.controllers").exists(),
    }


def errno_numbers() -> dict[str, int]:
    import errno
    return {name: int(getattr(errno, name)) for name in
            ("EAGAIN", "EWOULDBLOCK", "EINPROGRESS", "ETIMEDOUT", "EPIPE", "EBADF",
             "ENOBUFS", "EMFILE", "EINTR")}


def nonblock(fd: int) -> None:
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)


def outcome(exc: BaseException | None = None, value=None) -> dict:
    if exc is None:
        return {"outcome": "ok", "type": None, "errno": None, "message": "",
                "value": value}
    return {"outcome": "error", "type": type(exc).__name__,
            "errno": getattr(exc, "errno", None), "message": str(exc), "value": value}


def try_call(fn, *args, **kwargs) -> dict:
    try:
        return outcome(None, fn(*args, **kwargs))
    except BaseException as exc:  # noqa: BLE001 - the answer is the record
        return outcome(exc)


def queued_bytes(sock: socket.socket) -> int:
    """Bytes the kernel says are still held by this socket's send side."""
    return struct.unpack("i", fcntl.ioctl(sock.fileno(), TIOCOUTQ, b"\0\0\0\0"))[0]


def fill_pipe(chunk: int, size: int | None = None) -> dict:
    """Write ``chunk`` bytes until the pipe refuses, and report what went in."""
    reader, writer = os.pipe()
    try:
        before = fcntl.fcntl(writer, F_GETPIPE_SZ)
        set_errno = None
        if size is not None:
            try:
                fcntl.fcntl(writer, F_SETPIPE_SZ, size)
            except OSError as exc:
                set_errno = exc.errno
        after = fcntl.fcntl(writer, F_GETPIPE_SZ)
        nonblock(writer)
        payload = b"x" * chunk
        total = 0
        calls = 0
        code = None
        while True:
            try:
                total += os.write(writer, payload)
                calls += 1
            except BlockingIOError as exc:
                code = exc.errno
                break
        return {"chunk": chunk, "size_set": size, "set_errno": set_errno,
                "size_before": before, "size_after": after, "filled": total,
                "calls": calls, "errno": code, "pages": total / PAGE}
    finally:
        os.close(reader)
        os.close(writer)


def unix_fill(chunk: int, sndbuf: int | None = None) -> dict:
    """Send ``chunk`` bytes into an AF_UNIX socketpair until the send side refuses."""
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        if sndbuf is not None:
            left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        left.setblocking(False)
        reported = left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        peer = right.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        payload = b"x" * chunk
        total = 0
        calls = 0
        code = None
        while True:
            try:
                total += left.send(payload)
                calls += 1
            except BlockingIOError as exc:
                code = exc.errno
                break
        queued = queued_bytes(left)
        return {"chunk": chunk, "sndbuf_set": sndbuf, "sndbuf_reported": reported,
                "peer_rcvbuf": peer, "accepted": total, "calls": calls, "errno": code,
                "queued": queued, "charge_per_call": (queued / calls) if calls else None}
    finally:
        left.close()
        right.close()


def tcp_fill(chunk: int, sndbuf: int | None = None) -> dict:
    """Fill a loopback TCP send buffer whose peer never reads."""
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(1)
    client = socket.create_connection(server.getsockname())
    conn, _ = server.accept()
    try:
        before = client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        if sndbuf is not None:
            client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        reported = client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        peer = conn.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
        client.setblocking(False)
        payload = b"x" * chunk
        total = 0
        calls = 0
        code = None
        while True:
            try:
                total += client.send(payload)
                calls += 1
            except BlockingIOError as exc:
                code = exc.errno
                break
        return {"chunk": chunk, "sndbuf_set": sndbuf, "sndbuf_before": before,
                "sndbuf_reported": reported, "peer_rcvbuf": peer, "accepted": total,
                "calls": calls, "errno": code, "queued": queued_bytes(client)}
    finally:
        client.close()
        conn.close()
        server.close()


def summarise(runs: list, key: str, number: bool = True) -> dict:
    values = [run[key] for run in runs if run.get(key) is not None]
    if not values:
        return {"median": None, "min": None, "max": None, "n": 0}
    if number and all(isinstance(value, (int, float)) for value in values):
        return {"median": statistics.median(values), "min": min(values),
                "max": max(values), "n": len(values)}
    texts = [value if isinstance(value, str) else repr(value) for value in values]
    return {"median": texts[0] if len(set(texts)) == 1 else ",".join(sorted(set(texts))),
            "min": min(texts), "max": max(texts), "n": len(texts)}


def write(name: str, payload: dict) -> pathlib.Path:
    RESULTS.mkdir(exist_ok=True)
    path = RESULTS / f"{name}.json"
    path.write_text(json.dumps(payload, indent=1, sort_keys=False) + "\n", encoding="utf-8")
    print(f"wrote {path} ({path.stat().st_size} B)")
    return path
The host: kernel, limits, sysctls and page size, read first sandbox/01_facts.py
"""What this host says before any arm runs: the numbers errno 11 is compared with."""
from __future__ import annotations

import os
import socket

import probelib


def main() -> None:
    facts = probelib.facts()
    numbers = probelib.errno_numbers()
    joined = socket.socket()
    try:
        connected = socket.socket()
        server = socket.socket()
        server.bind(("127.0.0.1", 0))
        server.listen(1)
        connected.connect(server.getsockname())
        peer, _ = server.accept()
        connected_state = {
            "sndbuf": connected.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
            "rcvbuf": peer.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF),
            "fresh_sndbuf": joined.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
        }
        connected.close()
        peer.close()
        server.close()
    finally:
        joined.close()
    notes = {
        "facts": facts,
        "errno": numbers,
        "strerror": {str(value): os.strerror(value) for value in
                     sorted(set(numbers.values()))},
        "blocking_io_error_is_oserror": issubclass(BlockingIOError, OSError),
        "tcp_socket_defaults": connected_state,
        "limits_read_at": probelib.when(),
    }
    probelib.write("01_facts", {
        "probe": "01_facts",
        "when": probelib.when(),
        "repeats": 1,
        "arms": [],
        "notes": notes,
    })


if __name__ == "__main__":
    main()
The twenty-call matrix, one interpreter per arm sandbox/02_matrix.py
"""Every call this page puts in one table, each in its own interpreter and run five times.

A limit an arm lowers cannot reach the next arm, because each arm is a child process and the
parent only reads the one JSON line it prints.
"""
from __future__ import annotations

import fcntl
import json
import os
import resource
import socket
import struct
import subprocess
import sys
import time

import probelib

REPEATS = 5


def arm_pipe_full_write() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(writer)
        os.write(writer, b"x" * 65536)
        return probelib.try_call(os.write, writer, b"y" * 4096)
    finally:
        os.close(reader)
        os.close(writer)


def arm_pipe_empty_read() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        return probelib.try_call(os.read, reader, 4096)
    finally:
        os.close(reader)
        os.close(writer)


def arm_pipe_oversize_write() -> dict:
    """One byte more than an empty pipe holds."""
    reader, writer = os.pipe()
    try:
        probelib.nonblock(writer)
        return probelib.try_call(os.write, writer, b"y" * 65537)
    finally:
        os.close(reader)
        os.close(writer)


def arm_unix_recv_empty() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        return probelib.try_call(left.recv, 1)
    finally:
        left.close()
        right.close()


def arm_unix_recv_dontwait() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        return probelib.try_call(left.recv, 1, socket.MSG_DONTWAIT)
    finally:
        left.close()
        right.close()


def arm_unix_send_when_full() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        while True:
            left.send(b"x" * 4096)
    except BlockingIOError as exc:
        return probelib.outcome(exc, {"queued": probelib.queued_bytes(left)})
    finally:
        left.close()
        right.close()


def arm_accept_empty() -> dict:
    server = socket.socket()
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    server.setblocking(False)
    try:
        return probelib.try_call(server.accept)
    finally:
        server.close()


def arm_connect_in_progress() -> dict:
    server = socket.socket()
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    client = socket.socket()
    client.setblocking(False)
    try:
        return probelib.try_call(client.connect, server.getsockname())
    finally:
        client.close()
        server.close()


def arm_flock_contended() -> dict:
    path = "/tmp/eagain-probe.lock"
    first = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
    second = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
    try:
        fcntl.flock(first, fcntl.LOCK_EX)
        return probelib.try_call(fcntl.flock, second, fcntl.LOCK_EX | fcntl.LOCK_NB)
    finally:
        os.close(first)
        os.close(second)
        os.unlink(path)


def arm_fork_at_nproc() -> dict:
    """Set RLIMIT_NPROC to the uid's own task count and try to add one more task.

    The count is the kernel's unit, threads included, so a process running threads has
    already spent several of the limit before it forks.
    """
    count = probelib.task_count()
    _, hard = resource.getrlimit(resource.RLIMIT_NPROC)
    resource.setrlimit(resource.RLIMIT_NPROC, (count, hard))
    try:
        pid = os.fork()
    except BaseException as exc:  # noqa: BLE001 - the answer is the record
        return probelib.outcome(exc, {"nproc_set": count})
    if pid == 0:
        os._exit(0)
    os.waitpid(pid, 0)
    return probelib.outcome(None, {"nproc_set": count})


def arm_socket_send_timeout() -> dict:
    """A blocking socket whose kernel-side send timeout expires answers 11."""
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", 0, 50_000))
        started = time.perf_counter()
        total = 0
        while True:
            try:
                total += left.send(b"x" * 4096)
            except BlockingIOError as exc:
                return probelib.outcome(exc, {
                    "sent": total, "elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
                    "timeout_us": struct.unpack("ll", left.getsockopt(
                        socket.SOL_SOCKET, socket.SO_SNDTIMEO, 16))[1]})
    finally:
        left.close()
        right.close()


def arm_python_settimeout() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.settimeout(0.05)
        started = time.perf_counter()
        total = 0
        while True:
            try:
                total += left.send(b"x" * 4096)
            except OSError as exc:
                return probelib.outcome(exc, {
                    "sent": total, "elapsed_ms": round((time.perf_counter() - started) * 1000, 1)})
    finally:
        left.close()
        right.close()


def arm_send_after_shutdown() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.shutdown(socket.SHUT_WR)
        return probelib.try_call(left.send, b"x")
    finally:
        left.close()
        right.close()


def arm_read_at_eof() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        os.close(writer)
        return probelib.try_call(os.read, reader, 4096)
    finally:
        os.close(reader)


def arm_send_zero_bytes() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        return probelib.try_call(left.send, b"")
    finally:
        left.close()
        right.close()


def arm_fileio_read_empty() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        stream = os.fdopen(reader, "rb", buffering=0)
        try:
            return probelib.try_call(stream.read, 4096)
        finally:
            stream.close()
    finally:
        os.close(writer)


def arm_buffered_read_empty() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        stream = os.fdopen(reader, "rb", buffering=8192)
        try:
            return probelib.try_call(stream.read, 4096)
        finally:
            stream.close()
    finally:
        os.close(writer)


def arm_buffered_read1_empty() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        stream = os.fdopen(reader, "rb", buffering=8192)
        try:
            return probelib.try_call(stream.read1, 4096)
        finally:
            stream.close()
    finally:
        os.close(writer)


def arm_makefile_read_empty() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        stream = left.makefile("rb")
        try:
            return probelib.try_call(stream.read, 4096)
        finally:
            stream.close()
    finally:
        left.close()
        right.close()


def arm_textio_read_empty() -> dict:
    """The text layer most callers use: what does it answer with nothing to read?"""
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        stream = os.fdopen(reader, "r", encoding="utf-8")
        try:
            return probelib.try_call(stream.read, 4096)
        finally:
            stream.close()
    finally:
        os.close(writer)


ARMS = {
    "pipe_full_write": arm_pipe_full_write,
    "pipe_empty_read": arm_pipe_empty_read,
    "pipe_oversize_write": arm_pipe_oversize_write,
    "unix_recv_empty": arm_unix_recv_empty,
    "unix_recv_dontwait": arm_unix_recv_dontwait,
    "unix_send_when_full": arm_unix_send_when_full,
    "accept_empty": arm_accept_empty,
    "connect_in_progress": arm_connect_in_progress,
    "flock_contended": arm_flock_contended,
    "fork_at_nproc": arm_fork_at_nproc,
    "socket_send_timeout": arm_socket_send_timeout,
    "python_settimeout": arm_python_settimeout,
    "send_after_shutdown": arm_send_after_shutdown,
    "read_at_eof": arm_read_at_eof,
    "send_zero_bytes": arm_send_zero_bytes,
    "fileio_read_empty": arm_fileio_read_empty,
    "buffered_read_empty": arm_buffered_read_empty,
    "buffered_read1_empty": arm_buffered_read1_empty,
    "makefile_read_empty": arm_makefile_read_empty,
    "textio_read_empty": arm_textio_read_empty,
}


def run_one(label: str) -> None:
    record = ARMS[label]()
    print("@@RESULT@@" + json.dumps(record, default=repr))


def main() -> None:
    if len(sys.argv) == 3 and sys.argv[1] == "--arm":
        run_one(sys.argv[2])
        return
    arms = []
    for label in ARMS:
        runs = []
        for _ in range(REPEATS):
            completed = subprocess.run([sys.executable, __file__, "--arm", label],
                                       capture_output=True, text=True, timeout=120)
            line = next((text for text in completed.stdout.splitlines()
                         if text.startswith("@@RESULT@@")), None)
            if line is None:
                runs.append({"outcome": "crashed", "type": "subprocess",
                             "errno": completed.returncode,
                             "message": completed.stderr.strip()[-300:]})
                continue
            runs.append(json.loads(line[len("@@RESULT@@"):]))
        summary = {"outcome": probelib.summarise(runs, "outcome", number=False),
                   "errno": probelib.summarise(runs, "errno"),
                   "type": probelib.summarise(runs, "type", number=False),
                   "value": probelib.summarise(runs, "value", number=False)}
        for key in ("sent", "elapsed_ms", "nproc_set"):
            summary[key] = probelib.summarise(runs, key)
        arms.append({"label": label, "runs": runs, "summary": summary})
        print(f"{label:24s} {[str(run.get('type')) + ':' + str(run.get('errno')) for run in runs]}",
              flush=True)
    probelib.write("02_matrix", {
        "probe": "02_matrix",
        "when": probelib.when(),
        "repeats": REPEATS,
        "arms": arms,
        "notes": {"arm_count": len(arms), "runs_total": len(arms) * REPEATS,
                  "nproc": {"unit": "tasks (threads) of the real uid",
                            "counted": probelib.task_count(),
                            "limit": probelib.limits()["NPROC"][0]},
                  "facts": probelib.facts(), "errno": probelib.errno_numbers()},
    })


if __name__ == "__main__":
    main()
The pipe’s budget, the size ladder and the room in the last page sandbox/03_pipe.py
"""How many bytes a pipe holds, and what a write of a given size finds at its edge.

Nothing here changes a limit or a global, so the arms run in this interpreter; each arm builds
its own pipe and closes it, and every arm runs five times.
"""
from __future__ import annotations

import os
import select

import probelib

REPEATS = 5
FILL_CHUNKS = (1, 2, 3, 100, 4096, 65_536)
SET_SIZES = (4096, 8192, 1_048_576, 2_097_152)


def room_arm(free: int, request: int) -> dict:
    """Fill a pipe so that ``free`` bytes remain in its last page, then ask for ``request``.

    ``free=0`` leaves the pipe empty, so the room it has is the whole budget: the record
    carries both the bytes that were written and the room that was really left.
    """
    reader, writer = os.pipe()
    try:
        capacity = 65_536
        filled = capacity - free if free else 0
        if filled:
            os.write(writer, b"x" * filled)
        probelib.nonblock(writer)
        writable = bool(select.select([], [writer], [], 0)[1])
        record = probelib.try_call(os.write, writer, b"y" * request)
        record |= {"filled": filled, "free_room": capacity - filled, "request": request,
                   "writable": writable}
        return record
    finally:
        os.close(reader)
        os.close(writer)


def run_chunk(chunk: int) -> dict:
    return probelib.fill_pipe(chunk)


def run_set(size: int) -> dict:
    return probelib.fill_pipe(4096, size=size)


def main() -> None:
    arms = []
    fills: dict[int, int] = {}
    for chunk in FILL_CHUNKS:
        runs = [run_chunk(chunk) for _ in range(REPEATS)]
        fills[chunk] = int(probelib.summarise(runs, "filled")["median"])
        arms.append({"label": f"chunk_{chunk}", "runs": runs, "summary": {
            "filled": probelib.summarise(runs, "filled"),
            "calls": probelib.summarise(runs, "calls"),
            "errno": probelib.summarise(runs, "errno"),
            "size_after": probelib.summarise(runs, "size_after"),
        }})
        print(f"chunk {chunk:6d}: {[run['filled'] for run in runs]}", flush=True)
    for size in SET_SIZES:
        runs = [run_set(size) for _ in range(REPEATS)]
        arms.append({"label": f"set_{size}", "runs": runs, "summary": {
            "filled": probelib.summarise(runs, "filled"),
            "size_after": probelib.summarise(runs, "size_after"),
            "size_before": probelib.summarise(runs, "size_before"),
            "set_errno": probelib.summarise(runs, "set_errno"),
        }})
        print(f"set {size:8d}: {[(run['size_after'], run['filled'], run['set_errno']) for run in runs]}",
              flush=True)
    ladders = [
        (0, 8192), (1, 8192), (1000, 8192), (4095, 8192), (4096, 8192), (5000, 8192),
        (8192, 8192), (9000, 8192), (1000, 4096), (4096, 4096), (5000, 4096),
        # Requests small enough to land in what is left of the last page, and one byte too
        # large for it: this is the half of the page rule the multi-page ladder cannot show.
        (1000, 3), (1000, 1000), (1000, 1001), (1, 1), (1, 2), (96, 100),
    ]
    for free, request in ladders:
        runs = [room_arm(free, request) for _ in range(REPEATS)]
        arms.append({"label": f"room_{free}_request_{request}", "runs": runs, "summary": {
            "outcome": probelib.summarise(runs, "outcome", number=False),
            "value": probelib.summarise(runs, "value"),
            "writable": probelib.summarise(runs, "writable", number=False),
        }})
        print(f"room {free:5d} request {request:5d}: "
              f"{[(run['outcome'], run['value'], run['writable']) for run in runs][:2]}",
              flush=True)
    facts = probelib.facts()
    page = facts["page_bytes"]
    capacity = fills[4096]
    pages = capacity // page
    # Every figure here is arithmetic over the fills just measured, not a number typed by hand:
    # the two totals are compared with their own arms so the record shows the arithmetic closed.
    notes = {
        "measured_capacity_4096": capacity,
        "measured_capacity_1": fills[1],
        "measured_capacity_3": fills[3],
        "measured_capacity_100": fills[100],
        "pages": pages,
        "page_bytes": page,
        "three_byte_waste_per_page": page % 3,
        "hundred_byte_waste_per_page": page % 100,
        "three_byte_total": (page // 3) * 3 * pages,
        "hundred_byte_total": (page // 100) * 100 * pages,
        "three_byte_total_closes": (page // 3) * 3 * pages == fills[3],
        "hundred_byte_total_closes": (page // 100) * 100 * pages == fills[100],
        "pipe_max_size": facts["pipe_max_size"],
        "pipe_buf": facts["pipe_buf"],
    }
    probelib.write("03_pipe", {
        "probe": "03_pipe", "when": probelib.when(), "repeats": REPEATS,
        "arms": arms, "notes": notes,
    })


if __name__ == "__main__":
    main()
The socketpair: three send sizes, three buffers, the charge ladder, the readiness gap sandbox/04_unix.py
"""What an AF_UNIX stream socket accepts, and where its readiness check gives up.

Three chunk arms show the charge per call on the default buffer: the same buffer holds 180,224
bytes in 4 KiB sends and 278 bytes in 1-byte sends. The ladder arms walk the send size from one
byte to 16 KiB and record where the charge steps, so the floor and the bucket edges the page
quotes are measured rather than assumed: on this host every send of 192 bytes or fewer is
charged the same 768 bytes, the last bucket below a page ends at 3,776, and a page-sized send
is charged its payload plus that floor.
The readiness arm fills page by page and records the first level at which select() stops
calling the socket writable, which is nowhere near the send buffer.
"""
from __future__ import annotations

import select
import socket

import probelib

REPEATS = 5
CHUNKS = (1, 512, 4096)
SNDBUFS = (None, 65_536, 131_072)
# The send sizes that bracket every charge step this host shows, plus the page multiples the
# article quotes: 192 is the largest send charged the floor, 193 the first above it; 704 and
# 1,728 are the last sends in the next two buckets; 3,775 and 3,776 sit inside the last bucket
# below a page and 3,777 is the first send past it, so that edge is sampled on both sides
# instead of being inferred from the jump from 3,584 to a page; 4 KiB and above are page-sized
# sends.
LADDER = (1, 64, 128, 192, 193, 256, 512, 704, 705, 1024, 1728, 1729, 2048, 3584, 3775,
          3776, 3777, 4095, 4096, 8192, 16384)


def readiness(sndbuf: int | None = None) -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        if sndbuf is not None:
            left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        left.setblocking(False)
        reported = left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        pages = 0
        while True:
            if not select.select([], [left], [], 0)[1]:
                break
            try:
                left.send(b"x" * 4096)
                pages += 1
            except BlockingIOError:
                break
        stalled = {"pages_writable": pages, "bytes_sent": pages * 4096,
                   "queued": probelib.queued_bytes(left), "sndbuf": reported}
        while True:
            try:
                left.send(b"x" * 4096)
                pages += 1
            except BlockingIOError:
                break
        stalled |= {"pages_total": pages, "accepted": pages * 4096,
                    "queued_at_refusal": probelib.queued_bytes(left)}
        return stalled
    finally:
        left.close()
        right.close()


def summarise_arm(label: str, runs: list[dict]) -> dict:
    keys = ("accepted", "calls", "queued", "sndbuf_reported", "peer_rcvbuf",
            "charge_per_call", "errno")
    return {"label": label, "runs": runs,
            "summary": {key: probelib.summarise(runs, key) for key in keys}}


def main() -> None:
    arms = []
    default: dict[int, dict] = {}
    for sndbuf in SNDBUFS:
        for chunk in CHUNKS:
            runs = [probelib.unix_fill(chunk, sndbuf) for _ in range(REPEATS)]
            medians = {key: probelib.summarise(runs, key)["median"] for key in
                       ("accepted", "calls", "queued", "sndbuf_reported", "peer_rcvbuf",
                        "charge_per_call")}
            if sndbuf is None:
                default[chunk] = medians
            arms.append(summarise_arm(f"sndbuf_{sndbuf}_chunk_{chunk}", runs))
            print(f"sndbuf {str(sndbuf):8s} chunk {chunk:5d}: "
                  f"{[(run['accepted'], run['calls'], run['queued']) for run in runs][:2]}",
                  flush=True)
    # The ladder walks the send size with the buffer left alone, so every charge it records is
    # the default socket's own and can be compared across sizes.
    ladder: dict[int, dict] = {}
    for chunk in LADDER:
        runs = [probelib.unix_fill(chunk) for _ in range(REPEATS)]
        arms.append(summarise_arm(f"ladder_chunk_{chunk}", runs))
        ladder[chunk] = {key: probelib.summarise(runs, key)["median"] for key in
                         ("accepted", "calls", "queued", "charge_per_call")}
        print(f"ladder {chunk:6d}: {[(run['calls'], run['charge_per_call']) for run in runs][:2]}",
              flush=True)
    for sndbuf in (None, 65_536):
        runs = [readiness(sndbuf) for _ in range(REPEATS)]
        arms.append({"label": f"readiness_{sndbuf}", "runs": runs, "summary": {
            "pages_writable": probelib.summarise(runs, "pages_writable"),
            "bytes_sent": probelib.summarise(runs, "bytes_sent"),
            "queued": probelib.summarise(runs, "queued"),
            "sndbuf": probelib.summarise(runs, "sndbuf"),
            "pages_total": probelib.summarise(runs, "pages_total"),
            "accepted": probelib.summarise(runs, "accepted"),
            "queued_at_refusal": probelib.summarise(runs, "queued_at_refusal"),
        }})
        print(f"readiness sndbuf {sndbuf}: "
              f"{[(run['pages_writable'], run['queued'], run['sndbuf'], run['pages_total']) for run in runs][:2]}",
              flush=True)
    # The notes read the ladder back, so the floor, its ceiling and the bucket edges the page
    # quotes are the recorded medians rather than numbers typed beside the run. The floor is the
    # smallest charge the ladder saw, not a subtraction from the 4 KiB arm: subtracting assumes
    # that a call costs payload plus a constant, which is the error these notes exist to close.
    charges = {chunk: int(records["charge_per_call"]) for chunk, records in ladder.items()}
    floor = min(charges.values())
    floor_chunks = [chunk for chunk in sorted(charges) if charges[chunk] == floor]
    floor_ceiling = max(floor_chunks)
    first_above = min(chunk for chunk in charges if chunk > floor_ceiling)
    steps: list[dict] = []
    ceilings: list[dict] = []
    for chunk in sorted(charges):
        if not steps or charges[chunk] != steps[-1]["charge"]:
            steps.append({"chunk": chunk, "charge": charges[chunk]})
            ceilings.append({"charge": charges[chunk], "first_chunk": chunk, "ceiling": chunk})
        else:
            ceilings[-1]["ceiling"] = chunk
    page_sends = [chunk for chunk in (4096, 8192, 16384) if chunk in charges]
    notes = {
        "ladder_chunks": sorted(charges),
        "ladder_charges": {str(chunk): charges[chunk] for chunk in sorted(charges)},
        "truesize_floor": floor,
        "truesize_floor_ceiling": floor_ceiling,
        "truesize_floor_next_chunk": first_above,
        "truesize_floor_next_charge": charges[first_above],
        "truesize_bucket_steps": steps,
        "truesize_bucket_ceilings": ceilings,
        "truesize_floor_closes": all(charges[chunk] == floor for chunk in floor_chunks)
        and charges[first_above] > floor,
        "truesize_floor_is_not_payload_plus_constant": charges[1] == floor
        and charges[1] != 1 + floor,
        "page_sends_pay_payload_plus_floor": all(charges[chunk] - chunk == floor
                                                 for chunk in page_sends),
        "charge_4k": charges[4096],
        "charge_512": charges[512],
        "charge_1": charges[1],
        "charge_192": charges[192],
        "charge_193": charges[193],
        "charge_704": charges[704],
        "charge_705": charges[705],
        "charge_1728": charges[1728],
        "charge_1729": charges[1729],
        "charge_3584": charges[3584],
        "charge_3775": charges[3775],
        "charge_3776": charges[3776],
        "charge_3777": charges[3777],
        "the_step_below_a_page_is_sampled_on_both_sides": charges[3776] == charges[3584]
        and charges[3777] > charges[3776],
        "charge_8192": charges[8192],
        "charge_16384": charges[16384],
        "default_sndbuf": default[4096]["sndbuf_reported"],
        "default_peer_rcvbuf": default[4096]["peer_rcvbuf"],
        "max_4k_calls": default[4096]["calls"],
        "max_1byte_calls": default[1]["calls"],
        "max_512_calls": default[512]["calls"],
        "charge_512_closes": charges[512] == 512 + floor,
    }
    probelib.write("04_unix", {
        "probe": "04_unix", "when": probelib.when(), "repeats": REPEATS,
        "arms": arms, "notes": notes,
    })


if __name__ == "__main__":
    main()
Loopback TCP: the buffer that grows, the split, the readiness stop sandbox/05_tcp.py
"""TCP on loopback: the send buffer grows with the connection, and a peer's window adds to it."""
from __future__ import annotations

import select
import socket

import probelib

REPEATS = 5


def fill(chunk: int, sndbuf: int | None) -> dict:
    record = probelib.tcp_fill(chunk, sndbuf)
    return record


def delivered() -> dict:
    """Accepted bytes split into what the sender still holds and what the peer already has."""
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(1)
    client = socket.create_connection(server.getsockname())
    conn, _ = server.accept()
    try:
        client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 65_536)
        client.setblocking(False)
        accepted = 0
        calls = 0
        while True:
            try:
                accepted += client.send(b"x" * 4096)
                calls += 1
            except BlockingIOError:
                break
        queued = probelib.queued_bytes(client)
        conn.settimeout(2)
        got = 0
        while True:
            piece = conn.recv(1 << 20)
            if not piece:
                break
            got += len(piece)
            if got >= accepted:
                break
        return {"accepted": accepted, "calls": calls, "queued": queued,
                "not_in_sender": accepted - queued, "total_read": got,
                "sndbuf": client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF),
                "peer_rcvbuf": conn.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF),
                "all_accounted": got == accepted}
    finally:
        client.close()
        conn.close()
        server.close()


def readiness(sndbuf: int | None) -> dict:
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(1)
    client = socket.create_connection(server.getsockname())
    conn, _ = server.accept()
    try:
        if sndbuf is not None:
            client.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sndbuf)
        reported = client.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
        client.setblocking(False)
        sent = 0
        while True:
            if not select.select([], [client], [], 0)[1]:
                break
            try:
                sent += client.send(b"x" * 4096)
            except BlockingIOError:
                break
        stalled = {"sent_when_unwritable": sent, "queued": probelib.queued_bytes(client),
                   "sndbuf": reported}
        while True:
            try:
                sent += client.send(b"x" * 4096)
            except BlockingIOError:
                break
        stalled |= {"accepted": sent, "queued_at_refusal": probelib.queued_bytes(client)}
        return stalled
    finally:
        client.close()
        conn.close()
        server.close()


def main() -> None:
    arms = []
    for chunk, sndbuf in ((4096, 65_536), (1, 65_536), (65_536, 65_536), (4096, None)):
        runs = [fill(chunk, sndbuf) for _ in range(REPEATS)]
        arms.append({"label": f"chunk_{chunk}_sndbuf_{sndbuf}", "runs": runs, "summary": {
            "accepted": probelib.summarise(runs, "accepted"),
            "calls": probelib.summarise(runs, "calls"),
            "queued": probelib.summarise(runs, "queued"),
            "sndbuf_reported": probelib.summarise(runs, "sndbuf_reported"),
            "peer_rcvbuf": probelib.summarise(runs, "peer_rcvbuf"),
            "errno": probelib.summarise(runs, "errno"),
        }})
        print(f"tcp chunk {chunk:6d} sndbuf {str(sndbuf):7s}: "
              f"{[(run['accepted'], run['queued'], run['sndbuf_reported']) for run in runs][:2]}",
              flush=True)
    runs = [delivered() for _ in range(REPEATS)]
    arms.append({"label": "split_accepted", "runs": runs, "summary": {
        "accepted": probelib.summarise(runs, "accepted"),
        "queued": probelib.summarise(runs, "queued"),
        "not_in_sender": probelib.summarise(runs, "not_in_sender"),
        "total_read": probelib.summarise(runs, "total_read"),
        "all_accounted": probelib.summarise(runs, "all_accounted", number=False),
    }})
    print("split:", [(run["accepted"], run["queued"], run["not_in_sender"],
                      run["total_read"], run["all_accounted"]) for run in runs], flush=True)
    for sndbuf in (65_536, None):
        runs = [readiness(sndbuf) for _ in range(REPEATS)]
        arms.append({"label": f"readiness_{sndbuf}", "runs": runs, "summary": {
            "sent_when_unwritable": probelib.summarise(runs, "sent_when_unwritable"),
            "queued": probelib.summarise(runs, "queued"),
            "sndbuf": probelib.summarise(runs, "sndbuf"),
            "accepted": probelib.summarise(runs, "accepted"),
            "queued_at_refusal": probelib.summarise(runs, "queued_at_refusal"),
        }})
        print(f"tcp readiness sndbuf {sndbuf}: "
              f"{[(run['sent_when_unwritable'], run['queued'], run['sndbuf'], run['accepted']) for run in runs][:2]}",
              flush=True)
    facts = probelib.facts()
    probelib.write("05_tcp", {
        "probe": "05_tcp", "when": probelib.when(), "repeats": REPEATS, "arms": arms,
        "notes": {"fresh_sndbuf": 16_384, "tcp_wmem": facts["tcp_wmem"],
                  "tcp_rmem": facts["tcp_rmem"], "page_bytes": facts["page_bytes"]},
    })


if __name__ == "__main__":
    main()
Four timeouts and the blocking write that waits for a drain sandbox/06_timeouts.py
"""Four ways to be told 'not now', and what each one lets you know about the bytes sent."""
from __future__ import annotations

import os
import select
import socket
import struct
import threading
import time

import probelib

REPEATS = 5


def sndtimeo() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setsockopt(socket.SOL_SOCKET, socket.SO_SNDTIMEO, struct.pack("ll", 0, 50_000))
        started = time.perf_counter()
        total = 0
        while True:
            try:
                total += left.send(b"x" * 4096)
            except BlockingIOError as exc:
                return {"sent": total, "elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
                        "errno": exc.errno, "type": type(exc).__name__,
                        "queued": probelib.queued_bytes(left)}
    finally:
        left.close()
        right.close()


def rcvtimeo() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("ll", 0, 50_000))
        started = time.perf_counter()
        try:
            left.recv(4096)
        except BlockingIOError as exc:
            return {"elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
                    "errno": exc.errno, "type": type(exc).__name__}
        return {"elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
                "errno": None, "type": None}
    finally:
        left.close()
        right.close()


def python_timeout() -> dict:
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.settimeout(0.05)
        started = time.perf_counter()
        total = 0
        while True:
            try:
                total += left.send(b"x" * 4096)
            except OSError as exc:
                return {"sent": total, "elapsed_ms": round((time.perf_counter() - started) * 1000, 1),
                        "errno": getattr(exc, "errno", None), "type": type(exc).__name__,
                        "queued": probelib.queued_bytes(left)}
    finally:
        left.close()
        right.close()


def blocking_write() -> dict:
    """A blocking write into a full pipe: the same call, without the flag, simply waits."""
    reader, writer = os.pipe()
    try:
        os.write(writer, b"x" * 65_536)
        stamps: dict[str, float] = {}

        def drain() -> None:
            time.sleep(0.05)
            stamps["drained"] = time.perf_counter()
            os.read(reader, 4096)

        thread = threading.Thread(target=drain)
        thread.start()
        started = time.perf_counter()
        written = os.write(writer, b"y" * 4096)
        elapsed = (time.perf_counter() - started) * 1000
        thread.join()
        return {"written": written, "elapsed_ms": round(elapsed, 1),
                "errno": None, "type": None}
    finally:
        os.close(reader)
        os.close(writer)


def ready_says_no() -> dict:
    """Fill until select() refuses, then keep sending: how far does the buffer really go?"""
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        pages = 0
        while select.select([], [left], [], 0)[1]:
            left.send(b"x" * 4096)
            pages += 1
        at_refusal = {"pages": pages, "sent": pages * 4096,
                      "queued": probelib.queued_bytes(left),
                      "sndbuf": left.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)}
        after = 0
        while True:
            try:
                left.send(b"x" * 4096)
                after += 1
            except BlockingIOError:
                break
        return at_refusal | {"pages_after_readiness_refused": after,
                             "accepted_total": (pages + after) * 4096,
                             "queued_total": probelib.queued_bytes(left)}
    finally:
        left.close()
        right.close()


def main() -> None:
    arms = []
    for label, fn in (("sndtimeo_50ms", sndtimeo), ("rcvtimeo_50ms", rcvtimeo),
                      ("python_timeout_50ms", python_timeout),
                      ("blocking_write_full_pipe", blocking_write),
                      ("ready_says_no_send_continues", ready_says_no)):
        runs = [fn() for _ in range(REPEATS)]
        summary = {}
        for key in ("sent", "elapsed_ms", "errno", "queued", "pages", "pages_after_readiness_refused",
                    "accepted_total", "queued_total", "written"):
            summary[key] = probelib.summarise(runs, key)
        summary["type"] = probelib.summarise(runs, "type", number=False)
        arms.append({"label": label, "runs": runs, "summary": summary})
        print(f"{label:32s} {[(run) for run in runs][:2]}", flush=True)
    probelib.write("06_timeouts", {
        "probe": "06_timeouts", "when": probelib.when(), "repeats": REPEATS,
        "arms": arms,
        "notes": {"timeout_us": 50_000, "drain_delay_ms": 50},
    })


if __name__ == "__main__":
    main()
Readiness: stale event, level against edge, the cost of a loop sandbox/07_ready.py
"""What a readiness answer is worth: one hint, not a reservation and not a byte count."""
from __future__ import annotations

import os
import select
import socket
import threading
import time

import probelib

REPEATS = 5
WINDOW_S = 0.2


def stale_readiness() -> dict:
    """poll() says readable, another consumer takes the byte, the reserved read answers 11."""
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        os.write(writer, b"x")
        poller = select.poll()
        poller.register(reader, select.POLLIN)
        first = poller.poll(0)
        os.read(reader, 1)          # the other worker, between the answer and the read
        second = probelib.try_call(os.read, reader, 1)
        return {"poll_events": len(first), "second_poll": len(poller.poll(0)),
                "outcome": second["outcome"], "errno": second["errno"],
                "type": second["type"]}
    finally:
        os.close(reader)
        os.close(writer)


def level_vs_edge() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        level = select.poll()
        level.register(reader, select.POLLIN)
        edge = select.epoll()
        edge.register(reader, select.EPOLLIN | select.EPOLLET)
        os.write(writer, b"x" * 8192)
        first_level = len(level.poll(0))
        first_edge = len(edge.poll(0))
        os.read(reader, 4096)
        second_level = len(level.poll(0))
        second_edge = len(edge.poll(0))
        remaining = len(os.read(reader, 4096))
        third_edge = len(edge.poll(0))
        drained = probelib.try_call(os.read, reader, 4096)
        return {"first_level": first_level, "first_edge": first_edge,
                "second_level": second_level, "second_edge": second_edge,
                "remaining_without_event": remaining, "third_edge": third_edge,
                "after_drain_outcome": drained["outcome"],
                "after_drain_errno": drained["errno"]}
    finally:
        os.close(reader)
        os.close(writer)


def busy_retry() -> dict:
    reader, writer = os.pipe()
    try:
        probelib.nonblock(reader)
        calls = 0
        start_wall = time.perf_counter()
        start_cpu = time.process_time()
        while time.perf_counter() - start_wall < WINDOW_S:
            try:
                os.read(reader, 1)
            except BlockingIOError:
                calls += 1
        wall = time.perf_counter() - start_wall
        cpu = time.process_time() - start_cpu
        return {"calls": calls, "wall_s": round(wall, 3), "cpu_ms": round(cpu * 1000, 1),
                "calls_per_s": round(calls / wall)}
    finally:
        os.close(reader)
        os.close(writer)


def waiting() -> dict:
    """The same window spent in poll(): how much CPU does waiting cost?"""
    reader, writer = os.pipe()
    try:
        poller = select.poll()
        poller.register(reader, select.POLLIN)
        start_wall = time.perf_counter()
        start_cpu = time.process_time()
        poller.poll(int(WINDOW_S * 1000))
        wall = time.perf_counter() - start_wall
        cpu = time.process_time() - start_cpu
        return {"wall_s": round(wall, 3), "cpu_ms": round(cpu * 1000, 1)}
    finally:
        os.close(reader)
        os.close(writer)


def wake_latency() -> dict:
    reader, writer = os.pipe()
    try:
        stamps: dict[str, float] = {}

        def announce() -> None:
            time.sleep(0.02)
            stamps["sent"] = time.perf_counter()
            os.write(writer, b"x")

        thread = threading.Thread(target=announce)
        thread.start()
        poller = select.poll()
        poller.register(reader, select.POLLIN)
        poller.poll(2000)
        stamps["woke"] = time.perf_counter()
        thread.join()
        return {"latency_us": round((stamps["woke"] - stamps["sent"]) * 1e6, 1)}
    finally:
        os.close(reader)
        os.close(writer)


def gate_then_send() -> dict:
    """Poll-gated sending: wait for writability, then send, until a 50 ms budget runs out."""
    left, right = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        left.setblocking(False)
        deadline = time.perf_counter() + 0.05
        poller = select.poll()
        poller.register(left, select.POLLOUT)
        sent = 0
        waits = 0
        while time.perf_counter() < deadline:
            remaining_ms = int((deadline - time.perf_counter()) * 1000)
            if not poller.poll(max(0, remaining_ms)):
                break
            waits += 1
            try:
                sent += left.send(b"x" * 4096)
            except BlockingIOError:
                break
        return {"sent_gated": sent, "waits": waits,
                "queued": probelib.queued_bytes(left),
                "errno": None if sent else 11}
    finally:
        left.close()
        right.close()


def main() -> None:
    arms = []
    for label, fn in (("stale_readiness", stale_readiness), ("level_vs_edge", level_vs_edge),
                      ("busy_retry", busy_retry), ("waiting", waiting),
                      ("wake_latency", wake_latency), ("gate_then_send", gate_then_send)):
        runs = [fn() for _ in range(REPEATS)]
        summary = {}
        for key in ("poll_events", "second_poll", "errno", "first_level", "first_edge",
                    "second_level", "second_edge", "remaining_without_event", "third_edge",
                    "after_drain_errno", "calls", "calls_per_s", "cpu_ms", "wall_s",
                    "latency_us", "sent_gated", "waits", "queued"):
            summary[key] = probelib.summarise(runs, key)
        summary["outcome"] = probelib.summarise(runs, "outcome", number=False)
        arms.append({"label": label, "runs": runs, "summary": summary})
        print(f"{label:20s} {runs[:2]}", flush=True)
    probelib.write("07_ready", {
        "probe": "07_ready", "when": probelib.when(), "repeats": REPEATS, "arms": arms,
        "notes": {"window_s": WINDOW_S, "gate_budget_ms": 50, "poison_byte": 1},
    })


if __name__ == "__main__":
    main()
The accept queue: four backlog sizes and the empty queue sandbox/08_accept.py
"""The accept queue: what a full backlog tells the client, and what it tells the server."""
from __future__ import annotations

import select
import socket
import time

import probelib

REPEATS = 5
ATTEMPTS = 4


def backlog(backlog: int) -> dict:
    server = socket.socket()
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("127.0.0.1", 0))
    server.listen(backlog)
    clients = []
    answers = []
    try:
        for _ in range(ATTEMPTS):
            client = socket.socket()
            client.setblocking(False)
            answers.append(probelib.try_call(client.connect, server.getsockname()))
            clients.append(client)
        time.sleep(0.3)
        writable = sum(1 for client in clients if select.select([], [client], [], 0)[1])
        # the server can take what made it into the queue, and one more asks for another
        server.setblocking(False)
        accepted = 0
        codes = []
        while True:
            outcome = probelib.try_call(server.accept)
            if outcome["outcome"] != "ok":
                codes.append(outcome["errno"])
                break
            accepted += 1
            outcome["value"][0].close()
        return {"backlog": backlog, "attempts": ATTEMPTS,
                "completed": writable, "answers": [answer["errno"] for answer in answers],
                "accepted_from_queue": accepted, "final_accept_errno": codes[-1]}
    finally:
        for client in clients:
            client.close()
        server.close()


def empty_queue() -> dict:
    server = socket.socket()
    server.bind(("127.0.0.1", 0))
    server.listen(4)
    server.setblocking(False)
    try:
        outcome = probelib.try_call(server.accept)
        return {"outcome": outcome["outcome"], "errno": outcome["errno"],
                "type": outcome["type"]}
    finally:
        server.close()


def main() -> None:
    arms = []
    for depth in (0, 1, 2, 8):
        runs = [backlog(depth) for _ in range(REPEATS)]
        arms.append({"label": f"backlog_{depth}", "runs": runs, "summary": {
            "completed": probelib.summarise(runs, "completed"),
            "accepted_from_queue": probelib.summarise(runs, "accepted_from_queue"),
            "final_accept_errno": probelib.summarise(runs, "final_accept_errno"),
            "answers": probelib.summarise(runs, "answers", number=False),
        }})
        print(f"backlog {depth}: {[(run['completed'], run['accepted_from_queue']) for run in runs]}",
              flush=True)
    runs = [empty_queue() for _ in range(REPEATS)]
    arms.append({"label": "empty_queue", "runs": runs, "summary": {
        "outcome": probelib.summarise(runs, "outcome", number=False),
        "errno": probelib.summarise(runs, "errno"),
    }})
    print("empty:", runs[:2], flush=True)
    probelib.write("08_accept", {
        "probe": "08_accept", "when": probelib.when(), "repeats": REPEATS, "arms": arms,
        "notes": {"attempts": ATTEMPTS, "settle_ms": 300,
                  "queue_depth_rule": "one more than the backlog argument"},
    })


if __name__ == "__main__":
    main()
The tree’s own counts: tests, package lines, example lines sandbox/09_counts.py
"""Count what the page claims about its own tree: tests, lines, probes, the example."""
from __future__ import annotations

import json
import pathlib
import re
import subprocess
import sys

import probelib

HERE = pathlib.Path(__file__).resolve().parent.parent


def lines(paths: list[pathlib.Path]) -> int:
    return sum(len(path.read_text(encoding="utf-8").splitlines()) for path in paths)


def python_files(base: pathlib.Path) -> list[pathlib.Path]:
    return sorted(path for path in base.rglob("*.py") if "__pycache__" not in path.parts)


def main() -> None:
    package = [path for path in python_files(HERE / "nbio") if "tests" not in path.parts]
    tests = python_files(HERE / "nbio" / "tests")
    probes = python_files(HERE / "sandbox")
    examples = python_files(HERE / "examples")
    completed = subprocess.run([sys.executable, "-m", "pytest", "nbio/tests", "-q",
                                "-p", "no:warnings", "-p", "no:asyncio"],
                               cwd=str(HERE), capture_output=True, text=True, timeout=600)
    passed = re.search(r"(\d+) passed", completed.stdout + completed.stderr)
    example = subprocess.run([sys.executable, "examples/eagain_demo.py"], cwd=str(HERE),
                             capture_output=True, text=True, timeout=600,
                             env={"PATH": "/usr/local/bin:/usr/bin:/bin",
                                  "PYTHONPATH": str(HERE)})
    notes = {
        "pytest_passed": int(passed.group(1)) if passed else 0,
        "pytest_rc": completed.returncode,
        "package_files": len(package),
        "package_lines": lines(package),
        "test_files": len(tests),
        "test_lines": lines(tests),
        "probe_files": len(probes),
        "probe_lines": lines(probes),
        "example_files": len(examples),
        "example_lines": lines(examples),
        "example_returncode": example.returncode,
        "example_tail": example.stdout.strip().splitlines()[-1] if example.stdout.strip() else "",
        "example_lines_printed": len(example.stdout.strip().splitlines()),
    }
    print(json.dumps(notes, indent=1), flush=True)
    probelib.write("09_counts", {
        "probe": "09_counts", "when": probelib.when(), "repeats": 1, "notes": notes,
    })


if __name__ == "__main__":
    main()
The suite re-run in a clean root made from the printed files sandbox/10_layout.py
"""Prove the tree the page prints is a tree that runs, from an empty directory.

The page prints the three package files and the example whole, and folds the three test files into
the appendix. This copies exactly those paths under a fresh temporary root, then runs the suite
and the example there - a ``parents[N]`` that only works in the working tree fails here.
"""
from __future__ import annotations

import json
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile

import values  # noqa: E402 - the tree's own module, found through PYTHONPATH

HERE = pathlib.Path(__file__).resolve().parent.parent
PRINTED = (
    "nbio/__init__.py",
    "nbio/buffers.py",
    "nbio/retry.py",
    "examples/eagain_demo.py",
    "nbio/tests/test_buffers.py",
    "nbio/tests/test_retry.py",
    "nbio/tests/test_walls.py",
)


def run(argv: list[str], cwd: pathlib.Path) -> dict:
    result = subprocess.run([sys.executable, *argv], cwd=str(cwd), capture_output=True,
                            text=True, env={**os.environ, "PYTHONPATH": str(cwd)})
    tail = (result.stdout + result.stderr).strip().splitlines()
    return {"argv": argv, "returncode": result.returncode, "tail": tail[-3:]}


def main() -> None:
    root = pathlib.Path(tempfile.mkdtemp(dir="/tmp", prefix="p44_layout_"))
    try:
        sizes = {}
        for rel in PRINTED:
            source = HERE / rel
            target = root / rel
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(source, target)
            sizes[rel] = len(source.read_bytes())
        pytest_result = run(["-m", "pytest", "nbio/tests", "-q", "-p", "no:cacheprovider",
                             "-p", "no:warnings", "-p", "no:asyncio"], root)
        answer = " ".join(pytest_result["tail"])
        passed = int(match.group(1)) if (match := re.search(r"(\d+) passed", answer)) else 0
        example_result = run(["examples/eagain_demo.py"], root)
        record = {
            "probe": "10_layout",
            "root": "a temporary directory holding only the paths the page prints",
            "paths": list(PRINTED),
            "bytes": sizes,
            "pytest": pytest_result,
            "pytest_passed": passed,
            "pytest_expected": int(values.IDENTIFIERS["tests"]),
            "example": example_result,
        }
        (HERE / "results" / "10_layout.json").write_text(json.dumps(record, indent=1) + "\n",
                                                         encoding="utf-8")
        print(f"copied {len(PRINTED)} files into a clean root")
        print(f"pytest on the copy: {answer or 'no summary line'} (rc {pytest_result['returncode']})")
        print(f"example on the copy: rc {example_result['returncode']}")
        if pytest_result["returncode"] != 0 or passed != int(values.IDENTIFIERS["tests"]):
            raise SystemExit("the printed tree does not reproduce the suite")
        if example_result["returncode"] != 0:
            raise SystemExit("the example does not run from the printed tree")
        print("the paths the page prints are a tree in which its tests and its example run")
    finally:
        shutil.rmtree(root, ignore_errors=True)


if __name__ == "__main__":
    main()
The example’s five lines, recorded as they were printed sandbox/11_demo.py
"""Run the example the page prints and record its five lines."""
from __future__ import annotations

import subprocess
import sys

import probelib

HERE = __import__("pathlib").Path(__file__).resolve().parent.parent

completed = subprocess.run([sys.executable, "examples/eagain_demo.py"], cwd=str(HERE),
                           capture_output=True, text=True, timeout=120,
                           env={"PATH": "/usr/local/bin:/usr/bin:/bin",
                                "PYTHONPATH": str(HERE)})
lines = completed.stdout.strip().splitlines()
probelib.write("11_demo", {
    "probe": "11_demo",
    "when": probelib.when(),
    "repeats": 1,
    "notes": {
        "returncode": completed.returncode,
        "lines": lines,
        "line_count": len(lines),
        "budget_line": next((line for line in lines if line.startswith("budget:")), ""),
        "wrote_line": next((line for line in lines if line.startswith("wrote:")), ""),
        "pages_line": next((line for line in lines if line.startswith("pages:")), ""),
        "readiness_line": next((line for line in lines if line.startswith("readiness:")), ""),
        "gated_line": next((line for line in lines if line.startswith("gated:")), ""),
        "all_rc_zero": completed.returncode == 0,
    },
})
print(completed.stdout)
The three shell blocks, run and recorded sandbox/12_shell.py
"""Run each shell block the page prints, in the order it prints them, and record the output."""
from __future__ import annotations

import subprocess

import probelib
import shellblocks

records = []
for title, command in shellblocks.BLOCKS:
    completed = subprocess.run(["sh", "-c", command], capture_output=True, text=True,
                               timeout=120)
    record = {"title": title, "command": command, "rc": completed.returncode,
              "stdout": completed.stdout.strip(), "stderr": completed.stderr.strip()[-400:]}
    records.append(record)
    print(f"{title}: rc={record['rc']} out={record['stdout'][:120]!r}", flush=True)

probelib.write("12_shell", {
    "probe": "12_shell",
    "when": probelib.when(),
    "repeats": 1,
    "records": records,
    "notes": {
        "blocks": len(records),
        "all_ran": all(record["rc"] == 0 for record in records),
        "pipe_size_printed": any(record["stdout"].strip() == "65536" for record in records),
        "pipe_buf_printed": any("4096" in record["stdout"].splitlines() for record in records),
        "pipe_max_printed": any("1048576" in record["stdout"] for record in records),
        "sndbuf_printed": any(record["stdout"].strip() == "212992" for record in records),
    },
})

Keep reading

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