BrokenPipeError Errno 32: 5 States, 1 Accepted Write, Exit 120

Dark cover headed 'BrokenPipeError': 5 peer states share errno 32, one 4 KiB write is accepted after the reader closes, a pipe holds its 65,536-byte capacity or 64,000 with 100-byte lines, and the name on the HTTP path follows the client's exit - errno 104 on 20 of 25 failed replies, errno 32 on 5

TL;DR: One Number, Five States, One Write Too Late

  • BrokenPipeError: [Errno 32] is one number that arrived from 5 different states in these runs: a TCP peer, a Unix peer, a pipe with no reader, this end shut down, and a socket never connected.
  • A write after the reader leaves does not fail at once. A socket accepted exactly 1 further write at every chunk size tested, up to 256 KiB; a pipe filled to 65,536 bytes first, or to 64,000 with 100-byte lines.
  • The name on the HTTP path follows the client’s exit: of 25 failed replies, 20 were ConnectionResetError after a client that left unread bytes and 5 were BrokenPipeError after a client that drained the reply, so a handler has to catch both names.
  • A failed write cannot be retried on the connection that failed. Stop writing, flush what a reader may still take, and exit with a status you chose; the fallback is 120.

Scope. Every figure comes from one Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, loopback sockets, Unix socketpairs and anonymous pipes only, 5 repeats per arm. The peer states are 10, the socket chunk sizes 5, the pipe line sizes 3, the pipe fills 8, the HTTP arms 6, and the TCP_INFO arms 3. Another kernel, a container runtime or a proxy may report the same event under another number; where this page did not reproduce a case, it says so instead of generalising.

Fix It First: Eight Changes, in the Order They Cost

Find the line in your log, stop at the first row that matches it, and make that change: reading the number is free, catching the second name is a line of code, and redirecting a descriptor is a decision about status codes.

What the log showsChange to makeMeasured on this page
BrokenPipeError: [Errno 32] from a writeStop writing, flush what the reader may still take, and exit; do not retry on that connectionone number, 5 states (section 1)
ConnectionResetError: [Errno 104] after a client goes awayCatch both names and read the errno; which one arrives depends on how the client left20 of 25 HTTP write failures (section 4)
The write after a close is reported as successfulCount the bytes you hand over and stop at the first failing write; the accepted one is invisible to the callerexactly 1 write accepted at every chunk size (section 2)
A job writes tens of kilobytes, then diesTreat the pipe buffer as a buffer: the last bytes are not delivered65,536 bytes accepted before EPIPE, 64,000 with 100-byte lines (section 2)
A command exits 120 and prints Exception ignoredPoint descriptor 1 at /dev/null before exiting, so the shutdown flush has nothing to fail onstatus 120 with 124 bytes on stderr (section 6)
A command exits 1 with a traceback under head or grep -qCatch at the write site, then redirect the descriptor; a bare catch alone is not enoughtraceback of 256 bytes, status 1 (section 6)
A worker dies with status -13, or a shell reports 141Python ignores SIGPIPE at startup; restore the ignore, or send with MSG_NOSIGNALtwo of 5 dispositions died on signal 13 (section 5)
A socket server prints Broken pipe for a peer that is not thereCheck that the socket was connected and still open for writing; the number does not tell that apart from a reader that lefta socket with no peer raised the same number as a closed pipe (section 1)
Table 1: eight changes, matched to the line a reader is looking at. The last column names the measurement behind each row and the section that reports it.

1. One Number, Five States

BrokenPipeError subclasses OSError and carries errno 32; what it does not carry is which situation produced it. Probe 02 sends 4 KiB at a time from a writer whose socket or pipe is in one of ten states, and records the writes accepted before the first error, the exception that arrived, and its number.

What was true at the writeWrites acceptedFirst errorNumber
TCP peer closed (FIN), then a write1BrokenPipeError32
TCP peer reset (RST), then a write0ConnectionResetError104
Unix socket peer closed0BrokenPipeError32
Pipe read end closed0BrokenPipeError32
This end shut down for writing0BrokenPipeError32
A socket that was never connected0BrokenPipeError32
This end already closed0OSError9
Writing to a pipe’s read end0OSError9
Peer half-closed, still reading5none in five writesnone
Peer half-closed, never reading1,900,544 bytesblocked after 500 msnone
Table 2: ten states at the moment of the write, five repeats each, identical within every arm. Errno 32 covers five of them – a family name, not a diagnosis – and the last two rows are the half-close control.

Two rows are worth a second look. A socket that was never connected raises BrokenPipeError, so a service that reports “the client disconnected” may be reporting a missing connect(). A descriptor this process already closed raises errno 9, which is the one a handler is most likely to skip.

The classifier follows the cause chain to the first OSError, because the exception a caller catches is rarely the one that decided the outcome, and maps the number to a remedy and a retry budget; anything outside the four rows returns as unrelated. The ESHUTDOWN row says in its own text that these probes did not produce it – a local shutdown returned 32 – and its remedy warns against reopening the connection per request.

"""What a failed write means, read from its errno rather than from its message.

The same event reaches Python under three names: ``BrokenPipeError`` for EPIPE,
``ConnectionResetError`` for ECONNRESET, and a bare ``OSError`` for a descriptor that was already
closed. A handler that catches one of them lets the other two through, which is how a dropped
reader turns into a 500 in one service and a silent loop in the next. This module turns whichever
arrived into one record: the number, the group it belongs to, what it says about the reader, and
what the writer may do next.

Every group in the table has a retry budget of zero, and the budget describes one write on the
connection that failed, not a client that reconnects and resends an idempotent request.
"""

from __future__ import annotations
import errno
from dataclasses import dataclass
from enum import Enum


class Kind(str, Enum):
    """The four groups a failed write falls into."""

    READER_GONE = "reader gone"
    RESET = "reset"
    CLOSED_HANDLE = "closed handle"
    UNRELATED = "unrelated"


@dataclass(frozen=True)
class Fault:
    """One classified failure: the number, its group, what it means and the next move."""

    number: int | None
    kind: Kind
    meaning: str
    remedy: str
    retry_budget: int


TABLE: dict[int, Fault] = {
    errno.EPIPE: Fault(errno.EPIPE, Kind.READER_GONE,
                       "the reader closed its end of the pipe",
                       "stop writing: nothing after this call can be delivered",
                       0),
    errno.ECONNRESET: Fault(errno.ECONNRESET, Kind.RESET,
                            "the peer sent RST, so the reply was refused",
                            "stop writing and let the connection close",
                            0),
    errno.ESHUTDOWN: Fault(errno.ESHUTDOWN, Kind.CLOSED_HANDLE,
                           "the transport endpoint was already shut down "
                           "(not reproduced here: a local shutdown() returned 32)",
                           "find who shut the endpoint down; a per-request reopen hides it",
                           0),
    errno.EBADF: Fault(errno.EBADF, Kind.CLOSED_HANDLE,
                       "the descriptor was closed before the write",
                       "fix who owns the descriptor, not the write",
                       0),
}


def unwrap(exc: BaseException) -> BaseException:
    """Follow the cause chain to the first OSError, which is where the errno lives."""
    current: BaseException = exc
    seen: set[int] = set()
    while id(current) not in seen:
        seen.add(id(current))
        if isinstance(current, OSError):
            return current
        nxt = current.__cause__ or current.__context__
        if nxt is None:
            return current
        current = nxt
    return current


def classify(exc: BaseException) -> Fault:
    """Return the record for the failure that reached the caller, wrappers included."""
    inner = unwrap(exc)
    number = inner.errno if isinstance(inner, OSError) else None
    if number in TABLE:
        return TABLE[number]
    return Fault(number, Kind.UNRELATED,
                 "not a pipe or socket write failure",
                 "read the errno: this table does not classify it", 0)


def is_reader_gone(exc: BaseException) -> bool:
    """True when the failure says the other side stopped reading, in either form."""
    return classify(exc).kind in (Kind.READER_GONE, Kind.RESET)

The budget is zero for every row and says one thing: a write on the connection that just failed cannot reach the reader. It is a statement about that socket, not about the request – a client whose idle pooled connection was reset may open a new one and resend an idempotent request, which is a different write to a live peer. The record is frozen so two handlers cannot classify the same failure differently.

2. The Write That Succeeds Into a Dead Reader

The first surprise is that the write after the reader’s departure does not fail: the kernel takes the bytes, returns their length, and the application believes it has replied. Probe 03 measures how much it can believe.

BufferPiece sizeAccepted before the errorFirst error
TCP send buffer1,024 B1 write (1,024 B)EPIPE 32
TCP send buffer4,096 B1 write (4,096 B)EPIPE 32
TCP send buffer16,384 B1 write (16,384 B)EPIPE 32
TCP send buffer65,536 B1 write (65,536 B)EPIPE 32
TCP send buffer262,144 B1 write (262,144 B)EPIPE 32
Pipe to head -1100 B lines64,000 BEPIPE 32
Pipe to head -11,024 B lines65,536 BEPIPE 32
Pipe to head -14,096 B lines65,536 BEPIPE 32
Table 3: how much one dead reader absorbs – one write on a socket, whatever its size, and what the buffer holds on a pipe. Counts are the sum of return values, because a call may accept less than it was offered. Five repeats were identical; one later run of the 1,024-byte arm delivered a slot more.

The pipe rows explain a support ticket. A command that writes 65,536 bytes to head -1 has handed every byte to the kernel; head read one line and exited; the rest waited in the buffer until the next write found the read end gone. Nothing in the log separates that from a successful 65,536 bytes.

The 100-byte arm stopped 1,536 bytes below the capacity, and the reason is structural. The buffer is a ring of 16 page-sized slots of 4,096 bytes. A write smaller than a page joins the last slot while it has room, so 100-byte lines fill 40 to a slot and cannot start another: 100 bytes do not fit in the 96 left over. 16 slots of 40 lines make 64,000 bytes, and the missing 1,536 are the leftovers.

Probe 09 tests that model against six line sizes and two capacities, filling a pipe nothing reads until the kernel reports it full; it matches in every arm.

Line sizeCapacityLinesBytes acceptedSlots x lines x line
64 B65,5361,02465,53616 x 64 x 64
100 B65,53664064,00016 x 40 x 100
128 B65,53651265,53616 x 32 x 128
512 B65,53612865,53616 x 8 x 512
1,024 B65,5366465,53616 x 4 x 1,024
4,096 B65,5361665,53616 x 1 x 4,096
100 B, grown131,0721,280128,00032 x 40 x 100
1,024 B, grown131,072128131,07232 x 4 x 1,024
Table 4: one pipe, eight fills, five repeats each. The last column is the model – capacity over page for the slots, page over line for the lines a slot holds – and it equals the measurement in every row, including the two grown to 131,072 bytes.

On a socket the arithmetic is sharper: exactly one write is accepted, at every size from 1,024 B to 262,144 B – which is why an HTTP server logs a 200 for a client that has gone, and why the error points at the write after the one that lost the reply.

3. FIN, RST, and the Reader That Only Stopped Talking

A TCP peer has two ways to leave, and the writer sees different numbers. A close sends FIN: the peer will read nothing more, but the connection is intact. A reset sends RST: the connection is gone and any bytes in flight are refused. This end’s own shutdown is a third state, in Table 2 rather than here.

