mmap vs read(): 16,384 Pages, a Truncate SIGBUS, and ENOMEM at 65,482

Dark cover headed 'mmap vs read()': 16,384 pages covered by about 1,025 faults, a file-backed resident set of 262,144 KiB for a 256 MiB file, 2 of 6 file changes that removed mapped pages and raised SIGBUS 5 of 5 times, a dirty 64 MiB mapping synced at 303 MiB/s, and a process that stopped mapping at 65,482 mappings with ENOMEM

TL;DR: The Copy and the Fault Are Two Different Bills

  • One pass over the 64 MiB file took 1,025 faults for 16,384 pages – one per 16 pages, because the kernel maps a window of 16 around the page that faulted. MAP_POPULATE removed none of that work; it moved 96% of it into the mmap() call, which then took 24.2 ms.
  • Pair the arms fairly and the ranking survives. An arm that touches one byte per page prices the fault, not the read, so the same bytes were hashed through both calls: the read took 14.7% more per MiB at 64 MiB and 13.0% more at 128 MiB (1.10 against 1.25 ms per MiB in the larger run) – the copy it makes and the mapping does not. The read was the slower arm in all 5 repeats of the larger pair, by 5.7% to 69.6%: that spread is the honest size of the claim, and the median is the number to quote.
  • A resident set the size of the file is page cache, not a leak: the 256 MiB mapping added 262,144 KiB of RssFile, no RssAnon, and MADV_DONTNEED returned all of it while the mapping stayed open.
  • Six scenarios changed a file under a live mapping. The two that removed mapped pages – truncating to zero and to one page – killed the reader with SIGBUS in 5 of 5 runs each; the four that left every page alive did not. A truncate to 4,100 bytes read a zero out of the tail of a page that still existed.

Scope. One Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, uid 1000 without privilege, files on a virtiofs mount at /workspace, 4,096-byte pages, a clock resolving 1 ns. Every timing is a median of 5 runs. The two timing probes ran their arms in a different order in every repeat after one warm-up, so no arm owns the cold cache or the first position; ranges appear where they matter. Fault counts and resident sets were read from /proc around the arm that produced them. Six platform rules are quoted, not measured, and marked where they appear: the alignment O_DIRECT documents (4,096-byte blocks here, 512-byte sectors), which this mount did not enforce; the kernel rule that a page past the end of a truncated file raises SIGBUS; the fault-around window of 16 pages, which the measurement matches but does not set; C’s side of the same fault, where mmap() accepts a length past the end and a SIGBUS handler can map a page over the faulting address and return, or leave with siglongjmp; the kernel’s test of the map count, which refuses a new area only once the count is already above the setting; and the [vsyscall] line a map file prints from a pseudo area no process owns. CPython’s signal.signal() is not on that list: section 5 installs a handler and records what a fault does with it. No arm here is a cold read: POSIX_FADV_DONTNEED did not evict this file, and each cold arm matched its warm twin (1 major fault for the mapped arms, 0 for the read arms).

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

Find the sentence that matches what happened, stop at the first row that fits, and make that change: establish what the file did, then choose the call that survives it.

What you sawChange to make (and what measured it)
Bus error (core dumped) after a log rotationThe process reads a mapping of a file that lost pages underneath it. A rotation that renames is harmless – the mapping holds the old inode – while logrotate’s copytruncate empties the file in place and kills readers. Stop mapping files another program rewrites in place; where a mapping is unavoidable, guard every read with a stat: the two scenarios that removed mapped pages raised SIGBUS in 5 of 5 runs each (sections 5 and 10)
RSS is exactly the size of a mapped file and the alert firesThat is RssFile: page cache the kernel can take back. The 256 MiB mapping added no anonymous memory, and MADV_DONTNEED dropped it all in one call (section 4)
A benchmark says mmap is faster, or slower, than read()Check what each arm did with the bytes. Hashing every byte in both left the read 13.0% slower per MiB (1.10 against 1.25 ms, median of 5 repeats); a walk against a copy measures neither (section 3)
A program that maps many small files dies with ENOMEMEvery mapping is a VMA and the cap is per process: the run stopped at 65,482 mappings. Reuse one mapping, batch, or raise vm.max_map_count – the same cap stopped a 1,048,576-byte bytearray allocation (section 8)
Data appended to the file never appears in the mappingA mapping’s length is fixed at the call; reading past it raises IndexError. Remap after the flush (section 7)
A write through the mapping is not in the file another service readsYou have a MAP_PRIVATE mapping, or you read a different inode. Shared writes were visible before any msync; private ones never reached the file (section 6)
O_DIRECT raised no EINVAL on this hostThis mount accepted the flag without enforcing it: all 5 arms, including an allocator-placed buffer and a length that was not a block multiple, transferred what they asked for. Whether the cache was bypassed is not shown (section 9)
ValueError: cannot mmap an empty file at startupA file that may be empty must be read: the interpreter refuses it before the kernel sees the call, and refuses a length past the end the same way (section 7)
A large file is read once, front to back, and the mapping looks pointlessUse read() in blocks: no file page faults, no SIGBUS on a file that shrinks, and a copy at 0.55 ms per MiB here (sections 3 and 10)
Table 1: nine changes, matched to the sentence a reader has. Each row names the measurement behind it.

1. Two Ways Into One File

read() copies: the kernel writes the file’s bytes into a buffer the process owns, and the process pays for the copy every time. mmap() maps: the kernel adds the file’s pages to the address space and returns a pointer, no bytes move until one is touched, and the fault that follows fills a page table entry rather than the heap.

CallWhat it does to your processWhat it costs
read(), preadv()Copies the bytes into your bufferOne copy and one syscall per block, no file-page faults
mmap()Maps file pages at a chosen protection and sharingOne syscall, then a minor fault per group of pages
madvise()Advises the kernel on access pattern or page retentionOne syscall; it may be ignored, and here it changed no fault count
msync()Writes dirty pages of a shared mapping back and waitsBounded by dirty bytes, not file size: 211.5 ms for a dirty 64 MiB mapping
ftruncate()Changes the file’s length, and whether a mapped page existsNothing; SIGBUS to a mapping touching a page past the new end
Table 2: five calls, and what each asks the kernel to do. Only the first two read a file; the last three decide what happens to bytes already mapped.

The edge that matters is what happens when the file changes length under a reader. A copy path sees a shorter file and returns fewer bytes. A mapping does not shrink with the file: it keeps its length, and a page whose bytes are gone is not a short read but a signal. The page reader below is the copy path in two functions – one reused buffer, a copy yielded per block, and read_page for callers that need a window by number.

"""Reading a file in pages without mapping it, so a caller has the copy-free path's control.

A page reader does one thing a mapping cannot: it never holds a page that no longer exists. Each
call hands back the bytes that were just copied, so truncation shortens the next read instead of
killing the process. The price is the copy, and these two functions are the whole of it.
"""

from __future__ import annotations
import os


def chunks(fd: int, size: int = 1 << 20):
    """Yield the file from its current position in blocks, reusing one read buffer.

    Each block is handed back as a new bytes object, so the caller owns what it gets and the
    buffer is not overwritten while the caller still holds the previous block.
    """
    if size <= 0:
        raise ValueError("chunk size must be positive")
    buffer = bytearray(size)
    view = memoryview(buffer)
    while True:
        count = os.readv(fd, [view])
        if not count:
            return
        yield bytes(view[:count])


def read_page(fd: int, index: int, page: int = 4096) -> bytes:
    """One page by number, short at the end of the file and empty past it."""
    if index < 0:
        raise ValueError("page index must not be negative")
    if page <= 0:
        raise ValueError("page size must be positive")
    offset = index * page
    buffer = bytearray(page)
    view = memoryview(buffer)
    position = 0
    while position < page:
        count = os.preadv(fd, [view[position:]], offset + position)
        if not count:
            break
        position += count
    return bytes(view[:position])

2. A Thousand Faults for Sixteen Thousand Pages

Probe 02 reads or maps one 64 MiB file eight ways, timing the setup apart from the pass because one arm does most of its work inside the call. Four walk arms touch one byte per page – enough to fault a page in, not enough to measure more than the kernel; two read arms copy the whole file through a buffer allocated before the timer; and two hash every byte, one through the mapping and one through a 1 MiB buffer, so the same bytes cross each boundary.

ArmCall before the passThe passTotalMinor faultsMajor faults
mmap, one byte per page, no advice0.08 ms25.67 ms25.8 ms1,0251
mmap with MAP_POPULATE24.17 ms1.12 ms25.3 ms1,0250
mmap, MADV_SEQUENTIAL before the pass0.09 ms24.95 ms25.0 ms1,0231
mmap, MADV_WILLNEED before the pass0.09 ms24.98 ms25.1 ms1,0241
read() into one 1 MiB buffer0.00 ms28.67 ms28.7 ms00
read() into one 64 KiB buffer0.00 ms29.05 ms29.1 ms00
mmap, every byte hashed0.08 ms63.46 ms63.6 ms1,0241
read() into one 1 MiB buffer, every byte hashed0.00 ms72.88 ms72.9 ms00
Table 3: 8 arms over the same 64 MiB, median of 5 runs in a different order each repeat, after one warm-up. The four walk arms touch one byte per page; the two read arms copy everything; the last two hash every byte.

The plain pass took 1,025 faults for 16,384 pages. The kernel’s fault-around window maps the pages around the one that faulted, so one fault covers 16 pages – 15,359 faults never taken, and 1,024 of them in the hashed mapping arm that read every byte. A mapping of a large file will therefore never show one fault per page, and a program reading every page pays one fault per window of 16 pages.

MAP_POPULATE did not remove the work; it moved it. The call itself took 24.2 ms – 95.6% of the arm’s total – and the pass that followed took 1.1 ms, with a fault count equal to the plain arm’s. The faults happened inside the call, where a timer started after mmap() returns cannot see them. Prefaulting moves latency to open time; it is not a way to pay less.

MADV_SEQUENTIAL and MADV_WILLNEED changed the total to 24.5-28.3 ms and 24.4-31.5 ms against the plain arm’s 24.1-27.3 ms, with no change in fault count. Those ranges overlap, so this page claims no speed-up from either; in the fixed order the same three arms measured 26.5, 27.9 and 26.9 ms, with the plain arm first and fastest, so neither the advice nor the warm cache moved it. A file already in the page cache has no readahead left to trigger – an inference from the mechanism, not a measurement here – so the advice would need a cold file, which this host could not produce.

What each arm did with the bytesmmapread()What the gap is
Touched one byte per page, against a full copy25.8 ms28.7 msTwo jobs: a fault every 16 pages against a copy of every byte. The gap prices the fault, not the call
Hashed every byte, both sides63.6 ms72.9 msThe read is 14.7% slower: the copy it makes and the mapping does not
The same gap per MiB, at 128 MiB, hashed1.101.25The read is 13.0% slower per MiB again: the two totals rose 2.22× and 2.19× for a file of twice the size, so over the two sizes measured the gap follows the bytes – two points, not a curve
Table 4: the same file, four ways of spending it. The first row is the comparison a benchmark makes by accident; only the second prices the two calls against each other.

The same pair at 64 MiB left no overlap at all: 62.8-64.7 ms for the hashed mapping against 70.9-74.0 ms for the hashed read, with the read slower in every repeat by 12.3% to 15.6%. A smaller file leaves less room for a stall to land between the two arms.

That is the honest shape of the choice: a mapping avoids the copy and pays a fault per group of pages, a read pays the copy and no file-page faults, and on a cached file the read costs 14.7% more per MiB at 64 MiB and 13.0% more at 128 MiB – the same gap read the other way as a mapping 12.8% and 11.5% cheaper. The mechanism decides the runbook, not the percentage.

3. What the Pass Costs, Split Between User and Kernel

A wall clock cannot say who did the work, so probe 04 times a 128 MiB pass five ways and records the process’s own user and system time around each, in a different arm order every repeat. Two arms touch one byte per page and two hash every byte: the first pair prices the fault, the second prices moving the bytes.

ArmWall, median (min – max)UserSystemMinor faults
mmap, one byte per page56.8 ms (52.8 – 71.3)6.3 ms46.6 ms2,049
read() into one 1 MiB buffer70.8 ms (59.0 – 152.9)0.0 ms55.4 ms0
read() into one 4 KiB buffer84.5 ms (75.9 – 95.9)16.0 ms62.5 ms0
mmap, every byte hashed141.4 ms (130.8 – 166.6)76.9 ms62.0 ms2,048
read() into one 1 MiB buffer, every byte hashed159.8 ms (150.9 – 253.9)86.7 ms58.7 ms0
Table 5: the same 128 MiB, median of 5 runs in a shuffled order after one warm-up of every arm, with the range of the five wall clocks under each median. User and system time are the process’s own counters: they include the loop or hash above the call and exclude everything before the arm.

Per MiB the walk cost 0.44 ms and the 1 MiB copy 0.55 ms – the price of a fault and the price of a copy, two jobs. The pair that did the same work is the hashed one: 1.10 ms per MiB through the mapping against 1.25 through the buffer, 13.0% more for the copy by median. That median sits inside a wide spread: the mapping arm’s five repeats ran 130.8-166.6 ms and the read arm’s 150.9-253.9 ms, so the two ranges overlap, and one repeat of the read took 253.9 ms – 69.6% above the mapping arm’s time in that same repeat. The shape is what a runbook uses: 82% of the walk arm’s wall clock was kernel time, because the fault handler did the work; in the hashed pair the kernel’s share was 44% for the mapping and 37% for the read, and the rest was the hash (76.9 ms against 86.7 ms of user time).

Five repeats on one VM is not a margin, and this one says so plainly. The same probe produced a 152.9 ms round for an arm whose median is 70.8 ms – a stall the size of the whole comparison – and the read was the slower arm in all 5 rounds, by 5.7% to 69.6%. So the direction is what this run establishes and the 13% is a median with a range around it, not a margin that separates the calls on any host. Two limits belong beside it: every arm here read a file already in the page cache, because the eviction advice this mount ignores could not make a cold one, and a single VM’s scheduler is the same machine that produced the 152.9 ms round. Measure the pair on the mount and block size in question before quoting a percentage.

The third arm charges the caller: a 4,096-byte buffer still copied the file in 84.5 ms, but 16.0 ms of that was the process’s own loop – one syscall per page and a Python call around it. A block size is a decision that lives in user space.

So the calls are not rivals with a winner. mmap() is how a program reaches into a file at a chosen offset, parses a format in place, or shares a read-only image between workers. read() streams bytes it does not intend to keep, and is the only one of the two that survives a file shrinking underneath it.

4. A Resident Set the Size of the File

Probe 07 measures the same 256 MiB twice – once as an anonymous buffer the process owns, once as a shared mapping of a file – reading VmRSS, RssAnon and RssFile from /proc/self/status while each is resident.

ArmVmRSS after the passof which RssAnonof which RssFileChange after release
private anonymous buffer, every page written262,148 KiB262,148 KiB0 KiB-262,148 KiB
shared file mapping, every page read262,144 KiB0 KiB262,144 KiB-262,144 KiB
Table 6: 256 MiB, median of 5 runs. The last column is MADV_DONTNEED for the mapping and the buffer’s release for the anonymous arm, both while the process kept running.

The mapping added 262,144 KiB of resident set and 0 KiB of anonymous memory: every resident page belonged to the file. That answers the alert that fires because a service’s RSS equals the file it maps – page cache the kernel can take back, charged to the process only because the process mapped it. The last column is the proof: MADV_DONTNEED dropped 262,144 KiB – exactly what the pass added – while the mapping stayed open.

Two practical notes. A container’s memory limit counts file-backed pages while they are resident, and an alert on VmRSS counts them too, so a service that maps a large file can look like a problem it is not. The kernel reclaims clean file pages before it would kill anything, which is why most services never notice; what does hurt is reclaim that cannot keep up – dirty pages waiting to be written, a mapping held by mlock, a limit so tight that reclaim throttles the service – or a human paged by an RSS threshold. MADV_DONTNEED after a pass is the cheap defence, and table 6 is the evidence it returns the memory; the cgroup behaviour itself is mechanism, not measured here. RssShmem is a third bucket – shared anonymous memory, which Python creates for mmap(-1, ...) – and it counts in VmRSS like a file mapping.

5. The Truncate That Kills the Reader

Probe 05 maps 8 pages of a file, changes the file underneath the mapping, then touches one offset. A child interpreter runs each arm, so a signal ends the child and the probe records the exit status: a negative return code is the signal that killed it. A second set of children installs a Python SIGBUS handler before the same mapping is truncated, and those runs are given a deadline instead of being waited out – the last two paragraphs of this section have what they did.

What changed, and what was touchedOffsetResultWhat the child printed
truncated to zero, first page touched0SIGBUSmapped 32768 now 0
truncated to one page, a page past it touched16,384SIGBUSmapped 32768 now 4096
truncated to 4,100 bytes, a byte inside page 0 touched100no signalmapped 32768 now 4100 byte 100 97
truncated to 4,100 bytes, a byte past 4,100 in the last partial page touched4,195no signalmapped 32768 now 4100 byte 4195 0
file unlinked, a byte inside the mapping touched100no signalmapped 32768 now 32768 byte 100 97
another file renamed over the path, the first byte touched0no signalmapped 32768 now 32768 byte 0 97
Table 7: 6 arms, each repeated 5 times with the same answer. The mapping was 32,768 bytes – 8 pages – before each change; the child printed its length and the file’s size, then the byte it read.

Of the six scenarios, the two that removed mapped pages – truncating to zero and to one page – ended the child with SIGBUS in 5 of 5 runs each, and the four that left every page alive did not. Both are the same rule: a page that no longer exists cannot be faulted in. The signal arrives on the touch, not the truncate, so the truncating process is fine and the reader dies later, possibly in a different library. That is why logrotate’s default configuration is safe for a reader that maps the file and its copytruncate option is not: a rename leaves the old inode and its pages, while copying then truncating empties the file the mapping still points at.

