ENOSPC errno 28: Full Blocks, Full Inodes, Deleted Files Still Open

Dark cover headed 'No space left on device': errno 28, 190,263 zero-byte files that used 0 blocks, a write that landed 8,192 of 65,536 bytes, a truncate that returned 32 MiB while the writer held the log, and 63 passing tests

TL;DR: Four Findings Before the Runbook

  • ENOSPC (errno 28) names a device, not a resource. On this host the same number meant no data blocks, no inodes, or blocks held by a file whose name was deleted while a process kept it open.
  • Inodes run out with the disk empty: 190,263 zero-byte files took every inode on a 16,384-block mount and used none of its data blocks, so df -h read 0.0% used while every new file failed.
  • A write lands what fits before it fails, and a buffered writer reports success until flush or close: a 65,536-byte write into 8,192 bytes of free space returned 8,192, while a 100-byte buffered write returned all 100 and put nothing on disk.
  • Deleting a held file frees nothing; emptying it through the writer returns the blocks. Only a writer opened with O_APPEND resumes at the start: one without it resumed at 4 MiB inside an empty file and left a hole, so the file claimed 4,194,404 bytes while holding 4,096. Finding the holder needs no extra package: section 4 reads /proc, 0.05 ms on the 14 descriptors this host had open.

Scope. One Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, uid 1000 without privilege. The filesystem filled here is a tmpfs mount of 64 MiB (size=65536k, 16,384 blocks of 4,096 bytes and 190,265 inodes), chosen because one call empties it again. A tmpfs sets that inode pool when the mount is created – half the RAM pages by default – so a reader’s mount will report a different count. The workspace is a virtiofs mount that reports 8 EiB of blocks and no inode count at all (df -i prints a dash there), so only the tmpfs could show either resource running out. No mount or user namespace is available to this user, so a second filesystem family was not measured: ext4 reserves 5% of its blocks for root, and a non-root writer cannot use them (f_bfree counts that reserve, f_bavail does not); XFS allocates inodes on demand; a network filesystem answers for a server. The inode behaviour in section 3, including the hard link this mount refused, is tmpfs’s: nothing here measures what ext4 or XFS would answer. EDQUOT is quoted rather than produced. Every arm ran 5 times, and the mount was restored to 16,384 free blocks after each. lsof, fuser and strace are absent on this host, so the descriptor scan in section 4 is built from /proc instead.

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

Find the line that matches the incident, make the one change on that row, and check the result against the measurement beside it rather than against the message text.

What you sawChange to make (and what measured it)
No space left on device, and df -h shows a few percent usedLook at inodes before anything else: df -i on the same mount. Filling this mount took 190,263 zero-byte files and no data blocks in 1,827 ms (section 3)
df -i is at 100% and no directory looks responsibleName the directory that holds them: du --inodes -x --max-depth=1 / | sort -rn | head. On a tree with 12,000 files in one directory it reported 12,001 – the files plus the directory – in 12.2 ms (section 3)
df -h and df -i both look healthy, and writes still failFind the descriptor that outlived its file name: a 32 MiB file deleted while open held 8,192 blocks until the process closed it (section 4)
A deploy replaced a binary and left a file that will not execute, or a config half writtenNever write the real name in place. Write beside it and rename, which takes no data block. cp and dd into 400 KiB of free space left 409,600 bytes of a 1,048,576-byte payload under the target name and exited non-zero (section 6)
A Python service lost its last log lines and reported the error much laterCheck where the exception surfaced, not where the data was lost. A default buffered write of 100 bytes returned 100 with no error and put 0 bytes on disk; the exception came at flush or close (section 2)
The log-rotation script deleted the log and free space did not moverm reclaimed 0 blocks while the writer held the file; truncate -s 0 through the writer’s own descriptor reclaimed 8,192 (section 4)
The log was emptied and ls now shows a huge file that du calls small: > is safe only for a writer opened with O_APPEND. One without it resumed at 4 MiB inside an empty file: the file then claimed 4,194,404 bytes and held 4,096. Restart the writer or make it seek to 0 after the emptying (section 4)
A backup or container copy filled the disk with a file that looked smallCopy sparse files with allocation in mind: cp --sparse=never allocated 12,288 blocks for a 48 MiB file that holds one byte, and --sparse=auto allocated 1 (section 5)
A job that preallocates its output still dies with the same errorfallocate reserves blocks immediately: it took 12,288 blocks up front, and with only 20 blocks free it failed leaving a 0-byte file. Ask statvfs first (section 8)
sed -i failed on a config file that then looked damagedOn this host sed -i exited 4 and left the original 1,048,576 bytes intact in 5 of 5 runs: the temp copy is what ran out (section 6)
touch, mkdir and truncate keep working while data writes failThose need an inode or a dentry, not a data block: all three succeeded at 0 free blocks, and truncate -s 8M produced an 8 MiB file with no blocks behind it (sections 3 and 6)
The message says No space left on device but a quota is the real causeRead the number, not the sentence: EDQUOT is errno 122 and ENOSPC is 28. This page could not produce a quota, so that row is quoted from errno(3) (section 7)
Table 1: twelve changes, matched to the sentence a reader has in front of them. Every row names the measurement behind it, and sections 2 to 8 carry the numbers.

1. What "No Space" Covers

The kernel returns one number for more than one shortage, and the manual pages put two of them in writing. Read the two sentences below side by side: the first is about room for data, the second about room for a file. That difference is what this page is built on – a file needs a name and an inode before it needs a single data block, and the kernel counts those separately.

The resourceWhat the manual saysWhat this host did
Data blocksThe device containing pathname has no room for the new dataA write kept the bytes that fit and failed after them: a 65,536-byte write landed 8,192 bytes and the next call returned errno 28 (section 2)
Inodes, and the names that point at themENOSPC pathname was to be created but the device containing pathname has no room for the new fileCreation failed after 190,263 files while 0 data blocks were in use and the mount still held 64 MiB (section 3)
Blocks nobody can nameNo manual sentence covers this state; the file is gone and the descriptor is notAn unlink reclaimed 0 blocks, and the close returned all 8,192 (section 4)
The limit that is not the filesystemerrno 27 is File too largeA process over its file-size limit was killed by signal 25 at 1,048,576 bytes, and with that signal ignored it got errno 27 instead (section 7)
Table 2: the resources behind one error number, the sentence that describes each, and the measurement that separated them here. Rows 1, 2 and 4 are quoted rules; row 3 is this host’s behaviour, because no page documents it.

Two consequences follow. The error is raised by a filesystem operation, so the caller has to know which one: a failed open says nothing about data blocks, and a failed write says nothing about inodes. And the sentence in the log is the same in every case, so the number and the timestamp are the only fields worth grepping.

2. How Much Lands Before the Error

A writer that assumes a failed write wrote nothing will lose data silently, because the kernel fills what it can. Each arm below left the mount with exactly two free blocks (8,192 bytes), or with none for the two buffered rows that needed an empty mount, and recorded every return value, the file’s size afterwards, and the errno of the call that failed.

The writeReturnedOn diskEnded with
one 65,536-byte write8,192 bytes, a short count8,192 bytesthe next write, errno 28
4,096-byte writes2 full calls8,192 bytesthe third call, errno 28
one byte at a time8,192 accepted bytes8,192 bytesthe next byte, errno 28
exactly 8,192 bytesthe full count8,192 bytesno error: the payload fitted
8,193 bytes, one overa short count8,192 byteserrno 28
buffered 1,048,576 bytesraised during write8,192 byteserrno 28
buffered 100 bytes, no space, flushed100 bytes, no error0 byteserrno 28 at flush
buffered 100 bytes, no space, closed100 bytes, no error0 byteserrno 28 at close
Table 3: eight write shapes, two free blocks except the two buffered rows with none, 5 runs each. All eight produced identical results in every run; the boundary rows are the two that decide how a writer must loop.

The pattern is not a rounding error. A single large write is answered with a short count, 12.5% of what was asked, and the error arrives on the following call. A writer that checks only for exceptions therefore reports success while most of its buffer never reached the file. The loop that survives this is the boring one:

"""The write loop from section 2, as a file so it can be run and tested."""

from __future__ import annotations
import errno


def write_all(handle, data: bytes) -> int:
    """Write every byte or raise. A short write is not an error; it is a partial success."""
    view = memoryview(data)
    written = 0
    while written < len(data):
        count = handle.write(view[written:])
        if not count:
            raise OSError(errno.ENOSPC, "write made no progress")
        written += count
    return written

The buffered rows are the ones that surprise a service. With no space, a 100-byte write returned the full count – the bytes were in the buffer – and the error appeared at the next flush, or at close when the application never flushed. On disk there was nothing in either case. A logging call that is expected to raise has to flush; a service that relies on the implicit flush at exit will lose the record and may not see the exception at all.

3. Full Inodes With an Empty Disk

The cleanest way to see the second resource is to fill the mount with files that hold nothing. Each run created empty files until the kernel refused, then looked at what statvfs and the tools said about a filesystem that had just run out.

What the run recordedValue
Inodes free, reported before the run190,263
Files created before the refusal190,263
Files the free inode count predicted, minus what was created0
Data blocks consumed by those files0
df -h used, as blocks0.0%
Inodes left0
Time for the whole run1,827.3 (1,415.6–2,185.1 ms)
Time per file9.60 (7.4–11.5 µs)
Table 4: filling every inode on a 64 MiB mount, 5 runs. The prediction from statvfs was exact in every run, and the block counter never moved.

The prediction is the useful part. statvfs reports free inodes for the same reason it reports free blocks, so a monitor can watch both without creating anything, and here the number of files the mount would still accept was correct to the file. df -h meanwhile described a filesystem that was 0.0% used, because it counts blocks and there were no blocks to count.

With creation failing, the operations that need no new inode still worked – which is exactly the split a deploy or a log rotation cares about.

Operation, with every inode takenWorkedErrno
create a new file0 of 528
mkdir0 of 528
write 1,048,576 bytes to a file that already exists5 of 5–
rename an existing file5 of 5–
hard-link an existing file0 of 528
unlink one file to make room5 of 5–
create a file after that unlink5 of 5–
Table 5: what still answers at zero free inodes on this tmpfs, 5 attempts per operation. The write to an existing file consumed 256 blocks while no file could be created.

That last row changes the advice here. The usual fix for a partially written file – write a temporary file, rename it – fails at the step that creates the temporary file, because a new file needs an inode; sed -i edits a sibling copy and fails the same way. What remains possible is the opposite shape: write into a file that already exists, then rename over the name. A deploy that keeps a spare empty file per target survives an inode shortage that breaks every tool which creates its own.

The hard-link row is this mount’s answer, not a general law. tmpfs charges a directory entry to its inode pool, so a second name for an existing inode was refused in every run; a filesystem that keeps directory entries in data blocks may accept the same command with no inode to spare. Nothing here measures that case.

Once the pool is empty, df -i says so and stops: it reports the mount, not the directory that filled it. GNU du --inodes counts files and directories per directory, so the pipeline below names the directories that hold the most, and a find that prints each file’s parent answers the same question where du has no --inodes. On a tree built for this measurement – 12,000 files in one directory, 3,000 in a nested one, 250 in a third – du reported 12,001, 3,002 and 251, each count the files plus the directory itself, and 15,255 for the tree against the 15,250 files that were created. find reported the file counts alone and finished in 11.4 ms; du took 12.2 ms. On this host’s /usr mount the same one-liner named /usr/local with 1,170 inodes and counted 2,175 in 22.4 ms.

# Which directories hold the inodes on one mount, largest first.
du --inodes -x --max-depth=2 / | sort -rn | head -20

# The same question without --inodes: count each file's parent directory.
find / -xdev -type f -printf '%h\n' 2>/dev/null | sort | uniq -c | sort -rn | head -20

4. Space With No Name

The third state has no built-in error of its own: the disk is full because of a file that df counts and no directory lists. A process opened a 32 MiB file and unlinked it; the inode stays alive while the descriptor is open, and so do its blocks.

Momentrm while the writer holds ittruncate -s 0 through the descriptor
free blocks after the file was written8,1928,192
free blocks right after the action8,19216,384
blocks the action reclaimed08,192
free blocks after the writer appended 1 MiB7,93616,128
apparent size the writer now holds33 MiB1 MiB
free blocks after the descriptor closed16,38416,128
Table 6: the same 32 MiB log, removed one way and emptied the other, 5 runs each. Every value was identical in every run.

The unlink arm is the incident: the file disappeared from ls, the directory walk found 0 files and 0 allocated bytes, and the mount stayed as full as before – then the writer appended a megabyte and made it worse. The truncate arm is the fix: the blocks came back before any process was restarted, and the writer kept its descriptor and kept appending to a file that started from zero again.

That fix works because the writer in this probe opened its log with O_APPEND. The emptying itself – : > file in a rotation script, or truncate -s 0 – resets the file’s size, not the writer’s position. A writer that opened the log without O_APPEND keeps the offset it had reached, and its next line lands there, past the end of an empty file. The bytes in between are a hole: they read back as zeros, they count in the apparent size, and they cost no blocks.

The writer’s descriptorFirst line lands atApparent sizeAllocatedBytes at 1 MiB
opened with O_APPEND0100 B4,096 Bpast the end
opened without it4,194,3044,194,404 B4,096 B8 zeros
without it, then seeking to 00100 B4,096 Bpast the end
Table 7: one 4 MiB log emptied with : > while a writer held it, then one 100-byte line, 5 runs each and every value identical. The middle row is the trap: a file of 4,194,404 bytes that occupies 4,096.

The middle row is why du and ls disagree after a careless rotation. ls shows a multi-megabyte log, du shows one block, and anything that reads the file from the start – a log shipper, cp, a checksum – reads megabytes of zeros. The emptying still returns the blocks: 1,023 of them in every arm, all but the one the surviving line occupies. Two repairs, both cheap: open the log with O_APPEND (Python’s 'a' mode does), or have the writer seek to 0 after the emptying. Only the writer can move its own descriptor, so a service that cannot be changed and does not append is better restarted than emptied.

Finding the holder needs no extra package, because /proc already lists it: every open descriptor is a symlink whose target gains a (deleted) suffix when the name goes. The scan is cheap enough to run at the top of an incident – 0.05 ms for the descriptors of the process that held the file in this measurement, and 0.05 ms across all 14 descriptors this host had open. That second number is a sandbox’s: the loop reads every process this user may see, so it grows with the host. Behind a child process holding 4,000 descriptors the same scan took 5.85 ms, or 1.45 µs per descriptor over the baseline; with 1,000 it took 1.57 ms. A production host with a hundred thousand open descriptors should expect a fraction of a second, not the milliseconds quoted here. The package’s version of the same scan, which also checks each candidate’s device, is timed in section 8.