What the peer didWhat the writer sawDeliveredWhat it means
close(), sending FINBrokenPipeError, errno 32, on the write after the one it accepted1 writethe peer finished reading but did not reset; the first write is absorbed, the reset answers it, the next write raises
close() with SO_LINGER 0, sending RSTConnectionResetError, errno 104 on the first write0 writesthe peer refused the connection outright; nothing is absorbed and the first write fails
shutdown(SHUT_WR), still readingno error in five writes5 writesa half-close is a request to finish, not a departure; the peer still reads what you send
shutdown(SHUT_WR), never reading1,900,544 bytes accepted, then blocked at the probe’s 500 ms timeout1,856 KiBthe window and buffer fill; without a timeout the writer waits forever, and a socket timeout is the only thing that ends it
Table 5: four peer states on loopback, five repeats each. Delivered counts what the kernel accepted, not what the peer application read: after FIN the bytes were handed over and then reset, which is why the loss is invisible from the return value.

A FIN means the client finished reading and closed: the reply in flight is lost, and the next write says so. An RST means the connection never had a chance to finish, and the write that meets it is the one that fails. A half-close is the opposite of both – the client stopped sending and is still waiting for the reply, so aborting it is the bug; an API that treats every client EOF as a reason to stop writing turns a normal upload into a truncated download.

The fourth row ends in an incident rather than an exception. A peer that half-closed and stopped reading leaves the writer blocked after 1,856 KiB, with no error at all. That figure is not a constant of TCP: it is how far the send buffer and the receive window had grown when the timeout fired, and the split was not measured. The shape is what travels: the writer waits for a reader that will never read, and only a timeout turns that wait into a failure.

The two exits above can be located more precisely than the half-close was, because the kernel reports where the socket stood: TCP_INFO carries tcpi_state, and probe 10 reads it immediately before and after every write – including one that meets a reset while it is blocked inside send.

What happenedState before the writeWrites acceptedFirst errorState after
RST met a write that was blocked in send1 ESTABLISHED3 calls (2,625,195 B), the last one shortnone7 CLOSE
the next write, which started from CLOSE7 CLOSE0ConnectionResetError, errno 1047 CLOSE
FIN received; the first write into CLOSE_WAIT8 CLOSE_WAIT1 (4,096 B)none7 CLOSE
the next write, after the peer answered that one with RST7 CLOSE0BrokenPipeError, errno 327 CLOSE
RST processed before the write7 CLOSE0ConnectionResetError, errno 1047 CLOSE
Table 6: five writes, five repeats each, with tcpi_state read from TCP_INFO immediately before and after each call. The first two rows are one arm: a loop of 1 MiB sends that meets a reset while it is blocked, so the count in the first row is every call the loop had placed. All five repeats stopped at the same byte count – 528,043 B of the 1,048,576 offered – and that figure is not a constant: the probe waits 50 ms before it resets the peer, so another delay or kernel could split it differently.

The rule lives in the kernel’s mapping, not in the state a write starts from: a reset that arrives on a socket still ESTABLISHED is reported as 104, and a reset that answers a write on a socket which had already received the peer’s FIN – one in CLOSE_WAIT – is reported as 32. Table 6 lines up both paths and adds a third case in its first two rows: a reset that arrives while a call is blocked in send does not fail that call at all. The kernel returns what it had already copied – 528,043 B – and the error waits for the next call, which raises 104 from a socket whose state already reads CLOSE. When FIN arrives first, the write lands in CLOSE_WAIT and is accepted, the peer’s closed socket answers it with RST, and the following write raises EPIPE 32. Both numbers are read after the state has reached CLOSE, so what separates them is where the reset met the connection – the part an exception name alone cannot tell you.

4. On the HTTP Path the Name Follows the Client’s Exit

Everything above is socket arithmetic; it matters because the socket sits under an HTTP server. Probe 04 runs a threaded HTTP/1.1 server with a chunked reply, and six clients that read the headers and leave: two chunk sizes crossed with two gaps, a client that resets, and one that drains before closing. Which name the server’s write loop sees depends on the client’s exit.

ArmDelivered before the errorErrorElapsed
1 KiB chunks, no gap204,800 B in all 5 repeats, no errornone0.28 ms to 0.61 ms
1 KiB chunks, 2 ms gap3,072 BConnectionResetError 5/56.29 ms to 6.35 ms
64 KiB chunks, no gap2,621,440 BConnectionResetError 5/55.18 ms to 5.28 ms
64 KiB chunks, 2 ms gap196,608 BConnectionResetError 5/56.36 ms to 6.50 ms
1 KiB chunks, 2 ms gap, client resets1,024 BConnectionResetError 5/52.12 ms to 2.21 ms
1 KiB chunks, 2 ms gap, client drains then closes4,096 BBrokenPipeError 5/58.37 ms to 8.72 ms
Table 7: one client that leaves, six ways. The first arm is the one to keep in mind: with small chunks and no gap the server delivered its whole reply into a client that was already gone, in all 5 repeats, and recorded no error. The last two rows change only the client’s exit.

Across the 30 observations, 25 replies ended in an error, and every one carried one of two numbers: 20 were ConnectionResetError with errno 104, 5 were BrokenPipeError with errno 32. A client that closes with unread bytes in its receive queue makes its kernel send RST; a client that drains first sends FIN, and the writer keeps pushing into a closed connection.

That is why the name in a title is a poor filter: a handler written around BrokenPipeError catches 5 of these 25 failures, one written around ConnectionResetError the other 20, and the errno then says whether a close, a reset or a descriptor this process closed itself is behind it. The remaining 5 replies finished with no error at all, into a client that had read nothing since its first read: the reply was shorter than the kernel would absorb, so a dashboard built on exceptions shows a healthy server.

The last two HTTP arms are the control for the amount: the client that reset before closing left 1,024 bytes delivered, the client that drained and closed left 4,096, with the same chunk size and gap. The exit decides both the amount and the name, and neither amount is zero – so “the client disconnected” is a state to detect before the write, not an exception to handle after it.

5. Why Python Raises Where C Dies

A write to a socket or pipe with no reader sets a condition the kernel also reports as SIGPIPE; whether the process sees an exception or dies is a property of the signal disposition, which CPython changes at startup. Probe 05 runs the same write with the disposition untouched, restored to the default, and bypassed with MSG_NOSIGNAL.

Child’s writeDispositionWhat the child sawExit status
pipe, interpreter default1 (ignore)BrokenPipeError 320
pipe, SIG_DFL restored0 (default)killed by signal 13 before any handler ran-13
socket, interpreter default1 (ignore)BrokenPipeError 320
socket, SIG_DFL restored0 (default)killed by signal 13 before any handler ran-13
socket, SIG_DFL, MSG_NOSIGNAL0 (default)BrokenPipeError 320
Table 8: five children, one write each, five repeats, identical. A negative status records a process the kernel killed; the signal’s number is the documented value for SIGPIPE, not a measurement of this host.

The disposition is visible from inside the interpreter – probe 01 reads it back as 1, which is SIG_IGN – and that is why a Python service sees an exception where a program on the default disposition dies. An extension that restores the default turns the same write into a killed worker with no traceback: -13 in a supervisor log and 0 with the exception caught are one event under two policies.

The last row is the policy for code that must not die: pass 16,384 to send – MSG_NOSIGNAL on Linux – and the kernel reports EPIPE to the call instead of raising the signal, whatever the disposition. Ordinary Python code does not need the flag; a library that hands a socket to C, or runs where the disposition is not the interpreter’s, does.

6. The Pipeline’s Three Exit Codes

A command-line tool meets the same event with a different contract: the caller is a program reading a pipe, and the question is the status the tool leaves behind. Probe 06 starts five children; for the first two it reads one line the way head -1 would, for the other three the reader leaves before the child writes.

ChildStatusstderrWhat it means
loop of print, no handler1256 B, tracebackthe error escaped from the loop and the interpreter printed it
loop, except BrokenPipeError: pass00 B, no messagestatus 0 while the reader got one line and the rest was dropped; the failure is hidden, not handled
buffered write after the reader left120124 B, Exception ignoredthe write went into the buffer, the failure happened in the shutdown flush
same, with a catch at the flush120124 B, Exception ignoredcatching the flush is not enough: the interpreter flushes again on its way out
same, with the descriptor redirected00 Bthe status the program chose, and no message, because nothing was left to fail
Table 9: five ways a command can meet a closed stdout, five repeats each. Status 0 appears twice with empty stderr, and only one of them is the program’s decision. The byte counts are this host’s and include the child’s path in the traceback; the status does not move.

The status 120 deserves a sentence of its own, because it is the one people search for. CPython flushes standard streams during shutdown; if that flush fails, it prints Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, followed by the exception, and exits with that status instead of the program’s – not a bug in the command, but the interpreter reporting that its last request could not be done. Pointing descriptor 1 at /dev/null makes the flush a write that cannot fail.

The function below is the whole fix: flush what the reader may still take, open /dev/null, duplicate it onto descriptor 1, close the extra descriptor, and exit with the status the caller chose. It catches OSError on the flush because a broken pipe arrives under either name, and nothing around the redirect.

"""Ending a command-line program whose reader has gone.

When stdout is a pipe and the reader exits - ``head``, ``grep -q``, a pager someone quit - the
next write raises ``BrokenPipeError``. Letting it escape prints a traceback. Catching it and
returning is not enough either: the interpreter flushes the same dead pipe during shutdown, prints
``Exception ignored`` on stderr and exits with status 120.

Both outcomes are avoided by doing the one thing the interpreter will not do for itself: point
descriptor 1 at ``/dev/null`` while it is still open, then exit with the status the program
chooses. After the redirect there is nothing left for the shutdown flush to fail on.
"""

from __future__ import annotations
import os
import sys
from typing import NoReturn


def exit_quietly(code: int = 0) -> NoReturn:
    """Flush what the reader may still take, silence descriptor 1, and exit with ``code``."""
    try:
        sys.stdout.flush()
    except OSError:
        pass
    try:
        devnull = os.open(os.devnull, os.O_WRONLY)
    except OSError:
        raise SystemExit(code)
    os.dup2(devnull, sys.stdout.fileno())
    os.close(devnull)
    raise SystemExit(code)

7. The One Log Line That Ends the Guessing

A traceback says Traceback (most recent call last):, names the exception as BrokenPipeError: [Errno 32] Broken pipe, and then lists the framework’s call stack. What the next person needs is four fields on one line: what was being written to, which number arrived with which group, how many bytes had been delivered, and what the policy allows next.

"""One log line for a failed write, carrying the number the next person needs.

A traceback names the exception type and stops there: ``BrokenPipeError: [Errno 32] Broken pipe``
says which number, but a server log that records only the type loses it, and one that records the
whole traceback buries it under twenty frames. The line below keeps the four fields that decide
what happens next: the target, the errno with its group, how many bytes were delivered, and the
retry budget.
"""

from __future__ import annotations
from .errors import classify
from .writes import Delivery


def describe_failure(exc: BaseException, target: str, delivery: Delivery | None = None) -> str:
    """Return one line: target, errno, group, bytes delivered and the retry budget."""
    fault = classify(exc)
    number = "none" if fault.number is None else str(fault.number)
    sent = "unknown" if delivery is None else str(delivery.sent_bytes)
    return (f"write to {target}: errno {number} ({fault.kind.value}); "
            f"delivered {sent} B; retries {fault.retry_budget}")

The delivery record is optional because the byte count separates the failures this page keeps apart: a reply cut after 65,536 bytes reads differently from one cut after 2,621,440.

The budget in the line is what stops an argument: a retry policy usually lives in a configuration file written by someone who never saw the failure, while here it is decided with the evidence (section 1).

Log the line once per reply, not once per chunk. A dead reader raises on every iteration of a loop that catches and continues – in the 64 KiB HTTP arm the failing write came after 2.5 MiB had been accepted – and the counting record stops the loop where the reader stopped.