The third and fourth arms are the surprise, and the page each one touches is why. Offset 100 is page 0, bytes 0-4,095, and that page still existed after the truncate because part of it is still in the file – so the read returned the original byte without a signal. Offset 4,195 is a different page: page 1, bytes 4,096-8,191, the last partial page of the file, of which only the bytes from 4,096 through 4,099 survived the truncate to 4,100. That page exists because part of it does, and the rest of it reads as zeros rather than faulting – so a program reading a tail can get a value that looks like data and is not. The last two arms are the opposite surprise: unlinking the file and renaming another over its path left the mapping untouched, because it holds the inode and not the name – the space is freed when the last mapping goes.

No amount of checking closes that window: the file can shrink between the check and the read. A guard narrows it from one request to one window, and the class below parts company with itself after the check. read() copies inside the guard, so the bytes it returns are the process’s own and a later truncate cannot touch them; window() returns a view into the mapping, still the kernel’s memory, and the stat covered the moment the view was taken rather than the moment it is read. Reading a page that has gone under such a view is the SIGBUS of table 7. A view is safe only where the file cannot be emptied underneath it: a writer that replaces the file by rename, a lock the writers respect (flock with LOCK_SH here, LOCK_EX there), or a snapshot.

In C a handler can step out of that fault alive, which changes the choice: the default action for SIGBUS ends the process, but a handler can map an anonymous page over the faulting address with MAP_FIXED and return, so the retried instruction reads zeros, or leave with siglongjmp. A Python caller has neither, and that is measured here rather than assumed.

Probe 05 installs signal.signal(SIGBUS, handler) in a child whose handler appends a line to a log file, then truncates the file under the child’s mapping and touches the page. In 5 of 5 runs the handler was never entered: the log stayed empty, the child was still in state R with 1.91 s of CPU time when the probe’s 2 s deadline expired, and the probe killed it. What it did with that time is the kernel handing the same instruction its SIGBUS again, and nothing on this host can count that from outside – strace and perf are not installed, this image ships no package source that carries one, and ptrace returns EPERM – so the probe counted it from inside the process, with a handler written as 12 bytes of machine code that increments a counter in a shared page and returns. The same truncate under that handler took 749,279 deliveries in a 1 s window, 756,847 per CPU-second, and had passed 953,206 by the time the probe killed it.

The Python handler is not deaf, either: it ran for a SIGBUS the child sent itself with os.kill() – 1 call – and a truncate that left the touched page in the file ran it 0 times and returned from the read. A signal from outside is handed to Python at the next bytecode boundary; a fault is retried inside the load that took it, so the interpreter never reaches a boundary to run the callable, and the child goes on faulting at the rate the counter recorded. C’s handler can therefore do something Python’s cannot – repair the page or leave it – and what is left for a Python caller is a mapping of a file that can shrink with no recovery path. The choice is a copy, or a file that cannot shrink.

from __future__ import annotations
import mmap
import os
from .errors import TruncatedFile


class Mapping:
    """A read-only shared mapping with an identity check in front of every window."""

    def __init__(self, path: str) -> None:
        self.path = path
        self.fd = -1
        self.handle: mmap.mmap | None = None
        self.size = 0
        self.device = 0
        self.inode = 0
        self.views: list[memoryview] = []

    def open(self) -> "Mapping":
        if self.handle is not None or self.fd >= 0:
            raise RuntimeError(f"{self.path} is already mapped by this object")
        fd = os.open(self.path, os.O_RDONLY)
        try:
            info = os.fstat(fd)
            self.size = info.st_size
            self.device = info.st_dev
            self.inode = info.st_ino
            self.handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        except BaseException:
            os.close(fd)
            self.size = 0
            self.device = 0
            self.inode = 0
            raise
        self.fd = fd
        return self

    def same_file(self) -> bool:
        """True while the path still names the inode this mapping was opened on."""
        try:
            info = os.stat(self.path)
        except OSError:
            return False
        return (info.st_dev, info.st_ino) == (self.device, self.inode)

    def check(self) -> None:
        """Raise TruncatedFile unless the path still holds the mapped inode at its full size."""
        try:
            info = os.stat(self.path)
        except OSError as exc:
            raise TruncatedFile(self.path, self.size, 0) from exc
        if (info.st_dev, info.st_ino) != (self.device, self.inode):
            raise TruncatedFile(self.path, self.size, info.st_size)
        if info.st_size < self.size:
            raise TruncatedFile(self.path, self.size, info.st_size)

    def _bounds(self, offset: int, length: int) -> None:
        """Refuse a window the mapping does not cover, and a read after the close."""
        if self.handle is None:
            raise ValueError("the mapping is closed")
        if offset < 0 or length < 0 or offset + length > self.size:
            raise ValueError(f"{offset}+{length} is outside a {self.size}-byte mapping")

    def window(self, offset: int, length: int) -> memoryview:
        """A zero-copy view, guarded when it is taken and not afterwards.

        The check runs first, and the view then points into the mapping itself. A file truncated
        after this call removes pages under the view, and reading one of them ends the process
        with SIGBUS: a stat before a view cannot protect a read that happens later. Keep the
        view only while the file cannot be truncated (replace-by-rename, a respected lock, a
        snapshot) - otherwise call read(), which copies inside the guard.
        """
        self.check()
        self._bounds(offset, length)
        view = memoryview(self.handle)[offset:offset + length]
        self.views.append(view)
        return view

    def read(self, offset: int, length: int) -> bytes:
        """The same window as bytes the process owns, copied inside the guard.

        Slicing the mapping returns a copy, so a read in a loop leaves nothing behind: a view is
        registered only for a caller that asked for one and keeps it. The copy happens while the
        stat is still fresh, so a truncate after the return cannot touch these bytes; a truncate
        that lands between the stat and the copy still raises SIGBUS, which is one copy wide
        rather than one request wide.
        """
        self.check()
        self._bounds(offset, length)
        return self.handle[offset:offset + length]

    def close(self) -> None:
        # A live memoryview keeps the map exported, and closing the map under it raises
        # BufferError, so the views this object handed out are released first.
        for view in self.views:
            try:
                view.release()
            except ValueError:
                pass
        self.views.clear()
        if self.handle is not None:
            self.handle.close()
            self.handle = None
        if self.fd >= 0:
            os.close(self.fd)
            self.fd = -1

    def __enter__(self) -> "Mapping":
        # open_mapping() already opened it; entering must not open a second mapping over the first.
        if self.handle is None and self.fd < 0:
            self.open()
        return self

    def __exit__(self, *exc_info) -> None:
        self.close()

Two details there exist because the alternative failed. close() releases the views it handed out before it closes the mapping, because a live memoryview keeps the map exported and closing it under the view raises BufferError. And same_file() compares device and inode rather than size: a file replaced by a rename has the same length and a different identity, which is the last arm of table 7.

6. Writing Through the Mapping

Probe 06 writes one byte through a mapping and asks a separate process what the file says, in four of its five configurations, each repeated 5 times. The reader is a child interpreter, so the table records visibility between processes, not between two views inside one.

ArmThe writer’s own viewWhat another process readThe file’s byteFile size aftermsync
MAP_SHARED write, reader without msync0x5a0x5a0x5a1,048,576not called
MAP_SHARED write, then msync(MS_SYNC)0x5a0x5a0x5a1,048,5760.06 ms
MAP_PRIVATE write, then msync0x430x780x781,048,5760.00 ms
MAP_SHARED write of the last byte0x5a0x5a0x5a1,048,576not called
MAP_SHARED write of one byte per page over 64 MiB, then msync0x59not read0x5967,108,864211.53 ms
Table 8: five writes, median of 5 runs. In the four arms that ask one, the reader is a separate interpreter that opens the path; the fifth arm’s byte was read from the file by the probe after the mapping closed.

The first and third arms carry the rule. A shared write is visible to every other process as soon as it is made, with no msync at all, because both processes look at the same page in the page cache. msync is about durability – the bytes reaching the filesystem – not visibility to readers on the same host. A service that writes through a map and skips msync is not hiding data from its peers; it is risking it on a crash.

The second arm loses data silently: a MAP_PRIVATE write changed the writer’s view to 0x43 and left the file at 0x78, with msync returning in microseconds because there was nothing of the file to write. Private is copy-on-write: the first write takes a private copy of the page and everything after it is thrown away. The fourth arm shows a write inside the last page cannot make a file longer; extending needs ftruncate(). The fifth prices durability: after a byte per page of a 64 MiB mapping, msync(MS_SYNC) took 211.5 ms – about 303 MiB/s of dirty pages reaching the filesystem – against 0.06 ms for a single byte: the call is priced by dirty bytes, not mapping size.

7. The Window Is Fixed at the Call

A mapping’s length is decided once, by the call. Probe 09 maps a 1 MiB file, appends one page (4,096 bytes) from another descriptor, and asks the mapping for the first byte past its end.

QuestionThe mapping’s lengthWhat the file did nextWhat the mapping saw
A file grows after its mapping1,048,576 before and aftersize 1,052,672IndexError at the new offset; the old bytes read unchanged
An empty file is mappedValueErrornothing – the interpreter refused before the kernel saw the callcannot mmap an empty file
A length past the end of the file is asked forValueError, refused by the interpreternothingmmap length is greater than file size
Table 9: three ways a mapping meets a file whose length is not what the caller assumed. The last two rows never reach the kernel – the interpreter checks the size first.

The growth case wastes an afternoon: the mapping kept its length while the file grew a page past it, and reading at the old end raised IndexError rather than returning the new bytes. A reader that tails a growing file must remap or use pread(). The two refusals are worth knowing because they are not errnos: C’s mmap() accepts a length past the file and lets the caller meet SIGBUS on the first page past the end, while CPython compares the length with st_size and raises ValueError – a signal-shaped failure turned into an exception, as long as the caller opens the mapping through the interpreter.

The package classifies those failures in errors.py, printed in the appendix, and the classification is the whole recovery policy: an empty file, a length past the end, a missing path, a file that moved under a live mapping, the mapping limit and a permission problem are six different answers, and code that catches OSError and retries gets all six wrong at once. Note what is not in it: SIGBUS. A signal is not an exception, and no classifier turns it into one.

8. The Limit at Sixty-Five Thousand Mappings

The last limit is not bytes. Every mapping a process holds is a virtual memory area, and vm.max_map_count caps how many it may hold: 65,530 on this host. Probe 09 asks for 4,096-byte mappings in a child until the kernel refuses, five times, then asks the same child for an ordinary allocation. The child reads its own map file twice at each of three moments – before the loop, at the refusal, after the list is cleared – and prints every line that is not one of the loop’s own mappings in full, so the lines can be added up rather than guessed at. Each pair of reads returned the same count, so reading the file added no area of its own.

The refusal came at 65,482 mappings, with errno 12 (ENOMEM) in every run. The cap is on mappings, and the interpreter allocates through mappings, so the claim is worth stating as narrowly as it was measured: the one ordinary allocation the child tried next, 1,048,576 bytes of bytearray, raised MemoryError in all 5 runs. That is one allocation at the cap, not a statement that a process close to it can never allocate, and not a statement about how the room was spent.

The three moments are in table 10, and each row is the sum of its named parts. The child started with 44 lines, one of them [vsyscall], so it held 43 areas and no arenas. At the refusal the file shows 65,532 lines: the same 43 areas, 6 anonymous 1 MiB areas – the object allocator’s arenas, which the list holding the mappings needed – and the loop’s 65,482 mappings, each one a /dev/zero (deleted) line. Added up: 43 + 6 + 65,482 = 65,531 areas. After the clear the file is back to 45 lines: the same 43 areas and 1 arena that the allocator kept, so 5 of the six went back with the list.

Read of the map fileLinesThe loop’s mappings1 MiB arenasAreas the kernel counts
Before the loop440043
At the refusal65,53265,482665,531
After the list is cleared450144
Table 10: three moments in one child’s map file, every run alike. Each read printed 1 line for [vsyscall], which the kernel gives a reader of the map file from a pseudo area no process owns, so the last column is the first less that line: 44 – 1, 65,532 – 1, 45 – 1. The two columns between name what the areas went to.

Two named things explain why the refusal shows 65,532 lines for a cap of 65,530. The first is [vsyscall]: the kernel appends a pseudo area – a static VMA it hands to a reader of the map file, outside the process’s own count – so the file here is always one line longer than the areas. The second is the test itself: the kernel refuses a new area only when the count is already greater than the setting, so the last mapping that succeeded took the count to 65,531 – one above the cap – and the next call was the one that failed. Both are kernel rules quoted rather than measured here; the rows above are what ties them to this run, because with either rule otherwise the counts would not add up.

The subtraction a reader will do first is the misleading one: the cap minus the loop’s mappings is 48, and that is not the room the child had – the 43 areas it started with are mappings too, and the room was 65,488 (65,530 – 43 + 1). The run spent exactly that: 65,482 mappings from the loop and 6 arenas. A second child holding exactly 1,000 mappings read 1,044 lines from the same 44-line start, so the file moves one line per mapping and the baseline is the same from the other end.

Two operational notes. The limit is per process but set per system or container namespace, so a container with a lower vm.max_map_count changes what a program can do without changing a line of it. And the number to watch is the headroom – /proc/sys/vm/max_map_count minus the areas in the process’s map file, which is one line fewer than the file has – because the failure arrives as MemoryError from unrelated code.

9. O_DIRECT: Accepted, and Not Enforced

O_DIRECT is the flag a program opens a file with when it wants reads and writes to skip the page cache. The documented rule is that the buffer’s address, offset and length must all be multiples of the file system’s block size – 4,096 bytes on this mount, whose device reports 512-byte sectors – and breaking the rule expects EINVAL. Probe 10 tries four ways to break it and one that keeps to the rule, five times each.

Armopen()writeBytes writtenread backBytes read
block-aligned buffer, offset and lengthyesok4,096ok4,096
length of 1,000 bytesyesok1,000ok1,000
offset of 512 bytesyesok4,096ok4,096
a bytearray, address chosen by the allocator (alignment not recorded)yesok4,096ok4,096
length of one 512-byte sectoryesok512ok512
Table 11: 5 direct transfers, median of 5 runs each, on the virtiofs mount this page describes. Every arm answered identically in every run.

Every arm succeeded, including the bytearray whose address the allocator chose and the probe did not check, the one that asked for 1,000 bytes and the one that moved a single 512-byte sector: no EINVAL, and the bytes came back exactly as written. The bytearray arm is the weakest – it shows an allocator-placed buffer was accepted, not a misaligned address.

That is a property of this filesystem, not of O_DIRECT, and the limit belongs in the same sentence: the arms show the mount did not refuse a misaligned transfer, and none shows whether it went through the page cache. Reading it as “the cache is bypassed here” goes further than the evidence. Verify the flag on the mount the service uses – a misaligned buffer is the cheapest probe, because an enforcing filesystem refuses it – and treat the absence of an error as no evidence.

The same mount ignored POSIX_FADV_DONTNEED too: each arm that asked for this file’s pages to be dropped took the same major faults as its warm twin – 1 for the mapped arms, 0 for the read arms – so no arm here is a cold read. The two results are one warning from two syscalls: an advice or a flag the filesystem does not implement is not an error, and a program cannot tell by looking.

10. The Runbook: Five Decisions in Order

Everything above reduces to five decisions, and the first one decides the rest: what can happen to this file while the program is reading it.

1. If the file can be truncated or replaced, read it. A deploy that rewrites a file, a writer that regenerates a cache, a rotation that copies and then truncates – any of these can remove a page under a mapping, and the reader dies with SIGBUS: in section 5 the two such scenarios killed it in 5 of 5 runs each. A rotation that renames is safe, because a rename never touches the mapped inode. read() copied at 0.55 ms per MiB and cannot die that way; a guard narrows the window, it does not close it.

2. If the file is stable and large, map it, and guard every window anyway. A file whose length cannot change is the case a mapping fits: it reaches into the file without a copy, and Mapping.check() before each window costs one stat – 1.48 µs here. Guard per block rather than per page: a check at open time says nothing about the tenth read, and the view a check has passed can outlive it, which is why read() is the method wherever the bytes must survive the file. Table 12 prices that stat beside the reads it can precede.

3. Choose MAP_POPULATE to move latency, never to reduce it. The work was 24.2 ms inside the call instead of spread over the pass, and the total did not fall. That is useful at startup, when the first request must not pay for the first touch, and useless as a performance claim.

4. Read the resident split before chasing a leak. RssFile is page cache the kernel can take back; RssAnon is memory the process owns. In a memory-limited cgroup, call MADV_DONTNEED after a large pass – it returned 262,144 KiB here – rather than grow the limit, and do not page anyone on VmRSS alone: clean file pages are the first thing reclaim takes.

5. Count mappings, not bytes. The cap is 65,530 areas per process, and the run stopped at 65,482 with ENOMEM – after which the 1 MiB allocation the probe tried failed too. Reuse one mapping for many files, batch, or raise the limit deliberately; and watch the headroom rather than the count.

One guard is one stat: probe 11 timed it in 5 rounds of tens of thousands of calls, and the descriptor stat that skips the path lookup costs 0.77 µs. The reads beside it are the same 4 KiB: a copied slice of a live mapping at 0.14 µs, a pread of one hot page at 0.48 µs, and a pread that walks a file with a new page every call at 0.72 µs over 4 MiB and 1.02 µs over 128 MiB – 40% more, for the one reason the file’s size gives: 4 MiB stays in this CPU’s cache between rounds and 128 MiB cannot, so the larger file’s page is copied from memory. Walking all 32,768 pages of that file once per round came to 1.00 µs a page, with 0 page faults: once the page cache holds the file, walking all of it costs what walking its head does, and the 40% belongs to the CPU cache rather than to the length. What is left is table 5’s 2.58 µs page: that pass recorded 1.91 µs of system time and 0.49 of user time per page, and the same 32,768 calls cost 1.00 µs a page here, while its own five rounds spread 2.32 to 2.93. A per-page figure therefore belongs to the run behind it; the guard, in this run, is 10.8× the slice it protects and 2.0× the 4 MiB walk.

