0055. mmap is an optional, SIGBUS-safe reader path
- Status: Accepted
- Date: 2026-10-31
- Plan: M6.2
- Review: Fast command-line tools first; extends ADR-0054
Context
Mapping a large file can avoid a copy, but a file truncated by another process raises SIGBUS on the next access, which must never kill a Harness program. The read path is already the product, and whether mapping wins is unmeasured.
Decision
Mapping is off unless HRT_MMAP_MIN=<bytes>
is set; the mmap-threshold experiment decides any
default. Only a File reader of a regular, non-empty
file at offset zero, at or above the threshold, maps. Pipes,
stdin, zero-size procfs files and any failed step stay on
read. fs.read never maps, because mapped
bytes could change beneath an immutable value. The interpreter
never maps.
The reader exposes windows of at most 1 MiB. Before each it
touches one byte per page, so a truncation faults in the reader's
own step, then re-fstats and clamps to the current
file size. Past the mapped size it continues with
read, so a file that grew behaves as on the read
path.
A SA_SIGINFO SIGBUS handler is installed by the
first mapping, not at startup. It uses only mmap and
sigaction and reads a static table. An address inside
a mapping gets anonymous zero pages over the rest of that mapping,
and execution resumes. Any other address restores
SIG_DFL and returns, so the fault kills normally.
macOS may raise SIGSEGV instead; it is handled behind
__APPLE__, unverified. Mappings stay until exit,
because a view may outlive the switch to read. At
most 64 stay mapped; later files use read.
Alternatives considered
- Always mmap — pipes cannot map, mapped pages
inflate
ru_maxrss, and many small files may lose; unmeasured. - Bare SIGBUS death — a concurrent truncation would kill a tool with no message.
- Mapping
fs.readresults — breaks value immutability. - Snapshotting mapped stream windows — copying each exposed window removes the zero-copy benefit; keep mapping opt-in with the mutation exception below.
Consequences
Mapped stream views are live file-backed memory, not immutable
snapshots. External in-place overwrites can change an already
exposed view, including a previously validated str;
validation happens at exposure, not on every use. Truncation after
exposure can zero bytes of the current view. These external
mutations are stated exceptions to value immutability and output
parity with read and the interpreter. Unmodified
files retain parity; fs.read and copied retained
values remain snapshots of the bytes read or copied.
Mutation stays memory-safe. A synchronized Linux test pins overwrite visibility in a live line without truncation, outside differential goldens. The truncation race itself cannot be forced, so tests cover truncation before a window is touched and faults during a scan, not truncation landing between touch and use.