8. What Not to Do

  • Retry the write on a dead connection. The second attempt reaches the same closed end and produces the same number, as every repeat in the HTTP arms did.
  • Catch one name. In the HTTP arms one name covered 20 failures and the other 5. Catch OSError and classify the errno.
  • Treat a short write as success. A non-blocking write of 1 MiB returned 65,536 bytes on this host, and the count is the only warning.
  • Let Exception ignored stand as the error message. Status 120 with that line is a write policy failing, not a bug to file against CPython.
  • Turn a client disconnect into a server error. A 500 in the access log and an alert on the error rate both describe a client that closed a tab; count it, and compare the reply’s byte count with the intended one.
  • Assume 64 KiB fits any write. The buffer is a kernel default and holds whole page slots, so 100-byte lines fill 64,000 of its 65,536; the writer is told about the reader one buffer late.

9. Triage in Sixty Seconds

When the line appears, the order below answers the question in the order the evidence becomes available. Each step is one lookup or one line of code, and stopping at the first step that explains the failure is the point.

  1. Read the number, not the name. 32 means the family in section 1, 104 means a reset, 9 means this process closed its own descriptor. The name and the number disagree often enough that the number is the one to trust.
  2. Ask which end moved. A FIN, an RST and this end’s own shutdown are three different repairs; section 3 has the first two, and Table 2 has the shutdown.
  3. Count the bytes. Zero delivered means the first write met a closed end; a buffer’s worth means the reply was absorbed and the reader left mid-reply. The count separates a deployment that dropped a connection from a client that walked away.
  4. Stop writing. Nothing after the failure can be delivered, and a loop that keeps calling turns one line in the log into thousands.
  5. Flush what the reader may still take, then exit with the status the program chose. For a CLI that means flushing first and then pointing descriptor 1 at /dev/null; for a server it means closing the connection and recording the reply’s byte count.
  6. Log one line with target, errno, bytes and the retry budget, and let the request end. That line is what the next incident is diagnosed from.

The whole policy is three verbs: stop writing when the number says the reader is gone, flush what a reader might still take, and exit – with a chosen status in a command, with a closed connection in a server. Everything else on this page is the evidence for those three.

Frequently asked questions

Is BrokenPipeError the same as ConnectionResetError?

No, though they belong to one event. BrokenPipeError is errno 32 and ConnectionResetError is errno 104: a peer that closes cleanly produces the first on a later write, a peer that resets the second on the write that meets it. One HTTP run produced both, with 20 of 25 failed replies carrying 104 and 5 carrying 32.

Should I retry a write that failed with EPIPE?

Not on the connection that failed: the reader’s decision cannot change between attempts on the same socket, and every repeat in the buffer and HTTP arms returned the same error at the same byte count. Section 1 separates that from a client that opens a new connection to resend an idempotent request.

Why did my Python command exit with status 120?

120 is what CPython returns when flushing standard output fails while the interpreter shuts down. It printed Exception ignored and the BrokenPipeError first, in 124 bytes on this host. Stop writing, flush, point descriptor 1 at /dev/null, and exit with your own status.

Why does head -1 turn my script into a traceback?

Because the loop writes until the pipe’s buffer is full and the reader is already gone, and an unhandled error escapes from the write: the traceback was 256 bytes and status 1 in the probe. Catching it and returning gives status 0 with no message, which hides the loss; the redirect makes the exit deliberate.

My server finished a reply with no error to a client that had left. Did it succeed?

Not in any sense the client could use. The kernel accepted 204,800 bytes with no gap, in all 5 repeats, and no later write was long enough to meet the closed reader. Compare delivered bytes with intended bytes instead of either side’s status.

My worker was killed by signal 13. Why was there no exception?

Because the disposition was not the interpreter’s. CPython sets SIGPIPE to ignore at startup – probe 01 reads 1 – and a child, an embedded interpreter or an extension can put the default back. Two of 5 dispositions died with status -13 before any handler ran; restore the ignore, or send with MSG_NOSIGNAL.

TechBobby Engineering writes runbooks from measured failures: every number on this page came from a probe in the appendix, run on the host described at the top of this page.

Take the next step

Appendix: Every File This Page Quotes

The probes and the package are printed in full, so the numbers above are checkable against the code that produced them. The tree below is the one that ran, and the run order reproduces it from an empty directory. Every fold is a character-for-character copy of its file.

Folder structure

post33/
  sandbox/
    probe.py                 one connected pair, repeats, and the JSON writer
    child_signal.py          the child that writes once, with a chosen SIGPIPE disposition
    child_stdout.py          the child that prints, in five exit policies
    01_conditions.py         host, interpreter, pipe capacity, dispositions
    02_states.py             ten peer states, one writer
    03_buffers.py            socket chunks and pipe lines, until EPIPE
    04_http.py               a chunked reply to six clients that leave
    05_sigpipe.py            five dispositions, five child processes
    06_stdout.py             five ways to meet a closed stdout
    07_policy.py             the classifier against live errnos and recorded failures
    08_tests.py              pytest, and the tree's own counts
    09_pipe_slots.py         pipe slots: line sizes, capacity, and a grown pipe
    10_tcp_state.py          tcpi_state from TCP_INFO, before and after the failing write
  module/
    pipepath/
      __init__.py            what a service imports
      errors.py              errno to Fault, with a retry budget
      writes.py              counting delivery, stopping at the reader
      stdout.py              the quiet exit for a command-line program
      report.py              one log line
      tests/
        conftest.py          a pipe pair and a socket pair
        test_errors.py       classification
        test_writes.py       delivery counting
        test_stdout.py       the descriptor move
        test_report.py       the log line
  results/                   one JSON per probe, written by it

Run order

The measurement probes need only the standard library. 08_tests.py needs pytest, and pyflakes is only for the static check: both are optional for reproducing the measurements. 07_policy.py imports the package, so it runs with PYTHONPATH pointing at module/.

$ python3 -m pip install pytest pyflakes      # optional: 08_tests.py and the static check

$ cd sandbox
$ python3 01_conditions.py       # facts: python, kernel, pipe capacity, dispositions
$ python3 02_states.py           # table 2
$ python3 03_buffers.py          # table 3
$ python3 04_http.py             # table 7
$ python3 05_sigpipe.py          # table 8
$ python3 06_stdout.py           # table 9
$ python3 09_pipe_slots.py       # table 4
$ python3 10_tcp_state.py        # table 6
$ PYTHONPATH=../module python3 07_policy.py    # section 1 and 4 counts
$ PYTHONPATH=../module python3 08_tests.py     # pytest, passed count

$ cd ../module && python3 -m pytest pipepath/tests -q
58 passed
The connected pair, the repeat, and the JSON writer every probe imports. probe.py
"""Shared parts of the probes: a connected pair, repeats, and one JSON file per probe.

Every probe writes what it observed, not what it expected. ``repeat`` runs the same call five
times and keeps each observation, so a figure in the article can be reported as a median with its
range instead of a single run that happened to be first.
"""
from __future__ import annotations

import json
import pathlib
import socket
import statistics
import time

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


def save(number: str, name: str, payload: dict) -> pathlib.Path:
    """Write one probe's record and print where it went."""
    RESULTS.mkdir(parents=True, exist_ok=True)
    path = RESULTS / f"{number}_{name}.json"
    path.write_text(json.dumps(payload, ensure_ascii=False, indent=1, sort_keys=True) + "\n",
                    encoding="utf-8")
    print("wrote", path.name)
    return path


def repeat(call, times: int = REPEATS) -> list:
    """Call the same measurement ``times`` times and keep every result."""
    return [call() for _ in range(times)]


def summary(values: list[float]) -> dict:
    """The three figures a five-run arm can honestly report."""
    return {"min": min(values), "median": statistics.median(values), "max": max(values)}


def tcp_pair() -> tuple[socket.socket, socket.socket]:
    """A connected loopback pair: the first socket writes, the second is the reader."""
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("127.0.0.1", 0))
    listener.listen(1)
    writer = socket.create_connection(listener.getsockname())
    reader, _ = listener.accept()
    listener.close()
    return writer, reader


def reset_close(peer: socket.socket, millis: int = 20) -> None:
    """Close with SO_LINGER 0, so the kernel sends RST instead of FIN."""
    peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                    b"\x01\x00\x00\x00\x00\x00\x00\x00")
    peer.close()
    time.sleep(millis / 1000)


def close_quietly(sock: socket.socket) -> None:
    """Close without letting a teardown error become the measurement."""
    try:
        sock.close()
    except OSError:
        pass
Host, interpreter, pipe capacity and signal dispositions. 01_conditions.py
"""Probe 01: the host, the interpreter, and the constants this page argues with.

None of these are results; they are the conditions a reader needs in order to know whether a
number from this page applies to their machine. The pipe capacity and the TCP buffer defaults are
read from the running kernel, not quoted from a manual.
"""
from __future__ import annotations

import errno
import fcntl
import io
import os
import platform
import signal
import socket

import probe


def read_sysctl(name: str) -> str:
    """Read one /proc/sys/net value as the kernel prints it."""
    try:
        return open(f"/proc/sys/net/{name}", encoding="ascii").read().strip()
    except OSError:
        return "unavailable"


def pipe_capacity() -> int:
    """The kernel's pipe buffer, asked of a real pipe."""
    read_fd, write_fd = os.pipe()
    try:
        return int(fcntl.fcntl(write_fd, fcntl.F_GETPIPE_SZ))
    finally:
        os.close(read_fd)
        os.close(write_fd)


def main() -> None:
    read_fd, write_fd = os.pipe()
    throughput = 0
    try:
        os.set_blocking(write_fd, False)
        throughput = int(os.write(write_fd, b"x" * (1 << 20)))
    finally:
        os.close(read_fd)
        os.close(write_fd)

    facts = {
        "python": platform.python_version(),
        "kernel": platform.release(),
        "machine": platform.machine(),
        "cpu_count": os.cpu_count() or 0,
        "pipe_capacity": pipe_capacity(),
        "pipe_nonblocking_write": throughput,
        "tcp_wmem": read_sysctl("ipv4/tcp_wmem"),
        "tcp_rmem": read_sysctl("ipv4/tcp_rmem"),
        "tcp_wmem_default": int(read_sysctl("ipv4/tcp_wmem").split()[1]),
        "tcp_rmem_default": int(read_sysctl("ipv4/tcp_rmem").split()[1]),
        "sigpipe_disposition": int(signal.getsignal(signal.SIGPIPE)),
        "sigpipe_ignored": int(signal.SIG_IGN),
        "sigpipe_default": int(signal.SIG_DFL),
        "sigpipe_number": int(signal.SIGPIPE),
        "msg_nosignal": int(socket.MSG_NOSIGNAL),
        "default_buffer": io.DEFAULT_BUFFER_SIZE,
        "epipe": errno.EPIPE,
        "econnreset": errno.ECONNRESET,
        "ebadf": errno.EBADF,
        "repeats": probe.REPEATS,
    }
    probe.save("01", "conditions", {"facts": facts})


if __name__ == "__main__":
    main()
Ten peer states, one writer, five repeats each. 02_states.py
"""Probe 02: what the writer sees for each state the other end can be in.

Ten states, one per arm, on the same host: a reader that closed, one that reset, one that only
closed its writing direction, a reader still open but never reading, a Unix socket whose peer
closed, a pipe whose read end closed, this end shutting down, this end already closed, a socket
that was never connected, and a write to a pipe's read end. The writer sends 4 KiB at a time and
the probe records how many writes were accepted before the first error, which error it was, and
that error's number.
"""
from __future__ import annotations

import os
import socket
import time

import probe

CHUNK = 4096
LIMIT = 5