What one call costs (median of the rounds)µs per callWhat it is for
os.stat(path) – the guard Mapping.check() uses1.48 µs3.1× the offset-0 pread below, 10.8× the slice
os.fstat(fd) – the same check without the path lookup0.77 µsSlightly over half the price, for a caller that holds the descriptor
os.preadv(), 4 KiB of the same page at offset 00.48 µsA hot page: the cache hit and the page-table entry are already there
os.preadv(), 4 KiB walking a 4 MiB file, a page per call0.72 µsThe whole file stays in the CPU’s cache, so a later round finds the bytes there
os.preadv(), 4 KiB walking a 128 MiB file, its first 5,000 pages1.02 µsThe same call on a page the CPU’s cache cannot hold: copied from memory
os.preadv(), 4 KiB over all 32,768 pages of that file, a page per call1.00 µsThe shape of table 5’s block loop: no page twice, 0 major faults
A 4 KiB slice of a live mapping, copied0.14 µsThe window the guard protects, already mapped; a first touch would also fault
Table 12: one call’s price, median of 5 rounds of 20,000, 5,000 or 32,768 calls. The offset-0 pread repeats one hot page; the walking preads cross a 4 MiB file, the first 5,000 pages of a 128 MiB file, and then all 32,768 pages of it. The block loop of table 5 has the shape of the last one.

The limits module below is the arithmetic behind the last decision: the cap, the count this process holds and the room left. The count skips the [vsyscall] line the map file prints, and the room leaves space for the one mapping that may take the count past the cap. The package’s other parts are above and in the appendix; the tests import them, while the probes that produced these tables are standalone scripts.

"""The limit that ends a program's mappings, and how close the process already is to it.

Every mapping a process holds is a VMA in the kernel, and vm.max_map_count caps how many it may
have. The count is not a memory limit: a process at the cap cannot map a 4 KiB file, and an
allocation the interpreter needs a new arena for fails, because its arenas are mappings too.
Reading the limit next to the current count is the difference between a diagnosis and a guess.

Two details decide whether that reading is exact. The map file has one line the kernel prints
from a pseudo area that no process owns - ``[vsyscall]`` - so counting lines overstates the count
by one. And the kernel refuses a new area only when the count is already above the cap, so a
process at the cap may still create one more mapping.
"""

from __future__ import annotations
import os
import pathlib

LIMIT_PATH = pathlib.Path("/proc/sys/vm/max_map_count")
PSEUDO = "[vsyscall]"


def max_map_count(path: pathlib.Path | str = LIMIT_PATH) -> int:
    """The kernel's cap on mappings per process."""
    return int(pathlib.Path(path).read_text(encoding="utf-8").strip())


def mapping_count(pid: int | None = None, path: pathlib.Path | str | None = None) -> int:
    """How many mappings one process holds now: this one, or the one a map file names."""
    if path is None:
        target = os.getpid() if pid is None else pid
        path = f"/proc/{target}/maps"
    body = pathlib.Path(path).read_text(encoding="utf-8")
    return len([line for line in body.splitlines()
                if line.strip() and not line.rstrip().endswith(PSEUDO)])


def headroom(pid: int | None = None) -> int:
    """How many more mappings this process may create before the next call fails."""
    return max_map_count() - mapping_count(pid) + 1

Frequently asked questions

Is mmap faster than read()?

On a cached file the read took 13.0% more per MiB when every byte was hashed through both calls: 1.10 against 1.25 ms on the same 128 MiB file, median of 5 repeats whose per-repeat gap ran 5.7% to 69.6%. That is the copy it does not make, and it is small. An arm that touches one byte per page measures the fault, not the read. Choose by what you have to do with the bytes.

Why does my program die with Bus error when a log rotates?

Because it reads a mapping of a file that lost pages underneath it – with logrotate that means its copytruncate option, while the default rename leaves the mapped inode alone. The two scenarios that removed mapped pages raised SIGBUS in 5 of 5 runs each, on the touch rather than on the truncate. Read the file instead, or guard each window with a stat and treat a shorter file as the end of the mapping.

Why is RSS as large as the file I mapped, and is it a leak?

It is RssFile – page cache charged to the process because the process mapped it. The 256 MiB mapping added 262,144 KiB of it and no anonymous memory, and MADV_DONTNEED returned all of it while the mapping stayed open. It is a leak only if RssAnon grows, and most containers reclaim it before they would kill anything.

Does a write through mmap reach the file without msync?

It reaches the page cache immediately, so another process on the same host reads it at once – the reader in table 8 saw the byte before any msync. It reaches the filesystem only when the kernel writes the page back, which msync(MS_SYNC) forces: 211.5 ms for a dirty 64 MiB mapping, priced by dirty bytes rather than by map size.

Why did mmap fail with ENOMEM when there is plenty of free memory?

Because the limit is mappings, not bytes: the run stopped at 65,482 against a cap of 65,530, and the next allocation the probe tried, 1,048,576 bytes of bytearray, failed too. Each mapping is a VMA, and the interpreter allocates through mappings. Reuse mappings and check the headroom before blaming memory.

Is O_DIRECT a way to bypass the page cache?

Not on every filesystem. On the mount this page measured the flag was accepted and not enforced: all 5 arms – including a buffer the allocator placed and a 1,000-byte length – transferred without EINVAL. That says the mount did not refuse the transfers; it does not show the cache was bypassed. Verify on the mount the service uses.

TechBobby Engineering writes runbooks from measured failures: every measured number here 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 every number above can be checked against the code that produced it. Every fold is a character-for-character copy of its file.

Folder structure

Each file below is printed in full under its own fold; the tree names them in run order.

post36/
  sandbox/       probe.py  01_facts.py  02_faults.py  03_cache.py  04_cost.py
                 05_sigbus.py  06_write.py  07_rss.py  08_tests.py  09_limits.py
                 10_direct.py  11_statcost.py
  module/
    filemap/     __init__.py  errors.py  limits.py  mapping.py  procstat.py
                 reader.py
      tests/     conftest.py  test_errors.py  test_limits.py  test_mapping.py
                 test_procstat.py  test_reader.py
  results/       one JSON per probe, written by it

Run order

The probes need only the standard library, except 08_tests.py, which needs pytest, and 10_direct.py, which needs a filesystem that accepts O_DIRECT – on this host the flag is accepted and ignored.

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

$ cd sandbox
$ python3 01_facts.py            # host, mount, page size, the two limits
$ python3 02_faults.py           # tables 3 and 4
$ python3 03_cache.py            # the warm arms, and the DONTNEED that evicted nothing
$ python3 04_cost.py             # table 5
$ python3 05_sigbus.py           # table 7, and the handler the fault never reaches
$ python3 06_write.py            # table 8
$ python3 07_rss.py              # table 6
$ python3 08_tests.py            # pytest's own summary, and the line counts
$ python3 09_limits.py           # tables 9 and 10, and the mapping limit
$ python3 10_direct.py           # table 11
$ python3 11_statcost.py         # table 12

$ cd ../module && python3 -m pytest filemap/tests -q
A scratch file, five repeats, the fault counters and the resident split. probe.py
"""Shared parts of the probes: a scratch file, fault counters, and one JSON.

Every probe writes what it observed, not what it expected. Each one runs a measurement five times
and keeps every observation, so a figure in the article is a median with its range rather than a
first run that happened to be quick. ``faults`` reads the two counters the kernel keeps per
process, and ``rss`` reads the resident-set split, so a claim about page faults or memory is read
from /proc rather than inferred from a clock.
"""
from __future__ import annotations

import json
import pathlib
import shutil
import statistics
import subprocess
import sys

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


def work_dir(name: str, size_mib: int = 0, fill: bytes = b"x") -> pathlib.Path:
    """An empty directory for one probe, on the filesystem the article describes."""
    path = HERE.parent / "scratch" / name
    if path.exists():
        shutil.rmtree(path)
    path.mkdir(parents=True)
    if size_mib:
        with open(path / "data.bin", "wb") as handle:
            block = fill * (1024 * 1024)
            for _ in range(size_mib):
                handle.write(block)
    return path


def save(number: str, name: str, payload: dict) -> pathlib.Path:
    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 summary(values: list[float]) -> dict:
    return {"min": round(min(values), 3), "median": round(statistics.median(values), 3),
            "max": round(max(values), 3)}


def faults() -> dict:
    """Minor and major faults, in the order the kernel counts them."""
    stat = pathlib.Path("/proc/self/stat").read_text(encoding="utf-8")
    fields = stat.rsplit(")", 1)[1].split()
    # After the comm field: state is fields[0], minflt is field 10 of the line (index 7)
    # and majflt field 12 (index 9); the next field is the children's minor faults.
    return {"minor": int(fields[7]), "major": int(fields[9])}


def rss() -> dict:
    """The resident-set split: anonymous pages against file-backed ones."""
    out: dict[str, int] = {}
    for line in pathlib.Path("/proc/self/status").read_text(encoding="utf-8").splitlines():
        key, _, value = line.partition(":")
        if key in ("VmRSS", "RssAnon", "RssFile", "RssShmem"):
            out[key] = int(value.split()[0])
    return out


def counter(before: dict, after: dict) -> dict:
    return {key: after[key] - before[key] for key in before}


def child(code: str, *args: str, timeout: int = 120) -> subprocess.CompletedProcess:
    """Run a snippet in a fresh interpreter, so a signal kills the snippet and not the probe."""
    return subprocess.run([sys.executable, "-c", code, *args], capture_output=True, text=True,
                          timeout=timeout)
Host, mount, clock, an empty file and a length past the end. 01_facts.py
"""Probe 01: the host, the mount, the clock, and the two limits this page measures.

The mount is found by longest prefix in /proc/mounts, so the page can name the filesystem its
numbers came from instead of assuming one. The empty-file and length-beyond-EOF arms are run
here because they answer one question between them: what the mapping call itself refuses.
"""
from __future__ import annotations

import errno
import mmap
import os
import pathlib
import platform
import sys
import time

import probe


def mount_of(path: pathlib.Path) -> tuple[str, str]:
    """The filesystem type and mount point that actually carry ``path``."""
    target = str(path.resolve())
    best = ("", "")
    for line in pathlib.Path("/proc/mounts").read_text(encoding="utf-8").splitlines():
        parts = line.split()
        if len(parts) < 3:
            continue
        mount_point = parts[1].replace("\\040", " ")
        if target == mount_point or target.startswith(mount_point.rstrip("/") + "/"):
            if len(mount_point) >= len(best[1]):
                best = (parts[2], mount_point)
    return best


def empty_file() -> dict:
    """What mmap() does with a zero-byte file, on this interpreter."""
    folder = probe.work_dir("facts")
    path = folder / "empty.bin"
    path.write_bytes(b"")
    fd = os.open(path, os.O_RDONLY)
    try:
        try:
            mmap.mmap(fd, 0, prot=mmap.PROT_READ)
        except ValueError as exc:
            return {"kind": "ValueError", "message": str(exc)}
        except OSError as exc:
            return {"kind": "OSError", "number": exc.errno,
                    "name": errno.errorcode.get(exc.errno, "?")}
        return {"kind": "accepted", "message": ""}
    finally:
        os.close(fd)


def length_beyond_eof() -> dict:
    """A mapping longer than its file: the call decides, and the tail decides later."""
    folder = probe.work_dir("facts-length")
    path = folder / "one-page.bin"
    path.write_bytes(b"a" * mmap.PAGESIZE)
    fd = os.open(path, os.O_RDONLY)
    try:
        try:
            handle = mmap.mmap(fd, mmap.PAGESIZE * 2, prot=mmap.PROT_READ)
        except ValueError as exc:
            # The interpreter compares the length with the file's size before it calls the
            # kernel, so this refusal is Python's, not the syscall's, and the page says so.
            return {"accepted": False, "number": 0, "name": "ValueError",
                    "message": str(exc), "refused_by": "interpreter"}
        except OSError as exc:
            return {"accepted": False, "number": exc.errno,
                    "name": errno.errorcode.get(exc.errno, "?"), "refused_by": "kernel"}
        try:
            return {"accepted": True, "length": len(handle), "number": 0,
                    "name": "accepted", "refused_by": "none"}
        finally:
            handle.close()
    finally:
        os.close(fd)


def main() -> None:
    folder = probe.work_dir("facts-mount")
    fs_type, mount_point = mount_of(folder / "x")
    clock = time.clock_getres(time.CLOCK_MONOTONIC)
    payload = {
        "facts": {
            "kernel": platform.release(),
            "machine": platform.machine(),
            "python": sys.version.split()[0],
            "cpu_count": os.cpu_count(),
            "uid": os.getuid(),
            "page_size": mmap.PAGESIZE,
            "allocation_granularity": mmap.ALLOCATIONGRANULARITY,
            "address_bits": 64 if sys.maxsize > 2 ** 32 else 32,
            "fs_type": fs_type,
            "mount_point": mount_point,
            "clock_resolution_s": clock,
            "max_map_count": int(pathlib.Path("/proc/sys/vm/max_map_count")
                                 .read_text().strip()),
            "overcommit_memory": int(pathlib.Path("/proc/sys/vm/overcommit_memory")
                                     .read_text().strip()),
            "maps_baseline": len(pathlib.Path("/proc/self/maps").read_text().splitlines()),
            "empty_mmap": empty_file(),
            "length_beyond_eof": length_beyond_eof(),
        }
    }
    print(payload["facts"])
    probe.save("01", "facts", payload)


if __name__ == "__main__":
    main()
Eight arms over 64 MiB: a walk, a copy and a hash, in both orders. 02_faults.py
"""Probe 02: what one pass over a 64 MiB file costs, mapped and copied eight ways.

The mapping call and the first pass are timed apart, because one of the arms does all its work
inside the call: MAP_POPULATE fills the page tables before mmap() returns, so a timer that starts
afterwards credits the pass with work it did not do.

Two of the arms exist to keep the comparison honest. The four walk arms touch one byte per page,
which is enough to fault a page in and nothing else, while both read() arms copy the whole file;
the last two arms therefore hash every byte through each call, so the same bytes cross the same
kind of boundary and the only difference left is the one the table is about. Before any arm is
timed, every arm runs once untimed and the file is read front to back, and each of the five
repeats runs the arms in a different recorded order, so no arm owns the first position.
"""
from __future__ import annotations

import hashlib
import mmap
import os
import random
import time

import probe

SIZE_MIB = 64
WARMUPS = 1
ARMS = [
    (0, "mmap, one byte per page, no advice", "walk", None),
    (1, "mmap with MAP_POPULATE", "walk", "populate"),
    (2, "mmap, MADV_SEQUENTIAL before the pass", "walk", "sequential"),
    (3, "mmap, MADV_WILLNEED before the pass", "walk", "willneed"),
    (4, "read() into one 1 MiB buffer", "copy", 1 << 20),
    (5, "read() into one 64 KiB buffer", "copy", 64 << 10),
    (6, "mmap, every byte hashed", "hash_map", None),
    (7, "read() into one 1 MiB buffer, every byte hashed", "hash_read", 1 << 20),
]


def walk_mapped(path, advice: str | None) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        flags = mmap.MAP_SHARED | (mmap.MAP_POPULATE if advice == "populate" else 0)
        started = time.perf_counter()
        handle = mmap.mmap(fd, 0, flags=flags, prot=mmap.PROT_READ)
        mapped = time.perf_counter()
        if advice in ("sequential", "willneed"):
            handle.madvise(mmap.MADV_SEQUENTIAL if advice == "sequential"
                           else mmap.MADV_WILLNEED)
        advised = time.perf_counter()
        total = 0
        for offset in range(0, len(handle), mmap.PAGESIZE):
            total += handle[offset]
        touched = time.perf_counter()
        result = {"call_ms": (mapped - started) * 1000,
                  "advice_ms": (advised - mapped) * 1000,
                  "pass_ms": (touched - advised) * 1000,
                  "total_ms": (touched - started) * 1000,
                  "bytes": len(handle), "checksum": total,
                  "rss_while_mapped": probe.rss()}
        handle.close()
        return result
    finally:
        os.close(fd)


def copy_read(path, block: int, digest: bool = False) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        buffer = bytearray(block)
        view = memoryview(buffer)
        total = 0
        sink = hashlib.sha256() if digest else None
        started = time.perf_counter()
        while True:
            size = os.readv(fd, [view])
            if not size:
                break
            total += size
            if sink is not None:
                sink.update(view[:size])
        finished = time.perf_counter()
        return {"call_ms": 0.0, "advice_ms": 0.0, "pass_ms": (finished - started) * 1000,
                "total_ms": (finished - started) * 1000, "bytes": total,
                "checksum": 0, "digest": sink.hexdigest() if sink else "",
                "rss_while_mapped": probe.rss()}
    finally:
        os.close(fd)


def hash_mapped(path) -> dict:
    """Every byte of the file, read through the mapping and hashed in C."""
    fd = os.open(path, os.O_RDONLY)
    try:
        started = time.perf_counter()
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        mapped = time.perf_counter()
        sink = hashlib.sha256(handle)
        hashed = time.perf_counter()
        result = {"call_ms": (mapped - started) * 1000, "advice_ms": 0.0,
                  "pass_ms": (hashed - mapped) * 1000, "total_ms": (hashed - started) * 1000,
                  "bytes": len(handle), "checksum": 0, "digest": sink.hexdigest(),
                  "rss_while_mapped": probe.rss()}
        handle.close()
        return result
    finally:
        os.close(fd)


def run_arm(path, kind: str, setting) -> dict:
    if kind == "walk":
        return walk_mapped(path, setting)
    if kind == "hash_map":
        return hash_mapped(path)
    return copy_read(path, setting, digest=(kind == "hash_read"))


def order_for(repeat: int) -> list[int]:
    """A recorded order per repeat: no arm keeps one position, and arm 0 rarely leads."""
    base = [arm[0] for arm in ARMS]
    shuffled = list(base)
    random.Random(36 + repeat).shuffle(shuffled)
    return shuffled


def warm_up(path) -> float:
    """One untimed pass over the file, front to back, before anything is measured."""
    started = time.perf_counter()
    with open(path, "rb") as handle:
        while handle.read(1 << 20):
            pass
    for _, _, kind, setting in ARMS:
        run_arm(path, kind, setting)
    return (time.perf_counter() - started) * 1000