# Every descriptor whose file name is gone, with the process that holds it.
sudo find /proc/[0-9]*/fd -lname '* (deleted)' -printf '%p -> %l\n' 2>/dev/null

# The same, for one filesystem only: follow each link to the inode's device.
dev=$(stat -c %d /var/log)
find /proc/[0-9]*/fd -lname '* (deleted)' -printf '%p\n' 2>/dev/null |
while read -r fd; do
  [ "$(stat -Lc %d "$fd" 2>/dev/null)" = "$dev" ] && printf '%s -> %s\n' "$fd" "$(readlink "$fd")"
done

The find command is the one to keep: -lname lets the kernel do the filtering, and the device check keeps a busy host’s output to the mount being examined. Neither loop needs lsof, which is absent on the host measured here.

5. Apparent Size Against Allocated Blocks

A file’s size and the space it occupies are two different numbers, and almost every tool prints the first. That gap is how a 48 MiB file travels as 1 block and lands as 12,288.

How the file was madeApparent sizeAllocatedBlocks taken
truncate -s 48M50,331,648 B0 B0
then one byte written half way in50,331,648 B4,096 B1
posix_fallocate of the same size50,331,648 B50,331,648 B12,288
cp --sparse=auto of the file above50,331,648 B4,096 B1
cp --sparse=never of the same file50,331,648 B50,331,648 B12,288
posix_fallocate with only 20 blocks free0 B0 B0
Table 8: five ways to produce one 48 MiB file, 5 runs each, all identical. The last row is the failure mode of preallocation: no partial reservation is left behind.

The first two rows are the same file before and after one byte is written: the apparent size never moves, the allocation goes from 0 to 4,096 bytes, and one block for that single byte is all the file has. That is what makes a sparse file useful and dangerous at once – it can be listed, checksummed and transferred at its apparent size by anything that does not ask the filesystem. fallocate asks for the blocks immediately, 12,288 times the space of the sparse file, and fails cleanly when the space is not there.

The two copy rows are the same payload through different intentions. The default copies holes as holes; --sparse=never writes every zero, which turns a one-block file into 12,288 blocks. When a backup fills a disk that the source never filled, this is usually the line to look for, and the fix is the flag rather than a bigger disk.

6. What the Tools Do and What They Leave

Every arm below started from a mount with zero free blocks, except the three that began with 400 KiB free to show what a partial write leaves behind. Each held one 1,048,576-byte payload to copy and one file of the same size to edit. The third column is the file left under the target name afterwards, which is the part that decides whether the next start reads a working file.

ToolExitLeft behindWhat it printed
dd bs=64k count=16, no space10 Bdd: error writing 't': No space left on device
dd bs=64k count=16, 400 KiB free1409,600 Bdd: error writing 't': No space left on device
cp payload t, no space10 Bcp: error copying 'payload' to 't': No space left on device
cp payload t, 400 KiB free1409,600 Bcp: error copying 'payload' to 't': No space left on device
tee t, no space10 Btee: t: No space left on device
cat payload > t10 Bcat: payload: No space left on device
install -m 75510 Binstall: error copying 'payload' to 't': No space left on device
sed -i on a 1 MiB file41,048,576 B, unchangedsed: couldn't write 1048577 items to ./sedXXXXXX: No space left on device
truncate -s 8M t08,388,608 Bnothing
fallocate -l 8M t10 Bfallocate: fallocate failed: No space left on device
touch t00 Bnothing
mkdir d0a directorynothing
mv existing renamed01,048,576 Bnothing
open(...,'wb'), 1 MiB, buffered00 Bwrite 28 / close ok
open(...,'wb',buffering=0), 1 MiB00 Bwrite 28 / close ok
the same, unbuffered, 400 KiB free0409,600 Bwrite returned 409600 / close ok
Table 9: 16 ways to write into a full mount, 5 runs each. 9 exited non-zero and 3 of those left a file behind: dd and cp at 409,600 bytes of the payload, sed its original 1,048,576 bytes unchanged. The other 7 returned zero, either because they needed no data block or because the caller caught the error.

Read the third column rather than the second. dd and cp stopped with an error and left 39.1% of the payload in place, under the name a start script would use; with no space at all they left a zero-byte file instead, a different failure with the same name. install stopped the same way cp did at zero free space, and tee reported the error and left nothing, because it writes as it reads.

The wording in the last column is worth taking literally, because one tool can print two shapes for the same errno. This host runs GNU coreutils 9.7: cat names the input file when both ends are regular files and the kernel does the copy through copy_file_range, which is where cat: payload: comes from, and reports cat: write error only when it moves the bytes itself, as it must for a pipe or a device. cp splits the same way: error copying 'payload' to 't' is the kernel copy failing and error writing '/dev/full' is its own write loop, so a log rule that matches one shape will quietly miss the other.

Two tools came out of the full mount better than expected. sed -i exited 4 – its own code for a failed write – and the file it was asked to edit still held its 1,048,576 bytes, unchanged in 5 of 5 runs, because the edit happens on a copy that never replaced the original. truncate succeeded outright: an 8,388,608-byte file with no block behind it is free. Anything that verifies a file by its size alone will be fooled by both.

The Python rows show the difference between raising and telling. Both buffered and unbuffered writes hit errno 28 with no space, and the process exited 0 because the script caught the exception. With 400 KiB free the unbuffered write returned 409,600 of 1,048,576 bytes and raised nothing: 39.1% of the payload was written, and the call looked like a success to any code that only wraps it in try.

set -eu
target=/srv/app/bin/service
staged="$target.new.$$"

# Write beside the target, check the bytes, and only then take the name.
install -m 755 "$release/service" "$staged"
test "$(stat -c %s "$staged")" -eq "$(stat -c %s "$release/service")"
mv -f "$staged" "$target"      # rename: no data block, no inode, no partial name

# A log a process still holds is emptied, never removed - and only a writer that opened it
# with O_APPEND resumes at the start. Any other writer keeps its old offset and leaves a hole
# that ls counts and du does not; restart it, or make it seek to 0 after the emptying.
: > /var/log/app/service.log

That script is the whole of section 6 on one screen: the staged name can fail without consequence, the size check catches a short copy, and the rename is the only step that touches the live name. It also needs one inode for the staged file, which is why section 3’s shape – write into a file that already exists, then rename over the target – is the one to reach for when inodes, not blocks, are what ran out.

7. The Two Errors Next Door

Two other numbers arrive in the same kind of log line and lead to different work. One is the file-size limit, which is per process and has nothing to do with free space; the other is a quota, which is per user or project and does not appear in df at all. The first can be produced here, the second cannot, so this section measures one and quotes the other.

The writeExitWhat happened
write of 4 KiB to /dev/full0write 28 / close ok
buffered 100 bytes to /dev/full0write returned 100 / close 28
printf x > /dev/full1sh: 1: printf: printf: I/O error
dd 4 KiB to /dev/full1dd: error writing '/dev/full': No space left on device
cp 1 MiB file to /dev/full1cp: error writing '/dev/full': No space left on device
file-size limit reached, signal at its default-25killed by signal 25 after 1,048,576 bytes
the same limit, with that signal ignored0inherited 1 / write 27 after 1048576
ulimit -f 1024 then dd 2 MiB153signal 25, message File size limit exceeded
Table 10: the device that always answers ENOSPC, and a per-process limit that answers twice. 5 runs per row; the two limit rows are the ones that depend on a signal disposition.

The limit rows are worth reading twice. With the signal at its default the process is killed at the boundary, and the exit status carries the signal rather than an error code – -25 from a Python child, 153 from a shell that reports signal 25 with its 128 offset. With the signal ignored the write returns 27 once the file has reached 1,048,576 bytes. The same code can die or return depending on what its parent did with that signal before it started.

NumberNameMeansHow this page knows
28ENOSPCNo space left on devicemeasured: blocks, inodes, a held file, and /dev/full (sections 2 to 4, 7)
27EFBIGFile too largemeasured against a file-size limit (this section)
122EDQUOTDisk quota exceededquoted from errno(3); no quota could be produced on this host
25SIGXFSZthe signal raised with the size limitmeasured: an exit status of signal plus the shell’s 128 offset
Table 11: four numbers that reach the same log line. Only three of them could be produced here, and the table says which.

There is one more place worth checking before blaming the disk: in a container the writable layer is its own filesystem with its own free blocks, an overlay mount can fill only its upper layer, and a read-only mount answers errno 30 (EROFS) instead of 28. On this host an attempt to change a kernel setting returned 13 rather than a filesystem error – a reminder that the errno belongs to the operation, and the permission check may come first.

8. A Ten-Second Audit

The package below is the checks of this page as functions. Each row is a call measured against the same 64 MiB mount, so the cost of asking is a number rather than a guess.

CallCostWhat it did
space(path), 1000 calls2.13 µs per callread statvfs: both resources, no file created
deleted_open, whole /proc, one 32 MiB hold0.14 msfound the held file, 33,554,432 bytes reported
ensure_free, 1 MiB asked, 2 blocks free45.2 µsraised InsufficientSpace with errno 28 and created nothing
truncate_in_place on a held 32 MiB log1.28 msreclaimed 8,192 blocks while the writer held it
a 1-byte writability probeone block while it exists1 block used, 0 after removal
Table 12: the audit calls and their cost on this host, 5 runs each. The scan row is measured with the 14 descriptors this sandbox had open and grows with the host’s count (section 4); the probe row is the reason the package asks statvfs instead, because a probe consumes what it measures.
Write, with 2 free blocks and 1 MiB to writeErrnoTarget afterwardsTemporary fileBlocks after
open(...,'wb') and write288,192 B–0
atomic_write(ensure=True)28none02
atomic_write(ensure=False)28none02
Table 13: the same 1 MiB write against the same two free blocks, three ways. The plain write leaves a partial file and takes both blocks; both atomic paths leave the mount as they found it.

The two atomic rows differ in where the decision is made, not in the outcome. Without ensure the failure comes from the kernel during the write, the temporary file is removed, and the target is untouched – correct, but late. With it, statvfs is read first and the write never starts. On a mount that is full but still has inodes, both are safe; on the inode-exhausted mount of section 3 the temporary file cannot be created at all, and only the in-place shape from section 6 works.

9. The Runbook for the First Ten Minutes

  1. Name the resource. df -h and df -i on the mount, in that order. Blocks near 100% and inodes near 100% look the same in a log and are different incidents; on this mount inode exhaustion happened at 0.0% block use. If it is the inode pool, du --inodes -x --max-depth=1 / | sort -rn | head names the directories holding it (section 3).
  2. Find what has no name. Scan /proc for descriptors ending in (deleted) before deleting anything else: a 32 MiB hold is invisible to du and to the directory listing, and closing or truncating it is the cheapest space on the host.
  3. Empty the holders you may empty. Restart the writer, truncate the file through /proc/<pid>/fd/<n>, or close the descriptor: the blocks return as soon as the last reference goes. Removing the name of a log whose writer will keep running frees nothing, and the space is then invisible to the next person on the host.
  4. Count before you retry. A failed write may have written part of its payload: compare the target’s size with the source before rerunning, as in the 409,600-byte residue from section 6.
  5. Prefer rename to write. A rename takes no data block, so it works on a full mount and even at zero free inodes; an in-place write does not.
  6. Empty logs in place, never remove them – and check the writer’s open mode. A writer opened with O_APPEND resumes at the start and the mount gets its 8,192 blocks back immediately. A writer without it keeps its old offset and leaves a hole (section 4): restart it, or make it seek to 0.
  7. Check the copies. A backup, a container image or a cp into a staging directory can multiply a file by 12,288; look for the flag before looking for a bigger disk.
  8. Leave headroom and a timer. Ask statvfs on both resources, refuse writes under a floor, and set the floor from the largest file the service writes: 45.2 µs is what the check costs.

Steps three and four are the only ones that need judgement about content, and both are cheaper when the report in section 8 was already being written to a log every minute. The measurements above are the argument for the reserve: every case reached zero free before anything was watching, and none of them had to.

10. The Package, and What It Does Not Do

The three questions of section 8 are the whole of spaceguard, 2 modules and 255 non-blank lines, with 63 tests. It needs Python 3.8 or newer on Linux and nothing else: no root, no lsof, no mount option.

"""The audit from section 8, as a file so it can be run against a real path."""

from __future__ import annotations
import spaceguard


def audit(path: str) -> dict:
    """Print both resources and the holders, and return the report for a log line."""
    state = spaceguard.verdict(spaceguard.space(path))
    print(state.kind, "-", state.detail)
    payload = spaceguard.report(path)
    print(payload["held_count"], payload["held_bytes"])
    return payload

verdict answers the question the log line cannot, and report names the holders without listing any other process’s descriptors. The verdict function is pure – it takes a Space and returns a named tuple – so the decision can be tested without a full disk, which is why 63 tests run in a fraction of a second in 1 file of 267 non-blank lines.

What it deliberately does not do

It does not delete anything. Every function returns numbers, or writes one file the caller named; nothing walks a directory looking for space to reclaim, because the file that looks safe to remove is usually held open by the process that caused the incident. It reads the blocks this user may allocate (f_bavail), not the total the filesystem calls free, so on ext4 it refuses inside the 5% reserved for root, and it treats a mount that reports no inode count (this host’s virtiofs mount does) as having no inode limit. On a host with hidepid the scan reports what it can see, and says how many descriptors it read. It cannot produce the quota error: nothing here measures EDQUOT.

Questions This Page Answers

Is ENOSPC always a full disk?

No. It is the error for any resource that mount cannot supply: data blocks, inodes, or a file-size limit in the neighbouring number. Here 190,263 zero-byte files produced it with all 64 MiB free, and /dev/full produces it with nothing to fill.

Why does df show free space while writes fail?

Because df prints blocks. The inode count is a separate limit, printed by df -i; at the point every inode was taken the block counter was at 0.0% and creation failed with errno 28.

How much of a write reaches the disk before it fails?

As much as fits, in the same call. A 65,536-byte write into 8,192 bytes returned 8,192, and the error came on the next call. Loop until the return value accounts for every byte.

Does Python’s write() raise, or return a short count?

Both, depending on the buffering. An unbuffered write returns the count that reached the file – 409,600 of 1,048,576 in section 6 – while a buffered one can return the full count and raise at flush or close.

I deleted the log file and the disk is still full. Why?