def send_until_error(sock: socket.socket, chunk: bytes = b"x" * CHUNK,
                     limit: int = LIMIT) -> tuple[int, str | None, int | None]:
    """Send at most ``limit`` pieces and report how many the kernel took before failing."""
    accepted = 0
    for _ in range(limit):
        try:
            sock.send(chunk)
        except OSError as exc:
            return accepted, type(exc).__name__, int(exc.errno or 0)
        accepted += 1
    return accepted, None, None


def tcp_peer_close() -> dict:
    writer, reader = probe.tcp_pair()
    reader.close()
    time.sleep(0.02)
    accepted, error, number = send_until_error(writer)
    probe.close_quietly(writer)
    return {"accepted": accepted, "error": error, "errno": number}


def tcp_peer_reset() -> dict:
    writer, reader = probe.tcp_pair()
    probe.reset_close(reader)
    accepted, error, number = send_until_error(writer)
    probe.close_quietly(writer)
    return {"accepted": accepted, "error": error, "errno": number}


def tcp_peer_half_close() -> dict:
    writer, reader = probe.tcp_pair()
    reader.shutdown(socket.SHUT_WR)
    time.sleep(0.02)
    accepted, error, number = send_until_error(writer)
    probe.close_quietly(writer)
    probe.close_quietly(reader)
    return {"accepted": accepted, "error": error, "errno": number}


def tcp_peer_not_reading() -> dict:
    """Half-closed reader that never reads: the writer fills the window and then waits."""
    writer, reader = probe.tcp_pair()
    reader.shutdown(socket.SHUT_WR)
    time.sleep(0.02)
    writer.settimeout(0.5)
    sent = 0
    outcome = "accepted all"
    try:
        for _ in range(200):
            sent += writer.send(b"x" * 65536)
    except socket.timeout:
        outcome = "blocked"
    except OSError as exc:                       # noqa: BLE001 - recorded, not raised
        outcome = f"{type(exc).__name__} {exc.errno}"
    writer.settimeout(None)
    probe.close_quietly(writer)
    probe.close_quietly(reader)
    return {"accepted": sent, "error": outcome, "errno": None}


def unix_peer_close() -> dict:
    near, far = socket.socketpair()
    far.close()
    accepted, error, number = send_until_error(near)
    probe.close_quietly(near)
    return {"accepted": accepted, "error": error, "errno": number}


def pipe_reader_close() -> dict:
    read_fd, write_fd = os.pipe()
    os.close(read_fd)
    try:
        os.write(write_fd, b"x" * CHUNK)
    except OSError as exc:
        return {"accepted": 0, "error": type(exc).__name__, "errno": int(exc.errno or 0)}
    finally:
        os.close(write_fd)
    return {"accepted": 1, "error": None, "errno": None}


def local_shutdown() -> dict:
    writer, reader = probe.tcp_pair()
    writer.shutdown(socket.SHUT_WR)
    accepted, error, number = send_until_error(writer)
    probe.close_quietly(writer)
    probe.close_quietly(reader)
    return {"accepted": accepted, "error": error, "errno": number}


def local_closed() -> dict:
    writer, reader = probe.tcp_pair()
    writer.close()
    accepted, error, number = send_until_error(writer)
    probe.close_quietly(reader)
    return {"accepted": accepted, "error": error, "errno": number}


def never_connected() -> dict:
    sock = socket.socket()
    accepted, error, number = send_until_error(sock)
    probe.close_quietly(sock)
    return {"accepted": accepted, "error": error, "errno": number}


def write_to_read_end() -> dict:
    read_fd, write_fd = os.pipe()
    try:
        os.write(read_fd, b"x")
    except OSError as exc:
        return {"accepted": 0, "error": type(exc).__name__, "errno": int(exc.errno or 0)}
    finally:
        os.close(read_fd)
        os.close(write_fd)
    return {"accepted": 1, "error": None, "errno": None}


ARMS = {
    "tcp_peer_close": tcp_peer_close,
    "tcp_peer_reset": tcp_peer_reset,
    "tcp_peer_half_close": tcp_peer_half_close,
    "tcp_peer_not_reading": tcp_peer_not_reading,
    "unix_peer_close": unix_peer_close,
    "pipe_reader_close": pipe_reader_close,
    "local_shutdown": local_shutdown,
    "local_closed": local_closed,
    "never_connected": never_connected,
    "write_to_read_end": write_to_read_end,
}


def main() -> None:
    arms = []
    for name, call in ARMS.items():
        observations = probe.repeat(call)
        first = observations[0]
        identical = all(observation == first for observation in observations)
        arms.append({"name": name, "repeats": len(observations), "identical": identical,
                     **first, "all": observations})
        print(f"{name:22s} accepted={first['accepted']:<8} error={first['error']} "
              f"errno={first['errno']} identical={identical}")
    probe.save("02", "states", {"chunk": CHUNK, "limit": LIMIT, "repeats": probe.REPEATS,
                                "arms": arms})


if __name__ == "__main__":
    main()
Five socket chunk sizes and three pipe line sizes, until EPIPE. 03_buffers.py
"""Probe 03: how much the kernel accepts after the reader is gone.

Two buffers hide the loss. A socket accepts one write into its send buffer before the reset
arrives; a pipe accepts up to its capacity (65,536 bytes here, and 64,000 in the 100-byte-line arm)
and only then reports EPIPE. This probe measures both: five chunk sizes on a socket whose peer has
closed, and three line sizes written to ``head -1``, which reads one line and exits.

Every byte count here is the sum of what the calls returned, never a piece size multiplied by a
call count: ``send`` and ``write`` may accept less than they were offered, and that shortfall is
exactly what the page warns about.
"""
from __future__ import annotations

import os
import subprocess
import time

import probe

SOCKET_CHUNKS = [1024, 4096, 16384, 65536, 262144]
PIPE_LINES = [100, 1024, 4096]
LIMIT = 8


def socket_arm(chunk: int) -> dict:
    """Send fixed-size pieces to a peer that has closed, and count what is accepted."""
    writer, reader = probe.tcp_pair()
    reader.close()
    time.sleep(0.02)
    accepted = 0
    accepted_bytes = 0
    short = 0
    error = None
    number = None
    for _ in range(LIMIT):
        try:
            written = writer.send(b"x" * chunk)
        except OSError as exc:
            error, number = type(exc).__name__, int(exc.errno or 0)
            break
        accepted += 1
        accepted_bytes += written
        if written != chunk:
            short += 1
    probe.close_quietly(writer)
    return {"chunk": chunk, "accepted": accepted, "bytes": accepted_bytes, "short": short,
            "error": error, "errno": number}


def pipe_arm(line: int) -> dict:
    """Write fixed-size lines to ``head -1`` until the pipe says the reader has gone."""
    reader = subprocess.Popen(["head", "-1"], stdin=subprocess.PIPE,
                              stdout=subprocess.DEVNULL, bufsize=0)
    payload = b"x" * (line - 1) + b"\n"
    sent = 0
    lines = 0
    error = None
    number = None
    where = None
    try:
        for _ in range(20000):
            rest = payload
            while rest:
                written = os.write(reader.stdin.fileno(), rest)
                sent += written
                rest = rest[written:]
            lines += 1
    except OSError as exc:
        error, number = type(exc).__name__, int(exc.errno or 0)
        where = "write"
    try:
        reader.stdin.close()
    except OSError as exc:
        if error is None:
            error, number = type(exc).__name__, int(exc.errno or 0)
            where = "close"
    status = reader.wait()
    return {"line": line, "bytes": sent, "lines": lines, "error": error, "errno": number,
            "where": where, "reader_status": status}


def main() -> None:
    sockets = []
    for chunk in SOCKET_CHUNKS:
        observations = probe.repeat(lambda chunk=chunk: socket_arm(chunk))
        first = observations[0]
        sockets.append({"chunk": chunk, "accepted": first["accepted"], "bytes": first["bytes"],
                        "short": first["short"],
                        "error": first["error"], "errno": first["errno"],
                        "identical": all(o == first for o in observations)})
        print("socket", chunk, first)

    pipes = []
    for line in PIPE_LINES:
        observations = probe.repeat(lambda line=line: pipe_arm(line))
        values = [observation["bytes"] for observation in observations]
        pipes.append({"line": line, "bytes_min": min(values),
                      "bytes_median": sorted(values)[len(values) // 2],
                      "bytes_max": max(values),
                      "lines": observations[0]["lines"],
                      "error": observations[0]["error"], "errno": observations[0]["errno"],
                      "where": observations[0]["where"],
                      "reader_status": observations[0]["reader_status"],
                      "all": observations})
        print("pipe", line, values)

    probe.save("03", "buffers", {"limit": LIMIT, "repeats": probe.REPEATS,
                                 "socket_arms": sockets, "pipe_arms": pipes})


if __name__ == "__main__":
    main()
A chunked HTTP reply to six clients that leave, the last two controlling the exit. 04_http.py
"""Probe 04: one closed client, two exception names, on the same HTTP write path.

A threaded HTTP/1.1 server sends a chunked reply; the client reads the headers and one chunk and
closes. The server writes on, once per chunk, and records which error ended the reply. Four arms
close the client normally, crossing two chunk sizes with two gaps between writes, a fifth resets
it instead, and a sixth drains what has arrived before closing, so its FIN meets a socket with
nothing left to reset. Five repeats each, because whether the write that fails reports EPIPE or
ECONNRESET depends on whether the reset had arrived when it ran.
"""
from __future__ import annotations

import socket
import threading
import time

import probe

TOTAL_CHUNKS = 200
ARMS = [
    ("chunk_1k_no_delay", 1024, 0.0, "close"),
    ("chunk_1k_gap_2ms", 1024, 0.002, "close"),
    ("chunk_64k_no_delay", 65536, 0.0, "close"),
    ("chunk_64k_gap_2ms", 65536, 0.002, "close"),
    ("reset_1k_gap_2ms", 1024, 0.002, "reset"),
    ("drain_1k_gap_2ms", 1024, 0.002, "drain"),
]


def drain(client: socket.socket) -> int:
    """Read what has arrived without waiting, so ``close`` sends FIN rather than RST."""
    total = 0
    client.setblocking(False)
    try:
        while True:
            piece = client.recv(1 << 20)
            if not piece:
                break
            total += len(piece)
    except (BlockingIOError, OSError):
        pass
    finally:
        client.setblocking(True)
    return total


def serve_once(chunk: int, gap: float, closing: str = "close") -> dict:
    """Run one server/client arm and return what the server's writes saw."""
    listener = socket.socket()
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("127.0.0.1", 0))
    listener.listen(1)
    record: dict = {}

    def server() -> None:
        connection, _ = listener.accept()
        connection.recv(65536)
        sent = 0
        started = time.perf_counter()
        error = None
        number = None
        try:
            connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
                               b"Transfer-Encoding: chunked\r\n\r\n")
            for _ in range(TOTAL_CHUNKS):
                connection.sendall(b"%x\r\n" % chunk + b"x" * chunk + b"\r\n")
                sent += chunk
                if gap:
                    time.sleep(gap)
        except OSError as exc:
            error, number = type(exc).__name__, int(exc.errno or 0)
        record.update({"bytes": sent, "error": error, "errno": number,
                       "elapsed_ms": round((time.perf_counter() - started) * 1000, 3)})
        probe.close_quietly(connection)

    thread = threading.Thread(target=server, daemon=True)
    thread.start()
    client = socket.create_connection(listener.getsockname())
    client.sendall(b"GET / HTTP/1.1\r\nHost: probe\r\n\r\n")
    client.recv(2048)
    if closing == "reset":
        client.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
                          b"\x01\x00\x00\x00\x00\x00\x00\x00")
        client.close()
        time.sleep(0.02)
    elif closing == "drain":
        time.sleep(0.005)
        record["drained"] = drain(client)
        client.close()
    else:
        time.sleep(0.005)
        client.close()
    thread.join(30)
    listener.close()
    return record