def measure(path, orders: list[list[int]]) -> tuple[dict[int, list[dict]], dict[int, list[int]]]:
    """Run every order once per repeat and return each arm's runs and its positions."""
    runs: dict[int, list[dict]] = {arm[0]: [] for arm in ARMS}
    positions: dict[int, list[int]] = {arm[0]: [] for arm in ARMS}
    by_index = {arm[0]: arm for arm in ARMS}
    for order in orders:
        for position, index in enumerate(order, start=1):
            _, _, kind, setting = by_index[index]
            before_faults = probe.faults()
            before_rss = probe.rss()
            result = run_arm(path, kind, setting)
            after_faults = probe.faults()
            result["minor"] = after_faults["minor"] - before_faults["minor"]
            result["major"] = after_faults["major"] - before_faults["major"]
            result["rss"] = probe.counter(before_rss, result["rss_while_mapped"])
            result["position"] = position
            runs[index].append(result)
            positions[index].append(position)
    return runs, positions


def records_of(runs: dict[int, list[dict]], positions: dict[int, list[int]]) -> list[dict]:
    records = []
    for index, label, kind, setting in ARMS:
        arm_runs = runs[index]
        record = {
            "index": index, "label": label, "kind": kind,
            "call_ms": probe.summary([run["call_ms"] for run in arm_runs]),
            "advice_ms": probe.summary([run["advice_ms"] for run in arm_runs]),
            "pass_ms": probe.summary([run["pass_ms"] for run in arm_runs]),
            "total_ms": probe.summary([run["total_ms"] for run in arm_runs]),
            "minor": probe.summary([run["minor"] for run in arm_runs]),
            "major": probe.summary([run["major"] for run in arm_runs]),
            "rss_kib": probe.summary([run["rss"]["VmRSS"] for run in arm_runs]),
            "rss_file_kib": probe.summary([run["rss"]["RssFile"] for run in arm_runs]),
            "rss_anon_kib": probe.summary([run["rss"]["RssAnon"] for run in arm_runs]),
            "positions": positions[index],
            "digest": arm_runs[0].get("digest", ""),
            "runs": arm_runs,
        }
        records.append(record)
    return records


def main() -> None:
    folder = probe.work_dir("faults", SIZE_MIB)
    path = folder / "data.bin"
    size = path.stat().st_size
    warm_ms = warm_up(path)
    print(f"warm-up {WARMUPS} pass(es) plus one of every arm: {warm_ms:.1f} ms")

    fixed = [[arm[0] for arm in ARMS] for _ in range(probe.REPEATS)]
    fixed_runs, fixed_positions = measure(path, fixed)
    fixed_records = records_of(fixed_runs, fixed_positions)
    print("fixed order:")
    for record in fixed_records:
        print(f"  {record['index']} {record['label']:48s} total "
              f"{record['total_ms']['median']:8.1f} ms positions {record['positions']}")

    orders = [order_for(repeat) for repeat in range(probe.REPEATS)]
    for repeat, order in enumerate(orders, start=1):
        print(f"repeat {repeat} order {order}")
    runs, positions = measure(path, orders)
    records = records_of(runs, positions)
    for record in records:
        print(f"{record['index']} {record['label']:48s} total "
              f"{record['total_ms']['median']:8.1f} ms "
              f"(min {record['total_ms']['min']:7.1f} max {record['total_ms']['max']:7.1f}) "
              f"minor {record['minor']['median']:6.0f} major {record['major']['median']:3.0f} "
              f"positions {record['positions']}")

    digests = {record["digest"] for record in records if record["digest"]}
    payload = {
        "repeats": probe.REPEATS,
        "warmups": WARMUPS,
        "warmup_ms": round(warm_ms, 3),
        "orders": orders,
        "fixed_order": fixed,
        "size_bytes": size,
        "size_mib": SIZE_MIB,
        "page_size": mmap.PAGESIZE,
        "arms": records,
        "fixed_order_arms": fixed_records,
        "read_arms": [record["index"] for record in records if record["kind"] == "copy"],
        "map_arms": [record["index"] for record in records
                     if record["kind"] in ("walk", "hash_map")],
        "digests_identical": len(digests) == 1,
        "digest": digests.pop() if len(digests) == 1 else "",
    }
    probe.save("02", "faults", payload)


if __name__ == "__main__":
    main()
Warm and asked-to-be-cold arms, and the major faults each took. 03_cache.py
"""Probe 03: the same pass with the file in cache and with it dropped.

POSIX_FADV_DONTNEED asks the kernel to drop the clean pages of this file, which is the one
supported way for an unprivileged process to make its own read cold. Whether it worked is not
assumed: every arm records the major faults it took, and a cold arm that took none would be an
arm that never left the cache.
"""
from __future__ import annotations

import mmap
import os
import time

import probe

SIZE_MIB = 64
ARMS = [
    (0, "warm: mmap pass", "mmap", None, False),
    (1, "cold: mmap pass after POSIX_FADV_DONTNEED", "mmap", None, True),
    (2, "warm: read() into 1 MiB", "read", 1 << 20, False),
    (3, "cold: read() into 1 MiB after POSIX_FADV_DONTNEED", "read", 1 << 20, True),
    (4, "cold: mmap, MADV_WILLNEED, then the pass", "mmap", "willneed", True),
]


def drop_cache(fd: int) -> None:
    os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)


def pass_mapped(path, advice: str | None, cold: bool) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        if cold:
            drop_cache(fd)
        started = time.perf_counter()
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        mapped = time.perf_counter()
        if advice:
            handle.madvise(mmap.MADV_WILLNEED)
        advised = time.perf_counter()
        total = 0
        for offset in range(0, len(handle), mmap.PAGESIZE):
            total += handle[offset]
        touched = time.perf_counter()
        result = {"call_ms": (mapped - started) * 1000,
                  "advice_ms": (advised - mapped) * 1000,
                  "pass_ms": (touched - advised) * 1000,
                  "total_ms": (touched - started) * 1000,
                  "bytes": len(handle), "checksum": total}
        handle.close()
        return result
    finally:
        os.close(fd)


def pass_read(path, block: int, cold: bool) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        if cold:
            drop_cache(fd)
        buffer = bytearray(block)
        view = memoryview(buffer)
        total = 0
        started = time.perf_counter()
        while True:
            size = os.readv(fd, [view])
            if not size:
                break
            total += size
        finished = time.perf_counter()
        return {"call_ms": 0.0, "advice_ms": 0.0, "pass_ms": (finished - started) * 1000,
                "total_ms": (finished - started) * 1000, "bytes": total, "checksum": 0}
    finally:
        os.close(fd)


def main() -> None:
    folder = probe.work_dir("cache", SIZE_MIB)
    path = folder / "data.bin"
    records = []
    # A warm arm first, so the cold arms start from a cache this probe itself filled.
    with open(path, "rb") as handle:
        while handle.read(1 << 20):
            pass
    for index, label, kind, advice_or_block, cold in ARMS:
        runs = []
        for _ in range(probe.REPEATS):
            before = probe.faults()
            result = (pass_mapped(path, advice_or_block, cold) if kind == "mmap"
                      else pass_read(path, advice_or_block, cold))
            after = probe.faults()
            result["minor"] = after["minor"] - before["minor"]
            result["major"] = after["major"] - before["major"]
            runs.append(result)
        record = {
            "index": index, "label": label, "kind": kind, "cold": cold,
            "call_ms": probe.summary([run["call_ms"] for run in runs]),
            "advice_ms": probe.summary([run["advice_ms"] for run in runs]),
            "pass_ms": probe.summary([run["pass_ms"] for run in runs]),
            "total_ms": probe.summary([run["total_ms"] for run in runs]),
            "minor": probe.summary([run["minor"] for run in runs]),
            "major": probe.summary([run["major"] for run in runs]),
            "runs": runs,
        }
        records.append(record)
        print(f"{index} {label:48s} total {record['total_ms']['median']:8.1f} ms "
              f"major {record['major']['median']:5.0f}")

    payload = {
        "repeats": probe.REPEATS,
        "size_bytes": path.stat().st_size,
        "size_mib": SIZE_MIB,
        "arms": records,
        "warm_arms": [record["index"] for record in records if not record["cold"]],
        "cold_arms": [record["index"] for record in records if record["cold"]],
    }
    probe.save("03", "cache", payload)


if __name__ == "__main__":
    main()
128 MiB five ways: a walk, two copies and two hashes, timed by arm. 04_cost.py
"""Probe 04: the same 128 MiB pass, timed five ways and split into user and kernel time.

A wall clock cannot say who did the work. The copy a read() makes happens in the kernel, on a
buffer the caller owns; a fault is also kernel work, but it happens once per sixteen pages and
then leaves the bytes where the file put them. So each arm records the process's own user and
system time, which is the difference the wall clock hides.

Two arms touch one byte per page and two hash every byte, because those measure different things:
the first pair prices the fault, the second pair prices moving the bytes. A comparison that pairs
a walk against a copy would charge the mapping with work it never did.
"""
from __future__ import annotations

import hashlib
import mmap
import os
import random
import resource
import time

import probe

SIZE_MIB = 128
ARMS = [
    (0, "mmap, one byte per page", "walk", 0),
    (1, "read() into one 1 MiB buffer", "copy", 1 << 20),
    (2, "read() into one 4 KiB buffer", "copy", 4 << 10),
    (3, "mmap, every byte hashed", "hash_map", 0),
    (4, "read() into one 1 MiB buffer, every byte hashed", "hash_read", 1 << 20),
]


def times() -> dict:
    usage = resource.getrusage(resource.RUSAGE_SELF)
    return {"user_s": usage.ru_utime, "system_s": usage.ru_stime}


def pass_walk(path) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        total = 0
        started = time.perf_counter()
        for offset in range(0, len(handle), mmap.PAGESIZE):
            total += handle[offset]
        finished = time.perf_counter()
        length = len(handle)
        handle.close()
        return {"wall_ms": (finished - started) * 1000, "bytes": length, "checksum": total,
                "digest": ""}
    finally:
        os.close(fd)


def pass_hash_map(path) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        started = time.perf_counter()
        sink = hashlib.sha256(handle)
        finished = time.perf_counter()
        length = len(handle)
        digest = sink.hexdigest()
        handle.close()
        return {"wall_ms": (finished - started) * 1000, "bytes": length, "checksum": 0,
                "digest": digest}
    finally:
        os.close(fd)


def pass_copy(path, block: int, digest: bool = False) -> dict:
    fd = os.open(path, os.O_RDONLY)
    try:
        buffer = bytearray(block)
        view = memoryview(buffer)
        total = 0
        sink = hashlib.sha256() if digest else None
        started = time.perf_counter()
        while True:
            size = os.readv(fd, [view])
            if not size:
                break
            total += size
            if sink is not None:
                sink.update(view[:size])
        finished = time.perf_counter()
        return {"wall_ms": (finished - started) * 1000, "bytes": total, "checksum": 0,
                "digest": sink.hexdigest() if sink else ""}
    finally:
        os.close(fd)


def run(path, kind: str, block: int) -> dict:
    if kind == "walk":
        return pass_walk(path)
    if kind == "hash_map":
        return pass_hash_map(path)
    return pass_copy(path, block, digest=(kind == "hash_read"))


def main() -> None:
    folder = probe.work_dir("cost", SIZE_MIB)
    path = folder / "data.bin"
    for _, _, kind, block in ARMS:                 # one untimed pass of every arm
        run(path, kind, block)
    orders = []
    for repeat in range(probe.REPEATS):
        order = [arm[0] for arm in ARMS]
        random.Random(64 + repeat).shuffle(order)
        orders.append(order)
    by_index = {arm[0]: arm for arm in ARMS}
    runs_by_arm: dict[int, list[dict]] = {arm[0]: [] for arm in ARMS}
    for repeat, order in enumerate(orders, start=1):
        print(f"repeat {repeat} order {order}")
        for position, index in enumerate(order, start=1):
            _, _, kind, block = by_index[index]
            before_faults = probe.faults()
            before_time = times()
            result = run(path, kind, block)
            after_time = times()
            after_faults = probe.faults()
            result["user_ms"] = (after_time["user_s"] - before_time["user_s"]) * 1000
            result["system_ms"] = (after_time["system_s"] - before_time["system_s"]) * 1000
            result["minor"] = after_faults["minor"] - before_faults["minor"]
            result["major"] = after_faults["major"] - before_faults["major"]
            result["position"] = position
            runs_by_arm[index].append(result)
    records = []
    for index, label, kind, block in ARMS:
        runs = runs_by_arm[index]
        record = {
            "index": index, "label": label, "kind": kind,
            "wall_ms": probe.summary([run["wall_ms"] for run in runs]),
            "user_ms": probe.summary([run["user_ms"] for run in runs]),
            "system_ms": probe.summary([run["system_ms"] for run in runs]),
            "minor": probe.summary([run["minor"] for run in runs]),
            "major": probe.summary([run["major"] for run in runs]),
            "bytes": runs[0]["bytes"],
            "digest": runs[0]["digest"],
            "positions": [run["position"] for run in runs],
            "runs": runs,
        }
        records.append(record)
        print(f"{index} {label:46s} wall {record['wall_ms']['median']:8.1f} ms "
              f"user {record['user_ms']['median']:7.1f} sys {record['system_ms']['median']:7.1f}")

    digests = {record["digest"] for record in records if record["digest"]}
    payload = {
        "repeats": probe.REPEATS,
        "size_bytes": path.stat().st_size,
        "size_mib": SIZE_MIB,
        "orders": orders,
        "arms": records,
        "checksums_identical": len({run["checksum"] for record in records
                                    if record["kind"] == "walk"
                                    for run in record["runs"]}) == 1,
        "digests_identical": len(digests) == 1,
        "digest": digests.pop() if len(digests) == 1 else "",
    }
    probe.save("04", "cost", payload)


if __name__ == "__main__":
    main()
Six changes under a live mapping, each in its own interpreter, and the same truncate under a Python handler. 05_sigbus.py
"""Probe 05: what happens to a live mapping when the file underneath it changes.

A signal cannot be caught and continued, so each arm runs in its own interpreter: the child maps
eight pages, the file is truncated, unlinked or replaced, and the child touches one offset. Its
exit status is the answer - a negative return code is the signal that ended it - and the same arm
is run five times so a signal that arrived once cannot pass for a rule.

Two more sets of children ask what the fault does with a handler installed. The first installs a
Python callable and is given a deadline: the handler is never entered, and the child spins until
the probe kills it. The second installs a handler written as machine code - this host has no
compiler - that increments a counter in a shared page and returns, so the number of times the
kernel hands the same instruction its SIGBUS can be counted from outside the loop while it runs.
"""
from __future__ import annotations

import ctypes
import os
import pathlib
import shutil
import signal
import struct
import subprocess
import sys
import time

import probe

PAGES = 8
# How long a child is given before the probe kills it: long enough for a handler to run, short
# enough that a fault that never reaches one is measured in seconds rather than waited out.
DEADLINE_S = 2.0
# How long the counting child is left to reach its fault, and how long its counter is watched.
SETTLE_S = 0.3
WINDOW_S = 1.0
COUNTER_BYTES = 4096

# Kept as one string so the page can print the exact code the children ran.
SCRIPT = """
import mmap
import os
import sys

path, action, offset = sys.argv[1], sys.argv[2], int(sys.argv[3])
fd = os.open(path, os.O_RDONLY)
handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
length = len(handle)
if action.startswith("truncate:"):
    os.truncate(path, int(action.split(":", 1)[1]))
elif action == "unlink":
    os.unlink(path)
elif action.startswith("rename:"):
    os.replace(action.split(":", 1)[1], path)
print("mapped", length, "now", os.fstat(fd).st_size, flush=True)
print("byte", offset, handle[offset], flush=True)
"""

ARMS = [
    (0, "truncated to zero, first page touched", "truncate:0", 0),
    (1, "truncated to one page, a page past it touched", "truncate:4096", 4 * 4096),
    (2, "truncated to 4,100 bytes, a byte inside page 0 touched", "truncate:4100", 100),
    (3, "truncated to 4,100 bytes, a byte past 4,100 in the last partial page touched",
     "truncate:4100", 4096 + 99),
    (4, "file unlinked, a byte inside the mapping touched", "unlink", 100),
    (5, "another file renamed over the path, the first byte touched", "rename", 0),
]

# The same mapping with a Python handler installed in the child. Kept as one string so the page
# can print the exact code the children ran.
SIGNAL_SCRIPT = """
import mmap
import os
import signal
import sys

path, mode, log = sys.argv[1], sys.argv[2], sys.argv[3]
seen = 0


def handler(signum, frame):
    global seen
    seen += 1
    with open(log, "a", encoding="utf-8") as out:
        out.write("call %d\\n" % seen)


signal.signal(signal.SIGBUS, handler)
fd = os.open(path, os.O_RDONLY)
handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
if mode == "sent":
    os.kill(os.getpid(), signal.SIGBUS)
    for _ in range(10000):
        pass
    print("survived", seen, flush=True)
elif mode == "truncated":
    os.truncate(path, 0)
    print("before", seen, flush=True)
    print("read", handle[0], "calls", seen, flush=True)
elif mode == "tail":
    os.truncate(path, 4100)
    print("before", seen, flush=True)
    print("read", handle[4096 + 99], "calls", seen, flush=True)
"""

SIGNAL_ARMS = [
    (0, "sent", "a SIGBUS the child sends itself with os.kill()"),
    (1, "truncated", "truncated to zero, first page touched, handler installed"),
    (2, "tail", "truncated to 4,100 bytes, a byte in the last partial page, handler installed"),
]