A process still holds the descriptor, so the inode and its blocks stay allocated. rm reclaimed 0 blocks in the measurement; truncating the file through its own descriptor reclaimed 8,192 immediately.

Does emptying a log with : > punch a hole in it?

Only for a writer that did not open the file with O_APPEND. In the measurement that writer kept its 4,194,304 offset, so the next 100 bytes landed there and the file claimed 4,194,404 bytes while occupying 4,096; a writer opened with O_APPEND resumed at 0. Empty through the writer, or make it seek to 0.

Which directory is using all the inodes?

du --inodes -x --max-depth=1 / | sort -rn | head prints the directories with the most inodes: on a tree with 12,000 files in one directory it reported 12,001, the files plus the directory. Where du has no --inodes, find -xdev -type f -printf '%h\n' | sort | uniq -c | sort -rn counts each file’s parent instead.

How do I find a deleted file that is still open without lsof?

Read /proc/<pid>/fd: every open descriptor is a symlink, and the target of one whose name was removed ends in (deleted). On this host the scan took 0.14 ms with one 32 MiB file held, and grows with the number of descriptors the host has open.

Can I write a file atomically when the disk is full?

Yes, if its target already exists: a rename takes no data block, so it works at zero free blocks and at zero free inodes, where both were measured. Creating the temporary file is the step that needs an inode, so keep one per target if the mount is inode-bound.

Does truncate -s allocate the space?

No. Truncating to 48 MiB allocated 0 blocks and consumed no free space; fallocate on the same size allocated 12,288 blocks, and du reports the allocated number while ls -l reports the size.

Is EFBIG the same as ENOSPC?

No. EFBIG is errno 27 and belongs to a file-size limit: it appeared at 1,048,576 bytes with a 1 MiB limit, and with the signal at its default the process was killed by signal 25 instead of returning the number.

What about a quota?

A quota answers errno 122, Disk quota exceeded, which is a different number from ENOSPC. This host has no quotable filesystem, so that row is quoted from errno(3) rather than measured here.

Take the next step

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.

Appendix: Every File Behind the Numbers

The package, its tests, and the 12 probes that produced every number in this page, each printed whole so the article and the tree can be compared line by line. The probes restore the mount to 16,384 free blocks when they finish.

The package’s public surface. __init__.py
"""spaceguard - decide whether a full disk is out of space or out of names, and write safely.

The three questions this package answers, in the order an incident asks them:

1. Which resource ran out - data blocks or inodes - from statvfs, before touching the disk.
2. Who is holding space that has no name, from /proc, without lsof.
3. How to replace a file without ever leaving a half-written one under the real name.

Python 3.8+ on Linux. Nothing here needs root, a mount option, or an external binary.
"""

from .disk import (
    Held,
    InsufficientSpace,
    Space,
    atomic_write,
    deleted_open,
    ensure_free,
    fmt_bytes,
    held_bytes,
    report,
    space,
    truncate_in_place,
    verdict,
)

__all__ = [
    "Held",
    "InsufficientSpace",
    "Space",
    "atomic_write",
    "deleted_open",
    "ensure_free",
    "fmt_bytes",
    "held_bytes",
    "report",
    "space",
    "truncate_in_place",
    "verdict",
]
__version__ = "1.0.0"
statvfs, the descriptor scan, and the two writes. disk.py
"""The measurements and the two writes, as small as the job allows."""
from __future__ import annotations

import errno
import os
import pathlib
import tempfile
from dataclasses import dataclass
from typing import Iterable, NamedTuple

PROC = "/proc"


class InsufficientSpace(OSError):
    """Raised before a write that statvfs says cannot fit, with the numbers that decided it."""

    def __init__(self, message: str, free_bytes: int, needed_bytes: int) -> None:
        super().__init__(errno.ENOSPC, message)
        self.free_bytes = free_bytes
        self.needed_bytes = needed_bytes


@dataclass(frozen=True)
class Space:
    """The two resources a filesystem can run out of, as statvfs reports them.

    ``blocks_free`` is statvfs's f_bfree, which on ext4 still counts the blocks reserved for
    root; ``blocks_available`` is f_bavail, the blocks this user may actually allocate. The
    second is optional so a hand-built Space (in a test) can name only the first.
    """

    block_size: int
    blocks_total: int
    blocks_free: int
    inodes_total: int
    inodes_free: int
    blocks_available: int | None = None

    @property
    def available_blocks(self) -> int:
        """Blocks this user may allocate: f_bavail, or f_bfree when no reserve was reported."""
        return self.blocks_free if self.blocks_available is None else self.blocks_available

    @property
    def free_bytes(self) -> int:
        return self.block_size * self.blocks_free

    @property
    def available_bytes(self) -> int:
        """Bytes this user may write: the number a floor has to be compared against."""
        return self.block_size * self.available_blocks

    @property
    def total_bytes(self) -> int:
        return self.block_size * self.blocks_total

    @property
    def used_bytes(self) -> int:
        return self.total_bytes - self.free_bytes

    @property
    def block_percent_used(self) -> float:
        if not self.blocks_total:
            return 0.0
        return 100.0 * (self.blocks_total - self.blocks_free) / self.blocks_total

    @property
    def inode_percent_used(self) -> float:
        if not self.inodes_total:
            return 0.0
        return 100.0 * (self.inodes_total - self.inodes_free) / self.inodes_total


class Verdict(NamedTuple):
    """What statvfs says is exhausted, and how much of each resource is left."""

    kind: str
    available_bytes: int
    inodes_free: int
    detail: str

    @property
    def exhausted(self) -> bool:
        return self.kind != "ok"


def space(path) -> Space:
    """Read one path's filesystem, without creating anything on it."""
    stat = os.statvfs(path)
    return Space(
        block_size=stat.f_frsize,
        blocks_total=stat.f_blocks,
        blocks_free=stat.f_bfree,
        inodes_total=stat.f_files,
        inodes_free=stat.f_ffree,
        blocks_available=stat.f_bavail,
    )


def verdict(measured: Space, block_floor: int = 0, inode_floor: int = 0) -> Verdict:
    """Name the resource that is at or under its floor. Pure, so it can be tested off-disk.

    The block test uses the blocks this user may allocate, so a reserve that only root may
    touch cannot make the answer 'ok' just before a non-root write fails.
    """
    blocks_left = measured.available_blocks
    blocks_out = blocks_left <= block_floor
    inodes_out = bool(measured.inodes_total) and measured.inodes_free <= inode_floor
    if blocks_out and inodes_out:
        kind = "both"
        detail = f"{blocks_left} blocks and {measured.inodes_free} inodes left"
    elif blocks_out:
        kind = "blocks"
        detail = (f"{blocks_left} blocks ({fmt_bytes(measured.available_bytes)}) left, "
                  f"{measured.inodes_free} inodes left")
    elif inodes_out:
        kind = "inodes"
        detail = (f"{measured.inodes_free} inodes left while "
                  f"{fmt_bytes(measured.available_bytes)} of blocks are free")
    else:
        kind = "ok"
        detail = (f"{blocks_left} blocks ({fmt_bytes(measured.available_bytes)}) and "
                  f"{measured.inodes_free} inodes left")
    return Verdict(kind, measured.available_bytes, measured.inodes_free, detail)


def fmt_bytes(count: float) -> str:
    """Bytes the way df prints them, base 1024, one decimal from KiB up."""
    for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
        if abs(count) < 1024 or unit == "TiB":
            return f"{count:.0f} {unit}" if unit == "B" else f"{count:.1f} {unit}"
        count /= 1024
    return f"{count:.1f} TiB"


class Held(NamedTuple):
    """One descriptor pointing at a file whose name is already gone."""

    pid: int
    fd: int
    path: str
    size: int
    device: int

    @property
    def name(self) -> str:
        suffix = " (deleted)"
        return self.path[:-len(suffix)] if self.path.endswith(suffix) else self.path


def deleted_open(proc: str = PROC, device: int | None = None,
                 pid_filter: Iterable[int] | None = None) -> list[Held]:
    """Find descriptors whose target ends in ' (deleted)', the way lsof +L1 would.

    A descriptor on another filesystem is kept only when its device matches, because the
    question being asked is usually 'who is holding space on this mount'.
    """
    wanted = set(pid_filter) if pid_filter is not None else None
    found: list[Held] = []
    for entry in os.scandir(proc):
        if not entry.name.isdigit():
            continue
        pid = int(entry.name)
        if wanted is not None and pid not in wanted:
            continue
        directory = os.path.join(proc, entry.name, "fd")
        try:
            names = os.listdir(directory)
        except OSError:            # a pid that exited, or a process this user cannot read
            continue
        for name in names:
            link = os.path.join(directory, name)
            try:
                target = os.readlink(link)
                if not target.endswith(" (deleted)"):
                    continue
                stat = os.stat(link)
            except OSError:
                continue
            if device is not None and stat.st_dev != device:
                continue
            found.append(Held(pid, int(name), target, stat.st_size, stat.st_dev))
    return found


def held_bytes(holds: Iterable[Held]) -> int:
    """Total apparent size of the held files, which is not always what the blocks hold."""
    return sum(hold.size for hold in holds)


def ensure_free(path, needed: int, reserve: int = 0,
                measured: Space | None = None) -> Space:
    """Refuse a write statvfs says will not fit, before any descriptor is created.

    The comparison is against f_bavail, not f_bfree, so the 5% ext4 keeps for root is not
    counted as room a service may write into.
    """
    current = measured if measured is not None else space(path)
    if current.available_bytes < needed + reserve:
        raise InsufficientSpace(
            f"{fmt_bytes(current.available_bytes)} available on {path}, "
            f"{fmt_bytes(needed)} needed"
            + (f" plus a {fmt_bytes(reserve)} reserve" if reserve else ""),
            current.available_bytes, needed)
    return current


def atomic_write(path, data: bytes, mode: int = 0o644, fsync: bool = True,
                 ensure: bool = False, reserve: int = 0) -> int:
    """Write beside the target and rename over it, so the name never shows a partial file.

    With ensure=True the write is refused up front when statvfs says the data cannot fit,
    which turns a half-written file into an exception before the first byte is written.
    """
    target = pathlib.Path(path)
    parent = target.parent
    if ensure:
        ensure_free(parent, len(data), reserve=reserve)
    handle, temporary = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=parent)
    try:
        with os.fdopen(handle, "wb") as stream:
            written = stream.write(data)
            stream.flush()
            if fsync:
                os.fsync(stream.fileno())
        os.chmod(temporary, mode)
        os.replace(temporary, target)
    except BaseException:
        try:
            os.unlink(temporary)
        except OSError:
            pass
        raise
    return written


def truncate_in_place(path, size: int = 0) -> int:
    """Empty a file through its own descriptor, which frees blocks even while it is held."""
    with open(path, "r+b") as stream:
        stream.truncate(size)
        stream.flush()
        os.fsync(stream.fileno())
    return size


def report(path) -> dict:
    """One dictionary for a log line: both resources, the verdict, and the held descriptors."""
    measured = space(path)
    state = verdict(measured)
    device = os.stat(path).st_dev
    holds = deleted_open(device=device)
    return {
        "path": str(path),
        "kind": state.kind,
        "detail": state.detail,
        "free_bytes": measured.free_bytes,
        "available_bytes": measured.available_bytes,
        "blocks_free": measured.blocks_free,
        "blocks_available": measured.available_blocks,
        "inodes_free": measured.inodes_free,
        "held_count": len(holds),
        "held_bytes": held_bytes(holds),
        "held": [{"pid": hold.pid, "fd": hold.fd, "size": hold.size, "name": hold.name}
                 for hold in holds],
    }
The tests that fix the boundaries. tests/test_disk.py
"""Tests for spaceguard, each one asserting a number the runbook depends on."""
from __future__ import annotations

import errno
import os

import pytest

import spaceguard
from spaceguard import (
    Held,
    InsufficientSpace,
    Space,
    atomic_write,
    deleted_open,
    ensure_free,
    fmt_bytes,
    held_bytes,
    report,
    space,
    truncate_in_place,
    verdict,
)
from spaceguard.disk import Verdict

MiB = 1 << 20


def make_space(blocks_free=1000, inodes_free=1000, block_size=4096, blocks_total=2000,
               inodes_total=2000) -> Space:
    return Space(block_size, blocks_total, blocks_free, inodes_total, inodes_free)


# --- Space arithmetic ---------------------------------------------------------------------

def test_free_bytes_is_blocks_times_block_size():
    assert make_space(blocks_free=10, block_size=4096).free_bytes == 40960


def test_total_bytes_uses_the_same_block_size():
    assert make_space(blocks_total=2000, block_size=512).total_bytes == 1024000


def test_used_bytes_is_the_difference():
    assert make_space(blocks_free=500).used_bytes == 1500 * 4096


def test_block_percent_used_is_a_percentage():
    assert make_space(blocks_free=500).block_percent_used == pytest.approx(75.0)


def test_block_percent_used_with_no_blocks_is_zero():
    assert make_space(blocks_total=0, blocks_free=0).block_percent_used == 0.0


def test_inode_percent_used_is_a_percentage():
    assert make_space(inodes_free=1900).inode_percent_used == pytest.approx(5.0)


def test_inode_percent_used_with_no_inode_count_is_zero():
    assert make_space(inodes_total=0, inodes_free=0).inode_percent_used == 0.0


def test_space_is_frozen():
    with pytest.raises(Exception):
        make_space().blocks_free = 1  # type: ignore[misc]


# --- verdict ------------------------------------------------------------------------------

def test_verdict_ok_when_both_resources_remain():
    state = verdict(make_space(blocks_free=100, inodes_free=100))
    assert state.kind == "ok"
    assert state.exhausted is False


def test_verdict_blocks_when_no_blocks_remain():
    state = verdict(make_space(blocks_free=0, inodes_free=100))
    assert state.kind == "blocks"
    assert state.exhausted is True


def test_verdict_inodes_when_only_inodes_ran_out():
    state = verdict(make_space(blocks_free=100, inodes_free=0))
    assert state.kind == "inodes"
    assert "blocks are free" in state.detail


def test_verdict_both_when_neither_remains():
    assert verdict(make_space(blocks_free=0, inodes_free=0)).kind == "both"


def test_verdict_respects_a_block_floor():
    assert verdict(make_space(blocks_free=5), block_floor=5).kind == "blocks"
    assert verdict(make_space(blocks_free=6), block_floor=5).kind == "ok"


def test_verdict_respects_an_inode_floor():
    assert verdict(make_space(inodes_free=10), inode_floor=10).kind == "inodes"