def main() -> None:
    arms = []
    for name, chunk, gap, closing in ARMS:
        observations = probe.repeat(
            lambda chunk=chunk, gap=gap, closing=closing: serve_once(chunk, gap, closing))
        errors = [observation["error"] for observation in observations]
        arms.append({
            "name": name, "chunk": chunk, "gap_ms": round(gap * 1000, 3),
            "closing": closing,
            "bytes_min": min(o["bytes"] for o in observations),
            "bytes_median": sorted(o["bytes"] for o in observations)[len(observations) // 2],
            "bytes_max": max(o["bytes"] for o in observations),
            "epipe": errors.count("BrokenPipeError"),
            "reset": errors.count("ConnectionResetError"),
            "other": sum(1 for error in errors
                         if error not in (None, "BrokenPipeError", "ConnectionResetError")),
            "completed": errors.count(None),
            "elapsed_min_ms": min(o["elapsed_ms"] for o in observations),
            "elapsed_max_ms": max(o["elapsed_ms"] for o in observations),
            "all": observations,
        })
        print(name, errors, [o["bytes"] for o in observations])

    total = sum(len(arm["all"]) for arm in arms)
    epipe = sum(arm["epipe"] for arm in arms)
    reset = sum(arm["reset"] for arm in arms)
    probe.save("04", "http", {
        "repeats": probe.REPEATS, "total_chunks": TOTAL_CHUNKS,
        "observations": total, "epipe": epipe, "reset": reset,
        "other": total - epipe - reset, "arms": arms,
    })


if __name__ == "__main__":
    main()
Five dispositions, each in its own child process. 05_sigpipe.py
"""Probe 05: why a broken pipe raises here and kills elsewhere.

A write to a dead reader is a condition the kernel signals with SIGPIPE as well as an errno. A C
program that never handles it dies; CPython sets the disposition to SIG_IGN at startup, so the
write raises instead. The probe runs the same write five ways in a child process: the interpreter's
default, SIG_DFL restored, a socket with each, and a socket send that passes MSG_NOSIGNAL.
"""
from __future__ import annotations

import os
import subprocess
import sys

import probe

HERE = probe.HERE
MODES = ["pipe_default", "pipe_dfl", "socket_default", "socket_dfl", "socket_dfl_nosig"]


def run(mode: str) -> dict:
    """Run the child once and report its status and the lines it managed to print."""
    read_fd, write_fd = os.pipe()
    os.close(read_fd)                                  # the reader is gone before the write
    try:
        result = subprocess.run([sys.executable, str(HERE / "child_signal.py"), mode],
                                stdout=write_fd, stderr=subprocess.PIPE, timeout=60)
    finally:
        os.close(write_fd)
    lines = result.stderr.decode().strip().splitlines()
    fields: dict[str, str] = {}
    for line in lines:
        key, _, value = line.partition("=")
        if value:
            fields[key] = value
    return {"returncode": result.returncode, "disposition": int(fields.get("disposition", -1)),
            "caught": fields.get("caught"), "survived": "survived" in fields,
            "killed_by_sigpipe": result.returncode == -13}


def main() -> None:
    arms = []
    for mode in MODES:
        observations = probe.repeat(lambda mode=mode: run(mode))
        first = observations[0]
        arms.append({"mode": mode, "returncode": first["returncode"],
                     "disposition": first["disposition"], "caught": first["caught"],
                     "survived": first["survived"],
                     "killed_by_sigpipe": first["killed_by_sigpipe"],
                     "identical": all(o == first for o in observations),
                     "repeats": len(observations)})
        print(mode, first)
    probe.save("05", "sigpipe", {"repeats": probe.REPEATS, "arms": arms})


if __name__ == "__main__":
    main()
Five ways a command meets a closed stdout. 06_stdout.py
"""Probe 06: the status a pipeline gets, and the message it leaves behind.

``command | head -1`` closes the pipe after one line. What the command exits with depends on where
its output was when the reader left: an error in the loop is a traceback and status 1; an error in
the shutdown flush is "Exception ignored" and status 120; and a catch that does not redirect the
descriptor can end with status 0 while quietly dropping output. Five modes, five repeats.
"""
from __future__ import annotations

import subprocess
import sys

import probe

HERE = probe.HERE
MODES = ["plain", "catch", "late", "late_catch", "late_quiet"]


def run(mode: str) -> dict:
    """Start the child, read one line, close the pipe the way ``head -1`` does, and wait."""
    child = subprocess.Popen([sys.executable, str(HERE / "child_stdout.py"), mode],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if mode.startswith("late"):
        first = b""                            # the reader leaves before the child writes
    else:
        first = child.stdout.readline()        # head -1 reads one line, then exits
    child.stdout.close()
    stderr = child.stderr.read().decode()
    status = child.wait(timeout=60)
    return {"mode": mode, "returncode": status, "first_line": first.decode().strip()[:12],
            "stderr_chars": len(stderr), "stderr_text": stderr.strip(),
            "exception_ignored": "Exception ignored" in stderr,
            "traceback": "Traceback" in stderr,
            "broken_pipe_named": "BrokenPipeError" in stderr}


def main() -> None:
    arms = []
    for mode in MODES:
        observations = probe.repeat(lambda mode=mode: run(mode))
        first = observations[0]
        arms.append({"mode": mode, "returncode": first["returncode"],
                     "first_line": first["first_line"],
                     "stderr_chars": first["stderr_chars"],
                     "stderr_text": first["stderr_text"],
                     "exception_ignored": first["exception_ignored"],
                     "traceback": first["traceback"],
                     "broken_pipe_named": first["broken_pipe_named"],
                     "identical": all(o == first for o in observations),
                     "all": observations,
                     "repeats": len(observations)})
        print(mode, first)
    probe.save("06", "stdout", {"repeats": probe.REPEATS, "arms": arms})


if __name__ == "__main__":
    main()
The classifier checked against live errnos and the recorded failures. 07_policy.py
"""Probe 07: how far the number 32 gets you, and what a handler around it misses.

Reads what probes 02 and 04 recorded and asks the package two questions: how many different states
share EPIPE, and how many failures a handler that catches only ``BrokenPipeError`` would let past.
Then it provokes four failures in this process and classifies them, so the table the package ships
is checked against live errnos rather than against constants it defined itself.
"""
from __future__ import annotations

import json
import os
import socket

import probe
from pipepath import TABLE, Kind, classify

STATES = json.loads((probe.RESULTS / "02_states.json").read_text(encoding="utf-8"))
HTTP = json.loads((probe.RESULTS / "04_http.json").read_text(encoding="utf-8"))


def live_failures() -> list[dict]:
    """Four real failures, each provoked and classified in this process."""
    read_fd, write_fd = os.pipe()
    os.close(read_fd)
    try:
        os.write(write_fd, b"x")
    except OSError as exc:
        pipe_error = exc
    finally:
        os.close(write_fd)

    near, far = socket.socketpair()
    far.close()
    try:
        near.send(b"x")
    except OSError as exc:
        unix_error = exc
    finally:
        near.close()

    writer, reader = probe.tcp_pair()
    probe.reset_close(reader)
    try:
        writer.send(b"x")
    except OSError as exc:
        reset_error = exc
    probe.close_quietly(writer)

    read_fd, write_fd = os.pipe()
    try:
        os.write(read_fd, b"x")
    except OSError as exc:
        badfd_error = exc
    finally:
        os.close(read_fd)
        os.close(write_fd)

    cases = [("pipe reader closed", pipe_error), ("unix peer closed", unix_error),
             ("tcp peer reset", reset_error), ("write to read end", badfd_error)]
    out = []
    for name, error in cases:
        fault = classify(error)
        out.append({"case": name, "errno": fault.number, "kind": fault.kind.value,
                    "retry_budget": fault.retry_budget})
    return out


def main() -> None:
    epipe_states = [arm["name"] for arm in STATES["arms"] if arm.get("errno") == 32]
    types = sorted({arm["error"] for arm in STATES["arms"]
                    if arm["error"] and arm["error"].endswith("Error")})
    classified = live_failures()
    observations = [observation for arm in HTTP["arms"] for observation in arm["all"]]
    http_errors = sum(1 for observation in observations if observation["error"])
    http_reset = sum(1 for observation in observations
                     if observation["error"] == "ConnectionResetError")
    http_epipe = sum(1 for observation in observations
                     if observation["error"] == "BrokenPipeError")
    total = len(observations)
    payload = {
        "epipe_states": len(epipe_states),
        "epipe_state_names": epipe_states,
        "distinct_error_types": len(types),
        "error_types": types,
        "table_rows": len(TABLE),
        "kinds": len({fault.kind for fault in TABLE.values()}),
        "classified_live": len(classified),
        "unclassified_live": sum(1 for case in classified if case["kind"] == Kind.UNRELATED.value),
        "retry_budget_total": sum(case["retry_budget"] for case in classified),
        "http_observations": total,
        "http_errors": http_errors,
        "http_reset": http_reset,
        "http_epipe": http_epipe,
        "http_completed": total - http_errors,
        "catch_broken_pipe_only_misses": http_errors - http_epipe,
        "cases": classified,
    }
    print(json.dumps(payload, indent=1, ensure_ascii=False))
    probe.save("07", "policy", payload)


if __name__ == "__main__":
    main()
pytest and the tree’s own counts, read from the files. 08_tests.py
"""Probe 08: the package's own size and the number of tests that pass, read from the tree.

The article quotes how many tests cover the module, how many files it ships and how many lines of
probe code produced its numbers. Those counts are taken here, with pytest run once, so the prose
cannot drift from the tree it describes.
"""
from __future__ import annotations

import pathlib
import re
import subprocess
import sys

import probe

MODULE = probe.HERE.parent / "module"
PACKAGE = MODULE / "pipepath"
TESTS = PACKAGE / "tests"


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


def main() -> None:
    result = subprocess.run([sys.executable, "-m", "pytest", "pipepath/tests", "-q",
                             "-p", "no:warnings"], cwd=str(MODULE), capture_output=True,
                            text=True)
    output = result.stdout + result.stderr
    match = re.search(r"(\d+) passed", output)
    if result.returncode != 0 or match is None:
        raise SystemExit(f"pytest did not pass:\n{output[-2000:]}")
    passed = int(match.group(1))
    test_files = sorted(TESTS.glob("test_*.py"))
    package_files = sorted(PACKAGE.glob("*.py"))
    probes = sorted(probe.HERE.glob("[0-9][0-9]_*.py"))
    payload = {
        "pytest_passed": passed,
        "pytest_rc": result.returncode,
        "test_files": len(test_files),
        "test_lines": sum(count(path) for path in test_files) + count(TESTS / "conftest.py"),
        "package_files": len(package_files),
        "package_lines": sum(count(path) for path in package_files),
        "probe_files": len(probes) + 3,
        "probe_lines": sum(count(path) for path in probes)
        + count(probe.HERE / "probe.py") + count(probe.HERE / "child_signal.py")
        + count(probe.HERE / "child_stdout.py"),
    }
    print(payload)
    probe.save("08", "tests", payload)


if __name__ == "__main__":
    main()
Pipe slots: line sizes, capacity, and the same pipe grown to twice it. 09_pipe_slots.py
"""Probe 09: why a pipe stops short of its capacity when the lines are small.

A pipe's buffer is a ring of page-sized slots, so the number of bytes it holds depends on how many
whole lines each slot can take. Probe 01 reads the capacity the kernel reports; probe 03 finds
that 100-byte lines stop 1,536 bytes below it. This probe fills a pipe that nothing reads until
the kernel reports it full, once per line size, then does it again with the pipe grown to twice its
default, and compares each result with the slots the capacity is made of.
"""
from __future__ import annotations

import fcntl
import os

import probe

F_GETPIPE_SZ = 1032
F_SETPIPE_SZ = 1031
LINES = [64, 100, 128, 512, 1024, 4096]
GROWN = 131072
MAX_LINES = 1_000_000


def pipe_max_size() -> int | None:
    """The largest size an unprivileged process may ask for, if the host publishes it."""
    try:
        return int(open("/proc/sys/fs/pipe-max-size").read().strip())  # noqa: SIM115
    except (OSError, ValueError):
        return None


def fill(line: int, size: int | None = None) -> dict:
    """Write whole lines into a non-blocking pipe until the kernel says it is full."""
    read_fd, write_fd = os.pipe()
    try:
        if size is not None:
            fcntl.fcntl(write_fd, F_SETPIPE_SZ, size)
        capacity = fcntl.fcntl(write_fd, F_GETPIPE_SZ)
        os.set_blocking(write_fd, False)
        payload = b"x" * (line - 1) + b"\n"
        accepted = 0
        lines = 0
        short = 0
        while lines < MAX_LINES:
            try:
                written = os.write(write_fd, payload)
            except BlockingIOError:
                break
            accepted += written
            lines += 1
            if written != line:            # a pipe write up to PIPE_BUF is all or nothing
                short += 1
                break
        page = os.sysconf("SC_PAGE_SIZE")
        slots = capacity // page
        per_slot = page // line
        model = slots * per_slot * line
        return {"line": line, "capacity": capacity, "page": page, "slots": slots,
                "lines_per_slot": per_slot, "accepted": accepted, "lines": lines,
                "model": model, "matches": accepted == model, "short": short}
    finally:
        os.close(read_fd)
        os.close(write_fd)


def main() -> None:
    arms = []
    for line in LINES:
        observations = probe.repeat(lambda line=line: fill(line))
        first = observations[0]
        arms.append({"case": f"{line}-byte lines", "size": None, **first,
                     "repeats": len(observations),
                     "identical": all(o == first for o in observations)})
        print("default", line, first["accepted"], "of", first["capacity"],
              "model", first["model"], first["matches"])
    for line in (100, 1024):
        observations = probe.repeat(lambda line=line: fill(line, GROWN))
        first = observations[0]
        arms.append({"case": f"{line}-byte lines, grown", "size": GROWN, **first,
                     "repeats": len(observations),
                     "identical": all(o == first for o in observations)})
        print("grown", line, first["accepted"], "of", first["capacity"],
              "model", first["model"], first["matches"])
    probe.save("09", "pipe_slots", {"lines": LINES, "grown": GROWN,
                                    "pipe_max_size": pipe_max_size(),
                                    "repeats": probe.REPEATS, "arms": arms})


if __name__ == "__main__":
    main()
tcpi_state from TCP_INFO before and after the write that fails. 10_tcp_state.py
"""Probe 10: which kernel state a TCP socket is in when the write fails, read from TCP_INFO.

The exception name in a log is a report about where the socket was, not only about what the peer
did. This probe reads ``tcpi_state`` out of ``TCP_INFO`` immediately before each write and again
after the first error, so the number can be tied to a state instead of inferred from it: a reset
that meets a socket still ESTABLISHED and a write on a socket that has already received FIN into
CLOSE_WAIT are two different places in the connection's life.

Three arms, five repeats each. The first resets the peer while the writer is blocked inside
``send``; the second lets the reset be processed first and then writes; the third lets the peer
send FIN, waits until the socket itself reports CLOSE_WAIT, and writes from there.
"""
from __future__ import annotations

import socket
import threading
import time

import probe

TCP_INFO = getattr(socket, "TCP_INFO", 11)          # Linux: 11, and no struct is needed for byte 0
INFO_SIZE = 104
FIN_WAIT = 2.0

STATES = {
    1: "ESTABLISHED",
    2: "SYN_SENT",
    3: "SYN_RECV",
    4: "FIN_WAIT1",
    5: "FIN_WAIT2",
    6: "TIME_WAIT",
    7: "CLOSE",
    8: "CLOSE_WAIT",
    9: "LAST_ACK",
    10: "LISTEN",
    11: "CLOSING",
}


def state(sock: socket.socket) -> dict:
    """The socket's TCP state, as the kernel reports it in the first byte of struct tcp_info."""
    number = sock.getsockopt(socket.IPPROTO_TCP, TCP_INFO, INFO_SIZE)[0]
    return {"number": number, "name": STATES.get(number, f"state {number}")}


def send_once(sock: socket.socket, piece: bytes) -> dict:
    """One write, with the state read before it and after it failed."""
    before = state(sock)
    started = time.perf_counter()
    try:
        sent = sock.send(piece)
    except OSError as exc:
        return {"state_before": before, "accepted": 0, "error": type(exc).__name__,
                "errno": int(exc.errno or 0), "state_after": state(sock),
                "elapsed_ms": round((time.perf_counter() - started) * 1000, 3)}
    return {"state_before": before, "accepted": 1, "bytes": sent, "error": None, "errno": None,
            "state_after": state(sock),
            "elapsed_ms": round((time.perf_counter() - started) * 1000, 3)}


def rst_while_blocked() -> dict:
    """Reset the peer while this end is blocked inside send(), keeping every call the loop made.

    The loop fills the window and then blocks, so the call that raises is not the one the reset met:
    the blocked call returns the bytes it had already handed over, and the failure arrives on the
    next call, whose state is read before it starts. Recording each call separately is what lets
    the table show both - the write that met the reset and the write that raised.
    """
    writer, reader = probe.tcp_pair()
    writer.settimeout(None)
    piece = b"x" * (1 << 20)
    calls: list[dict] = []

    def blocked() -> None:
        while len(calls) < 512:
            before = state(writer)
            started = time.perf_counter()
            try:
                sent = writer.send(piece)
            except OSError as exc:
                calls.append({"state_before": before, "accepted": 0, "error": type(exc).__name__,
                              "errno": int(exc.errno or 0), "state_after": state(writer),
                              "elapsed_ms": round((time.perf_counter() - started) * 1000, 3)})
                return
            calls.append({"state_before": before, "accepted": 1, "bytes": sent, "error": None,
                          "errno": None, "state_after": state(writer),
                          "elapsed_ms": round((time.perf_counter() - started) * 1000, 3)})

    thread = threading.Thread(target=blocked, daemon=True)
    thread.start()
    time.sleep(0.05)                       # the writer fills the window and blocks
    probe.reset_close(reader)
    thread.join(5)
    probe.close_quietly(writer)

    accepted = [call for call in calls if call["accepted"]]
    failure = calls[-1] if calls and calls[-1]["error"] else None
    return {"piece": len(piece),
            "calls_before": len(accepted),
            "bytes_before": sum(call["bytes"] for call in accepted),
            "blocked": accepted[-1] if accepted else None,
            "failure": failure,
            "calls": calls}


def rst_first_then_write() -> dict:
    """Let the RST be processed, then write: the socket is CLOSE and still reports the reset."""
    writer, reader = probe.tcp_pair()
    probe.reset_close(reader)
    time.sleep(0.02)
    result = send_once(writer, b"x" * 4096)
    probe.close_quietly(writer)
    return result


def fin_then_close_wait() -> dict:
    """Let the peer send FIN, wait for CLOSE_WAIT, then write until the socket fails."""
    writer, reader = probe.tcp_pair()
    reader.close()
    deadline = time.time() + FIN_WAIT
    observed = state(writer)
    while observed["number"] != 8 and time.time() < deadline:
        time.sleep(0.002)
        observed = state(writer)
    writes = []
    for _ in range(5):
        result = send_once(writer, b"x" * 4096)
        writes.append(result)
        if result["error"]:
            break
    probe.close_quietly(writer)
    first_error = next((write for write in writes if write["error"]), None)
    return {"state_before": observed,
            "accepted": sum(1 for write in writes if write["accepted"]),
            "error": first_error["error"] if first_error else None,
            "errno": first_error["errno"] if first_error else None,
            "state_after": writes[-1]["state_after"],
            "writes": writes}


ARMS = {
    "rst_while_blocked": rst_while_blocked,
    "rst_first_then_write": rst_first_then_write,
    "fin_then_close_wait": fin_then_close_wait,
}


def main() -> None:
    arms = []
    for name, call in ARMS.items():
        observations = probe.repeat(call)
        first = observations[0]
        arms.append({"name": name, "repeats": len(observations), **first, "all": observations})
        if "blocked" in first and first["blocked"]:
            blocked = first["blocked"]
            failure = first["failure"] or {}
            print(f"{name:22s} {first['calls_before']} calls / {first['bytes_before']:,} B "
                  f"before the error; the blocked call ran {blocked['elapsed_ms']} ms in "
                  f"{blocked['state_before']['name']} and returned {blocked['bytes']:,} B")
            print(f"{'':22s} then {failure.get('state_before', {}).get('name')} -> "
                  f"{failure.get('error')} {failure.get('errno')}")
        else:
            print(f"{name:22s} state={first['state_before']['name']:<12} "
                  f"accepted={first['accepted']} error={first.get('error')} "
                  f"errno={first.get('errno')} after={first.get('state_after')}")
        if "writes" in first:
            for write in first["writes"]:
                print("    write", write["state_before"]["name"], "->",
                      write["error"] or f"{write['bytes']} B accepted", "->",
                      write["state_after"]["name"])
    probe.save("10", "tcp_state", {"info_size": INFO_SIZE, "repeats": probe.REPEATS,
                                   "arms": arms})


if __name__ == "__main__":
    main()
The child that writes once with the disposition its mode asks for. child_signal.py
"""The child the SIGPIPE probe runs: one write, with the disposition the mode asks for.

It reports to stderr, because stdout is the closed pipe in the two pipe modes: the disposition the
process started with, what the write raised if anything, and whether the process survived it. A
process killed by SIGPIPE prints nothing after the disposition line, and its status says so.
"""
from __future__ import annotations

import os
import signal
import socket
import sys


def main() -> None:
    mode = sys.argv[1]
    if "dfl" in mode:
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    print(f"disposition={int(signal.getsignal(signal.SIGPIPE))}", file=sys.stderr)
    try:
        if mode.startswith("socket"):
            near, far = socket.socketpair()
            far.close()
            flags = socket.MSG_NOSIGNAL if mode.endswith("nosig") else 0
            sent = near.send(b"x", flags)
            print(f"sent={sent}", file=sys.stderr)
        else:
            os.write(1, b"x" * 10)
    except OSError as exc:
        print(f"caught={type(exc).__name__}/{exc.errno}", file=sys.stderr)
    print("survived=1", file=sys.stderr)


if __name__ == "__main__":
    main()
The child that prints, in five exit policies. child_stdout.py
"""Child for the stdout probe: a loop that prints, and the closest thing to ``head -1``.

Each mode is one way a command-line program can meet a reader that left: let the error escape,
catch it and return, catch it at the flush after the buffer already took the write, or catch it and
point descriptor 1 at /dev/null.
"""
from __future__ import annotations

import os
import sys
import time


def leave_quietly() -> None:
    """The policy the article recommends: silence descriptor 1, then exit with a chosen status."""
    devnull = os.open(os.devnull, os.O_WRONLY)
    os.dup2(devnull, sys.stdout.fileno())
    os.close(devnull)
    raise SystemExit(0)


def main() -> None:
    mode = sys.argv[1]
    if mode == "plain":
        for number in range(1, 300001):
            print(number)
    elif mode == "catch":
        try:
            for number in range(1, 300001):
                print(number)
        except BrokenPipeError:
            pass
    elif mode == "late":
        time.sleep(0.3)
        print("late")
    elif mode == "late_catch":
        time.sleep(0.3)
        try:
            sys.stdout.flush()
        except BrokenPipeError:
            pass
        print("after the catch")
    elif mode == "late_quiet":
        time.sleep(0.3)
        try:
            print("late")
            sys.stdout.flush()
        except BrokenPipeError:
            leave_quietly()
    else:
        raise SystemExit(f"unknown mode {mode}")


if __name__ == "__main__":
    main()
What a service imports from the package. pipepath/__init__.py
"""The part of pipepath a service imports: classification, delivery counting, a quiet exit."""
from __future__ import annotations

from .errors import TABLE, Fault, Kind, classify, is_reader_gone, unwrap
from .report import describe_failure
from .stdout import exit_quietly
from .writes import Delivery, deliver

__all__ = [
    "TABLE",
    "Delivery",
    "Fault",
    "Kind",
    "classify",
    "deliver",
    "describe_failure",
    "exit_quietly",
    "is_reader_gone",
    "unwrap",
]
Errno to Fault, with the retry budget of each group. pipepath/errors.py
"""What a failed write means, read from its errno rather than from its message.

The same event reaches Python under three names: ``BrokenPipeError`` for EPIPE,
``ConnectionResetError`` for ECONNRESET, and a bare ``OSError`` for a descriptor that was already
closed. A handler that catches one of them lets the other two through, which is how a dropped
reader turns into a 500 in one service and a silent loop in the next. This module turns whichever
arrived into one record: the number, the group it belongs to, what it says about the reader, and
what the writer may do next.

Every group in the table has a retry budget of zero, and the budget describes one write on the
connection that failed, not a client that reconnects and resends an idempotent request.
"""
from __future__ import annotations

import errno
from dataclasses import dataclass
from enum import Enum


class Kind(str, Enum):
    """The four groups a failed write falls into."""

    READER_GONE = "reader gone"
    RESET = "reset"
    CLOSED_HANDLE = "closed handle"
    UNRELATED = "unrelated"


@dataclass(frozen=True)
class Fault:
    """One classified failure: the number, its group, what it means and the next move."""

    number: int | None
    kind: Kind
    meaning: str
    remedy: str
    retry_budget: int


TABLE: dict[int, Fault] = {
    errno.EPIPE: Fault(errno.EPIPE, Kind.READER_GONE,
                       "the reader closed its end of the pipe",
                       "stop writing: nothing after this call can be delivered",
                       0),
    errno.ECONNRESET: Fault(errno.ECONNRESET, Kind.RESET,
                            "the peer sent RST, so the reply was refused",
                            "stop writing and let the connection close",
                            0),
    errno.ESHUTDOWN: Fault(errno.ESHUTDOWN, Kind.CLOSED_HANDLE,
                           "the transport endpoint was already shut down "
                           "(not reproduced here: a local shutdown() returned 32)",
                           "find who shut the endpoint down; a per-request reopen hides it",
                           0),
    errno.EBADF: Fault(errno.EBADF, Kind.CLOSED_HANDLE,
                       "the descriptor was closed before the write",
                       "fix who owns the descriptor, not the write",
                       0),
}


def unwrap(exc: BaseException) -> BaseException:
    """Follow the cause chain to the first OSError, which is where the errno lives."""
    current: BaseException = exc
    seen: set[int] = set()
    while id(current) not in seen:
        seen.add(id(current))
        if isinstance(current, OSError):
            return current
        nxt = current.__cause__ or current.__context__
        if nxt is None:
            return current
        current = nxt
    return current


def classify(exc: BaseException) -> Fault:
    """Return the record for the failure that reached the caller, wrappers included."""
    inner = unwrap(exc)
    number = inner.errno if isinstance(inner, OSError) else None
    if number in TABLE:
        return TABLE[number]
    return Fault(number, Kind.UNRELATED,
                 "not a pipe or socket write failure",
                 "read the errno: this table does not classify it", 0)


def is_reader_gone(exc: BaseException) -> bool:
    """True when the failure says the other side stopped reading, in either form."""
    return classify(exc).kind in (Kind.READER_GONE, Kind.RESET)
Counting delivery and stopping where the reader stopped. pipepath/writes.py
"""Sending a reply one piece at a time, and stopping when the reader leaves.

A loop that writes a reply has to answer three questions on every iteration: did the reader take
the piece, is the reader still there, and how much has been delivered. ``sendall`` answers none
of them. It returns ``None``, and when it raises it does not say how much of the piece the kernel
accepted, so the caller cannot tell a reply cut at the first chunk from one cut near its end.

The function here counts, stops at the first reader-gone fault, and returns a delivery record
instead of raising past its caller. ``os.write`` may accept less than it was offered, so a short
return does not move the loop on to the next piece: the rest of the slice is offered again, and
the loop leaves a piece only when all of it is in the kernel. A ``sendall``-shaped writer returns
``None`` and is counted by the length it was given, because it either takes the whole piece or
raises. A descriptor the caller closed by mistake, and a writer that accepts nothing at all, are
re-raised: the first is a bug outside this loop, and the second would spin on the same bytes.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Iterable

from .errors import Fault, classify, is_reader_gone


@dataclass(frozen=True)
class Delivery:
    """What one reply managed to deliver before the reader left, if it did."""

    sent_bytes: int
    pieces: int
    fault: Fault | None

    @property
    def complete(self) -> bool:
        """True only when every piece was accepted in full."""
        return self.fault is None


def deliver(write: Callable[[bytes], int | None], pieces: Iterable[bytes]) -> Delivery:
    """Write every piece in full, counting bytes, and stop on the first lost reader."""
    sent = 0
    count = 0
    for piece in pieces:
        offset = 0
        while offset < len(piece):
            rest = piece[offset:]
            try:
                written = write(rest)
            except OSError as exc:
                if is_reader_gone(exc):
                    return Delivery(sent, count, classify(exc))
                raise
            step = len(rest) if written is None else int(written)
            if step <= 0:
                raise RuntimeError(f"write accepted {step} of the {len(rest)} bytes offered")
            offset += step
            sent += step
        count += 1
    return Delivery(sent, count, None)
The quiet exit for a command-line program. pipepath/stdout.py
"""Ending a command-line program whose reader has gone.

When stdout is a pipe and the reader exits - ``head``, ``grep -q``, a pager someone quit - the
next write raises ``BrokenPipeError``. Letting it escape prints a traceback. Catching it and
returning is not enough either: the interpreter flushes the same dead pipe during shutdown, prints
``Exception ignored`` on stderr and exits with status 120.

Both outcomes are avoided by doing the one thing the interpreter will not do for itself: point
descriptor 1 at ``/dev/null`` while it is still open, then exit with the status the program
chooses. After the redirect there is nothing left for the shutdown flush to fail on.
"""
from __future__ import annotations

import os
import sys
from typing import NoReturn


def exit_quietly(code: int = 0) -> NoReturn:
    """Flush what the reader may still take, silence descriptor 1, and exit with ``code``."""
    try:
        sys.stdout.flush()
    except OSError:
        pass
    try:
        devnull = os.open(os.devnull, os.O_WRONLY)
    except OSError:
        raise SystemExit(code)
    os.dup2(devnull, sys.stdout.fileno())
    os.close(devnull)
    raise SystemExit(code)
One log line for a failed write. pipepath/report.py
"""One log line for a failed write, carrying the number the next person needs.

A traceback names the exception type and stops there: ``BrokenPipeError: [Errno 32] Broken pipe``
says which number, but a server log that records only the type loses it, and one that records the
whole traceback buries it under twenty frames. The line below keeps the four fields that decide
what happens next: the target, the errno with its group, how many bytes were delivered, and the
retry budget.
"""
from __future__ import annotations

from .errors import classify
from .writes import Delivery


def describe_failure(exc: BaseException, target: str, delivery: Delivery | None = None) -> str:
    """Return one line: target, errno, group, bytes delivered and the retry budget."""
    fault = classify(exc)
    number = "none" if fault.number is None else str(fault.number)
    sent = "unknown" if delivery is None else str(delivery.sent_bytes)
    return (f"write to {target}: errno {number} ({fault.kind.value}); "
            f"delivered {sent} B; retries {fault.retry_budget}")
A pipe pair and a socket pair for the tests. conftest.py
"""Shared fixtures: a pipe pair and a socket pair whose far end the test can close."""
from __future__ import annotations

import os
import socket

import pytest


@pytest.fixture()
def pipe_pair():
    """A read fd and a write fd, closed in the order the test asks for."""
    read_fd, write_fd = os.pipe()
    try:
        yield read_fd, write_fd
    finally:
        for fd in (read_fd, write_fd):
            try:
                os.close(fd)
            except OSError:
                pass


@pytest.fixture()
def socket_pair():
    """Two connected Unix sockets: the second is the reader the test closes."""
    near, far = socket.socketpair()
    try:
        yield near, far
    finally:
        near.close()
        far.close()
Classification, including a real closed pipe and a real socket. test_errors.py
"""Classification: the same reader-gone event, under every name Python gives it."""
from __future__ import annotations

import errno
import os

import pytest

from pipepath.errors import TABLE, Kind, classify, is_reader_gone, unwrap


@pytest.mark.parametrize("number,kind", [
    (errno.EPIPE, Kind.READER_GONE),
    (errno.ECONNRESET, Kind.RESET),
    (errno.ESHUTDOWN, Kind.CLOSED_HANDLE),
    (errno.EBADF, Kind.CLOSED_HANDLE),
])
def test_table_numbers_are_classified(number, kind):
    assert classify(OSError(number, os.strerror(number))).kind is kind


@pytest.mark.parametrize("number", sorted(TABLE))
def test_every_table_entry_has_zero_retry_budget(number):
    assert TABLE[number].retry_budget == 0


@pytest.mark.parametrize("number", sorted(TABLE))
def test_every_table_entry_names_a_remedy(number):
    assert TABLE[number].remedy.strip()


@pytest.mark.parametrize("number", sorted(TABLE))
def test_every_table_entry_prints_its_own_number(number):
    assert TABLE[number].number == number


@pytest.mark.parametrize("number", [errno.EINVAL, errno.EACCES, errno.EAGAIN, errno.ENOENT])
def test_unlisted_errno_is_unrelated(number):
    fault = classify(OSError(number, "x"))
    assert fault.kind is Kind.UNRELATED
    assert fault.retry_budget == 0


def test_non_oserror_is_unrelated():
    fault = classify(ValueError("not a write"))
    assert fault.kind is Kind.UNRELATED
    assert fault.number is None


def test_broken_pipe_is_reader_gone():
    assert classify(BrokenPipeError(errno.EPIPE, "Broken pipe")).kind is Kind.READER_GONE


def test_connection_reset_is_reset():
    assert classify(ConnectionResetError(errno.ECONNRESET, "reset")).kind is Kind.RESET


class Wrapper(Exception):
    """What a client library raises around the socket error."""

    def __init__(self, reason: BaseException) -> None:
        super().__init__("urlopen error")
        self.reason = reason
        self.__cause__ = reason


def test_unwrap_follows_the_cause_chain():
    inner = BrokenPipeError(errno.EPIPE, "Broken pipe")
    middle = Wrapper(inner)
    outer = RuntimeError("request failed")
    outer.__cause__ = middle
    assert unwrap(outer) is inner


def test_unwrap_prefers_cause_over_context():
    cause = OSError(errno.EPIPE, "one")
    context = OSError(errno.ECONNRESET, "two")
    error = RuntimeError("wrapped")
    error.__cause__ = cause
    error.__context__ = context
    assert unwrap(error) is cause


def test_unwrap_survives_a_cycle():
    error = RuntimeError("loops")
    error.__context__ = error
    assert unwrap(error) is error


def test_is_reader_gone_for_pipe_and_reset():
    assert is_reader_gone(BrokenPipeError(errno.EPIPE, "x"))
    assert is_reader_gone(ConnectionResetError(errno.ECONNRESET, "x"))


def test_is_reader_gone_is_false_for_a_closed_handle():
    assert not is_reader_gone(OSError(errno.EBADF, "x"))


def test_is_reader_gone_is_false_for_an_unrelated_error():
    assert not is_reader_gone(ValueError("x"))


def test_classify_reads_a_real_closed_pipe(pipe_pair):
    read_fd, write_fd = pipe_pair
    os.close(read_fd)
    with pytest.raises(BrokenPipeError) as caught:
        os.write(write_fd, b"x")
    assert classify(caught.value).kind is Kind.READER_GONE
    assert caught.value.errno == errno.EPIPE


def test_classify_reads_a_real_closed_socket(socket_pair):
    near, far = socket_pair
    far.close()
    with pytest.raises(BrokenPipeError) as caught:
        near.sendall(b"x")
    assert classify(caught.value).kind is Kind.READER_GONE


def test_table_keys_are_the_errno_module_numbers():
    assert TABLE[errno.EPIPE].number == 32
    assert TABLE[errno.ECONNRESET].number == 104
    assert TABLE[errno.ESHUTDOWN].number == 108
    assert TABLE[errno.EBADF].number == 9


def test_fault_is_frozen():
    fault = TABLE[errno.EPIPE]
    with pytest.raises(Exception):
        fault.retry_budget = 3       # type: ignore[misc]
Delivery counting against a pipe with no reader, and short writes. test_writes.py
"""Delivery counting: a reply that stops where the reader stopped, and says how far it got."""
from __future__ import annotations

import errno
import os

import pytest

from pipepath.writes import Delivery, deliver


def test_deliver_reports_complete_for_three_pieces():
    written: list[bytes] = []
    delivery = deliver(written.append, [b"a", b"bb", b"ccc"])
    assert delivery.complete
    assert delivery.sent_bytes == 6
    assert delivery.pieces == 3
    assert written == [b"a", b"bb", b"ccc"]


def test_deliver_counts_bytes_not_pieces():
    delivery = deliver(lambda piece: None, [b"x" * 10, b"y" * 5])
    assert delivery.sent_bytes == 15
    assert delivery.pieces == 2


def test_deliver_finishes_a_short_write_with_the_rest_of_the_piece():
    offered: list[bytes] = []

    def write(piece: bytes) -> int:
        offered.append(piece)
        return min(3, len(piece))

    delivery = deliver(write, [b"x" * 64, b"y" * 5])
    assert delivery.complete
    assert delivery.sent_bytes == 69
    assert delivery.pieces == 2
    # 64 bytes in 3-byte pieces is 21 calls plus one of 1 byte, then the 5-byte piece.
    assert len(offered) == 24
    assert offered[0] == b"x" * 64
    assert offered[-2:] == [b"yyyyy", b"yy"]
    assert all(len(piece) <= 64 for piece in offered)


def test_deliver_keeps_the_reader_gone_fault_after_a_partial_piece():
    calls = {"n": 0}

    def write(piece: bytes) -> int:
        calls["n"] += 1
        if calls["n"] == 3:
            raise BrokenPipeError(errno.EPIPE, "Broken pipe")
        return min(2, len(piece))

    delivery = deliver(write, [b"z" * 10])
    assert delivery.sent_bytes == 4
    assert delivery.pieces == 0
    assert not delivery.complete
    assert delivery.fault is not None and delivery.fault.number == errno.EPIPE


def test_deliver_refuses_a_writer_that_accepts_nothing():
    with pytest.raises(RuntimeError):
        deliver(lambda piece: 0, [b"x" * 8])


def test_deliver_of_nothing_is_complete():
    delivery = deliver(lambda piece: None, [])
    assert delivery == Delivery(0, 0, None)


def test_deliver_stops_at_a_real_closed_pipe(pipe_pair):
    read_fd, write_fd = pipe_pair
    os.close(read_fd)
    delivery = deliver(lambda piece: os.write(write_fd, piece), [b"first", b"second"])
    assert not delivery.complete
    assert delivery.sent_bytes == 0
    assert delivery.fault is not None
    assert delivery.fault.number == errno.EPIPE


def test_deliver_keeps_what_the_reader_took_before_it_left():
    taken: list[bytes] = []

    def write(piece: bytes) -> None:
        if len(taken) == 2:
            raise BrokenPipeError(errno.EPIPE, "Broken pipe")
        taken.append(piece)

    delivery = deliver(write, [b"a" * 4, b"b" * 6, b"c" * 8, b"d" * 10])
    assert delivery.sent_bytes == 10
    assert delivery.pieces == 2
    assert not delivery.complete


def test_deliver_stops_at_reset(socket_pair):
    near, far = socket_pair
    far.close()
    delivery = deliver(near.sendall, [b"x" * 64])
    assert not delivery.complete
    assert delivery.fault is not None
    assert delivery.fault.retry_budget == 0


def test_deliver_reraises_a_closed_handle():
    def write(piece: bytes) -> None:
        raise OSError(errno.EBADF, "Bad file descriptor")

    with pytest.raises(OSError) as caught:
        deliver(write, [b"x"])
    assert caught.value.errno == errno.EBADF


def test_deliver_reraises_an_unrelated_error():
    with pytest.raises(ValueError):
        deliver(lambda piece: (_ for _ in ()).throw(ValueError("bad")), [b"x"])


def test_delivery_is_frozen():
    delivery = Delivery(1, 1, None)
    with pytest.raises(Exception):
        delivery.sent_bytes = 2      # type: ignore[misc]
The descriptor move, and one real pipeline in a child. test_stdout.py
"""The quiet exit: a status the program chooses, and a descriptor that can no longer fail.

The unit tests replace the ``os`` the module calls with a recorder, because the function's whole
job is to move descriptor 1, and moving the test runner's descriptor 1 would blind its capture.
The last test runs the real function in a child process whose stdout is a closed pipe, which is
the arrangement the function exists for.
"""
from __future__ import annotations

import errno
import os
import subprocess
import sys
import textwrap
import types

import pytest

from pipepath.stdout import exit_quietly

MODULE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class FakeStdout:
    """A stdout whose flush the test can count and make fail."""

    def __init__(self, fail_flush: bool = False) -> None:
        self.fail_flush = fail_flush
        self.flushes = 0

    def flush(self) -> None:
        self.flushes += 1
        if self.fail_flush:
            raise BrokenPipeError(errno.EPIPE, "Broken pipe")

    def fileno(self) -> int:
        return 7


class FakeOs:
    """The three os calls exit_quietly makes, recorded instead of performed."""

    devnull = "/dev/null"
    O_WRONLY = os.O_WRONLY

    def __init__(self, fail_open: bool = False) -> None:
        self.fail_open = fail_open
        self.opened: list[str] = []
        self.duplicated: list[tuple[int, int]] = []
        self.closed: list[int] = []

    def open(self, path: str, flags: int) -> int:
        if self.fail_open:
            raise OSError(errno.EMFILE, "Too many open files")
        self.opened.append(path)
        return 42

    def dup2(self, source: int, target: int) -> int:
        self.duplicated.append((source, target))
        return target

    def close(self, fd: int) -> None:
        self.closed.append(fd)


@pytest.fixture()
def quiet(monkeypatch):
    """A recording os and a fake stdout, both wired into the module under test."""
    fake_os = FakeOs()
    fake_stdout = FakeStdout()
    monkeypatch.setattr("pipepath.stdout.os", fake_os)
    monkeypatch.setattr("pipepath.stdout.sys", types.SimpleNamespace(stdout=fake_stdout))
    return fake_os, fake_stdout


def test_exit_quietly_raises_system_exit(quiet):
    with pytest.raises(SystemExit):
        exit_quietly(0)


def test_exit_quietly_carries_the_code(quiet):
    with pytest.raises(SystemExit) as caught:
        exit_quietly(3)
    assert caught.value.code == 3


def test_exit_quietly_flushes_first(quiet):
    _, fake_stdout = quiet
    with pytest.raises(SystemExit):
        exit_quietly(0)
    assert fake_stdout.flushes == 1


def test_exit_quietly_opens_devnull(quiet):
    fake_os, _ = quiet
    with pytest.raises(SystemExit):
        exit_quietly(0)
    assert fake_os.opened == [os.devnull]


def test_exit_quietly_duplicates_devnull_onto_descriptor_one(quiet):
    fake_os, _ = quiet
    with pytest.raises(SystemExit):
        exit_quietly(0)
    assert fake_os.duplicated == [(42, 7)]
    assert fake_os.closed == [42]


def test_exit_quietly_survives_a_failed_flush(quiet, monkeypatch):
    _, fake_stdout = quiet
    fake_stdout.fail_flush = True
    with pytest.raises(SystemExit) as caught:
        exit_quietly(0)
    assert caught.value.code == 0


def test_exit_quietly_does_not_duplicate_when_devnull_cannot_open(monkeypatch):
    blocked = FakeOs(fail_open=True)
    monkeypatch.setattr("pipepath.stdout.os", blocked)
    monkeypatch.setattr("pipepath.stdout.sys",
                        types.SimpleNamespace(stdout=FakeStdout()))
    with pytest.raises(SystemExit):
        exit_quietly(0)
    assert blocked.duplicated == []


def test_exit_quietly_in_a_real_pipeline():
    """A child writes to a pipe whose reader is closed, and the status is the one it chose."""
    program = textwrap.dedent(f"""
        import sys
        sys.path.insert(0, {MODULE!r})
        from pipepath.stdout import exit_quietly
        try:
            sys.stdout.write("x" * 100000)
        except BrokenPipeError:
            exit_quietly(0)
    """)
    read_fd, write_fd = os.pipe()
    os.close(read_fd)                       # the reader has already gone
    try:
        result = subprocess.run([sys.executable, "-c", program], stdout=write_fd,
                                stderr=subprocess.PIPE, timeout=30)
    finally:
        os.close(write_fd)
    assert result.returncode == 0
    assert b"Exception ignored" not in result.stderr
    assert b"Traceback" not in result.stderr
The fields of the log line. test_report.py
"""The log line: four fields, one line, and the number a reader can act on."""
from __future__ import annotations

import errno

from pipepath.errors import TABLE
from pipepath.report import describe_failure
from pipepath.writes import Delivery


def test_line_carries_the_errno_and_its_group():
    line = describe_failure(BrokenPipeError(errno.EPIPE, "Broken pipe"), "api.test")
    assert "errno 32 (reader gone)" in line
    assert line.startswith("write to api.test: ")


def test_line_says_unknown_without_a_delivery():
    line = describe_failure(BrokenPipeError(errno.EPIPE, "Broken pipe"), "api.test")
    assert "delivered unknown B" in line


def test_line_reports_the_bytes_a_delivery_measured():
    delivery = Delivery(65536, 64, TABLE[errno.EPIPE])
    line = describe_failure(BrokenPipeError(errno.EPIPE, "Broken pipe"), "queue", delivery)
    assert "delivered 65536 B" in line
    assert "retries 0" in line


def test_line_for_an_unclassified_error_prints_no_number():
    line = describe_failure(ValueError("bad"), "parser")
    assert "errno none (unrelated)" in line


def test_line_ends_with_the_retry_budget():
    line = describe_failure(ConnectionResetError(errno.ECONNRESET, "reset"), "api.test")
    assert line.endswith("retries 0")

Keep reading

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