# The same fault with a handler that can return without the interpreter: the counter lives in a
# shared page, and the handler is three instructions assembled by hand, because no C compiler is
# installed on this host. Kept as one string so the page can print the exact code the children ran.
COUNTER_SCRIPT = """
import ctypes
import mmap
import os
import signal
import struct
import sys

path, counter, mode = sys.argv[1], sys.argv[2], sys.argv[3]
libc = ctypes.CDLL("libc.so.6", use_errno=True)

descriptor = os.open(counter, os.O_RDWR)
page = mmap.mmap(descriptor, 4096, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE)
address = ctypes.addressof(ctypes.c_char.from_buffer(page))

# mov rax, <counter address>; inc qword [rax]; ret
code = b"\\x48\\xb8" + struct.pack("<Q", address) + b"\\x48\\xff\\x00\\xc3"
trampoline = mmap.mmap(-1, 4096, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
trampoline.write(code)
handler = ctypes.addressof(ctypes.c_char.from_buffer(trampoline))
if libc.signal(signal.SIGBUS, ctypes.c_void_p(handler)) == ctypes.c_void_p(-1).value:
    print("signal", ctypes.get_errno(), flush=True)
    raise SystemExit(3)

fd = os.open(path, os.O_RDONLY)
handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
if mode == "sent":
    os.kill(os.getpid(), signal.SIGBUS)
    print("survived", struct.unpack("<Q", page[:8])[0], flush=True)
elif mode == "truncated":
    os.truncate(path, 0)
    print("before", flush=True)
    print("touch", handle[0], flush=True)
else:
    os.truncate(path, 4100)
    print("before", flush=True)
    print("touch", handle[4096 + 99], flush=True)
"""

DELIVERY_ARMS = [
    (0, "sent", "a SIGBUS the child sends itself, handler in machine code"),
    (1, "truncated", "truncated to zero, first page touched, handler in machine code"),
    (2, "tail", "truncated to 4,100 bytes, a byte in the last partial page, handler in machine code"),
]


def prepare(folder: pathlib.Path, index: int, run: int, action: str) -> tuple[pathlib.Path, str]:
    path = folder / f"arm{index}-{run}.bin"
    path.write_bytes(b"a" * (PAGES * 4096))
    other = folder / f"arm{index}-{run}.other"
    other.write_bytes(b"b" * (PAGES * 4096))
    return path, action if not action.startswith("rename:") else f"rename:{other}"


def cpu_of(pid: int) -> tuple[str, float]:
    """The child's state and the CPU time it has burned, from /proc while it is still alive."""
    body = pathlib.Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
    fields = body.rsplit(")", 1)[1].split()
    ticks = int(fields[11]) + int(fields[12])
    return fields[0], ticks / os.sysconf("SC_CLK_TCK")


def python_signal(folder: pathlib.Path) -> dict:
    """The identical mapping, a Python SIGBUS handler, and a deadline instead of a wait."""
    arms = []
    for index, mode, label in SIGNAL_ARMS:
        answers = []
        for run in range(probe.REPEATS):
            path = folder / f"signal{index}-{run}.bin"
            path.write_bytes(b"a" * (PAGES * 4096))
            log = folder / f"signal{index}-{run}.log"
            log.write_text("", encoding="utf-8")
            started = time.perf_counter()
            proc = subprocess.Popen([sys.executable, "-c", SIGNAL_SCRIPT, str(path), mode,
                                     str(log)], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    text=True)
            state, cpu = "gone", 0.0
            while time.perf_counter() - started < DEADLINE_S:
                if proc.poll() is not None:
                    break
                try:
                    state, cpu = cpu_of(proc.pid)
                except OSError:
                    break
                time.sleep(0.05)
            killed = proc.poll() is None
            if killed:
                proc.kill()
            out, err = proc.communicate()
            elapsed = time.perf_counter() - started
            answers.append({
                "killed_by_probe": killed,
                "elapsed_s": round(elapsed, 3),
                "state": state,
                "cpu_s": round(cpu, 3),
                "returncode": proc.returncode,
                "calls": len(log.read_text(encoding="utf-8").splitlines()),
                "stdout": out.strip().splitlines(),
                "stderr_tail": err.strip().splitlines()[-1:],
            })
            for leftover in folder.glob(f"signal{index}-{run}*"):
                leftover.unlink(missing_ok=True)
        first = answers[0]
        arms.append({
            "index": index, "mode": mode, "label": label,
            "killed_by_probe": first["killed_by_probe"],
            "state": first["state"],
            "returncode": first["returncode"],
            "calls": [answer["calls"] for answer in answers],
            "cpu_s": probe.summary([answer["cpu_s"] for answer in answers]),
            "elapsed_s": probe.summary([answer["elapsed_s"] for answer in answers]),
            "stdout": first["stdout"],
            "identical": all((answer["calls"], answer["killed_by_probe"])
                             == (first["calls"], first["killed_by_probe"]) for answer in answers),
            "answers": answers,
        })
        print(f"signal {index} {label:64s} calls={arms[-1]['calls']} "
              f"killed={arms[-1]['killed_by_probe']} state={arms[-1]['state']}")
    faults = [arm for arm in arms if arm["mode"] == "truncated"][0]
    sent = [arm for arm in arms if arm["mode"] == "sent"][0]
    return {
        "deadline_s": DEADLINE_S,
        "arms": arms,
        "fault_calls": faults["calls"][0],
        "fault_runs_killed": sum(1 for answer in faults["answers"] if answer["killed_by_probe"]),
        "fault_cpu_s": faults["cpu_s"],
        "fault_state": faults["state"],
        "sent_calls": sent["calls"][0],
        "identical": all(arm["identical"] for arm in arms),
        "script": SIGNAL_SCRIPT,
    }


def read_counter(path: pathlib.Path) -> int:
    """The handler's counter, read out of the shared page while the child is still spinning."""
    with open(path, "rb") as handle:
        return struct.unpack("<Q", handle.read(8))[0]


def traceme() -> int:
    """0 when this host lets a process trace its own child, else the errno PTRACE_TRACEME gave."""
    libc = ctypes.CDLL("libc.so.6", use_errno=True)
    pid = os.fork()
    if pid == 0:                                  # the child reports and leaves before any exec
        code = 0 if libc.ptrace(0, 0, None, None) == 0 else ctypes.get_errno()
        os._exit(code)
    status = os.waitpid(pid, 0)[1]
    return os.WEXITSTATUS(status) if os.WIFEXITED(status) else 255


def watchers() -> dict:
    """What this host offers for watching a child's signals from outside, and what it refuses."""
    return {"strace": shutil.which("strace") or "", "perf": shutil.which("perf") or "",
            "ptrace_errno": traceme()}


def machine_code(folder: pathlib.Path) -> dict:
    """How often the kernel hands the same instruction its SIGBUS, counted inside the loop."""
    arms = []
    for index, mode, label in DELIVERY_ARMS:
        answers = []
        for run in range(probe.REPEATS):
            path = folder / f"count{index}-{run}.bin"
            path.write_bytes(b"a" * (PAGES * 4096))
            counter = folder / f"count{index}-{run}.counter"
            counter.write_bytes(b"\x00" * COUNTER_BYTES)
            proc = subprocess.Popen([sys.executable, "-c", COUNTER_SCRIPT, str(path),
                                     str(counter), mode], stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE, text=True)
            time.sleep(SETTLE_S)
            started = time.perf_counter()
            first = read_counter(counter)
            try:
                cpu_first = cpu_of(proc.pid)[1]
            except OSError:
                cpu_first = 0.0
            time.sleep(WINDOW_S)
            second = read_counter(counter)
            try:
                cpu_second = cpu_of(proc.pid)[1]
            except OSError:
                cpu_second = cpu_first
            elapsed = time.perf_counter() - started
            killed = proc.poll() is None
            if killed:
                proc.kill()
            out, err = proc.communicate()
            total = read_counter(counter)
            cpu_s = round(cpu_second - cpu_first, 3)
            answers.append({
                "deliveries": second - first,
                "total": total,
                "elapsed_s": round(elapsed, 3),
                "cpu_s": cpu_s,
                "per_cpu_s": round((second - first) / cpu_s) if cpu_s > 0 else 0,
                "killed_by_probe": killed,
                "returncode": proc.returncode,
                "stdout": out.strip().splitlines(),
                "stderr_tail": err.strip().splitlines()[-1:],
            })
            for leftover in folder.glob(f"count{index}-{run}*"):
                leftover.unlink(missing_ok=True)
        first = answers[0]
        arms.append({
            "index": index, "mode": mode, "label": label,
            "deliveries": probe.summary([answer["deliveries"] for answer in answers]),
            "total": probe.summary([answer["total"] for answer in answers]),
            "cpu_s": probe.summary([answer["cpu_s"] for answer in answers]),
            "per_cpu_s": probe.summary([answer["per_cpu_s"] for answer in answers]),
            "elapsed_s": probe.summary([answer["elapsed_s"] for answer in answers]),
            "returncode": first["returncode"],
            "stdout": first["stdout"],
            "identical": all((answer["deliveries"] > 0) == (first["deliveries"] > 0)
                             for answer in answers),
            "answers": answers,
        })
        print(f"count {index} {label:64s} deliveries={arms[-1]['deliveries']['median']:,.0f} "
              f"cpu={arms[-1]['cpu_s']['median']} per_cpu_s={arms[-1]['per_cpu_s']['median']:,.0f}")
    faulting = [arm for arm in arms if arm["mode"] == "truncated"][0]
    sent = [arm for arm in arms if arm["mode"] == "sent"][0]
    quiet = [arm for arm in arms if arm["mode"] == "tail"][0]
    return {
        "window_s": WINDOW_S,
        "settle_s": SETTLE_S,
        "counter_bytes": COUNTER_BYTES,
        "script": COUNTER_SCRIPT,
        "arms": arms,
        "deliveries": faulting["deliveries"],
        "total": faulting["total"],
        "cpu_s": faulting["cpu_s"],
        "per_cpu_s": faulting["per_cpu_s"],
        "sent_deliveries": sent["total"],
        "quiet_deliveries": quiet["total"],
    }


def main() -> None:
    folder = probe.work_dir("sigbus")
    records = []
    for index, label, action, offset in ARMS:
        answers = []
        for run in range(probe.REPEATS):
            path, resolved = prepare(folder, index, run, action)
            result = probe.child(SCRIPT, str(path), resolved, str(offset))
            signalled = -result.returncode if result.returncode < 0 else 0
            answers.append({
                "signal": signalled,
                "signal_name": (signal.Signals(signalled).name if signalled else "none"),
                "stdout": result.stdout.strip().splitlines(),
                "stderr_tail": result.stderr.strip().splitlines()[-1:] or [],
                "returncode": result.returncode,
            })
            for leftover in path.parent.glob(f"arm{index}-{run}*"):
                leftover.unlink(missing_ok=True)
        first = answers[0]
        records.append({
            "index": index, "label": label, "action": action, "offset": offset,
            "signal": first["signal"], "signal_name": first["signal_name"],
            "identical": all(answer["signal"] == first["signal"] for answer in answers),
            "answers": answers,
        })
        print(f"{index} {label:64s} {first['signal_name']:8s} "
              f"{first['stdout'][-1] if first['stdout'] else ''}")

    payload = {
        "repeats": probe.REPEATS,
        "pages": PAGES,
        "arms": records,
        "watchers": watchers(),
        "delivery": machine_code(folder),
        "sigbus_arms": sum(1 for record in records if record["signal"] != 0),
        "quiet_arms": sum(1 for record in records if record["signal"] == 0),
        "identical": all(record["identical"] for record in records),
        "script": SCRIPT,
        "signal": python_signal(folder),
    }
    probe.save("05", "sigbus", payload)


if __name__ == "__main__":
    main()
Shared and private writes, a reader in another process, msync timed. 06_write.py
"""Probe 06: what a mapping writes, when another process can see it, and what msync buys.

Three questions, each answered by a separate pair of processes: whether a shared write is visible
to a reader that never calls msync, whether a private write reaches the file at all, and what a
sync costs when the mapping is dirty. The reader is a child interpreter, so the visibility is
between processes rather than between two views inside one.
"""
from __future__ import annotations

import mmap
import os
import time

import probe

SIZE_MIB = 1
BIG_MIB = 64
READER = """
import sys

with open(sys.argv[1], "rb") as handle:
    handle.seek(int(sys.argv[2]))
    print(handle.read(int(sys.argv[3])).hex())
"""


def read_from_another_process(path, offset: int, length: int) -> str:
    result = probe.child(READER, str(path), str(offset), str(length))
    if result.returncode != 0:
        raise RuntimeError(result.stderr[-400:])
    return result.stdout.strip()


def fresh_folder(name: str, size_mib: int = SIZE_MIB):
    folder = probe.work_dir(name, size_mib)
    return folder, folder / "data.bin"


def arm_shared(path, folder) -> dict:
    fd = os.open(path, os.O_RDWR)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE)
        handle[0] = 0x5A
        own = handle[0]
        seen = read_from_another_process(path, 0, 1)
        size = path.stat().st_size
        handle.close()
        return {"own_view": own, "reader_hex": seen, "file_size": size,
                "msync_ms": None, "file_byte": path.read_bytes()[0]}
    finally:
        os.close(fd)


def arm_shared_sync(path, folder) -> dict:
    fd = os.open(path, os.O_RDWR)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE)
        handle[0] = 0x5A
        seen = read_from_another_process(path, 0, 1)
        started = time.perf_counter()
        handle.flush()
        synced_ms = (time.perf_counter() - started) * 1000
        size = path.stat().st_size
        handle.close()
        return {"own_view": 0x5A, "reader_hex": seen, "file_size": size,
                "msync_ms": synced_ms, "file_byte": path.read_bytes()[0]}
    finally:
        os.close(fd)


def arm_private(path, folder) -> dict:
    fd = os.open(path, os.O_RDWR)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ | mmap.PROT_WRITE)
        handle[0] = 0x43
        own = handle[0]
        started = time.perf_counter()
        handle.flush()
        synced_ms = (time.perf_counter() - started) * 1000
        seen = read_from_another_process(path, 0, 1)
        size = path.stat().st_size
        handle.close()
        return {"own_view": own, "reader_hex": seen, "file_size": size,
                "msync_ms": synced_ms, "file_byte": path.read_bytes()[0]}
    finally:
        os.close(fd)


def arm_last_byte(path, folder) -> dict:
    fd = os.open(path, os.O_RDWR)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE)
        last = len(handle) - 1
        handle[last] = 0x5A
        handle.flush()
        own = handle[last]
        size_after = path.stat().st_size
        handle.close()
        data = path.read_bytes()
        return {"own_view": own, "reader_hex": read_from_another_process(path, last, 1),
                "file_size": size_after, "msync_ms": 0.0, "file_byte": data[-1],
                "size_before": last + 1}
    finally:
        os.close(fd)


def arm_dirty_sync(path, folder) -> dict:
    path = folder / "big.bin"
    path.write_bytes(b"z" * (BIG_MIB << 20))
    fd = os.open(path, os.O_RDWR)
    try:
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ | mmap.PROT_WRITE)
        for offset in range(0, len(handle), mmap.PAGESIZE):
            handle[offset] = 0x59
        started = time.perf_counter()
        handle.flush()
        synced_ms = (time.perf_counter() - started) * 1000
        size = path.stat().st_size
        handle.close()
        return {"own_view": 0x59, "reader_hex": "59", "file_size": size,
                "msync_ms": synced_ms, "file_byte": path.read_bytes()[0]}
    finally:
        os.close(fd)


ARMS = [
    (0, "MAP_SHARED write, reader without msync", arm_shared),
    (1, "MAP_SHARED write, then msync(MS_SYNC)", arm_shared_sync),
    (2, "MAP_PRIVATE write, then msync", arm_private),
    (3, "MAP_SHARED write of the last byte", arm_last_byte),
    (4, "MAP_SHARED write of one byte per page over 64 MiB, then msync", arm_dirty_sync),
]


def main() -> None:
    records = []
    for index, label, function in ARMS:
        runs = []
        for run in range(probe.REPEATS):
            folder, path = fresh_folder(f"write-{index}-{run}")
            result = function(path, folder)
            runs.append(result)
            for leftover in folder.glob("*"):
                leftover.unlink(missing_ok=True)
        record = {
            "index": index, "label": label,
            "own_view": runs[0]["own_view"], "reader_hex": runs[0]["reader_hex"],
            "file_byte": runs[0]["file_byte"], "file_size": runs[0]["file_size"],
            "msync_ms": probe.summary([run["msync_ms"] for run in runs
                                       if run["msync_ms"] is not None]) if index in (1, 2, 4)
            else None,
            "identical": len({(run["own_view"], run["reader_hex"], run["file_byte"],
                               run["file_size"]) for run in runs}) == 1,
            "runs": runs,
        }
        records.append(record)
        print(f"{index} {label:62s} own {record['own_view']:#04x} reader {record['reader_hex']} "
              f"file {record['file_byte']:#04x} size {record['file_size']}")

    payload = {
        "repeats": probe.REPEATS,
        "size_bytes": SIZE_MIB << 20,
        "big_mib": BIG_MIB,
        "arms": records,
        "reader_script": READER,
    }
    probe.save("06", "write", payload)


if __name__ == "__main__":
    main()
256 MiB anonymous and file-backed, with MADV_DONTNEED. 07_rss.py
"""Probe 07: what a mapped file does to the resident set, against what an anonymous buffer does.

The same 256 MiB, twice: once as a private anonymous mapping, once as a shared mapping of a file.
/proc/self/status splits the resident set into RssAnon and RssFile, which is the difference a
graph of VmRSS alone cannot show. MADV_DONTNEED is then asked to drop the pages while the mapping
is still open, so the probe records what the mapping cost and what it kept.
"""
from __future__ import annotations

import mmap
import os
import time

import probe

SIZE_MIB = 256
ARMS = [
    (0, "private anonymous buffer, every page written", "anon"),
    (1, "shared file mapping, every page read", "file"),
]


def touch(handle) -> int:
    total = 0
    for offset in range(0, len(handle), mmap.PAGESIZE):
        total += handle[offset]
    return total