def test_verdict_ignores_inodes_when_the_filesystem_reports_none():
    state = make_space(inodes_total=0, inodes_free=0, blocks_free=100)
    assert verdict(state).kind == "ok"


@pytest.mark.parametrize("blocks_free, expected", [(0, "blocks"), (1, "blocks"),
                                                   (2, "ok"), (500, "ok")])
def test_verdict_block_boundary(blocks_free, expected):
    assert verdict(make_space(blocks_free=blocks_free), block_floor=1).kind == expected


def test_verdict_carries_the_free_numbers():
    state = verdict(make_space(blocks_free=0, inodes_free=7))
    assert state.available_bytes == 0
    assert state.inodes_free == 7


def test_verdict_calls_a_full_root_reserve_exhausted():
    measured = Space(4096, 2000, 100, 2000, 1000, blocks_available=0)
    assert verdict(measured).kind == "blocks"
    assert "0 blocks" in verdict(measured).detail


def test_verdict_detail_names_the_byte_count():
    state = verdict(make_space(blocks_free=2, block_size=4096, inodes_free=3))
    assert "8.0 KiB" in state.detail


def test_verdict_is_a_named_tuple():
    assert isinstance(verdict(make_space()), Verdict)


# --- fmt_bytes ---------------------------------------------------------------------------

@pytest.mark.parametrize("count, expected", [
    (0, "0 B"),
    (512, "512 B"),
    (1024, "1.0 KiB"),
    (1536, "1.5 KiB"),
    (MiB, "1.0 MiB"),
    (64 * MiB, "64.0 MiB"),
    (3 * 1024 * MiB, "3.0 GiB"),
    (5 * (1 << 40), "5.0 TiB"),
])
def test_fmt_bytes(count, expected):
    assert fmt_bytes(count) == expected


# --- space() on a real path ---------------------------------------------------------------

def test_space_reports_a_positive_block_size(tmp_path):
    assert space(tmp_path).block_size > 0


def test_space_matches_statvfs(tmp_path):
    stat = os.statvfs(tmp_path)
    measured = space(tmp_path)
    assert measured.blocks_free == stat.f_bfree
    assert measured.blocks_available == stat.f_bavail
    assert measured.inodes_free == stat.f_ffree


def test_available_bytes_leaves_a_root_reserve_out():
    measured = Space(4096, 2000, 1000, 2000, 1000, blocks_available=900)
    assert measured.free_bytes == 4096 * 1000
    assert measured.available_bytes == 4096 * 900


def test_available_bytes_falls_back_to_the_free_count():
    assert make_space(blocks_free=10).available_bytes == 40960


def test_space_counts_at_most_the_total(tmp_path):
    measured = space(tmp_path)
    assert 0 <= measured.blocks_free <= measured.blocks_total


# --- ensure_free -------------------------------------------------------------------------

def test_ensure_free_returns_the_measurement_when_it_fits(tmp_path):
    measured = ensure_free(tmp_path, 1)
    assert measured.free_bytes >= 1


def test_ensure_free_refuses_more_than_the_filesystem_holds(tmp_path):
    measured = space(tmp_path)
    with pytest.raises(InsufficientSpace) as caught:
        ensure_free(tmp_path, measured.free_bytes + measured.block_size)
    assert caught.value.errno == errno.ENOSPC


def test_insufficient_space_keeps_both_numbers(tmp_path):
    measured = space(tmp_path)
    needed = measured.available_bytes + 4096
    with pytest.raises(InsufficientSpace) as caught:
        ensure_free(tmp_path, needed)
    assert caught.value.needed_bytes == needed
    assert caught.value.free_bytes == measured.available_bytes


def test_insufficient_space_names_the_reserve_in_its_message(tmp_path):
    measured = space(tmp_path)
    with pytest.raises(InsufficientSpace) as caught:
        ensure_free(tmp_path, measured.available_bytes, reserve=4096)
    assert "reserve" in str(caught.value)


def test_ensure_free_accepts_a_measurement_instead_of_a_path():
    measured = make_space(blocks_free=1)
    assert ensure_free("/does/not/exist", 4096, measured=measured) is measured


def test_ensure_free_refuses_on_an_injected_full_filesystem():
    with pytest.raises(InsufficientSpace):
        ensure_free("/does/not/exist", 1, measured=make_space(blocks_free=0))


def test_ensure_free_refuses_inside_the_root_reserve():
    measured = Space(4096, 2000, 100, 2000, 1000, blocks_available=0)
    with pytest.raises(InsufficientSpace) as caught:
        ensure_free("/does/not/exist", 1, measured=measured)
    assert caught.value.free_bytes == 0


def test_ensure_free_is_a_oserror_with_errno_28():
    assert issubclass(InsufficientSpace, OSError)
    assert InsufficientSpace("x", 0, 1).errno == errno.ENOSPC


# --- atomic_write ------------------------------------------------------------------------

def test_atomic_write_creates_the_file(tmp_path):
    target = tmp_path / "app.conf"
    assert atomic_write(target, b"threads = 4\n") == len(b"threads = 4\n")
    assert target.read_bytes() == b"threads = 4\n"


def test_atomic_write_sets_the_mode(tmp_path):
    target = tmp_path / "run.sh"
    atomic_write(target, b"#!/bin/sh\n", mode=0o755)
    assert target.stat().st_mode & 0o777 == 0o755


def test_atomic_write_replaces_an_existing_file(tmp_path):
    target = tmp_path / "app.conf"
    target.write_bytes(b"old")
    atomic_write(target, b"new")
    assert target.read_bytes() == b"new"


def test_atomic_write_leaves_no_temporary_file(tmp_path):
    atomic_write(tmp_path / "app.conf", b"data")
    assert [p.name for p in tmp_path.iterdir()] == ["app.conf"]


def test_atomic_write_is_atomic_for_a_reader(tmp_path):
    target = tmp_path / "app.conf"
    target.write_bytes(b"A" * 1000)
    atomic_write(target, b"B" * 1000)
    assert target.read_bytes() == b"B" * 1000


def test_atomic_write_with_ensure_refuses_before_creating_the_target(tmp_path):
    measured = space(tmp_path)
    target = tmp_path / "big.bin"
    with pytest.raises(InsufficientSpace):
        atomic_write(target, b"x" * 16, ensure=True, reserve=measured.free_bytes)
    assert not target.exists()


def test_atomic_write_keeps_the_old_file_when_the_rename_fails(tmp_path, monkeypatch):
    target = tmp_path / "app.conf"
    target.write_bytes(b"old")

    def broken(source, destination):
        raise OSError(errno.ENOSPC, "rename failed on purpose")

    monkeypatch.setattr(os, "replace", broken)
    with pytest.raises(OSError):
        atomic_write(target, b"new")
    assert target.read_bytes() == b"old"
    assert [p.name for p in tmp_path.iterdir()] == ["app.conf"]


def test_atomic_write_removes_the_temporary_file_when_the_write_fails(tmp_path, monkeypatch):
    target = tmp_path / "app.conf"

    def broken(fd, data):
        raise OSError(errno.ENOSPC, "write failed on purpose")

    source = os.fdopen
    monkeypatch.setattr(os, "fdopen", lambda fd, mode: FailingStream(fd, source))
    with pytest.raises(OSError):
        atomic_write(target, b"new", fsync=False)
    assert list(tmp_path.iterdir()) == []


class FailingStream:
    """A file object whose first write raises ENOSPC, to exercise the cleanup path."""

    def __init__(self, fd, opener):
        self._stream = opener(fd, "wb")

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self._stream.close()
        return False

    def write(self, data):
        raise OSError(errno.ENOSPC, "write failed on purpose")

    def flush(self):
        return None

    def fileno(self):
        return self._stream.fileno()


# --- truncate_in_place and the descriptors -------------------------------------------------

def test_truncate_in_place_empties_a_file(tmp_path):
    target = tmp_path / "app.log"
    target.write_bytes(b"x" * 4096)
    assert truncate_in_place(target) == 0
    assert target.stat().st_size == 0


def test_deleted_open_finds_our_own_unlinked_file(small_mount):
    path = small_mount / "held.bin"
    path.write_bytes(b"h" * (256 * 1024))
    handle = open(path, "rb+")
    try:
        os.unlink(path)
        device = os.stat(small_mount).st_dev
        found = deleted_open(device=device, pid_filter=[os.getpid()])
    finally:
        handle.close()
    sizes = [hold.size for hold in found if hold.name == str(path)]
    assert sizes == [256 * 1024]


def test_deleted_open_ignores_files_that_still_have_a_name(small_mount):
    path = small_mount / "live.bin"
    path.write_bytes(b"l" * 1024)
    handle = open(path, "rb+")
    try:
        found = deleted_open(device=os.stat(small_mount).st_dev, pid_filter=[os.getpid()])
    finally:
        handle.close()
    assert all(hold.name != str(path) for hold in found)


def test_deleted_open_reports_a_hold_as_a_named_tuple():
    assert Held(1, 2, "/tmp/x (deleted)", 3, 4)._fields == ("pid", "fd", "path", "size",
                                                           "device")


def test_held_removes_the_suffix_from_the_name():
    assert Held(1, 2, "/var/log/app.log (deleted)", 10, 4).name == "/var/log/app.log"


def test_deleted_open_skips_unknown_pids():
    assert deleted_open(pid_filter=[2 ** 31]) == []


def test_held_bytes_sums_the_sizes():
    assert held_bytes([Held(1, 2, "/a (deleted)", 10, 1), Held(1, 3, "/b (deleted)", 32, 1)]) \
        == 42


# --- report ------------------------------------------------------------------------------

def test_report_names_the_resource_state(tmp_path):
    assert report(tmp_path)["kind"] == "ok"


def test_report_carries_a_detail_line(tmp_path):
    assert "inodes" in report(tmp_path)["detail"]


def test_report_lists_the_held_entries_it_counted(small_mount):
    path = small_mount / "held2.bin"
    path.write_bytes(b"r" * 4096)
    handle = open(path, "rb+")
    try:
        os.unlink(path)
        payload = report(small_mount)
    finally:
        handle.close()
    assert payload["held_count"] == len(payload["held"])
    assert payload["held_bytes"] >= 4096


def test_package_exports_its_public_names():
    for name in ("Space", "verdict", "deleted_open", "atomic_write", "ensure_free"):
        assert hasattr(spaceguard, name)
The fixture that puts a test on the small mount. tests/conftest.py
"""Fixtures: a scratch directory on the small tmpfs, and the package on the path."""
from __future__ import annotations

import pathlib
import sys

import pytest

HERE = pathlib.Path(__file__).resolve().parents[2]
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

MOUNT = pathlib.Path("/dev/shm")


@pytest.fixture()
def small_mount(tmp_path):
    """A directory on the 64 MiB tmpfs, so block accounting is visible without filling it."""
    if not MOUNT.exists():
        pytest.skip("no /dev/shm on this host")
    directory = MOUNT / f"spaceguard-test-{tmp_path.name}"
    directory.mkdir()
    try:
        yield directory
    finally:
        for child in sorted(directory.rglob("*"), reverse=True):
            child.unlink() if not child.is_dir() else child.rmdir()
        directory.rmdir()
The host, the mount, and the errno numbers. 01_facts.py
"""Probe 01 - the host, the small filesystem under test, and the errno numbers.

Nothing here fills anything. This file records the conditions every later number was taken
under: which mount the space was taken from, how many blocks and inodes it started with, and
which neighbouring error numbers were available to contrast against ENOSPC.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import platform
import resource
import shutil
import stat

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "01_facts.json"
SHM = "/dev/shm"


def fs_type(path: str) -> str:
    """Name the filesystem holding a path, read from /proc/mounts by longest prefix."""
    best, kind = "", "unknown"
    for line in pathlib.Path("/proc/mounts").read_text().splitlines():
        fields = line.split()
        if len(fields) < 3:
            continue
        point = fields[1].replace("\\040", " ")
        if path.startswith(point) and len(point) > len(best):
            best, kind = point, fields[2]
    return kind


def mount_options(path: str) -> str:
    best, options = "", ""
    for line in pathlib.Path("/proc/mounts").read_text().splitlines():
        fields = line.split()
        if len(fields) < 4:
            continue
        point = fields[1].replace("\\040", " ")
        if path.startswith(point) and len(point) > len(best):
            best, options = point, fields[3]
    return options


def space(path: str) -> dict:
    s = os.statvfs(path)
    return {
        "block_size": s.f_frsize,
        "blocks_total": s.f_blocks,
        "blocks_free": s.f_bfree,
        "blocks_avail": s.f_bavail,
        "inodes_total": s.f_files,
        "inodes_free": s.f_ffree,
        "total_bytes": s.f_frsize * s.f_blocks,
        "free_bytes": s.f_frsize * s.f_bfree,
    }


def which(name: str) -> str | None:
    return shutil.which(name)


def main() -> None:
    uname = os.uname()
    soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
    shm_space = space(SHM)
    full = os.stat("/dev/full") if os.path.exists("/dev/full") else None
    facts = {
        "kernel": uname.release,
        "kernel_version": uname.version,
        "machine": uname.machine,
        "python": platform.python_version(),
        "cpu_count": os.cpu_count(),
        "uid": os.getuid(),
        "page_size": resource.getpagesize(),
        "workspace_fs": fs_type(str(HERE)),
        "workspace_fs_type_word": fs_type("/workspace"),
        "workspace_space": space(str(HERE)),
        "shm_fs": fs_type(SHM),
        "shm_mount_options": mount_options(SHM),
        "shm_space": shm_space,
        "shm_writable": os.access(SHM, os.W_OK),
        "tmp_fs": fs_type("/tmp"),
        "tmp_space": space("/tmp"),
        "root_space": space("/"),
        "rlimit_fsize_soft": soft,
        "rlimit_fsize_hard": hard,
        "dev_full_present": full is not None,
        "dev_full_major_minor": (os.major(full.st_rdev), os.minor(full.st_rdev)) if full else None,
        "can_mount": os.getuid() == 0,
        "userns_clone": pathlib.Path("/proc/sys/kernel/unprivileged_userns_clone").read_text().strip()
        if pathlib.Path("/proc/sys/kernel/unprivileged_userns_clone").exists() else "absent",
        "dev_fuse_present": os.path.exists("/dev/fuse"),
    }
    errnos = {
        "ENOSPC": errno.ENOSPC,
        "ENOSPC_message": os.strerror(errno.ENOSPC),
        "EDQUOT": errno.EDQUOT,
        "EDQUOT_message": os.strerror(errno.EDQUOT),
        "EFBIG": errno.EFBIG,
        "EFBIG_message": os.strerror(errno.EFBIG),
        "EROFS": errno.EROFS,
        "EROFS_message": os.strerror(errno.EROFS),
        "EMFILE": errno.EMFILE,
        "EACCES": errno.EACCES,
        "SIGXFSZ": 25,
    }
    sysctls = {}
    for name in ("fs/file-max", "fs/inotify/max_user_watches", "fs/inotify/max_user_instances",
                 "vm/overcommit_memory", "fs/protected_regular", "fs/nr_open"):
        path = pathlib.Path("/proc/sys") / name
        try:
            sysctls[name] = path.read_text().strip()
        except OSError:
            sysctls[name] = None
    tools = {name: bool(which(name)) for name in
             ("lsof", "fuser", "strace", "du", "df", "find", "cp", "dd", "tee", "truncate",
              "fallocate", "install", "sed", "mv", "touch", "stat", "sync", "xfs_io",
              "mkfs.ext4", "gcc", "unshare", "mount", "tail", "logger")}
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps({"facts": facts, "errno": errnos, "sysctl": sysctls,
                               "tools": tools}, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(facts, indent=1))
    print("errno:", errnos["ENOSPC"], errnos["ENOSPC_message"], "|", errnos["EDQUOT"],
          errnos["EDQUOT_message"], "|", errnos["EFBIG"], errnos["EFBIG_message"])
    print("tools:", {k: v for k, v in tools.items() if v})
    print("mode /dev/full:", oct(stat.S_IMODE(full.st_mode)) if full else "-")


if __name__ == "__main__":
    main()
What a write lands before ENOSPC. 02_blocks.py
"""Probe 02 - filling a small filesystem: how much lands before ENOSPC, and in what shape.

The filesystem under test is /dev/shm, a 64 MiB tmpfs mount this host already provides. Each
arm leaves exactly N blocks free, writes into them, and records what the kernel accepted: the
return value of every write, the size of the file afterwards, the blocks it really consumed,
and the errno of the call that failed. A ballast file holds the rest of the mount; the mount is
restored to empty after every run.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "02_blocks.json"
BASE = pathlib.Path("/dev/shm/enospc02")
BLOCK = 4096
REPEATS = 5


def free(path) -> tuple[int, int]:
    """Free blocks and free bytes, from statvfs itself rather than from a parsed df."""
    s = os.statvfs(path)
    return s.f_bfree, s.f_bfree * s.f_frsize


def ballast_to(path: pathlib.Path, keep_blocks: int) -> None:
    """Fill the mount with one ballast file until exactly keep_blocks blocks remain."""
    with open(path, "wb") as handle:
        written = 0
        while True:
            have, _ = free(path)
            if have <= keep_blocks:
                break
            step = min(1 << 20, (have - keep_blocks) * BLOCK)
            buf = b"\0" * min(step, 1 << 20)
            wrote = 0
            while wrote < step:
                n = handle.write(buf[: step - wrote])
                wrote += n
            written += wrote
    have, _ = free(path)


def cleanup() -> None:
    if BASE.exists():
        shutil.rmtree(BASE, ignore_errors=True)


def allocated(path: pathlib.Path) -> int:
    return path.stat().st_blocks * 512


def run_chunks(keep_blocks: int, chunk: int) -> dict:
    """Write equal chunks into the space left and record each return value."""
    ballast_to(BASE / "ballast", keep_blocks)
    free_before, bytes_before = free(BASE)
    target = BASE / "payload"
    calls: list[int] = []
    err = None
    buf = b"A" * chunk
    with open(target, "wb", buffering=0) as handle:
        for _ in range(4096):
            try:
                n = handle.write(buf)
            except OSError as exc:
                err = exc.errno
                break
            calls.append(n)
            if n != chunk:
                try:
                    handle.write(buf)
                except OSError as exc:
                    err = exc.errno
                break
    size = target.stat().st_size
    result = {
        "free_blocks_before": free_before,
        "free_bytes_before": bytes_before,
        "chunk": chunk,
        "calls": len(calls),
        "full_calls": sum(1 for n in calls if n == chunk),
        "last_call_bytes": calls[-1] if calls else 0,
        "bytes_written": size,
        "blocks_allocated": allocated(target),
        "errno": err,
        "free_blocks_after": free(BASE)[0],
    }
    target.unlink()
    return result


def run_bytes(keep_blocks: int) -> dict:
    """Write one byte at a time and count the bytes the last block accepts."""
    ballast_to(BASE / "ballast", keep_blocks)
    free_before, bytes_before = free(BASE)
    target = BASE / "payload"
    written = 0
    err = None
    with open(target, "wb", buffering=0) as handle:
        while written < 1 << 20:
            try:
                handle.write(b"x")
            except OSError as exc:
                err = exc.errno
                break
            written += 1
    result = {
        "free_blocks_before": free_before,
        "free_bytes_before": bytes_before,
        "bytes_written": written,
        "blocks_allocated": allocated(target),
        "errno": err,
        "free_blocks_after": free(BASE)[0],
    }
    target.unlink()
    return result


def run_exact(keep_blocks: int, extra: int) -> dict:
    """Fill the space left exactly, then (on the second arm) one byte past it."""
    ballast_to(BASE / "ballast", keep_blocks)
    free_before, bytes_before = free(BASE)
    target = BASE / "payload"
    payload = bytes_before + extra
    err = None
    with open(target, "wb", buffering=0) as handle:
        remaining = payload
        chunk = b"B" * (1 << 16)
        while remaining:
            view = chunk[: min(len(chunk), remaining)]
            try:
                n = handle.write(view)
            except OSError as exc:
                err = exc.errno
                break
            remaining -= n
    result = {
        "free_bytes_before": bytes_before,
        "payload": payload,
        "extra": extra,
        "bytes_written": target.stat().st_size,
        "fits_exactly": target.stat().st_size == payload,
        "errno": err,
        "free_blocks_after": free(BASE)[0],
    }
    target.unlink()
    return result


def run_buffered(keep_blocks: int, payload: int, mode: str) -> dict:
    """A default buffered writer: which call raises, and what has reached the disk by then."""
    ballast_to(BASE / "ballast", keep_blocks)
    free_before, bytes_before = free(BASE)
    target = BASE / "payload"
    stage, err, size_at = "none", None, None
    write_returned = None
    handle = open(target, "wb")
    try:
        try:
            stage = "write"
            write_returned = handle.write(b"C" * payload)
            if mode == "flush":
                stage = "flush"
                handle.flush()
            stage = "close"
            handle.close()
        except OSError as exc:
            err = exc.errno
            size_at = target.stat().st_size
    finally:
        try:
            handle.close()
        except OSError:
            pass
    result = {
        "free_blocks_before": free_before,
        "free_bytes_before": bytes_before,
        "payload": payload,
        "mode": mode,
        "write_returned": write_returned,
        "stage": stage,
        "errno": err,
        "size_at_error": size_at,
        "bytes_on_disk": target.stat().st_size,
        "blocks_allocated": allocated(target),
        "free_blocks_after": free(BASE)[0],
    }
    target.unlink()
    return result


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {
                    "median": statistics.median(values),
                    "min": min(values),
                    "max": max(values),
                }
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    cleanup()
    BASE.mkdir()
    arms: list[dict] = []

    def arm(label: str, function, *args) -> None:
        runs = []
        for _ in range(REPEATS):
            runs.append(function(*args))
        arms.append({"label": label, "runs": runs})
        cleanup()
        BASE.mkdir()

    arm("64 KiB writes into 2 free blocks (8 KiB)", run_chunks, 2, 1 << 16)
    arm("4 KiB writes into 2 free blocks", run_chunks, 2, BLOCK)
    arm("1 byte at a time into 2 free blocks", run_bytes, 2)
    arm("payload equal to the 8 KiB left", run_exact, 2, 0)
    arm("payload one byte over the 8 KiB left", run_exact, 2, 1)
    arm("buffered writer, 1 MiB into 8 KiB", run_buffered, 2, 1 << 20, "flush")
    arm("buffered writer, 100 bytes into no space, flushed", run_buffered, 0, 100, "flush")
    arm("buffered writer, 100 bytes into no space, closed only", run_buffered, 0, 100, "close")

    mount = os.statvfs(BASE)
    record = {
        "mount": "/dev/shm",
        "mount_options": "size=65536k",
        "block_size": mount.f_frsize,
        "blocks_total": mount.f_blocks,
        "inodes_total": mount.f_files,
        "repeats": REPEATS,
        "arms": summarise(arms),
        "cleanup_free_blocks": free("/dev/shm")[0],
    }
    cleanup()
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(arm_record["label"])
        for key, value in arm_record["summary"].items():
            print("   ", key, value["median"], f"[{value['min']}..{value['max']}]")
        print("    identical:", arm_record["identical"])
    print("free after cleanup:", record["cleanup_free_blocks"], "of", mount.f_blocks)


if __name__ == "__main__":
    main()
Filling every inode, and what still works. 03_inodes.py
"""Probe 03 - the other exhaustion: inodes, with the blocks untouched.

The mount is filled with zero-byte files until the kernel refuses to create another one. The
run records how many files that took against the inode count statvfs reported, how many data
blocks they consumed, and what still works once creation fails: writing to an existing file,
renaming it, linking it, and unlinking one file to make room again.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "03_inodes.json"
BASE = pathlib.Path("/dev/shm/enospc03")
REPEATS = 5


def space(path) -> dict:
    s = os.statvfs(path)
    return {"blocks_free": s.f_bfree, "inodes_free": s.f_ffree,
            "blocks_total": s.f_blocks, "inodes_total": s.f_files}


def attempt(function) -> dict:
    """Run one filesystem call and record whether it worked, and with which errno."""
    try:
        value = function()
        return {"ok": True, "errno": None, "value": value}
    except OSError as exc:
        return {"ok": False, "errno": exc.errno, "value": None}


def one_run() -> dict:
    before = space(BASE)
    t0 = time.perf_counter()
    created = 0
    err = None
    while True:
        try:
            os.close(os.open(BASE / f"f{created:06d}", os.O_CREAT | os.O_WRONLY, 0o644))
        except OSError as exc:
            err = exc.errno
            break
        created += 1
        if created > before["inodes_free"] + 1000:
            break
    elapsed = (time.perf_counter() - t0) * 1000
    after = space(BASE)

    # With every inode taken: which operations still work?
    target = BASE / "f000000"
    write_result = attempt(lambda: write_bytes(target, 1 << 20))
    blocks_after_write = space(BASE)["blocks_free"]
    behaviour = {
        "create_new": attempt(lambda: os.close(
            os.open(BASE / "extra", os.O_CREAT | os.O_WRONLY, 0o644))),
        "mkdir": attempt(lambda: os.mkdir(BASE / "extra_dir")),
        "write_existing": write_result,
        "rename_existing": attempt(lambda: os.rename(target, BASE / "renamed")),
        "hardlink_existing": attempt(lambda: os.link(BASE / "renamed", BASE / "linked")),
        "unlink_one": attempt(lambda: os.unlink(BASE / "renamed")),
        "create_after_unlink": attempt(lambda: os.close(
            os.open(BASE / "after", os.O_CREAT | os.O_WRONLY, 0o644))),
    }
    result = {
        "inodes_free_before": before["inodes_free"],
        "created": created,
        "shortfall": before["inodes_free"] - created,
        "errno": err,
        "ms": round(elapsed, 1),
        "us_per_file": round(elapsed * 1000 / max(created, 1), 1),
        "blocks_used": before["blocks_free"] - after["blocks_free"],
        "blocks_percent_used": round(
            (before["blocks_total"] - after["blocks_free"]) / before["blocks_total"] * 100, 3),
        "inodes_free_after": after["inodes_free"],
        "behaviour": {name: {"ok": value["ok"], "errno": value["errno"]}
                      for name, value in behaviour.items()},
        "bytes_written_to_existing": behaviour["write_existing"]["value"] or 0,
        "blocks_after_write": blocks_after_write,
    }
    return result


def write_bytes(path: pathlib.Path, payload: int) -> int:
    with open(path, "wb", buffering=0) as handle:
        return handle.write(b"z" * payload)


def cleanup() -> None:
    shutil.rmtree(BASE, ignore_errors=True)


def main() -> None:
    cleanup()
    BASE.mkdir()
    runs = []
    for _ in range(REPEATS):
        runs.append(one_run())
        cleanup()
        BASE.mkdir()
    numeric = {}
    for key in runs[0]:
        values = [run[key] for run in runs]
        if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
            numeric[key] = {"median": statistics.median(values), "min": min(values),
                            "max": max(values)}
    behaviour = {name: [run["behaviour"][name] for run in runs] for name in runs[0]["behaviour"]}
    record = {
        "mount": "/dev/shm",
        "repeats": REPEATS,
        "summary": numeric,
        "behaviour": behaviour,
        "runs": runs,
        "cleanup_inodes_free": space("/dev/shm")["inodes_free"],
        "cleanup_blocks_free": space("/dev/shm")["blocks_free"],
    }
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(record["summary"], indent=1))
    print(json.dumps(record["behaviour"], indent=1))
    print("cleanup inodes free:", record["cleanup_inodes_free"])


if __name__ == "__main__":
    main()
Space held by a file with no name. 04_deleted.py
"""Probe 04 - space that is gone but has no name: files deleted while a process holds them.

A file is opened, written and unlinked while the descriptor stays open. The run records what
statvfs says at each step, what the directory walk and du say, what the descriptor scan finds,
and how much a further write through the dead descriptor costs. A second arm compares removing a
log file with truncating it while a writer holds it.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "04_deleted.json"
BASE = pathlib.Path("/dev/shm/enospc04")
REPEATS = 5
BIG = 32 << 20
EXTRA = 1 << 20


def free_blocks() -> int:
    return os.statvfs(BASE).f_bfree


def write_file(path: pathlib.Path, payload: int) -> None:
    with open(path, "wb", buffering=0) as handle:
        chunk = b"d" * (1 << 20)
        left = payload
        while left:
            left -= handle.write(chunk[: min(left, len(chunk))])


def scan_deleted(root_pid: str = "") -> dict:
    """Walk /proc/<pid>/fd for descriptors whose link target ends in ' (deleted)'."""
    t0 = time.perf_counter()
    found = []
    scanned = 0
    for entry in os.scandir("/proc"):
        if not entry.name.isdigit():
            continue
        if root_pid and entry.name != root_pid:
            continue
        fd_dir = f"/proc/{entry.name}/fd"
        try:
            names = os.listdir(fd_dir)
        except OSError:
            continue
        for name in names:
            scanned += 1
            path = f"{fd_dir}/{name}"
            try:
                link = os.readlink(path)
                if not link.endswith(" (deleted)"):
                    continue
                size = os.stat(path).st_size
            except OSError:
                continue
            found.append({"pid": int(entry.name), "fd": int(name), "path": link,
                          "size": size})
    return {"found": found, "scanned": scanned,
            "ms": round((time.perf_counter() - t0) * 1000, 2)}