def run_arm(kind: str, path=None) -> dict:
    before = probe.rss()
    if kind == "anon":
        buffer = bytearray(SIZE_MIB << 20)
        started = time.perf_counter()
        for offset in range(0, len(buffer), mmap.PAGESIZE):
            buffer[offset] = 1
        checksum = len(buffer)
    else:
        fd = os.open(path, os.O_RDONLY)
        handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        started = time.perf_counter()
        checksum = touch(handle)
    touched = time.perf_counter()
    mapped = probe.rss()
    if kind == "anon":
        del buffer
        after_advice = probe.rss()
    else:
        handle.madvise(mmap.MADV_DONTNEED)
        after_advice = probe.rss()
        handle.close()
        os.close(fd)
    closed = probe.rss()
    return {
        "before": before, "mapped": mapped, "after_advice": after_advice, "closed": closed,
        "touch_ms": (touched - started) * 1000, "checksum": checksum,
        "mapped_delta": probe.counter(before, mapped),
        "advice_delta": probe.counter(mapped, after_advice),
        "closed_delta": probe.counter(before, closed),
    }


def main() -> None:
    folder = probe.work_dir("rss", SIZE_MIB)
    path = folder / "data.bin"
    records = []
    for index, label, kind in ARMS:
        runs = [run_arm(kind, path) for _ in range(probe.REPEATS)]
        record = {
            "index": index, "label": label, "kind": kind,
            "mapped_kib": probe.summary([run["mapped_delta"]["VmRSS"] for run in runs]),
            "mapped_anon_kib": probe.summary([run["mapped_delta"]["RssAnon"] for run in runs]),
            "mapped_file_kib": probe.summary([run["mapped_delta"]["RssFile"] for run in runs]),
            "mapped_shmem_kib": probe.summary([run["mapped_delta"]["RssShmem"] for run in runs]),
            "advice_kib": probe.summary([run["advice_delta"]["VmRSS"] for run in runs]),
            "advice_anon_kib": probe.summary([run["advice_delta"]["RssAnon"] for run in runs]),
            "advice_file_kib": probe.summary([run["advice_delta"]["RssFile"] for run in runs]),
            "closed_kib": probe.summary([run["closed_delta"]["VmRSS"] for run in runs]),
            "touch_ms": probe.summary([run["touch_ms"] for run in runs]),
            "runs": runs,
        }
        records.append(record)
        print(f"{index} {label:38s} VmRSS +{record['mapped_kib']['median']:.0f} KiB "
              f"(anon {record['mapped_anon_kib']['median']:.0f}, "
              f"file {record['mapped_file_kib']['median']:.0f}) "
              f"after DONTNEED {record['advice_kib']['median']:.0f}")

    payload = {
        "repeats": probe.REPEATS,
        "size_mib": SIZE_MIB,
        "size_kib": SIZE_MIB * 1024,
        "arms": records,
    }
    probe.save("07", "rss", payload)


if __name__ == "__main__":
    main()
pytest’s summary, and the line counts the article quotes. 08_tests.py
"""Probe 08: the test run, and the counts the article reads from the tree it ships.

pytest's own summary is parsed rather than assumed, and the file and line counts come from the
package and the probes as they are on disk, so a sentence about "sixty tests" cannot outlive the
suite it describes.
"""
from __future__ import annotations

import pathlib
import re
import subprocess
import sys

import probe

HERE = pathlib.Path(__file__).resolve().parent
PACKAGE = HERE.parent / "module" / "filemap"
TESTS = PACKAGE / "tests"


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


def main() -> None:
    result = subprocess.run([sys.executable, "-m", "pytest", "filemap/tests", "-q",
                             "-p", "no:warnings", "-p", "no:cacheprovider", "-p", "no:asyncio"],
                            cwd=str(PACKAGE.parent), 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("pytest did not pass:\n" + output[-1500:])
    passed = int(match.group(1))
    package_files = sorted(path for path in PACKAGE.glob("*.py"))
    test_files = sorted(TESTS.glob("*.py"))
    probe_files = sorted(path for path in HERE.glob("*.py"))
    payload = {
        "pytest_passed": passed,
        "pytest_returncode": result.returncode,
        "pytest_summary": next((line.strip() for line in output.splitlines()
                                if " passed" in line), ""),
        "package_files": len(package_files),
        "package_lines": lines_of(package_files),
        "test_files": len(test_files),
        "test_lines": lines_of(test_files),
        "probe_files": len(probe_files),
        "probe_lines": lines_of(probe_files),
    }
    print(payload)
    probe.save("08", "tests", payload)


if __name__ == "__main__":
    main()
Growth after the call, and the count at which mapping stops. 09_limits.py
"""Probe 09: the mapping that does not follow its file, and the count at which mapping stops.

A mapping is a fixed window: bytes appended after the call are not in it, and the length is
decided once. The other limit is the number of mappings a process may hold - each one is a VMA in
the kernel - and the count at which the kernel answers ENOMEM is measured in a child, so the
probe's own address space stays clean and the same run can be repeated. The child then tries one
ordinary allocation, because a process at that limit is not merely unable to map a new file.

The child reads its own map file three times - before the loop, at the refusal, and after the list
is cleared - and prints every line that is not one of the loop's own mappings, so the lines can be
added up rather than guessed at. Two of its lines are not areas the process holds: the kernel
prints the last one, ``[vsyscall]``, from a pseudo area that belongs to no process, and it is not
counted in the kernel's cap. The probe therefore reports the areas each read implies (lines minus
that one), checks that the three reads add up, and stops if they do not.
"""
from __future__ import annotations

import errno
import pathlib
import time

import probe

GROW = """
import mmap
import os
import sys

path = sys.argv[1]
fd = os.open(path, os.O_RDONLY)
handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
before = len(handle)
with open(path, "ab") as writer:
    writer.write(b"n" * 4096)
after = len(handle)
try:
    handle[before]
except IndexError as exc:
    print("length", before, after, "file", os.stat(path).st_size, "refused", type(exc).__name__)
else:
    print("length", before, after, "file", os.stat(path).st_size, "refused", "none")
print("last", handle[before - 1])
"""

MAPS = """
import errno
import mmap


def snap(name):
    \"\"\"One read of the map file: its lines, the loop's lines, and every other line in full.\"\"\"
    total = 0
    loop = 0
    other = []
    with open("/proc/self/maps", encoding="utf-8") as handle:
        for row in handle:
            row = row.strip()
            if not row:
                continue
            total += 1
            parts = row.split(None, 5)
            start, end = parts[0].split("-")
            size = int(end, 16) - int(start, 16)
            label = parts[5] if len(parts) > 5 else "-"
            if label == "/dev/zero (deleted)":
                loop += 1
            else:
                other.append("%d %s" % (size, label))
    print("snap\t%s\t%d\t%d" % (name, total, loop), flush=True)
    for entry in other:
        print("other\t%s\t%s" % (name, entry), flush=True)


snap("before")
snap("before2")
kept = []
count = 0
try:
    while True:
        kept.append(mmap.mmap(-1, 4096))
        count += 1
except (OSError, MemoryError) as exc:
    number = getattr(exc, "errno", 0) or 0
    print("failed\t%d\t%d\t%s"
          % (count, number, errno.errorcode.get(number, type(exc).__name__)), flush=True)
snap("refusal")
snap("refusal2")
try:
    blob = bytearray(1 << 20)
    print("alloc\tok\t%d" % len(blob), flush=True)
except MemoryError:
    print("alloc\tMemoryError\t0", flush=True)
kept.clear()
snap("after")
snap("after2")
"""

THOUSAND = """
import mmap


def lines():
    with open("/proc/self/maps", encoding="utf-8") as handle:
        return len(handle.read().splitlines())


before = lines()
kept = [mmap.mmap(-1, 4096) for _ in range(1000)]
print("lines", before, lines(), flush=True)
"""

MIB = 1 << 20
GATE = "[vsyscall]"


def growth() -> dict:
    folder = probe.work_dir("growth")
    path = folder / "grow.bin"
    path.write_bytes(b"a" * (1 << 20))
    result = probe.child(GROW, str(path))
    if result.returncode != 0:
        raise RuntimeError(result.stderr[-400:])
    head, tail = result.stdout.split("last", 1)
    words = head.split()
    return {"mapping_before": int(words[1]), "mapping_after": int(words[2]),
            "file_size": int(words[4]), "refused": words[6],
            "last_byte": int(tail.strip())}


def read_child(stdout: str) -> dict:
    """What the limit child printed: the refusal, the allocation, and four map-file reads."""
    failed: dict | None = None
    alloc = ("", 0)
    snaps: dict[str, dict] = {}
    for line in stdout.splitlines():
        words = line.split("\t")
        if not words:
            continue
        if words[0] == "snap":
            snaps[words[1]] = {"lines": int(words[2]), "loop": int(words[3]), "other": []}
        elif words[0] == "other":
            snaps.setdefault(words[1], {"lines": 0, "loop": 0, "other": []})["other"].append(
                words[2])
        elif words[0] == "failed":
            failed = {"count": int(words[1]), "number": int(words[2]), "name": words[3]}
        elif words[0] == "alloc":
            alloc = (words[1], int(words[2]))
    if failed is None:
        raise RuntimeError(f"the child never reported a refusal: {stdout[-400:]}")
    for name in ("before", "refusal", "after"):
        if name not in snaps:
            raise RuntimeError(f"the child never read the map file at {name}: {stdout[-400:]}")
    return {"failed": failed, "alloc": alloc, "snaps": snaps}


def areas(snap: dict) -> int:
    """The areas the kernel counts: every line but the pseudo one it prints from outside the mm."""
    return snap["lines"] - sum(1 for entry in snap["other"] if entry.endswith(GATE))


def versus(entry: str) -> tuple[int, str]:
    """One printed line as (size, label), so an anonymous arena can be named by its size."""
    size, _, label = entry.partition(" ")
    return int(size), label


def arenas(snap: dict) -> int:
    """The 1 MiB areas with no name: the object allocator's arenas, one per MiB."""
    return sum(1 for entry in snap["other"] if versus(entry) == (MIB, "-"))


def map_limit(max_map_count: int) -> dict:
    runs = []
    for _ in range(probe.REPEATS):
        started = time.perf_counter()
        result = probe.child(MAPS)
        elapsed = time.perf_counter() - started
        if result.returncode != 0:
            raise RuntimeError(result.stderr[-400:])
        answer = read_child(result.stdout)
        before = answer["snaps"]["before"]
        refusal = answer["snaps"]["refusal"]
        after = answer["snaps"]["after"]
        if answer["snaps"]["before2"]["lines"] != before["lines"]:
            raise RuntimeError("reading the map file at the start changed its own line count")
        if answer["snaps"]["refusal2"]["lines"] != refusal["lines"]:
            raise RuntimeError("reading the map file at the refusal changed its line count")
        if answer["snaps"]["after2"]["lines"] != after["lines"]:
            raise RuntimeError("reading the map file after the clear changed its line count")
        created = answer["failed"]["count"]
        closed = areas(refusal) == areas(before) + arenas(refusal) + created
        returned = areas(after) == areas(before) + arenas(after)
        room = max_map_count - areas(before) + 1 == arenas(refusal) + created
        if not (closed and returned and room):
            raise RuntimeError(
                f"the map file does not add up: before {before['lines']} lines, "
                f"{arenas(before)} arenas; refusal {refusal['lines']} lines, "
                f"{arenas(refusal)} arenas, {created} mappings made; after {after['lines']} "
                f"lines, {arenas(after)} arenas; cap {max_map_count}")
        runs.append({
            **answer["failed"],
            "alloc": answer["alloc"][0],
            "alloc_bytes": answer["alloc"][1],
            "maps_lines": after["lines"],
            "elapsed_ms": elapsed * 1000,
            "maps": {
                "before_lines": before["lines"],
                "before_loop": before["loop"],
                "before_arenas": arenas(before),
                "before_areas": areas(before),
                "refusal_lines": refusal["lines"],
                "refusal_loop": refusal["loop"],
                "refusal_arenas": arenas(refusal),
                "refusal_areas": areas(refusal),
                "after_lines": after["lines"],
                "after_loop": after["loop"],
                "after_arenas": arenas(after),
                "after_areas": areas(after),
                "other": {"before": before["other"], "refusal": refusal["other"],
                          "after": after["other"]},
            },
        })
    limit = {
        "count": probe.summary([run["count"] for run in runs]),
        "maps_lines": probe.summary([run["maps_lines"] for run in runs]),
        "elapsed_ms": probe.summary([run["elapsed_ms"] for run in runs]),
        "number": runs[0]["number"], "name": runs[0]["name"],
        "alloc": runs[0]["alloc"],
        "alloc_bytes": runs[0]["alloc_bytes"],
        "identical": len({(run["count"], run["alloc"]) for run in runs}) == 1,
        "runs": runs,
    }
    fields = [field for field in runs[0]["maps"] if field != "other"]
    for field in fields:
        limit.setdefault("maps", {})[field] = probe.summary(
            [float(run["maps"][field]) for run in runs])
    limit["maps"]["other"] = runs[0]["maps"]["other"]
    return limit


def thousand() -> dict:
    runs = []
    for _ in range(probe.REPEATS):
        result = probe.child(THOUSAND)
        before, after = (int(word) for word in result.stdout.split()[1:3])
        if after != before + 1000:
            raise RuntimeError(f"1,000 mappings moved the line count {before} -> {after}")
        runs.append((before, after))
    return {"before": probe.summary([float(run[0]) for run in runs]),
            "after": probe.summary([float(run[1]) for run in runs]),
            "added": probe.summary([float(run[1] - run[0]) for run in runs])}


def main() -> None:
    grow = growth()
    cap = int(pathlib.Path("/proc/sys/vm/max_map_count").read_text(encoding="utf-8").strip())
    limit = map_limit(cap)
    added = thousand()
    print("growth:", grow)
    print("limit:", {key: limit[key] for key in ("count", "maps_lines", "number", "name", "alloc")})
    print("limit maps:", {key: value["median"] for key, value in limit["maps"].items()
                          if key != "other"})
    print("thousand:", added)
    payload = {
        "repeats": probe.REPEATS,
        "growth": grow,
        "limit": limit,
        "thousand": added,
        "max_map_count": cap,
        "pseudo_line": GATE,
        "baseline_lines": len(open("/proc/self/maps").read().splitlines()),
        "errno_enomem": errno.ENOMEM,
    }
    probe.save("09", "limits", payload)


if __name__ == "__main__":
    main()
Five O_DIRECT transfers, four of them breaking the documented alignment. 10_direct.py
"""Probe 10: does O_DIRECT enforce the alignment its documentation promises on this mount?

The documented rule is that a direct read or write needs a buffer, an offset and a length that are
all multiples of the device's block size. Four arms break the rule in one way each and one keeps
it, five times, and the answer is recorded whether it is EINVAL or a plain success - a filesystem
that accepts the flag and ignores it is worth knowing about before a service relies on it.
"""
from __future__ import annotations

import errno
import mmap
import os

import probe

BLOCK = 4096
ARMS = [
    (0, "block-aligned buffer, offset and length", True, 0, BLOCK),
    (1, "length of 1,000 bytes", True, 0, 1000),
    (2, "offset of 512 bytes", True, 512, BLOCK),
    (3, "a bytearray, address chosen by the allocator (alignment not recorded)", False, 0, BLOCK),
    (4, "length of one 512-byte sector", True, 0, 512),
]


def attempt(path, aligned: bool, offset: int, length: int) -> dict:
    buffer = mmap.mmap(-1, BLOCK * 2) if aligned else bytearray(BLOCK * 2)
    try:
        try:
            fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_DIRECT, 0o600)
        except OSError as exc:
            return {"opened": False, "open_errno": exc.errno,
                    "open_name": errno.errorcode.get(exc.errno, "?"),
                    "write_bytes": 0, "write_errno": 0, "write_name": "not attempted",
                    "read_bytes": 0, "read_errno": 0, "read_name": "not attempted",
                    "equal": False}
        try:
            view = memoryview(buffer)
            try:
                written = os.pwritev(fd, [view[:length]], offset)
                write_errno, write_name = 0, "ok"
            except OSError as exc:
                written = 0
                write_errno = exc.errno
                write_name = errno.errorcode.get(exc.errno, "?")
            try:
                read_back = os.preadv(fd, [view[:length]], offset)
                read_errno, read_name = 0, "ok"
            except OSError as exc:
                read_back = 0
                read_errno = exc.errno
                read_name = errno.errorcode.get(exc.errno, "?")
            return {"opened": True, "open_errno": 0, "open_name": "ok",
                    "write_bytes": written, "write_errno": write_errno,
                    "write_name": write_name, "read_bytes": read_back,
                    "read_errno": read_errno, "read_name": read_name,
                    "equal": read_back == written and written > 0}
        finally:
            os.close(fd)
    finally:
        if aligned:
            view.release()
            buffer.close()


def main() -> None:
    folder = probe.work_dir("direct")
    records = []
    for index, label, aligned, offset, length in ARMS:
        answers = []
        for run in range(probe.REPEATS):
            path = folder / f"arm{index}-{run}.bin"
            answers.append(attempt(path, aligned, offset, length))
        first = answers[0]
        records.append({
            "index": index, "label": label, "offset": offset, "length": length,
            "aligned_buffer": aligned, "opened": first["opened"],
            "write_errno": first["write_errno"], "write_name": first["write_name"],
            "write_bytes": first["write_bytes"], "read_errno": first["read_errno"],
            "read_name": first["read_name"], "read_bytes": first["read_bytes"],
            "equal": first["equal"],
            "identical": len({(item["opened"], item["write_errno"], item["read_errno"])
                              for item in answers}) == 1,
            "answers": answers,
        })
        print(f"{index} {label:52s} open {first['opened']} write {first['write_name']} "
              f"{first['write_bytes']} read {first['read_name']} {first['read_bytes']}")

    payload = {
        "repeats": probe.REPEATS,
        "block": BLOCK,
        "arms": records,
        "accepted": sum(1 for record in records if record["write_errno"] == 0),
        "refused": sum(1 for record in records if record["write_errno"] != 0),
        "identical": all(record["identical"] for record in records),
    }
    probe.save("10", "direct", payload)


if __name__ == "__main__":
    main()