def du_bytes(path: pathlib.Path) -> dict:
    t0 = time.perf_counter()
    allocated = 0
    apparent = 0
    files = 0
    for root, _dirs, names in os.walk(path):
        for name in names:
            try:
                st = os.lstat(os.path.join(root, name))
            except OSError:
                continue
            allocated += st.st_blocks * 512
            apparent += st.st_size
            files += 1
    return {"allocated": allocated, "apparent": apparent, "files": files,
            "ms": round((time.perf_counter() - t0) * 1000, 2)}


def run_deleted_open() -> dict:
    holder = BASE / "held.bin"
    write_file(holder, BIG)
    free_written = free_blocks()
    handle = open(holder, "rb+")
    os.unlink(holder)
    free_unlinked = free_blocks()
    after_unlink = du_bytes(BASE)
    scan = scan_deleted(str(os.getpid()))
    scan_all = scan_deleted()
    handle.seek(0, os.SEEK_END)
    wrote = handle.write(b"e" * EXTRA)
    free_after_write = free_blocks()
    info = os.fstat(handle.fileno())
    handle.close()
    free_closed = free_blocks()
    return {
        "free_after_write": free_written,
        "free_after_unlink": free_unlinked,
        "free_after_extra_write": free_after_write,
        "free_after_close": free_closed,
        "dir_allocated_after_unlink": after_unlink["allocated"],
        "dir_apparent_after_unlink": after_unlink["apparent"],
        "dir_files_after_unlink": after_unlink["files"],
        "du_ms": after_unlink["ms"],
        "scan_found": len(scan["found"]),
        "scan_found_size": max([item["size"] for item in scan["found"]], default=0),
        "scan_scanned": scan["scanned"],
        "scan_ms": scan["ms"],
        "scan_all_found": len(scan_all["found"]),
        "scan_all_scanned": scan_all["scanned"],
        "scan_all_ms": scan_all["ms"],
        "stat_after_unlink_size": info.st_size,
        "extra_write_bytes": wrote,
        "held_blocks": free_after_write - free_unlinked,
    }


def run_log_holder(mode: str) -> dict:
    """A writer holds a log file. mode=unlink removes it, mode=truncate empties it in place."""
    log = BASE / "app.log"
    write_file(log, BIG)
    free_written = free_blocks()
    handle = open(log, "ab", buffering=0)
    freed = None
    if mode == "unlink":
        os.unlink(log)
        freed = free_blocks()
    else:
        os.ftruncate(handle.fileno(), 0)
        freed = free_blocks()
    wrote = handle.write(b"l" * EXTRA)
    free_after_write = free_blocks()
    size_after_write = os.fstat(handle.fileno()).st_size
    handle.close()
    free_closed = free_blocks()
    if mode != "unlink" and log.exists():
        log.unlink()
    return {
        "free_after_write": free_written,
        "free_after_action": freed,
        "free_after_extra_write": free_after_write,
        "free_after_close": free_closed,
        "extra_write_bytes": wrote,
        "size_after_write": size_after_write,
        "reclaimed_blocks": freed - free_written,
    }


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()
    arms: list[dict] = []

    def arm(label: str, function, *args) -> None:
        runs = []
        for _ in range(REPEATS):
            runs.append(function(*args))
            shutil.rmtree(BASE, ignore_errors=True)
            BASE.mkdir()
        arms.append({"label": label, "runs": runs})

    arm("open, unlink, keep the descriptor", run_deleted_open)
    arm("log file removed while the writer holds it", run_log_holder, "unlink")
    arm("log file truncated while the writer holds it", run_log_holder, "truncate")

    record = {
        "mount": "/dev/shm",
        "repeats": REPEATS,
        "payload_bytes": BIG,
        "extra_bytes": EXTRA,
        "arms": summarise(arms),
        "cleanup_free_blocks": free_blocks() if BASE.exists() else None,
    }
    shutil.rmtree(BASE, ignore_errors=True)
    record["cleanup_free_blocks"] = os.statvfs("/dev/shm").f_bfree
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(arm_record["label"])
        for key, value in arm_record["summary"].items():
            print("   ", key, value["median"], f"[{value['min']}..{value['max']}]")
        print("    identical:", arm_record["identical"])
    print("free after cleanup:", record["cleanup_free_blocks"])


if __name__ == "__main__":
    main()
Apparent size against allocated blocks. 05_sparse.py
"""Probe 05 - apparent size against allocated blocks: truncate, fallocate, and copying.

A file that claims 48 MiB can hold 4 KiB of disk, or all of it, depending on how it was made.
The arms record st_size, the blocks the file really owns, and the change in the mount's free
blocks, so the difference is a number rather than a habit.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import subprocess

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "05_sparse.json"
BASE = pathlib.Path("/dev/shm/enospc05")
REPEATS = 5
SIZE = 48 << 20
HOLE = 24 << 20


def free_blocks() -> int:
    return os.statvfs(BASE).f_bfree


def used_by(path: pathlib.Path) -> dict:
    st = path.stat()
    return {"size": st.st_size, "allocated": st.st_blocks * 512}


def du_pair(path: pathlib.Path) -> dict:
    real = subprocess.run(["du", "-s", "--block-size=1", str(path)], capture_output=True,
                          text=True)
    apparent = subprocess.run(["du", "-s", "--block-size=1", "--apparent-size", str(path)],
                              capture_output=True, text=True)
    return {"du_allocated": int(real.stdout.split()[0]) if real.stdout else -1,
            "du_apparent": int(apparent.stdout.split()[0]) if apparent.stdout else -1}


def run_truncate() -> dict:
    before = free_blocks()
    path = BASE / "trunc.bin"
    with open(path, "wb"):
        pass
    os.truncate(path, SIZE)
    after = free_blocks()
    info = used_by(path)
    pair = du_pair(path)
    return {"free_before": before, "free_after": after, "free_delta": after - before,
            "size": info["size"], "allocated": info["allocated"], **pair}


def run_hole_write() -> dict:
    path = BASE / "hole.bin"
    with open(path, "wb"):
        pass
    os.truncate(path, SIZE)
    before = free_blocks()
    with open(path, "r+b", buffering=0) as handle:
        handle.seek(HOLE)
        handle.write(b"!")
    after = free_blocks()
    info = used_by(path)
    return {"free_before": before, "free_after": after, "free_delta": after - before,
            "size": info["size"], "allocated": info["allocated"]}


def run_fallocate(keep_blocks: int | None) -> dict:
    path = BASE / "falloc.bin"
    ballast = None
    if keep_blocks is not None:
        ballast = BASE / "ballast"
        s = os.statvfs(BASE)
        want = (s.f_blocks - keep_blocks) * s.f_frsize
        with open(ballast, "wb") as handle:
            handle.write(b"\0" * want)
    before = free_blocks()
    err = None
    with open(path, "wb") as handle:
        try:
            os.posix_fallocate(handle.fileno(), 0, SIZE)
        except OSError as exc:
            err = exc.errno
    after = free_blocks()
    info = used_by(path)
    result = {"free_before": before, "free_after": after, "free_delta": after - before,
              "size": info["size"], "allocated": info["allocated"], "errno": err}
    if ballast is not None:
        ballast.unlink()
    return result


def run_copy(sparse: str) -> dict:
    source = BASE / "source.bin"
    target = BASE / f"target-{sparse}.bin"
    with open(source, "wb"):
        pass
    os.truncate(source, SIZE)
    with open(source, "r+b", buffering=0) as handle:
        handle.seek(HOLE)
        handle.write(b"!")
    before = free_blocks()
    completed = subprocess.run(["cp", f"--sparse={sparse}", str(source), str(target)],
                               capture_output=True, text=True)
    after = free_blocks()
    info = used_by(target) if target.exists() else {"size": 0, "allocated": 0}
    return {"free_before": before, "free_after": after, "free_delta": after - before,
            "size": info["size"], "allocated": info["allocated"],
            "source_allocated": used_by(source)["allocated"],
            "exit": completed.returncode,
            "stderr": completed.stderr.strip().splitlines()[:1]}


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()
    arms: list[dict] = []

    def arm(label: str, function, *args) -> None:
        runs = []
        for _ in range(REPEATS):
            runs.append(function(*args))
            shutil.rmtree(BASE, ignore_errors=True)
            BASE.mkdir()
        arms.append({"label": label, "runs": runs})

    arm("truncate to 48 MiB", run_truncate)
    arm("truncate to 48 MiB, then one byte at 24 MiB", run_hole_write)
    arm("posix_fallocate 48 MiB on 64 MiB free", run_fallocate, None)
    arm("posix_fallocate 48 MiB with 20 blocks free", run_fallocate, 20)
    arm("cp --sparse=auto of a 48 MiB file holding 1 byte", run_copy, "auto")
    arm("cp --sparse=never of the same file", run_copy, "never")

    record = {
        "mount": "/dev/shm",
        "repeats": REPEATS,
        "size_bytes": SIZE,
        "hole_offset": HOLE,
        "arms": summarise(arms),
    }
    shutil.rmtree(BASE, ignore_errors=True)
    record["cleanup_free_blocks"] = os.statvfs("/dev/shm").f_bfree
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(arm_record["label"])
        for key, value in arm_record["summary"].items():
            print("   ", key, value["median"], f"[{value['min']}..{value['max']}]")
        print("    identical:", arm_record["identical"])
    print("free after cleanup:", record["cleanup_free_blocks"])


if __name__ == "__main__":
    main()
Sixteen tools against a full mount. 06_tools.py
"""Probe 06 - what the usual tools do when the mount is full, and what they leave behind.

Every arm starts from a mount filled to a chosen number of free blocks, holding one 1 MiB
payload to copy and one 1 MiB text file to edit. The record is the exit status, the line the
tool printed, the size of whatever is left under the target name, and whether the file it was
asked to edit came through untouched — because a half-written file that looks complete is the
part that hurts.
"""
from __future__ import annotations

import hashlib
import json
import os
import pathlib
import re
import shutil
import statistics
import subprocess

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "06_tools.json"
BASE = pathlib.Path("/dev/shm/enospc06")
REPEATS = 5
PAYLOAD = 1 << 20
PARTIAL_KEEP = 100          # 400 KiB left free, for the arms that run out mid-copy


def write(path: pathlib.Path, payload: int, byte: bytes = b"p") -> None:
    with open(path, "wb") as handle:
        handle.write(byte * payload)


def fill_to(path: pathlib.Path, keep: int = 0) -> None:
    """Fill the mount's free blocks with one ballast file, leaving keep blocks free."""
    s = os.statvfs(path)
    want = s.f_bfree * s.f_frsize - keep * s.f_frsize
    chunk = b"\0" * (1 << 20)
    with open(path / "ballast", "wb") as handle:
        while want > 0:
            try:
                wrote = handle.write(chunk[: min(want, len(chunk))])
            except OSError:
                break
            if not wrote:
                break
            want -= wrote


def prepare(keep: int = 0) -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()
    write(BASE / "payload", PAYLOAD)
    write(BASE / "existing", PAYLOAD, b"a")
    fill_to(BASE, keep)


def size_of(name: str) -> int:
    try:
        return (BASE / name).stat().st_size
    except OSError:
        return -1


def digest(name: str) -> str:
    try:
        return hashlib.sha256((BASE / name).read_bytes()).hexdigest()[:12]
    except OSError:
        return "-"


def run(argv: list[str], keep: int = 0, target: str = "t", stdin: bytes | None = None,
        watch: str = "") -> dict:
    prepare(keep)
    before_existing = digest("existing")
    completed = subprocess.run(argv, cwd=BASE, capture_output=True, text=True,
                               input=stdin.decode() if stdin else None)
    line = (completed.stderr.strip().splitlines() or [""])[0][:200]
    line = re.sub(r"sed[A-Za-z0-9]{6}", "sedXXXXXX", line)
    return {
        "exit": completed.returncode,
        "stderr": line,
        "stdout": (completed.stdout.strip().splitlines() or [""])[0][:120],
        "target_size": size_of(watch or target),
        "target_exists": (BASE / (watch or target)).exists(),
        "existing_intact": digest("existing") == before_existing,
        "free_before": keep,
    }


def run_python(keep: int, buffered: bool) -> dict:
    prepare(keep)
    before_existing = digest("existing")
    source = (
        "handle = open('t', 'wb'" + ("" if buffered else ", buffering=0") + ")\n"
        "try:\n"
        "    n = handle.write(b'x' * (1 << 20))\n"
        "    print('write returned', n)\n"
        "except OSError as exc:\n"
        "    print('write', exc.errno)\n"
        "try:\n"
        "    handle.close()\n"
        "    print('close ok')\n"
        "except OSError as exc:\n"
        "    print('close', exc.errno)\n"
    )
    completed = subprocess.run(["python3", "-c", source], cwd=BASE, capture_output=True,
                               text=True)
    return {"exit": completed.returncode, "stderr": completed.stderr.strip()[:160],
            "stdout": " / ".join(completed.stdout.strip().splitlines()),
            "target_size": size_of("t"), "target_exists": (BASE / "t").exists(),
            "existing_intact": digest("existing") == before_existing, "free_before": keep}


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


ARMS = [
    ("dd bs=64k count=16 into no space", ["dd", "if=/dev/zero", "of=t", "bs=64k", "count=16"],
     0, "t", None, ""),
    ("dd 1 MiB into 400 KiB free",
     ["dd", "if=/dev/zero", "of=t", "bs=64k", "count=16"], PARTIAL_KEEP, "t", None, ""),
    ("cp 1 MiB into no space", ["cp", "payload", "t"], 0, "t", None, ""),
    ("cp 1 MiB into 400 KiB free", ["cp", "payload", "t"], PARTIAL_KEEP, "t", None, ""),
    ("tee into no space", ["tee", "t"], 0, "t", b"t" * PAYLOAD, ""),
    ("cat payload > t", ["sh", "-c", "cat payload > t"], 0, "t", None, ""),
    ("install -m 755 payload t", ["install", "-m", "755", "payload", "t"], 0, "t", None, ""),
    ("sed -i on a 1 MiB file", ["sed", "-i", "s/^/x/", "existing"], 0, "existing", None,
     "existing"),
    ("truncate -s 8M t", ["truncate", "-s", "8M", "t"], 0, "t", None, ""),
    ("fallocate -l 8M t", ["fallocate", "-l", "8M", "t"], 0, "t", None, ""),
    ("touch t", ["touch", "t"], 0, "t", None, ""),
    ("mkdir d", ["mkdir", "d"], 0, "d", None, ""),
    ("mv existing renamed", ["mv", "existing", "renamed"], 0, "existing", None, "renamed"),
]


def main() -> None:
    try:
        _main()
    finally:
        shutil.rmtree(BASE, ignore_errors=True)


def _main() -> None:
    arms: list[dict] = []
    for label, argv, keep, target, stdin, watch in ARMS:
        runs = [run(argv, keep, target, stdin, watch) for _ in range(REPEATS)]
        arms.append({"label": label, "runs": runs})
    for label, keep, buffered in (("python buffered 1 MiB into no space", 0, True),
                                  ("python unbuffered 1 MiB into no space", 0, False),
                                  ("python unbuffered 1 MiB into 400 KiB free",
                                   PARTIAL_KEEP, False)):
        runs = [run_python(keep, buffered) for _ in range(REPEATS)]
        arms.append({"label": label, "runs": runs})

    record = {
        "mount": "/dev/shm",
        "repeats": REPEATS,
        "payload_bytes": PAYLOAD,
        "partial_keep_blocks": PARTIAL_KEEP,
        "arms": summarise(arms),
    }
    shutil.rmtree(BASE, ignore_errors=True)
    record["cleanup_free_blocks"] = os.statvfs("/dev/shm").f_bfree
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        run0 = arm_record["runs"][0]
        print(f"{arm_record['label']}: exit {run0['exit']} | left {run0['target_size']} B | "
              f"exists {run0['target_exists']} | intact {run0['existing_intact']} | "
              f"{run0['stderr'][:80]!r} {run0['stdout'][:50]!r} | same "
              f"{arm_record['identical']}")
    print("free after cleanup:", record["cleanup_free_blocks"])


if __name__ == "__main__":
    main()
The size limit, and the device that always answers ENOSPC. 07_errno.py
"""Probe 07 - the two errors that look like ENOSPC and are not, and the device that always is.

/dev/full is a real device that answers every write with ENOSPC, so the application-side path can
be observed without filling anything. RLIMIT_FSIZE produces the neighbouring error: a process
that crosses its file-size limit is killed by SIGXFSZ, and if it ignores that signal it gets
EFBIG. Both are measured here so the number in a log can be told apart from a full disk.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import shutil
import statistics
import subprocess

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "07_errno.json"
BASE = pathlib.Path("/dev/shm/enospc07")
REPEATS = 5
LIMIT = 1 << 20
PAYLOAD = 2 << 20


def full_device_run(buffered: bool) -> dict:
    source = (
        "import errno\n"
        "handle = open('/dev/full', 'wb'" + ("" if buffered else ", buffering=0") + ")\n"
        "try:\n"
        "    n = handle.write(b'q' * (100 if " + str(buffered) + " else 4096))\n"
        "    print('write returned', n)\n"
        "except OSError as exc:\n"
        "    print('write', exc.errno)\n"
        "try:\n"
        "    handle.flush()\n"
        "    handle.close()\n"
        "    print('close ok')\n"
        "except OSError as exc:\n"
        "    print('close', exc.errno)\n"
    )
    completed = subprocess.run(["python3", "-c", source], capture_output=True, text=True)
    return {"exit": completed.returncode,
            "stdout": " / ".join(completed.stdout.strip().splitlines()),
            "stderr": completed.stderr.strip().splitlines()[:1]}


def shell_run(argv: list[str]) -> dict:
    completed = subprocess.run(argv, capture_output=True, text=True)
    return {"exit": completed.returncode,
            "stderr": (completed.stderr.strip().splitlines() or [""])[0][:160],
            "stdout": (completed.stdout.strip().splitlines() or [""])[-1][:160]}


def limit_run(ignore_signal: bool) -> dict:
    if BASE.exists():
        shutil.rmtree(BASE)
    BASE.mkdir()
    target = BASE / "big.bin"
    before = dict(free=os.statvfs(BASE).f_bfree)
    source = (
        "import resource, signal, sys\n"
        "resource.setrlimit(resource.RLIMIT_FSIZE, (" + str(LIMIT) + ", " + str(LIMIT) + "))\n"
        + "print('inherited', signal.getsignal(signal.SIGXFSZ))\n"
        + ("signal.signal(signal.SIGXFSZ, signal.SIG_IGN)\n" if ignore_signal
           else "signal.signal(signal.SIGXFSZ, signal.SIG_DFL)\n")
        + "handle = open(sys.argv[1], 'wb', buffering=0)\n"
        "written = 0\n"
        "try:\n"
        "    while written < " + str(PAYLOAD) + ":\n"
        "        written += handle.write(b'w' * 65536)\n"
        "    print('wrote', written)\n"
        "except OSError as exc:\n"
        "    print('write', exc.errno, 'after', written)\n"
    )
    completed = subprocess.run(["python3", "-c", source, str(target)], capture_output=True,
                               text=True)
    size = target.stat().st_size if target.exists() else -1
    return {"exit": completed.returncode,
            "stdout": " / ".join(completed.stdout.strip().splitlines()),
            "stderr": completed.stderr.strip().splitlines()[:1],
            "file_size": size,
            "free_delta": before["free"] - os.statvfs(BASE).f_bfree}


def readonly_run() -> dict:
    try:
        with open("/proc/sys/kernel/ostype", "w") as handle:
            handle.write("x")
        return {"errno": None, "detail": "opened for write"}
    except OSError as exc:
        return {"errno": exc.errno, "detail": os.strerror(exc.errno)}


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()
    payload_file = BASE / "payload"
    payload_file.write_bytes(b"z" * (1 << 20))
    arms: list[dict] = []

    def arm(label: str, function, *args) -> None:
        arms.append({"label": label, "runs": [function(*args) for _ in range(REPEATS)]})

    arm("python unbuffered write to /dev/full", full_device_run, False)
    arm("python buffered 100 bytes to /dev/full", full_device_run, True)
    arm("printf x > /dev/full", shell_run, ["sh", "-c", "printf x > /dev/full"])
    arm("dd 4 KiB to /dev/full", shell_run, ["dd", "if=/dev/zero", "of=/dev/full", "bs=4k",
                                             "count=1"])
    arm("cp 1 MiB file to /dev/full", shell_run, ["cp", str(payload_file), "/dev/full"])
    arm("RLIMIT_FSIZE 1 MiB, SIGXFSZ at default", limit_run, False)
    arm("RLIMIT_FSIZE 1 MiB, SIGXFSZ ignored", limit_run, True)
    arm("sh -c 'ulimit -f 1024; dd 2 MiB'", shell_run,
        ["sh", "-c", "cd /dev/shm/enospc07 && rm -f lim.bin && ulimit -f 1024 && "
                     "dd if=/dev/zero of=lim.bin bs=1k count=2048"])

    record = {
        "repeats": REPEATS,
        "limit_bytes": LIMIT,
        "payload_bytes": PAYLOAD,
        "arms": summarise(arms),
        "readonly_attempt": readonly_run(),
        "errno_values": {"ENOSPC": errno.ENOSPC, "EFBIG": errno.EFBIG,
                         "EDQUOT": errno.EDQUOT, "EROFS": errno.EROFS,
                         "SIGXFSZ": 25},
    }
    shutil.rmtree(BASE, ignore_errors=True)
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(f"{arm_record['label']}: {json.dumps(arm_record['runs'][0])[:170]}")
    print("readonly:", record["readonly_attempt"])


if __name__ == "__main__":
    main()
The package under the conditions it was written for. 08_library.py
"""Probe 08 - the package under the conditions it was written for.

Does the up-front check actually save the partial write, what does the descriptor scan cost, and
does emptying a held log give the blocks back? Each arm runs against the same 64 MiB tmpfs the
earlier probes used, five times.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import sys

HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(ROOT / "module"))

import spaceguard  # noqa: E402  (the package is put on the path just above)

OUT = HERE.parent / "results" / "08_library.json"
BASE = pathlib.Path("/dev/shm/enospc08")
REPEATS = 5
BIG = 32 << 20
PAYLOAD = 1 << 20


def free_blocks() -> int:
    return os.statvfs(BASE).f_bfree


def fill_to(keep: int) -> None:
    s = os.statvfs(BASE)
    want = s.f_bfree * s.f_frsize - keep * s.f_frsize
    chunk = b"\0" * (1 << 20)
    with open(BASE / "ballast", "wb") as handle:
        while want > 0:
            wrote = handle.write(chunk[: min(want, len(chunk))])
            if not wrote:
                break
            want -= wrote


def reset() -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()


def measure_space_call() -> dict:
    reset()
    import time
    start = time.perf_counter()
    for _ in range(1000):
        spaceguard.space(BASE)
    elapsed = (time.perf_counter() - start) * 1e6 / 1000
    return {"us_per_call": round(elapsed, 3)}


def measure_scan() -> dict:
    reset()
    path = BASE / "held.bin"
    with open(path, "wb") as handle:
        handle.write(b"h" * BIG)
    handle = open(path, "rb+")
    os.unlink(path)
    try:
        import time
        start = time.perf_counter()
        found = spaceguard.deleted_open(device=os.stat(BASE).st_dev)
        elapsed = (time.perf_counter() - start) * 1000
        payload = spaceguard.report(BASE)
    finally:
        handle.close()
    own = [hold for hold in found if hold.pid == os.getpid()]
    return {"ms": round(elapsed, 2), "found": len(own),
            "held_bytes": spaceguard.held_bytes(own),
            "report_kind": payload["kind"],
            "report_held_count": payload["held_count"]}


def measure_ensure() -> dict:
    reset()
    fill_to(2)
    import time
    start = time.perf_counter()
    err = None
    try:
        spaceguard.ensure_free(BASE, PAYLOAD)
    except spaceguard.InsufficientSpace as exc:
        err = exc.errno
    elapsed = (time.perf_counter() - start) * 1e6
    return {"errno": err, "us": round(elapsed, 1),
            "target_created": (BASE / "target.bin").exists(),
            "free_blocks_after": free_blocks()}


def measure_atomic(ensure: bool) -> dict:
    reset()
    fill_to(2)
    err = None
    try:
        spaceguard.atomic_write(BASE / "target.bin", b"a" * PAYLOAD, ensure=ensure)
    except OSError as exc:
        err = exc.errno
    temps = [p.name for p in BASE.iterdir() if p.name.startswith(".")]
    return {"errno": err, "target_size": (BASE / "target.bin").stat().st_size
            if (BASE / "target.bin").exists() else -1,
            "temp_files_left": len(temps), "free_blocks_after": free_blocks()}


def measure_plain_write() -> dict:
    reset()
    fill_to(2)
    err = None
    with open(BASE / "target.bin", "wb") as handle:
        try:
            handle.write(b"b" * PAYLOAD)
        except OSError as exc:
            err = exc.errno
    return {"errno": err, "target_size": (BASE / "target.bin").stat().st_size,
            "free_blocks_after": free_blocks()}


def measure_truncate_held() -> dict:
    reset()
    log = BASE / "app.log"
    with open(log, "wb") as handle:
        handle.write(b"t" * BIG)
    before = free_blocks()
    handle = open(log, "ab", buffering=0)
    try:
        import time
        start = time.perf_counter()
        spaceguard.truncate_in_place(log)
        elapsed = (time.perf_counter() - start) * 1000
        after = free_blocks()
        handle.write(b"after-truncate\n")
        after_write = free_blocks()
    finally:
        handle.close()
    return {"blocks_before": before, "blocks_after": after, "reclaimed": after - before,
            "ms": round(elapsed, 2), "blocks_after_write": after_write}


def measure_probe_write() -> dict:
    """A 1-byte probe file is the alternative to asking statvfs; here is what it costs."""
    reset()
    before = free_blocks()
    probe = BASE / ".writable"
    with open(probe, "wb") as handle:
        handle.write(b"x")
    during = free_blocks()
    probe.unlink()
    after = free_blocks()
    return {"blocks_during": during - before, "blocks_after": after - before}


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [r[key] for r in runs]
            if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(r, sort_keys=True) for r in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    reset()
    arms: list[dict] = []

    def arm(label: str, function, *args) -> None:
        runs = [function(*args) for _ in range(REPEATS)]
        arms.append({"label": label, "runs": runs})

    arm("space() x1000", measure_space_call)
    arm("deleted_open + report with one 32 MiB hold", measure_scan)
    arm("ensure_free on 2 free blocks, 1 MiB asked", measure_ensure)
    arm("atomic_write(ensure=True) on 2 free blocks", measure_atomic, True)
    arm("atomic_write(ensure=False) on 2 free blocks", measure_atomic, False)
    arm("plain open().write() on 2 free blocks", measure_plain_write)
    arm("truncate_in_place on a held 32 MiB log", measure_truncate_held)
    arm("1-byte writability probe", measure_probe_write)

    record = {
        "mount": "/dev/shm",
        "repeats": REPEATS,
        "payload_bytes": PAYLOAD,
        "version": spaceguard.__version__,
        "arms": summarise(arms),
    }
    reset()
    shutil.rmtree(BASE, ignore_errors=True)
    record["cleanup_free_blocks"] = os.statvfs("/dev/shm").f_bfree
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(f"{arm_record['label']}: {json.dumps(arm_record['summary'])[:220]} | same "
              f"{arm_record['identical']}")
    print("free after cleanup:", record["cleanup_free_blocks"])


if __name__ == "__main__":
    main()
The counts this page quotes. 09_tests.py
"""Probe 09 - run the package's tests and count what the article is about to claim.

The counts printed here are the ones the prose quotes: how many tests pass, how many lines the
package and its tests hold, and how many probe files produced the numbers. build.py re-reads this
file and refuses a draft whose declared counts disagree with it.
"""
from __future__ import annotations

import json
import pathlib
import re
import subprocess
import sys

HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parent
PACKAGE = ROOT / "module" / "spaceguard"
OUT = ROOT / "results" / "09_tests.json"


def count_lines(path: pathlib.Path) -> int:
    return len([line for line in path.read_text(encoding="utf-8").splitlines()
                if line.strip()])