One stat, one offset-0 read, a walking read and one slice, priced per call. 11_statcost.py
"""Probe 11: what one guard costs, next to the read it guards.

Every claim about checking a mapping before reading from it rests on an unstated price: one stat
per window. This probe puts that price next to the work it protects - a file descriptor stat, a
path stat (which is what a guard that re-opens by name pays), a 4 KiB pread of one page, a 4 KiB
pread that walks the file, and a 4 KiB slice out of a live mapping - in five rounds of thousands
of calls, so the figure is a median of rounds rather than of one warm loop.

The preads are not one measurement but three, because the same call costs what the page it copies
costs. Repeating offset 0 prices the call and the copy out of a page whose page-table entry is
already there, which is what a guard in front of a known window meets. Walking the first 5,000
pages of a 4 MiB file and of a 128 MiB file prices the same call with a fresh page each time, and
the two files differ only in where the bytes come from: 4 MiB stays in this CPU's own caches, so
a later round finds it there, while a 128 MiB file cannot. A third arm walks all 32,768 pages of
the 128 MiB file once per round, which is the shape of the 4 KiB block loop in probe 04 - no page
is visited twice, so every copy comes from memory. Both files are read through once before the
timed rounds, so no arm pays for the file's first read.
"""
from __future__ import annotations

import mmap
import os
import pathlib
import time

import probe

ROUNDS = 5
FSTAT_CALLS = 20000
STAT_CALLS = 20000
PREAD_CALLS = 5000
STREAM_CALLS = 5000
SLICE_CALLS = 5000
PAGE = 4096
BIG_MIB = 128


def per_call(operation, calls: int) -> float:
    """Microseconds per call, measured over one round."""
    started = time.perf_counter()
    for _ in range(calls):
        operation()
    finished = time.perf_counter()
    return (finished - started) / calls * 1e6


def walk(fd: int, offsets: list[int], view: memoryview, calls: int) -> float:
    """One 4 KiB pread per call, the offset advancing a page each time."""
    started = time.perf_counter()
    done = 0
    while done < calls:
        for offset in offsets:
            os.preadv(fd, [view], offset)
            done += 1
            if done >= calls:
                break
    finished = time.perf_counter()
    return (finished - started) / calls * 1e6


def fill(path: pathlib.Path, size_mib: int, block: bytes) -> None:
    """A file of known size, written a MiB at a time."""
    with open(path, "wb") as out:
        for _ in range(size_mib):
            out.write(block)


def warm(fd: int, size: int) -> int:
    """Read the whole file once, so the page cache holds it before any round is timed."""
    buffer = memoryview(bytearray(1 << 20))
    position = 0
    try:
        while position < size:
            count = os.preadv(fd, [buffer], position)
            if count <= 0:
                break
            position += count
    finally:
        buffer.release()
    return position


def main() -> None:
    folder = probe.work_dir("statcost", 4)
    path = folder / "data.bin"
    big_path = folder / "big.bin"
    fill(big_path, BIG_MIB, b"y" * (1024 * 1024))
    fd = os.open(path, os.O_RDONLY)
    big_fd = os.open(big_path, os.O_RDONLY)
    handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
    buffer = bytearray(PAGE)
    view = memoryview(buffer)
    info = os.fstat(fd)
    big_size = os.fstat(big_fd).st_size
    try:
        warm_bytes = {"small": warm(fd, info.st_size), "big": warm(big_fd, big_size)}

        hot = 200
        for _ in range(hot):                       # the cache, the import, the first page
            os.fstat(fd)
            os.stat(path)
            os.preadv(fd, [view], 0)
            handle[0:PAGE]

        offsets = list(range(0, info.st_size, PAGE))
        big_head = list(range(0, big_size, PAGE))[:STREAM_CALLS]
        big_all = list(range(0, big_size, PAGE))

        arms = ["fstat_us", "stat_us", "pread4k_us", "pread4k_stream_us",
                "pread4k_stream128_us", "pread4k_pass128_us", "slice4k_us"]
        rounds = {name: [] for name in arms}
        faulted = {name: {"minor": [], "major": []} for name in arms}

        def measure(name: str) -> float:
            if name == "fstat_us":
                return per_call(lambda: os.fstat(fd), FSTAT_CALLS)
            if name == "stat_us":
                return per_call(lambda: os.stat(path), STAT_CALLS)
            if name == "pread4k_us":
                return per_call(lambda: os.preadv(fd, [view], 0), PREAD_CALLS)
            if name == "pread4k_stream_us":
                return walk(fd, offsets, view, STREAM_CALLS)
            if name == "pread4k_stream128_us":
                return walk(big_fd, big_head, view, STREAM_CALLS)
            if name == "pread4k_pass128_us":
                return walk(big_fd, big_all, view, len(big_all))
            return per_call(lambda: handle[0:PAGE], SLICE_CALLS)

        for round_index in range(ROUNDS):
            order = arms[round_index % len(arms):] + arms[:round_index % len(arms)]
            for name in order:
                before = probe.faults()
                rounds[name].append(measure(name))
                after = probe.faults()
                faulted[name]["minor"].append(after["minor"] - before["minor"])
                faulted[name]["major"].append(after["major"] - before["major"])

        payload = {
            "rounds": ROUNDS,
            "calls": {"fstat": FSTAT_CALLS, "stat": STAT_CALLS, "pread4k": PREAD_CALLS,
                      "pread4k_stream": STREAM_CALLS, "pread4k_stream128": STREAM_CALLS,
                      "pread4k_pass128": len(big_all), "slice4k": SLICE_CALLS},
            "page": PAGE,
            "size_bytes": info.st_size,
            "size_mib": info.st_size // (1024 * 1024),
            "big_bytes": big_size,
            "big_mib": big_size // (1024 * 1024),
            "warm_bytes": warm_bytes,
            "identity": [info.st_dev, info.st_ino],
            "faults": {name: {kind: probe.summary(values) for kind, values in kinds.items()}
                       for name, kinds in faulted.items()},
        }
        for key, values in rounds.items():
            payload[key] = probe.summary(values)
            print(f"{key:22s} median {payload[key]['median']:7.3f} µs  "
                  f"(min {payload[key]['min']:7.3f} max {payload[key]['max']:7.3f})")
        probe.save("11", "statcost", payload)
    finally:
        view.release()
        handle.close()
        os.close(fd)
        os.close(big_fd)


if __name__ == "__main__":
    main()
What a service imports from the package. filemap/__init__.py
"""filemap: a file mapping that refuses to be read after the file has moved out from under it.

Three things a service needs around mmap - a mapping that checks its file before every read, the
fault counters that make a measurement honest, and the two limits that end a mapping - in one
small package with no dependencies outside the standard library.
"""
from .errors import Fault, MappingError, TruncatedFile, classify, describe
from .limits import headroom, mapping_count, max_map_count
from .mapping import Mapping, open_mapping
from .procstat import faults, resident
from .reader import chunks, read_page

__all__ = [
    "Fault",
    "Mapping",
    "MappingError",
    "TruncatedFile",
    "chunks",
    "classify",
    "describe",
    "faults",
    "headroom",
    "mapping_count",
    "max_map_count",
    "open_mapping",
    "read_page",
    "resident",
]
Six refusal conditions, and one log line. filemap/errors.py
"""What a mapping call can refuse, and how to say so in one line.

Two of the refusals never reach the kernel: this interpreter compares the length with the file's
size before it calls mmap, so an empty file arrives as ValueError and a length past the end as
ValueError too. The rest are errnos, and ENOMEM from the mapping count can arrive as MemoryError
instead, because the interpreter allocates mappings of its own. A path that is gone before the
open is its own answer: calling it truncated would tell a caller to re-map a file that is not
there.
"""
from __future__ import annotations

import errno
from enum import Enum


class Fault(str, Enum):
    """The condition a caller has to handle differently."""

    EMPTY = "empty"
    BEYOND_EOF = "beyond-eof"
    MISSING = "missing"
    TRUNCATED = "truncated"
    LIMIT = "limit"
    PERMISSION = "permission"
    UNRELATED = "unrelated"


class MappingError(Exception):
    """A mapping call that failed for a reason the caller may recover from."""

    def __init__(self, fault: Fault, path: str, detail: str = "") -> None:
        super().__init__(f"{fault.value} on {path}" + (f": {detail}" if detail else ""))
        self.fault = fault
        self.path = path
        self.detail = detail


class TruncatedFile(Exception):
    """The file behind a live mapping is shorter than the mapping, so a page may be gone."""

    def __init__(self, path: str, mapped: int, current: int) -> None:
        super().__init__(f"{path} is {current} bytes, mapping covers {mapped}")
        self.path = path
        self.mapped = mapped
        self.current = current


TABLE = {
    errno.ENOMEM: Fault.LIMIT,
    errno.EACCES: Fault.PERMISSION,
    errno.EPERM: Fault.PERMISSION,
    errno.EINVAL: Fault.UNRELATED,
    errno.ENODEV: Fault.UNRELATED,
    errno.ENOENT: Fault.MISSING,
}

# The interpreter's own messages, which carry no errno at all.
MESSAGES = {
    "cannot mmap an empty file": Fault.EMPTY,
    "mmap length is greater than file size": Fault.BEYOND_EOF,
}


def classify(exc: BaseException) -> Fault:
    """Turn one failure into the condition a caller has to handle."""
    if isinstance(exc, TruncatedFile):
        return Fault.TRUNCATED
    if isinstance(exc, MemoryError):
        # At the mapping limit the interpreter cannot allocate either, and it says so this way.
        return Fault.LIMIT
    if isinstance(exc, ValueError):
        return MESSAGES.get(str(exc), Fault.UNRELATED)
    if isinstance(exc, OSError):
        return TABLE.get(exc.errno, Fault.UNRELATED)
    return Fault.UNRELATED


def describe(exc: BaseException, path: str) -> str:
    """One line for the log: the condition, the number, and the file."""
    fault = classify(exc)
    if isinstance(exc, OSError) and exc.errno:
        detail = f"{errno.errorcode.get(exc.errno, 'errno')} {exc.errno}"
    else:
        detail = type(exc).__name__
    return f"filemap: {fault.value} ({detail}) on {path}"
The mapping cap, the count this process holds, and the gap. filemap/limits.py
"""The limit that ends a program's mappings, and how close the process already is to it.

Every mapping a process holds is a VMA in the kernel, and vm.max_map_count caps how many it may
have. The count is not a memory limit: a process at the cap cannot map a 4 KiB file, and an
allocation the interpreter needs a new arena for fails, because its arenas are mappings too.
Reading the limit next to the current count is the difference between a diagnosis and a guess.

Two details decide whether that reading is exact. The map file has one line the kernel prints
from a pseudo area that no process owns - ``[vsyscall]`` - so counting lines overstates the count
by one. And the kernel refuses a new area only when the count is already above the cap, so a
process at the cap may still create one more mapping.
"""
from __future__ import annotations

import os
import pathlib

LIMIT_PATH = pathlib.Path("/proc/sys/vm/max_map_count")
PSEUDO = "[vsyscall]"


def max_map_count(path: pathlib.Path | str = LIMIT_PATH) -> int:
    """The kernel's cap on mappings per process."""
    return int(pathlib.Path(path).read_text(encoding="utf-8").strip())


def mapping_count(pid: int | None = None, path: pathlib.Path | str | None = None) -> int:
    """How many mappings one process holds now: this one, or the one a map file names."""
    if path is None:
        target = os.getpid() if pid is None else pid
        path = f"/proc/{target}/maps"
    body = pathlib.Path(path).read_text(encoding="utf-8")
    return len([line for line in body.splitlines()
                if line.strip() and not line.rstrip().endswith(PSEUDO)])


def headroom(pid: int | None = None) -> int:
    """How many more mappings this process may create before the next call fails."""
    return max_map_count() - mapping_count(pid) + 1
A mapping with an identity check in front of every window. filemap/mapping.py
"""A mapping that knows which file it is a mapping of, and refuses to be read after a change.

The kernel will happily hand a process a page of a file that has since been truncated, and the
touch that reaches a page which no longer exists ends the process with SIGBUS. No amount of
checking can make that window disappear - the file can change between the check and the read -
but a service can narrow the window from one request to one window, which is what this mapping
does: it records the device and inode at open time, and every window it hands out is preceded by
a stat that must agree.

That narrows the window; it does not close it, and the two methods part company after the guard.
``read()`` copies inside the guard, so the bytes it returns belong to the process and survive any
later change to the file. ``window()`` hands back a view into the mapping, which is still the
kernel's memory: the stat covered the moment the view was taken, not the moment it is read. A
view is safe only where the file cannot be truncated underneath it - a file that is replaced by
rename rather than rewritten, one held under a lock the writers respect, or a snapshot. Anything
else should call ``read()`` and pay for the copy.
"""
from __future__ import annotations

import mmap
import os

from .errors import Fault, MappingError, TruncatedFile, classify


class Mapping:
    """A read-only shared mapping with an identity check in front of every window."""

    def __init__(self, path: str) -> None:
        self.path = path
        self.fd = -1
        self.handle: mmap.mmap | None = None
        self.size = 0
        self.device = 0
        self.inode = 0
        self.views: list[memoryview] = []

    def open(self) -> "Mapping":
        if self.handle is not None or self.fd >= 0:
            raise RuntimeError(f"{self.path} is already mapped by this object")
        fd = os.open(self.path, os.O_RDONLY)
        try:
            info = os.fstat(fd)
            self.size = info.st_size
            self.device = info.st_dev
            self.inode = info.st_ino
            self.handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
        except BaseException:
            os.close(fd)
            self.size = 0
            self.device = 0
            self.inode = 0
            raise
        self.fd = fd
        return self

    def same_file(self) -> bool:
        """True while the path still names the inode this mapping was opened on."""
        try:
            info = os.stat(self.path)
        except OSError:
            return False
        return (info.st_dev, info.st_ino) == (self.device, self.inode)

    def check(self) -> None:
        """Raise TruncatedFile unless the path still holds the mapped inode at its full size."""
        try:
            info = os.stat(self.path)
        except OSError as exc:
            raise TruncatedFile(self.path, self.size, 0) from exc
        if (info.st_dev, info.st_ino) != (self.device, self.inode):
            raise TruncatedFile(self.path, self.size, info.st_size)
        if info.st_size < self.size:
            raise TruncatedFile(self.path, self.size, info.st_size)

    def _bounds(self, offset: int, length: int) -> None:
        """Refuse a window the mapping does not cover, and a read after the close."""
        if self.handle is None:
            raise ValueError("the mapping is closed")
        if offset < 0 or length < 0 or offset + length > self.size:
            raise ValueError(f"{offset}+{length} is outside a {self.size}-byte mapping")

    def window(self, offset: int, length: int) -> memoryview:
        """A zero-copy view, guarded when it is taken and not afterwards.

        The check runs first, and the view then points into the mapping itself. A file truncated
        after this call removes pages under the view, and reading one of them ends the process
        with SIGBUS: a stat before a view cannot protect a read that happens later. Keep the
        view only while the file cannot be truncated (replace-by-rename, a respected lock, a
        snapshot) - otherwise call read(), which copies inside the guard.
        """
        self.check()
        self._bounds(offset, length)
        view = memoryview(self.handle)[offset:offset + length]
        self.views.append(view)
        return view

    def read(self, offset: int, length: int) -> bytes:
        """The same window as bytes the process owns, copied inside the guard.

        Slicing the mapping returns a copy, so a read in a loop leaves nothing behind: a view is
        registered only for a caller that asked for one and keeps it. The copy happens while the
        stat is still fresh, so a truncate after the return cannot touch these bytes; a truncate
        that lands between the stat and the copy still raises SIGBUS, which is one copy wide
        rather than one request wide.
        """
        self.check()
        self._bounds(offset, length)
        return self.handle[offset:offset + length]

    def close(self) -> None:
        # A live memoryview keeps the map exported, and closing the map under it raises
        # BufferError, so the views this object handed out are released first.
        for view in self.views:
            try:
                view.release()
            except ValueError:
                pass
        self.views.clear()
        if self.handle is not None:
            self.handle.close()
            self.handle = None
        if self.fd >= 0:
            os.close(self.fd)
            self.fd = -1

    def __enter__(self) -> "Mapping":
        # open_mapping() already opened it; entering must not open a second mapping over the first.
        if self.handle is None and self.fd < 0:
            self.open()
        return self

    def __exit__(self, *exc_info) -> None:
        self.close()


def open_mapping(path: str) -> Mapping:
    """Open a mapping and let a refusal arrive as MappingError with a condition attached."""
    mapping = Mapping(path)
    try:
        return mapping.open()
    except (OSError, ValueError, MemoryError) as exc:
        fault = classify(exc)
        if fault is Fault.UNRELATED:
            raise
        raise MappingError(fault, path, str(exc)) from exc
Fault counters and the resident split, parsed from /proc. filemap/procstat.py
"""The two numbers /proc keeps about a process's pages: faults, and where the pages went.

A fault count is the only honest measure of what a mapping cost, and the resident-set split is the
only honest answer to "why is RSS as large as the file": RssFile is page cache the kernel can take
back, RssAnon is memory the process owns. Both parsers are separate functions so they can be
tested on a recorded line rather than on whatever this process happens to be doing.
"""
from __future__ import annotations

import os
import pathlib


def parse_stat(text: str) -> dict:
    """Minor and major faults from one /proc/PID/stat line."""
    # In the line, minflt is field 10 and majflt field 12; after the comm field the
    # indexing starts at the state, which makes them tail[7] and tail[9].
    tail = text.rsplit(")", 1)[1].split()
    return {"minor": int(tail[7]), "major": int(tail[9])}


def parse_status(text: str) -> dict:
    """The resident-set fields, in kilobytes, from one /proc/PID/status body.

    A kernel that does not report one of the four fields leaves it out of the result rather than
    reporting zero, so a caller can tell "not shown" from "no such memory".
    """
    out: dict[str, int] = {}
    for line in text.splitlines():
        key, _, value = line.partition(":")
        if key in ("VmRSS", "RssAnon", "RssFile", "RssShmem"):
            out[key] = int(value.split()[0])
    return out


def faults(pid: int | None = None) -> dict:
    """Fault counters for one process, this one by default, as absolute totals."""
    target = os.getpid() if pid is None else pid
    return parse_stat(pathlib.Path(f"/proc/{target}/stat").read_text(encoding="utf-8"))


def resident(pid: int | None = None) -> dict:
    """The resident set of one process, split by what the pages belong to."""
    target = os.getpid() if pid is None else pid
    return parse_status(pathlib.Path(f"/proc/{target}/status").read_text(encoding="utf-8"))
The copy path: blocks by size, one page by number. filemap/reader.py
"""Reading a file in pages without mapping it, so a caller has the copy-free path's control.

A page reader does one thing a mapping cannot: it never holds a page that no longer exists. Each
call hands back the bytes that were just copied, so truncation shortens the next read instead of
killing the process. The price is the copy, and these two functions are the whole of it.
"""
from __future__ import annotations

import os


def chunks(fd: int, size: int = 1 << 20):
    """Yield the file from its current position in blocks, reusing one read buffer.

    Each block is handed back as a new bytes object, so the caller owns what it gets and the
    buffer is not overwritten while the caller still holds the previous block.
    """
    if size <= 0:
        raise ValueError("chunk size must be positive")
    buffer = bytearray(size)
    view = memoryview(buffer)
    while True:
        count = os.readv(fd, [view])
        if not count:
            return
        yield bytes(view[:count])


def read_page(fd: int, index: int, page: int = 4096) -> bytes:
    """One page by number, short at the end of the file and empty past it."""
    if index < 0:
        raise ValueError("page index must not be negative")
    if page <= 0:
        raise ValueError("page size must be positive")
    offset = index * page
    buffer = bytearray(page)
    view = memoryview(buffer)
    position = 0
    while position < page:
        count = os.preadv(fd, [view[position:]], offset + position)
        if not count:
            break
        position += count
    return bytes(view[:position])
Files with known bytes, on the filesystem the tests run on. conftest.py
"""Fixtures: files whose bytes can be checked, on the filesystem the tests run on."""
from __future__ import annotations

import pathlib

import pytest


@pytest.fixture()
def folder(tmp_path: pathlib.Path) -> pathlib.Path:
    return tmp_path


@pytest.fixture()
def page_file(tmp_path: pathlib.Path) -> pathlib.Path:
    """Three pages of a known pattern, so a window can be checked byte for byte."""
    path = tmp_path / "pages.bin"
    path.write_bytes(bytes(range(256)) * 48)
    return path


@pytest.fixture()
def empty_file(tmp_path: pathlib.Path) -> pathlib.Path:
    path = tmp_path / "empty.bin"
    path.write_bytes(b"")
    return path
Every errno, the two ValueErrors, and the log line. test_errors.py
"""Classification: six refusals, one log line, and no retry table to get wrong."""
from __future__ import annotations

import errno

import pytest

from filemap.errors import Fault, MappingError, TruncatedFile, classify, describe


@pytest.mark.parametrize("number, expected", [
    (errno.ENOMEM, Fault.LIMIT),
    (errno.EACCES, Fault.PERMISSION),
    (errno.EPERM, Fault.PERMISSION),
    (errno.EINVAL, Fault.UNRELATED),
    (errno.ENOENT, Fault.MISSING),
    (errno.EIO, Fault.UNRELATED),
])
def test_errno_classes(number, expected):
    assert classify(OSError(number, "x")) is expected


def test_memory_error_is_the_mapping_limit():
    # The interpreter reports the kernel's ENOMEM as MemoryError when its own arena cannot grow.
    assert classify(MemoryError()) is Fault.LIMIT


@pytest.mark.parametrize("message, expected", [
    ("cannot mmap an empty file", Fault.EMPTY),
    ("mmap length is greater than file size", Fault.BEYOND_EOF),
    ("something else", Fault.UNRELATED),
])
def test_interpreter_refusals(message, expected):
    assert classify(ValueError(message)) is expected


def test_truncated_file_is_its_own_class():
    assert classify(TruncatedFile("/run/x", 10, 4)) is Fault.TRUNCATED


def test_a_missing_path_is_not_a_truncation():
    # Truncated means a live mapping lost pages; a path that never opened is a different answer.
    assert classify(OSError(errno.ENOENT, "x")) is Fault.MISSING
    assert classify(TruncatedFile("/run/x", 10, 0)) is not Fault.MISSING


def test_unknown_exception_is_unrelated():
    assert classify(RuntimeError("x")) is Fault.UNRELATED


def test_describe_carries_the_number_and_the_path():
    line = describe(OSError(errno.ENOMEM, "x"), "/run/map.bin")
    assert line == "filemap: limit (ENOMEM 12) on /run/map.bin"


def test_describe_names_the_class_for_a_value_error():
    line = describe(ValueError("cannot mmap an empty file"), "/run/empty.bin")
    assert line == "filemap: empty (ValueError) on /run/empty.bin"


def test_mapping_error_keeps_its_fault():
    error = MappingError(Fault.EMPTY, "/run/empty.bin", "cannot mmap an empty file")
    assert error.fault is Fault.EMPTY
    assert error.path == "/run/empty.bin"
    assert "empty" in str(error)


def test_truncated_file_reports_both_sizes():
    error = TruncatedFile("/run/x", 32768, 4100)
    assert (error.mapped, error.current) == (32768, 4100)
    assert "4100" in str(error)
The cap, the count, and the headroom shrinking by one. test_limits.py
"""The two limits: what the kernel allows, and how many mappings this process holds."""
from __future__ import annotations

import mmap

from filemap.limits import headroom, mapping_count, max_map_count


def test_max_map_count_is_a_positive_number():
    assert max_map_count() > 1024


def test_max_map_count_reads_a_file(tmp_path):
    path = tmp_path / "max_map_count"
    path.write_text("65530\n")
    assert max_map_count(path) == 65530


def test_mapping_count_counts_this_process():
    assert mapping_count() >= 1


def test_mapping_count_grows_with_a_mapping():
    before = mapping_count()
    handle = mmap.mmap(-1, 4096)
    try:
        assert mapping_count() == before + 1
    finally:
        handle.close()


def test_mapping_count_skips_the_pseudo_area(tmp_path):
    path = tmp_path / "maps"
    path.write_text("7f00-7f01 r-xp 00000000 00:00 0 [vdso]\n"
                    "7f01-7f02 rw-p 00000000 00:00 0\n"
                    "ffffffffff60-ffffffffff61 --xp 00000000 00:00 0 [vsyscall]\n")
    assert mapping_count(path=path) == 2


def test_headroom_allows_the_mapping_that_crosses_the_cap():
    assert headroom() == max_map_count() - mapping_count() + 1


def test_headroom_shrinks_by_one_per_mapping():
    before = headroom()
    handle = mmap.mmap(-1, 4096)
    try:
        assert headroom() == before - 1
    finally:
        handle.close()


def test_mapping_count_of_another_process():
    import os

    assert mapping_count(os.getpid()) == mapping_count()
Windows, truncation, unlink, replacement, and the BufferError. test_mapping.py
"""The mapping: its windows, its identity check, and the three ways a file leaves it behind."""
from __future__ import annotations

import os
import signal
import subprocess
import sys

import pytest

from filemap.errors import Fault, MappingError, TruncatedFile
from filemap.mapping import Mapping, open_mapping


def test_window_matches_the_file(page_file):
    with open_mapping(str(page_file)) as mapping:
        assert mapping.size == page_file.stat().st_size
        assert mapping.window(0, 16) == page_file.read_bytes()[:16]


def test_window_is_a_view_not_a_copy(page_file):
    with open_mapping(str(page_file)) as mapping:
        view = mapping.window(0, 4)
        assert isinstance(view, memoryview)
        assert bytes(view) == page_file.read_bytes()[:4]


def test_read_returns_bytes(page_file):
    with open_mapping(str(page_file)) as mapping:
        grabbed = mapping.read(4096, 8)
        assert isinstance(grabbed, bytes)
        assert grabbed == page_file.read_bytes()[4096:4104]


def test_a_view_is_not_guarded_after_the_call(page_file):
    # The guard covers the call that took the view, not the read that comes later; the page
    # under the view is gone, so reading it in this process would be the SIGBUS this whole
    # module is about. The child process takes the signal, and the assertion is the signal.
    script = (
        "import mmap, os, sys\n"
        "path = sys.argv[1]\n"
        "fd = os.open(path, os.O_RDONLY)\n"
        "handle = mmap.mmap(fd, 0, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)\n"
        "view = memoryview(handle)[0:8]\n"
        "os.truncate(path, 0)\n"
        "print(view[0], flush=True)\n"
    )
    result = subprocess.run([sys.executable, "-c", script, str(page_file)],
                            capture_output=True, text=True, timeout=60)
    assert result.returncode == -signal.SIGBUS, (result.returncode, result.stdout, result.stderr)


def test_a_read_copy_survives_the_truncate(page_file):
    # read() copies inside the guard, so the bytes it returns are the process's own: the file
    # can lose every page afterwards without touching them.
    with open_mapping(str(page_file)) as mapping:
        grabbed = mapping.read(0, 4096)
        os.truncate(page_file, 0)
        assert isinstance(grabbed, bytes)
        assert grabbed == bytes(range(256)) * 16


def test_window_past_the_end_is_refused(page_file):
    with open_mapping(str(page_file)) as mapping:
        with pytest.raises(ValueError):
            mapping.window(mapping.size - 1, 2)


@pytest.mark.parametrize("offset, length", [(-1, 4), (0, -4)])
def test_negative_window_is_refused(page_file, offset, length):
    with open_mapping(str(page_file)) as mapping:
        with pytest.raises(ValueError):
            mapping.window(offset, length)


def test_same_file_is_true_while_the_inode_lives(page_file):
    with open_mapping(str(page_file)) as mapping:
        assert mapping.same_file() is True


def test_truncation_is_caught_before_the_read(page_file):
    with open_mapping(str(page_file)) as mapping:
        os.truncate(page_file, 0)
        with pytest.raises(TruncatedFile) as caught:
            mapping.read(0, 1)
        assert caught.value.current == 0
        assert caught.value.mapped == mapping.size


def test_truncation_within_a_page_is_still_a_truncation(page_file):
    with open_mapping(str(page_file)) as mapping:
        os.truncate(page_file, 4100)
        with pytest.raises(TruncatedFile):
            mapping.check()


def test_unlink_is_caught_as_a_missing_identity(page_file):
    with open_mapping(str(page_file)) as mapping:
        os.unlink(page_file)
        assert mapping.same_file() is False
        with pytest.raises(TruncatedFile) as caught:
            mapping.check()
        assert caught.value.current == 0


def test_a_replaced_file_is_a_different_inode(page_file, tmp_path):
    other = tmp_path / "other.bin"
    other.write_bytes(b"z" * page_file.stat().st_size)
    with open_mapping(str(page_file)) as mapping:
        os.replace(other, page_file)
        assert mapping.same_file() is False
        with pytest.raises(TruncatedFile):
            mapping.check()


def test_growth_is_not_a_truncation(page_file):
    with open_mapping(str(page_file)) as mapping:
        with open(page_file, "ab") as writer:
            writer.write(b"n" * 4096)
        mapping.check()
        assert mapping.size == page_file.stat().st_size - 4096


def test_empty_file_refused_with_a_condition(empty_file):
    with pytest.raises(MappingError) as caught:
        open_mapping(str(empty_file))
    assert caught.value.fault is Fault.EMPTY


def test_missing_path_is_a_missing_file(tmp_path):
    with pytest.raises(MappingError) as caught:
        open_mapping(str(tmp_path / "absent.bin"))
    assert caught.value.fault is Fault.MISSING


def test_close_is_idempotent(page_file):
    mapping = open_mapping(str(page_file))
    mapping.close()
    mapping.close()
    assert mapping.handle is None
    assert mapping.fd == -1


def test_opening_twice_is_refused_instead_of_leaking(page_file):
    mapping = open_mapping(str(page_file))
    try:
        with pytest.raises(RuntimeError):
            mapping.open()
        assert mapping.fd >= 0
    finally:
        mapping.close()


def test_reopening_after_close_is_allowed(page_file):
    mapping = open_mapping(str(page_file))
    mapping.close()
    with mapping:
        assert bytes(mapping.read(0, 2)) == page_file.read_bytes()[:2]


def test_read_leaves_no_view_behind(page_file):
    # A read in a loop must not grow the view list; only a window the caller keeps is registered.
    with open_mapping(str(page_file)) as mapping:
        for _ in range(50):
            mapping.read(0, 4)
        assert mapping.views == []


def test_window_after_close_is_refused(page_file):
    mapping = open_mapping(str(page_file))
    mapping.close()
    with pytest.raises(ValueError):
        mapping.window(0, 1)
    with pytest.raises(ValueError):
        mapping.read(0, 1)


def test_context_manager_closes(page_file):
    with open_mapping(str(page_file)) as mapping:
        handle = mapping
    assert handle.handle is None


def test_entering_an_open_mapping_does_not_open_a_second(page_file):
    # The old __enter__ called open() again, replacing the descriptor and the mapping it held.
    mapping = open_mapping(str(page_file))
    descriptor, handle = mapping.fd, mapping.handle
    with mapping as entered:
        assert entered is mapping
        assert mapping.fd == descriptor
        assert mapping.handle is handle
    assert mapping.handle is None


def test_mapping_without_open_holds_nothing():
    mapping = Mapping("/nonexistent")
    assert mapping.handle is None
    assert mapping.size == 0
Recorded /proc lines, and this process’s own counters. test_procstat.py
"""The /proc parsers, tested on recorded lines and on this process."""
from __future__ import annotations

import os
import pathlib

from filemap.procstat import faults, parse_stat, parse_status, resident

STAT = ("4711 (python3) S 1 4711 4711 0 -1 4194560 1234 7 56 34 0 0 0 0 20 0 1 0 98765 "
        "18432000 4567 18446744073709551615")
STATUS = """Name:\tpython3
VmPeak:\t  204800 kB
VmSize:\t  195200 kB
VmRSS:\t    9876 kB
RssAnon:\t  1234 kB
RssFile:\t  8600 kB
RssShmem:\t  42 kB
"""


def test_stat_parses_the_fault_counters():
    assert parse_stat(STAT) == {"minor": 1234, "major": 56}


def test_stat_survives_a_name_with_spaces():
    line = STAT.replace("python3", "python3 helper")
    assert parse_stat(line)["minor"] == 1234


def test_status_parses_the_resident_split():
    parsed = parse_status(STATUS)
    assert parsed == {"VmRSS": 9876, "RssAnon": 1234, "RssFile": 8600, "RssShmem": 42}


def test_status_ignores_other_fields():
    parsed = parse_status("VmSize:\t 10 kB\nRssAnon:\t 4 kB\n")
    assert parsed == {"RssAnon": 4}


def test_faults_of_this_process_is_a_total():
    counts = faults()
    assert set(counts) == {"minor", "major"}
    assert counts["minor"] >= 0


def test_faults_grow_after_touching_new_memory():
    before = faults()["minor"]
    pages = [bytearray(1 << 20) for _ in range(4)]
    after = faults()["minor"]
    assert after > before
    assert len(pages) == 4


def test_faults_of_another_process():
    counts = faults(os.getppid())
    assert counts["minor"] >= 0


def test_resident_of_this_process_has_a_total():
    split = resident()
    assert split["VmRSS"] >= split["RssFile"]


def test_resident_of_another_process():
    split = resident(os.getppid())
    assert "VmRSS" in split


def test_reading_a_file_raises_rss_file():
    path = pathlib.Path(__file__).read_bytes()
    before = resident()["RssFile"]
    body = path[: 4 << 20]
    after = resident()["RssFile"]
    assert len(body) > 0
    assert after >= before
Blocks, pages, and a short read after a truncate. test_reader.py
"""The copy path: the same bytes, page by page, and nothing held after the call."""
from __future__ import annotations

import os

import pytest

from filemap.reader import chunks, read_page


def test_chunks_returns_the_whole_file(page_file):
    with open(page_file, "rb") as handle:
        body = b"".join(chunks(handle.fileno(), 1024))
    assert body == page_file.read_bytes()


def test_chunks_uses_the_block_size(page_file):
    with open(page_file, "rb") as handle:
        sizes = [len(block) for block in chunks(handle.fileno(), 4096)]
    assert sizes[-1] <= 4096
    assert all(size == 4096 for size in sizes[:-1])


def test_chunks_of_an_empty_file_is_nothing(empty_file):
    with open(empty_file, "rb") as handle:
        assert list(chunks(handle.fileno())) == []


def test_chunk_size_must_be_positive(page_file):
    with open(page_file, "rb") as handle:
        with pytest.raises(ValueError):
            list(chunks(handle.fileno(), 0))


def test_read_page_matches_the_file(page_file):
    body = page_file.read_bytes()
    with open(page_file, "rb") as handle:
        assert read_page(handle.fileno(), 1, 4096) == body[4096:8192]


def test_read_page_exactly_past_the_end_is_empty(page_file):
    body = page_file.read_bytes()
    with open(page_file, "rb") as handle:
        last = read_page(handle.fileno(), len(body) // 4096, 4096)
    assert last == b""


def test_read_page_past_the_end_is_empty(page_file):
    with open(page_file, "rb") as handle:
        assert read_page(handle.fileno(), 99) == b""


def test_read_page_rejects_a_negative_index(page_file):
    with open(page_file, "rb") as handle:
        with pytest.raises(ValueError):
            read_page(handle.fileno(), -1)


def test_read_page_rejects_a_zero_page_size(page_file):
    # A zero-size page would return b'' for every index and look like an empty file.
    with open(page_file, "rb") as handle:
        with pytest.raises(ValueError):
            read_page(handle.fileno(), 0, 0)


def test_a_truncated_file_shortens_the_next_page(page_file):
    with open(page_file, "rb") as handle:
        os.truncate(page_file, 100)
        assert read_page(handle.fileno(), 0, 4096) == page_file.read_bytes()

Keep reading

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