def main() -> None:
    completed = subprocess.run(
        [sys.executable, "-m", "pytest", "-q", "spaceguard/tests"],
        cwd=ROOT / "module", capture_output=True, text=True)
    summary = [line for line in completed.stdout.splitlines() if "passed" in line]
    if completed.returncode != 0 or not summary:
        print(completed.stdout[-2000:])
        raise SystemExit("pytest did not pass")
    passed = int(re.search(r"(\d+) passed", summary[-1]).group(1))
    package_files = sorted(package for package in PACKAGE.glob("*.py"))
    test_files = sorted(PACKAGE.glob("tests/*.py"))
    probes = sorted(HERE.glob("[0-9]*.py"))
    records = sorted((ROOT / "results").glob("*.json"))
    record = {
        "pytest_passed": passed,
        "pytest_summary": summary[-1].strip(),
        "package_files": len(package_files),
        "package_lines": sum(count_lines(path) for path in package_files),
        "test_files": len(test_files) - 1,
        "test_lines": sum(count_lines(path) for path in test_files
                          if path.name != "conftest.py"),
        "conftest_lines": count_lines(PACKAGE / "tests" / "conftest.py"),
        "probe_files": len(probes),
        "probe_lines": sum(count_lines(path) for path in probes),
        "record_files": len(records),
        "tests_per_file": round(passed / max(len(test_files) - 1, 1), 2),
    }
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    print(json.dumps(record, indent=1))


if __name__ == "__main__":
    main()
Emptying a held log, and where the writer resumes. 10_truncate.py
"""Probe 10 - emptying a log a writer still holds, and where that writer resumes.

A process opens a log, writes a payload, and keeps the descriptor. The log is then emptied the
way a shell does it - ``: > file``, which opens with O_TRUNC - and the writer appends two short
lines through the descriptor it already had. Three arms differ only in how that descriptor was
opened: with O_APPEND, without it, and without it but seeking to zero after the truncation.

The run records where the first write after the truncation landed, the size the file then
claims, the blocks it actually holds, and whether the gap reads back as zeros. The gap is the
trap: a writer with a fixed offset resumes inside a file that no longer has anything before
that point, so the file grows a hole that ``ls`` counts and ``du`` does not. The third arm is
the repair - the same writer seeking to zero after the emptying - so the page can print the
difference and not only the danger.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import subprocess

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "10_truncate.json"
BASE = pathlib.Path("/dev/shm/enospc10")
PAYLOAD = 4 << 20
LINE = b"l" * 100
HOLE_PROBE = 1 << 20


def free_blocks() -> int:
    return os.statvfs(BASE).f_bfree


def empty_with_shell(path: pathlib.Path) -> None:
    """Empty the file the way an operator does at three in the morning."""
    subprocess.run(["sh", "-c", ': > "$1"', "sh", str(path)], check=True)


def allocated_bytes(path: pathlib.Path) -> int:
    return os.stat(path).st_blocks * 512


def zero_bytes_at(path: pathlib.Path, offset: int) -> int:
    """How many of the bytes at ``offset`` read back as zero, and 0 past the end of the file."""
    with open(path, "rb") as reader:
        reader.seek(offset)
        return reader.read(8).count(0)


def run_arm(mode: str) -> dict:
    log = BASE / "service.log"
    flags = os.O_WRONLY | os.O_CREAT
    if mode == "append":
        flags |= os.O_APPEND
    handle = os.open(log, flags, 0o644)
    written = 0
    while written < PAYLOAD:
        written += os.write(handle, b"a" * min(1 << 20, PAYLOAD - written))
    free_before = free_blocks()
    offset_before = os.lseek(handle, 0, os.SEEK_CUR)

    empty_with_shell(log)
    size_after_empty = os.stat(log).st_size

    if mode == "seek0":
        os.lseek(handle, 0, os.SEEK_SET)
    returned = os.write(handle, LINE)
    size_after_write = os.stat(log).st_size
    # An O_APPEND descriptor keeps lseek reporting the old position until the write
    # happens, so where the line landed is read back from the size it produced.
    landing = size_after_write - returned
    allocated = allocated_bytes(log)
    zeros = zero_bytes_at(log, HOLE_PROBE)
    os.write(handle, LINE)
    size_after_second = os.stat(log).st_size
    free_after = free_blocks()
    os.close(handle)
    return {
        "offset_before": offset_before,
        "size_after_empty": size_after_empty,
        "landing_offset": landing,
        "write_returned": returned,
        "size_after_write": size_after_write,
        "allocated_bytes": allocated,
        "zero_bytes_at_hole": zeros,
        "size_after_second_write": size_after_second,
        "free_before": free_before,
        "free_after": free_after,
        "reclaimed_blocks": free_after - free_before,
    }


def summarise(arms: list[dict]) -> list[dict]:
    out = []
    for arm in arms:
        runs = arm["runs"]
        numeric = {}
        for key in runs[0]:
            values = [run[key] for run in runs]
            if all(isinstance(value, (int, float)) and not isinstance(value, bool)
                   for value in values):
                numeric[key] = {"median": statistics.median(values), "min": min(values),
                                "max": max(values)}
        out.append({"label": arm["label"], "summary": numeric,
                    "identical": len({json.dumps(run, sort_keys=True) for run in runs}) == 1,
                    "runs": runs})
    return out


def main() -> None:
    shutil.rmtree(BASE, ignore_errors=True)
    BASE.mkdir()
    arms: list[dict] = []
    for label, mode in (("writer opened with O_APPEND", "append"),
                        ("writer opened without O_APPEND", "fixed"),
                        ("writer opened without O_APPEND, then seeks to zero", "seek0")):
        runs = []
        for _ in range(5):
            runs.append(run_arm(mode))
            shutil.rmtree(BASE, ignore_errors=True)
            BASE.mkdir()
        arms.append({"label": label, "runs": runs})

    record = {
        "mount": "/dev/shm",
        "repeats": 5,
        "payload_bytes": PAYLOAD,
        "line_bytes": len(LINE),
        "hole_probe_offset": HOLE_PROBE,
        "arms": summarise(arms),
    }
    shutil.rmtree(BASE, ignore_errors=True)
    record["cleanup_free_blocks"] = os.statvfs("/dev/shm").f_bfree
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for arm_record in record["arms"]:
        print(arm_record["label"])
        for key, value in arm_record["summary"].items():
            print("   ", key, value["median"], f"[{value['min']}..{value['max']}]")
        print("    identical:", arm_record["identical"])
    print("free after cleanup:", record["cleanup_free_blocks"])


if __name__ == "__main__":
    main()
Which directory holds the inodes, checked against a counted tree. 11_inodes_dir.py
"""Probe 11 - which directory is holding the inodes, checked against a tree that was counted.

A mount with no inodes left answers one question and refuses the next: ``df -i`` says the pool
is at 100% and nothing says where it went. Two commands answer it without a package - ``du
--inodes``, which counts files and directories per directory, and a ``find`` that prints each
file's parent and counts the repeats - and this probe runs both against a tree whose shape is
known before the command starts: 12,000 files in one directory, 3,000 in a nested one, 250 in a
third.

The recorded counts are compared with the numbers the probe created, so the page can claim the
commands agree with the file system rather than that they printed something. The same one-liner
is then run against a real mount on this host, to show the cost of asking.
"""
from __future__ import annotations

import json
import os
import pathlib
import shutil
import statistics
import subprocess
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "11_inodes_dir.json"
BASE = pathlib.Path("/dev/shm/enospc11")
SHAPE = {"a": 12_000, "b/deep": 3_000, "c": 250}
REAL_MOUNT = "/usr"


def build_tree() -> int:
    """Create the tree, returning how many files were made."""
    made = 0
    for relative, count in SHAPE.items():
        directory = BASE / relative
        directory.mkdir(parents=True)
        for index in range(count):
            (directory / f"f{index}").touch()
            made += 1
    return made


def run(argv: list[str], shell: bool = False) -> tuple[str, float]:
    started = time.perf_counter()
    completed = subprocess.run(argv, shell=shell, capture_output=True, text=True)
    elapsed = (time.perf_counter() - started) * 1000
    if completed.returncode != 0:
        raise SystemExit(f"{argv} failed: {completed.stderr[-400:]}")
    return completed.stdout, round(elapsed, 2)


def du_inodes(root: pathlib.Path) -> tuple[dict[str, int], float]:
    output, ms = run(["du", "--inodes", "-x", "--max-depth=1", str(root)])
    counts: dict[str, int] = {}
    for line in output.splitlines():
        count, _, path = line.partition("\t")
        counts[os.path.relpath(path, root) if path != str(root) else "."] = int(count)
    return counts, ms


def find_parents(root: pathlib.Path) -> tuple[dict[str, int], int, float]:
    pipeline = ("find \"$1\" -xdev -type f -printf '%h\\n' | sort | uniq -c | sort -rn")
    output, ms = run(["sh", "-c", pipeline, "sh", str(root)])
    counts: dict[str, int] = {}
    for line in output.splitlines():
        count, _, path = line.strip().partition(" ")
        counts[os.path.relpath(path, root) if path != str(root) else "."] = int(count)
    total, _ = run(["sh", "-c", "find \"$1\" -xdev -type f | wc -l", "sh", str(root)])
    return counts, int(total.strip()), ms


def measure() -> dict:
    made = build_tree()
    du_counts, du_ms = du_inodes(BASE)
    find_counts, find_total, find_ms = find_parents(BASE)
    return {
        "files_created": made,
        "du_a": du_counts.get("a", 0),
        "du_b": du_counts.get("b", 0),
        "du_c": du_counts.get("c", 0),
        "du_total": du_counts.get(".", 0),
        "du_ms": du_ms,
        "find_a": find_counts.get("a", 0),
        "find_b": find_counts.get("b/deep", 0),
        "find_c": find_counts.get("c", 0),
        "find_total": find_total,
        "find_ms": find_ms,
    }


def main() -> None:
    version, _ = run(["du", "--version"])
    real_runs = []
    for _ in range(5):
        usr_counts, usr_ms = du_inodes(pathlib.Path(REAL_MOUNT))
        top = max(((count, name) for name, count in usr_counts.items() if name != "."),
                  default=(0, "-"))
        real_runs.append({"total": usr_counts.get(".", 0), "top_count": top[0],
                          "top_name": top[1], "ms": usr_ms})
    real_median = statistics.median([entry["ms"] for entry in real_runs])

    runs = []
    for _ in range(5):
        shutil.rmtree(BASE, ignore_errors=True)
        BASE.mkdir()
        runs.append(measure())
    shutil.rmtree(BASE, ignore_errors=True)

    numeric = {}
    for key in runs[0]:
        values = [entry[key] for entry in runs]
        numeric[key] = {"median": statistics.median(values), "min": min(values),
                        "max": max(values)}
    record = {
        "mount": "/dev/shm",
        "repeats": 5,
        "shape": SHAPE,
        "du_version": version.strip(),
        "real_mount": REAL_MOUNT,
        "real_ms": real_median,
        "real_total": real_runs[0]["total"],
        "real_top_count": real_runs[0]["top_count"],
        "real_top_name": real_runs[0]["top_name"],
        "real_runs": real_runs,
        "real_identical": len({(entry["total"], entry["top_count"], entry["top_name"])
                                for entry in real_runs}) == 1,
        "identical": len({json.dumps(entry, sort_keys=True) for entry in runs}) == 1,
        "summary": numeric,
        "runs": runs,
        "cleanup_free_blocks": os.statvfs("/dev/shm").f_bfree,
    }
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    for key, value in numeric.items():
        print(f"{key:16s} {value['median']} [{value['min']}..{value['max']}]")
    print("identical:", record["identical"])
    print(f"{REAL_MOUNT}: total {record['real_total']} in {real_median} ms, "
          f"top {record['real_top_name']} {record['real_top_count']}, "
          f"identical {record['real_identical']}")


if __name__ == "__main__":
    main()
The descriptor scan at none, a thousand, and four thousand descriptors. 12_scan.py
"""Probe 12 - what the descriptor scan costs when the host has more to read.

The scan that finds a deleted-but-open file walks /proc/<pid>/fd for every process this user may
read. On the sandbox used for the rest of this page that was a handful of descriptors, so the
time it printed is the floor of the measurement and not a server's number. This probe puts a
known number of descriptors behind a child process and times the same scan with none, a
thousand, and four thousand of them, so the page can print the cost per descriptor instead of a
single small number that invites the wrong conclusion.
"""
from __future__ import annotations

import json
import os
import pathlib
import statistics
import subprocess
import sys
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "12_scan.json"

CHILD = """
import os
import resource
import sys
import time

count = int(sys.argv[1])
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (min(hard, count + 64), hard))
kept = [os.open(os.devnull, os.O_RDONLY) for _ in range(count)]
print("ready", os.getpid(), len(kept), flush=True)
time.sleep(30)
"""


def scan(root_pid: str = "") -> dict:
    """Walk /proc/<pid>/fd for descriptors whose link target ends in ' (deleted)'."""
    started = time.perf_counter()
    found = 0
    scanned = 0
    pids = 0
    for entry in os.scandir("/proc"):
        if not entry.name.isdigit():
            continue
        if root_pid and entry.name != root_pid:
            continue
        directory = f"/proc/{entry.name}/fd"
        try:
            names = os.listdir(directory)
        except OSError:
            continue
        pids += 1
        for name in names:
            scanned += 1
            try:
                if os.readlink(f"{directory}/{name}").endswith(" (deleted)"):
                    found += 1
            except OSError:
                continue
    return {"ms": round((time.perf_counter() - started) * 1000, 3), "scanned": scanned,
            "found": found, "pids": pids}


def measure(count: int) -> dict:
    child = None
    if count:
        child = subprocess.Popen([sys.executable, "-c", CHILD, str(count)],
                                 stdout=subprocess.PIPE, text=True)
        child.stdout.readline()
    try:
        scan()                      # warm the page cache of /proc and the interpreter
        return scan()
    finally:
        if child is not None:
            child.kill()
            child.wait()


def main() -> None:
    arms = []
    for label, count in (("no child process", 0), ("1000 descriptors", 1000),
                         ("4000 descriptors", 4000)):
        runs = [measure(count) for _ in range(5)]
        numeric = {}
        for key in runs[0]:
            values = [run[key] for run in runs]
            numeric[key] = {"median": statistics.median(values), "min": min(values),
                            "max": max(values)}
        arms.append({"label": label, "added": count, "summary": numeric, "runs": runs})
        print(label, {key: value["median"] for key, value in numeric.items()})

    record = {
        "repeats": 5,
        "baseline_summary": arms[0]["summary"],
        "arms": arms,
    }
    OUT.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8")
    print("wrote", OUT)


if __name__ == "__main__":
    main()

Keep reading

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