ETXTBSY errno 26: 7 Writes Refused, Rename Works, Scripts Never Locked

Dark cover headed 'Text file busy': errno 26 on a running binary, 7 write modes refused, a denial that lasted 1200.8 ms for a 1.20 s process, 46 of 46 execs refused by a held descriptor, a rename whose median was 9.55 ms while a process ran, and 53 passing tests

TL;DR: Seven Writes Refused, One Rename That Works

  • A file that is being executed refuses every write that needs a writable descriptor: 7 of the 9 open modes tried returned ETXTBSY (errno 26), and the two that were allowed open it for reading only.
  • The refusal lasts exactly as long as the process does: for a 1.20 s program the denial measured 1200.8 ms, 99.5% of its life, and not one poll in 4,384 found the file writable while it ran.
  • The same rule runs backwards: 46 of 46 exec attempts were refused while any process held a write descriptor, and the first attempt after the release ran 5 of 5 times.
  • A #! script is never locked while it runs, which makes it writable, not safe: a running script executes whichever text its interpreter reaches next, so a 5 KB bash script rewritten 0.30 s into its run ran a median of 101 old commands and 99 new ones over 5 runs; dash switched at the same 327 commands once the script passed its first read; and CPython ran only its old text (section 5).
  • Replacing the name still works: 100 renames of a name whose inode a process was executing cost a median of 9.55 ms, and the process kept the bytes it started with in 100 of 100.

Scope. One Linux host: kernel 6.12.118-guest-1.1, CPython 3.12.16, 2 CPUs, uid 1000 without privilege, 4,096-byte pages, the scratch directory on a virtiofs mount and the timing control on tmpfs. The binary under test is a 43,432-byte copy of /bin/sleep. Every arm was repeated 5 times with a fresh copy and a fresh process; timing is a median of 5 blocks of 20 operations, with the range beside it. The shell under test is bash 5.2.37, with dash – this host’s /bin/sh – measured against it, and every row that used a shell names which. Two sentences are quoted rather than measured and are marked where they appear: the open and execve manual pages say what the error means. Nothing below covers a network filesystem with its own locks, an overlay or a container’s layered filesystem, a runtime that intercepts execve, or a vendor-patched kernel.

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

Find the line that matches what you saw, make that one change, and check it against the measurement in the right-hand column rather than against intuition.

What you sawChange to make (and what measured it)
OSError: [Errno 26] Text file busy when a deploy overwrites a service binary that is still runningStop writing the inode. Write the new bytes to a temporary file beside the target and rename it over the name: the in-place write was refused with ETXTBSY 5 of 5 times and the rename accepted every time
cp: cannot create regular file ...: Text file busy, and the deploy script treats it as a disk problemcp opens the target for writing and stops at the inode; cp -f, install and sed -i all replaced the same running file, and only sed -i is atomic among the three (section 8)
set -e aborts a shell line at printf x > tool, and the line above it wrote half a binaryA redirect truncates first, so it needs the writable descriptor the kernel refuses. Write to tool.new and rename, which is also the only shape that never exposes a half-written name (section 8)
The error appears only in production, never on a laptopThe lock belongs to a running process, not to the machine: a 0.30 s process held it for 300.8 ms, and a host where nothing runs the binary never shows the error (section 3)
ps shows no such process, and the write still failsLook at the inode, not the name: a hard link and a symbolic link to the same inode are refused exactly like the original (26 and 26 refusals in section 6), and a copy with its own inode is not
A helper opens the binary for writing, then forks, and the child cannot exec itFind out who holds it: a descriptor in the parent refuses the child’s exec even when the child inherits nothing, a descriptor the child does inherit refuses it after the parent has closed its own, and one marked close-on-exec still refuses while the child sits between fork and exec (section 4)
A restart loop reports Text file busy for a second, then succeedsThe window is the process’s whole life, so the retry has to outlast it: with a 1 ms interval the measured wait after exit was 2.32 ms, with 20 ms it was 21.56 ms (section 10)
A shell script rewrites itself and keeps working, so the team rewrites a script that is still runningA script is not the file the kernel locks, and the interpreter decides what happens next: rewriting a running script changed the commands it executed in 5 of 8 rewrite arms (section 5). Replace the name
The service is written in Go or Rust and the deploy replaces it with cp inside a containerThe rule follows the inode, whatever compiled the binary: rename inside the same filesystem, or swap a fixed-name symlink atomically, and keep the old release directory until the process exits (sections 6 and 7)
The deploy probes the target by opening it for writing and a parallel start-up suddenly failsAsk the process table instead: reading /proc/<pid>/maps and the open descriptors found the running process in 0.35 ms without touching the file. Those two entries belong to the process, not to the reader, so a deploy user that is not the service user is refused them: count the refused processes and print how many were read, or a quiet answer is not proof (section 9)
Table 1: ten changes, matched to the sentence a reader has. Every row names the measurement behind it, and sections 3 to 10 carry the numbers.

1. What the Kernel Locks at Exec

An execve call hands the kernel a path. The kernel opens that file, checks that it may be executed, and denies every writer access to it for as long as the program runs: in its bookkeeping the inode carries a negative writer count, so any later write open is refused with ETXTBSY until the last reference to the image goes away. That description comes from the kernel source and is not measured here; what this page measures is everything a reader can see from outside.

The rule, quotedWhat this host did with it
open: ETXTBSY means the path refers to an executable image which is currently being executed and write access was requested7 write modes refused, 2 read modes allowed, each 5 of 5 (section 2)
execve: ETXTBSY means the Executable was open for writing by one or more processes46 of 46 execs refused while a descriptor was held, and 5 of 5 accepted after the release (section 4)
The lock belongs to the inode, so every name for that inode inherits itA hard link and a symbolic link were both refused with 26 and 26, and the inode in /proc/<pid>/maps equalled the file’s own inode 5 of 5 times
Neither page puts a time limit on it: the deny lasts while the image is mappedThe denial tracked the process to within 0.78 ms at the 1.20 s lifetime, and the file was writable again within 2.28 ms of the exit (section 3)
Table 2: the two quoted rules, the one inference from the kernel’s own data structures, and the measurement that met each. The quotes are from the manual pages; the numbers are this host’s.

Two consequences matter more than the error number. Any path that reaches the same inode reaches the same refusal, so the name is not what is locked; and a process that never writes the binary can still hold it open and stop the next exec, so a deploy that opens a file for writing and then forks can break its own child. A script bends both rules: the kernel executes the script’s inode first, but the process that ends up running is the interpreter, so the script itself is never locked again (section 5).

2. Seven Write Modes Refused, Two Read Modes Not

The first experiment asks the simplest question: with the binary running, which of the ways a program opens a file are refused? Every arm uses a fresh copy, a fresh process, and 5 attempts, and every attempt at the same mode got the same answer.

How the file was openedAttempts that opened itAttempts refusedRefusal
open('r')50opened
open('rb')50opened
open('r+')05ETXTBSY
open('w')05ETXTBSY
open('a')05ETXTBSY
os.open(O_WRONLY)05ETXTBSY
os.open(O_WRONLY|O_TRUNC)05ETXTBSY
os.open(O_RDWR)05ETXTBSY
os.open(O_APPEND|O_WRONLY)05ETXTBSY
Table 3: nine open modes against a running binary, 5 attempts each. The two read modes are the only ones the kernel allows.

The split is exactly at writability: r and rb opened the file 5 times out of 5, and the seven arms that asked for write access – including update mode r+ and append mode a – were refused every time. There is no partial success to design around. A tenth arm produces a different number: opening with exclusive create returned errno 17, EEXIST, because the name is already there, which is a naming accident rather than the lock.

Operation on the running fileWorkedFailedResult
read 4 KiB50worked
unlink50worked
chmod50worked
utime50worked
hardlink50worked
copyfile05ETXTBSY
mv within one directory50worked
mv across filesystems50renamed; the command exits 1
cp05ETXTBSY
install50worked
dd05ETXTBSY
tee05ETXTBSY
truncate -s 005ETXTBSY
sed -i50worked
sh -c 'printf x > file'05ETXTBSY
Table 4: fifteen operations that a deploy, a package manager or a person at a shell might use, each 5 times. No row that writes the running inode was allowed; the one non-zero exit is explained in section 8.

Operations that touch the name or the metadata worked every time; operations that open the inode for writing were refused every time. The working side is not one shape, though, and the difference matters as soon as something can fail halfway. sed -i edits a sibling copy and renames it into place, so the name always points at a complete file. install, cp -f and a cross-mount mv remove the target and then write a new file under the same name, which is why they never touch the running inode – and why a crash inside them leaves an executable that is missing or short (section 8).

3. The Window Is the Process’s Life

A deploy that fails once and succeeds a second later needs to know how long the failure lasts and whether it is a race. The next experiment starts a copy of the binary with a requested lifetime, then tries to open the same path for writing every few hundred microseconds until the open is finally allowed. Three lifetimes, 5 runs each, so the answer can be compared across process durations rather than trusted from one.

Lifetime asked forFirst refusal after startDenied forDenied rangeProcess livedRefused polls
0.30 s4.54 ms300.8 ms300.6-300.9 ms306.9 ms1,106
0.60 s4.95 ms600.8 ms600.6-601.3 ms608.0 ms2,199
1.20 s4.99 ms1200.8 ms1200.7-1200.9 ms1207.4 ms4,384
Table 5: the refusal window against three process lifetimes, 5 runs each, reported as the median. The refused-poll column counts every attempt the kernel said no to.

Read the third and fifth columns together. At the 1.20 s lifetime the refusal lasted 1200.8 ms and the process lived 1207.4 ms: the window is the process, not a timer, not a lease and not a timeout. The two shorter lifetimes moved past the requested duration by 0.75 ms and 0.83 ms – a fraction of one exec, not a floor a deploy can round up to. Each run’s own poll count was recorded, so the fifteen runs together made 38,379 attempts, every one of them refused: a running file never flickers into a writable state, and there is no lucky moment to catch.

The second column is not a property of the kernel. It is the time between the call that starts the child and the first refusal, and most of it is the parent’s own work in that call: about 5.0 ms at every lifetime, the same order as the fork and exec themselves. The useful bound is the other end: the open was allowed again within 1.33 ms of the exit on the shortest lifetime and 2.28 ms on the middle one, so a retry sampling every few milliseconds cannot miss the release by more than its own interval.

4. The Other Direction: an Open Writer Blocks the Exec

The error also appears when the exec is the thing that fails. This experiment forks a child that calls execv on the binary and reports the error number it got back, while a write descriptor on that binary is held in one of several places: this process, an unrelated process, or a hard link to the same inode.

Who holds the write descriptorExecs that ranExecs refusedResult
nothing open50ran
read-only fd held here50ran
write fd held here, closed before exec50ran
write fd held here through exec05ETXTBSY
read-write fd held here05ETXTBSY
append fd held here05ETXTBSY
write fd held by another process05ETXTBSY
write fd through a hard link05ETXTBSY
write fd held here, released before exec50ran
Table 6: 9 arms, each 5 exec attempts of the same binary. A descriptor held by any process is enough.

Five arms failed every time: a write descriptor held in this process through the exec, a read-write descriptor, an append descriptor, a descriptor held by a separate process, and one opened through a hard link. 46 of 46 exec attempts made while another process held a write descriptor were refused – 100.0% – so this direction is not a race either. The arms that ran had no writer anywhere: nothing open, a read-only descriptor, and two arms that let go of their descriptor before the exec.

A descriptor shared between a parent and a child is where this turns into a deploy bug, and the first table cannot tell inheritance from parentage: in every failing arm the parent was still holding its own descriptor. The second experiment separates them. It opens a write descriptor, starts a helper that waits, closes the descriptor in the parent, and only then lets the helper exec the file – so a refusal can only come from a descriptor the helper holds itself.

How the helper was spawnedDescriptors it sawExecs that ranExecs refused
nothing open, ordinary spawn050
write descriptor kept by the parent005
write descriptor, parent closes, helper spawned with close_fds=True050
write descriptor passed with pass_fds, parent closes105
write descriptor, helper spawned with close_fds=False050
inheritable write descriptor, helper spawned with close_fds=False105
read-only descriptor passed with pass_fds150
Table 7: 7 spawn shapes, 5 attempts each, with the parent’s descriptor closed before the helper called exec – except in the row that deliberately keeps it.

The row that keeps the descriptor in the parent is refused 5 times while the helper holds nothing: presence in another process is enough. The helper that actually inherits it – through pass_fds, or as an inheritable descriptor kept by close_fds=False – is refused 5 and 5 times after the parent has closed its own copy, which is the part a closing call in the parent cannot fix. A descriptor kept across a fork with close_fds=False but still marked close-on-exec was gone by the time the helper ran (0 descriptors seen), because the helper’s own exec closed it.

That flag is where the race hides, and it is worth measuring rather than trusting. Close-on-exec closes a descriptor at exec, not at fork, so a child forked by another thread holds its own copy of a close-on-exec write descriptor for as long as it takes to reach its own exec – and an exec from a third party in that window fails exactly as if the descriptor had been inheritable. The next arm forks a helper from a second thread with the deploy thread’s close-on-exec descriptor open, parks the helper between fork and exec, and execs the binary from the parent in the meantime. With the helper parked for 0.30 s, 326 of 326 attempts were refused with ETXTBSY; with the helper parked for only 0.02 s, 25 of 25 were refused; with no descriptor open at all, 0 of 30 were. The child’s own report names the flag: it held the descriptor in 5 of 5 runs, with open flags 0o2100001, and its own exec of that same binary was refused 5 of 5 times for the same reason: the kernel checks for writers before it applies the flag.

The release is clean and immediate. Once the holding process exited, the first exec attempt ran 5 of 5 times with no wait and no warm-up, and a hard link does not help: the descriptor opened on tool.link refused an exec of tool.bin, because both names reach one inode (section 6).

5. Scripts Are Never Locked, Their Interpreter Is

Most of the shell scripts people deploy are not binaries, and the rule changes for them. The kernel opens the script, sees the #! line, and executes the interpreter named there; the process that ends up running is the interpreter, and the script is a file it has already opened. The next experiment points the same write test at five ways of running a program and asks two questions of each: was the write allowed, and which file does the kernel show as the executed one?

How it was runningWrites allowedWrites refusedThe kernel’s executed fileTimes it appeared in maps
ELF, running05[dir]/tool.bin5
shebang /bin/sh, running50/bin/dash0
shebang python, running50/usr/local/bin/python3.120
python3 script.py, running50/usr/local/bin/python3.120
copy of the script’s interpreter, running05[dir]/interp.bin5
Table 8: five running forms, 5 attempts each. The last column counts how often the file appeared in the process’s own memory map.

The compiled binary was refused 5 times and appeared in the process’s map 5 times out of 5: it is the executed image. The three script arms allowed the write every time, and in each of them the kernel’s executed file was the interpreter – /bin/dash for the shell script and /usr/local/bin/python3.12 for the two Python forms – while the script itself never appeared in the map at all. A copy of the shell, started directly, was refused 5 times out of 5: deploying a new interpreter while the old one runs is an inode write in everything but name.

Because the script is not locked, nothing refuses the write. What happens next depends on how the interpreter reads its source. CPython reads the file, compiles the whole module and only then executes it, so the bytes on disk stop mattering at the first instruction. bash goes back to the file mid-run, which the next table shows at both sizes: write into a script under a running bash, and the next read can return the new text.

The next experiment does exactly that. Each script prints one marker per command with a short sleep between them; 0.30 s into the run the file is rewritten in place, same length, different marker, and the run finishes. Truncating the same kind of script mid-run is the second shape, dash runs the same script at four sizes as a contrast, and a CPython script is the control.

Script rewritten mid-runCommands in itOld text ranNew text ranRuns that executed new text
bash script, 127 bytes5325 of 5
bash script, 5,012 bytes200101995 of 5
dash script, 5,012 bytes20020000 of 5
bash script truncated to 10 bytes2009700 of 5
CPython script20020000 of 5
dash script, 12,012 bytes4803271535 of 5
dash script, 16,012 bytes6403273135 of 5
dash script, 37,512 bytes1,5003271,1735 of 5
Table 9: eight scripts rewritten in place 0.30 s into the run, the median command counts over 5 runs. Every script was still running when the write landed, and the write itself was allowed every time.

Every arm here was alive at the write – the 127-byte script lived 512 ms against a write at 303 ms – so timing is not what separates them. The 127-byte bash script ran 3 old commands and then 2 new ones: at 127 bytes the rewritten text was sitting where the shell read next. The 5,012-byte script switched the same way (101 old, 99 new). dash, given the same 5,012 bytes and the same 0.30 s write, ran all 200 old commands and 0 new, because at that size the whole script sat inside its first read and the write had nothing left to change. Truncation does not fail either – it ends the run: 97 of the 200 commands ran and the shell exited with status 0, a silent short run rather than an error. CPython executed all 200 of its commands from the old file and 0 from the new one.

The three dash rows above 5 KB are the ones that place the boundary, because they stopped at the same command at every size. At 12,012 bytes the rewrite produced 327 old commands and then 153 new ones; at 16,012 and 37,512 bytes the old text stopped at the same 327 commands and the new text carried the rest (1,173 of 1,500 commands at the largest size). Those 327 commands are the 8,175 bytes of complete command blocks that follow the 12-byte #! line, so 8,187 bytes in all went into the first read – all but the last 5 bytes of an 8,192-byte (8 KiB) block, and those 5 bytes are the first five characters of the printf that opens the next command. That block is the same at every size, so dash had read that far and not one byte further when the write landed, and the command that straddled that boundary ran the new text. It is neither a whole-file parser like CPython nor a reader that goes back to the file at every command like bash: it executes the text in its first read, then continues from the file, and the switch came in the same order in 5 runs of 5 at every size above it – an old prefix, then the new text, never interleaved.

So the safe sentence is narrower than “a running script can be rewritten”. The kernel never refuses the write, and which text the process executes afterwards is the interpreter’s business: bash mixed the two texts at both sizes measured, dash kept the text in its first read and then continued from the rewritten file, CPython kept the program it compiled, and truncation stopped a run early with no error. For a deploy the conclusion is the same as for a binary, for a different reason: replace the name, and every running interpreter keeps the file it opened. The exec side is stricter than the write side: a script that is open for writing cannot be executed, both forms returning ETXTBSY (errno 26), because the script’s own inode is the one the kernel denies while it sets up the interpreter. Finish writing the file, then exec it.

6. The Lock Follows the Inode, Not the Name

Every deploy eventually asks whether the path is the problem. The next experiment gives one running binary several names and compares what each one allows: a hard link, a symbolic link, a copy, a rename during the run, and the kernel’s own view of the mapped inode.

What was triedWhat happenedSame in every run
write through a hard linkrefused with ETXTBSYyes
write through a symbolic linkrefused with ETXTBSYyes
write to a copy with its own inodeallowedyes
rename the running file, then write the old nameold name ENOENT, new name ETXTBSYyes
inode in /proc/pid/maps is the file’s inodeequalyes
unlink a running file, read the old bytesread the old bytesyes
exec the original name while a hard link is open for writingrefused with ETXTBSYyes
Table 10: seven arms against one running binary, 5 attempts each. The last column says whether all five attempts answered identically.

A hard link and a symbolic link were both refused with ETXTBSY – 26 and 26 – while a copy with its own inode was allowed: the lock is a property of the object, and every name that resolves to it inherits the refusal. That is why a deploy that writes through a symlink into a release directory fails, and why replacing the symlink itself works. Renaming the running binary during the run made the old path fail with ENOENT (2) and the new path fail with ETXTBSY (26), while the process kept running without noticing. The kernel’s own record agrees: the inode listed for the binary in /proc/<pid>/maps equalled the file’s own inode in all 5 runs, and after the file was unlinked the process continued with the old bytes while its /proc/<pid>/exe link ended in (deleted).

7. Three Deploy Shapes and the One That Costs Nothing

A deploy over a running binary has three obvious shapes: write the bytes into the file, write a temporary file and rename it over the target, or remove the target and create a new one. The experiment runs each against a process that is executing the target, then asks whether the process survived, whether the kernel marks its executed file as deleted, and whether it is still executing the old bytes.

ShapeWorked, of fiveProcess survivedOld bytes servedNew inode
in-place write0550
temp file and rename5555
unlink and recreate5555
Table 11: three replacement shapes, 5 runs each against a process that was executing the target; the executed file was marked deleted in every run that worked.

The in-place write was refused 5 times out of 5 with ETXTBSY, which is the error this page is about. The other two worked every time, and the columns to the right of them say the same thing: the process kept running on the bytes it started with. The difference between the two working shapes is the window in the name. A rename is atomic – the name points at the old inode, then at the new one – while remove-and-create leaves the name missing for as long as the write takes, and a crash there leaves an executable that does not exist or one that is empty. Section 8 shows that window on real tools.

FilesystemPayloadRename onlyWrite, fsync, renamePlain write
tmpfs43,4320.006 ms0.021 ms0.013 ms
12,000,0000.514 ms3.885 ms3.602 ms
virtiofs43,4329.747 ms23.815 ms14.745 ms
12,000,00010.439 ms137.115 ms132.036 ms
Table 12: the shapes timed on the two filesystems, 5 blocks of 20 operations each, reported as the median of the block medians. Nothing is running during this timing.

The point of the table is the rename column against the last. On the virtiofs mount a rename took 9.75 ms for the small payload and 10.44 ms for the large one, a factor of 1.07, while the plain write grew from 14.75 ms to 132.04 ms, a factor of 9.0. A rename is a metadata round trip, and the price barely follows the payload; the write pays for every byte. On the RAM-backed tmpfs at /tmp – a 128 MiB mount here, sized by its size= option rather than by a disk – the rename stayed cheap in absolute terms: 0.006 ms for the small payload, but at the large payload it grew by a factor of 89, to 0.51 ms, while the plain write grew by 279. A rename copies no bytes, so that growth is not a copy: the same call also releases the pages of the file it replaced, and this page did not separate the two costs, so read that cell as the rename plus what the kernel frees, not as the price of a directory entry on its own.

Those timings are of an idle file, so the column a deploy cares about was measured separately: 100 renames of the same 43,432-byte name, each into an inode a process was executing at that moment – a fresh process per rename, and the process’s /proc/<pid>/exe and memory map checked against the inode before the rename ran, which held in 100 of 100 cases. The median was 9.55 ms (9.34-9.80 ms), the process survived all 100 renames with its original bytes, and the idle rename of the same payload in the table above costs the same order. That is the operation this page recommends, at the price this host charges for it: a rename does not become expensive because the inode it replaces is running.

# the shape that works while the service runs
install -m 755 ./build/tool /srv/app/tool.new
chown root:root /srv/app/tool.new         # needs CAP_CHOWN; chown drops file caps, so it comes first
setcap cap_net_bind_service=+ep /srv/app/tool.new   # needs CAP_SETFCAP, after the chown
mv /srv/app/tool.new /srv/app/tool          # same directory, same filesystem

# what fails, and why, on the same running file
cp ./build/tool /srv/app/tool               # Text file busy
printf 'x' > /srv/app/tool                  # Text file busy
cp -f ./build/tool /srv/app/tool            # works: it removes the name first
cp --remove-destination ./build/tool /srv/app/tool   # works, and leaves the name empty

The first group writes the new bytes under a name nobody is executing, sets what a rename does not carry, and then moves the name into place; the mv is the step that changes what is live. The second group is the same replacement written the way most scripts write it, with the measured outcome of each line beside it.

A rename is not a full copy of the file’s identity, and the things it leaves behind are the ones that bite. It carries the mode bits only: the new file is owned by whoever ran the deploy, so a binary that was root:root and is replaced by a non-root user becomes that user’s, and a service that checks ownership notices. Extended attributes, the SELinux label and file capabilities live on the inode, not in the bytes, so a new inode starts with the directory’s defaults and loses a setcap or a label the old file carried. A hard link does not follow either: other names for the old inode keep the old bytes, and the new name has one link. And a deploy path that is a symbolic link is replaced as a link, not followed – os.replace puts a regular file where the link was – so a release-directory symlink is swapped by creating a new link under a temporary name and renaming it over the old one (mv -T); the file the link resolves to is not touched, and the only thing that changes is which release the name points at.

The order for everything a rename does not carry is therefore staged file first, rename last. chown, setcap, the extended attributes and the SELinux label are applied to the temporary file beside the target, and only then is the name moved onto it. Applied after the rename instead, each of them leaves a window in which the live name points at a file that is missing its owner or its capabilities, and a service that restarts inside that window runs as the wrong user or without the capability the old file had – with nothing in the deploy that can tell it happened. The staged order costs nothing extra: the same calls on a file nobody can reach yet. Two of them need privilege of their own – chown needs root or CAP_CHOWN, setcap needs CAP_SETFCAP – and they have an order between them too: chown clears the file’s capabilities, so a setcap before it would be undone, and the chown goes first. A deploy that runs as the service user can set neither, and must either leave the file with the owner and capabilities it arrived with or stage it as the user that may set them.

8. What the Tools Print, and Which Ones Still Work

The last measurement is the one a person meets at a shell. Thirteen commands ran against the same running binary, five times each, with the exit status and the first line of output recorded. What matters is which have a mode that already does the safe thing, and what each one leaves behind.

CommandExitOutcomeFirst line of output
cp1refusedcp: cannot create regular file '[dir]/tool.bin': Text file busy
cp -f0worked–
cp --remove-destination0worked–
install -m 7550worked–
dd1refuseddd: failed to open '[dir]/tool.bin': Text file busy
tee1refusedtee: [dir]/tool.bin: Text file busy
truncate -s 01refusedtruncate: cannot open '[dir]/tool.bin' for writing: Text file busy
sh -c 'printf x > file'2refusedsh: 1: cannot create [dir]/tool.bin: Text file busy
sed -i0worked–
touch0worked–
chmod 7550worked–
mv (same directory)0worked–
mv (from another mount, read-only)1replaced, exit 1mv: setting attribute 'security.selinux' for 'security.selinux': Operation not permitted
Table 13: 13 commands against a running binary, 5 times each. The message text is the tool’s own; only the first line is shown.

5 commands failed with the message and 7 worked. The failures all open the target for writing: dd with conv=notrunc, tee, truncate setting a size, and the shell’s > redirect, which creates its descriptor before the command runs. Their exit status differs for the same cause – cp, dd, tee and truncate exit 1 and the shell exits 2. The working commands are not one shape either: touch, chmod and a same-directory mv never open the file for writing, sed -i writes a temporary copy and renames it back, and install, cp -f and cp --remove-destination remove the target and create a new file under the same name – a window in which the name is not the file you meant.

The window is measurable. A second phase ran each replacement against an 8 MB file and polled the name from another thread while the command worked, recording how often the name was missing and how often it existed with fewer bytes than the payload. The target in this phase was idle – no process was executing it – so what the poll sees is the window each tool opens in the name itself, not the refusal a running binary would add. install showed the name at zero bytes in 3 of 3 runs and inode-changed in all of them: it removed the old name and filled the new file in place. cp -f against an idle target did not even change the inode – its first open succeeded, so it truncated in place – and the name was seen short in 597 polls per run. cp --remove-destination and the cross-mount mv left the name missing outright in 6 of their six runs, then at zero bytes. sed -i and a temporary file renamed by hand never showed either state: the name pointed at the old file, then at the complete new one, and that is the shape to copy (yes for every run of both).

The thirteenth row is the one to read twice. A cross-mount mv from the read-only system mount replaced the name 5 times out of 5 – a new inode, the running process left on the old one – and still exited 1, for two reasons that have nothing to do with the lock: the destination mount refused the security.selinux extended attribute (EPERM, errno 1), and the source, /bin/sleep, is on a read-only mount it could not remove. It is not EXDEV: the copy crossed the mount, the new file was filled under the name, and the name changed. So the busy message never appears in this row, and a pipeline that reads this exit status as “the file was busy” would draw the wrong conclusion about a file that had already been replaced.

  • Prefer a temporary file beside the target plus a rename: the name never points at a half-written file, whatever happens next. sed -i and a same-directory mv already work that way.
  • cp -f and install are not stronger writes; they fall back to remove and create, which is why they work on a running file and why a crash in the middle leaves an empty or short executable.
  • Read the exit status with the message beside it: five commands exit 1 and the shell exits 2, and one of those five, the cross-mount mv, never printed the busy message at all.

9. A Small Package That Makes the Decision

Everything above is a decision a deploy can make before it writes anything, and the package these excerpts come from writes it down once: a diagnosis that reads the process table, a planner with one production strategy, and a replacement that stages a synced sibling and renames it. It is 6 modules and 385 non-blank lines, with 53 tests in 6 files. None of it opens the target for writing.

The diagnosis is the part that replaces the old trial write. Opening a file with O_WRONLY to see whether the kernel refuses is a write attempt: on an idle binary it succeeds and holds a write descriptor for a moment, which is exactly enough to make a concurrent start-up fail with the error this page is about. Reading the process table asks the same question without touching the file – the maps that name the inode, and the descriptors open for writing.

"""Reading who holds a file, without writing to it.

The question a deploy asks - would a write or an exec fail right now - can be answered from the
kernel's own bookkeeping instead of from a trial write. Two places hold the answer and both are
read-only: ``/proc/<pid>/maps`` names the device and inode a process has mapped, and
``/proc/<pid>/fd`` with ``fdinfo`` shows descriptors that are open for writing. A probe built
this way can never be the reason a concurrent exec fails, and it leaves no state behind.

``busy`` here means what the kernel would refuse: a write to an inode that a process is
executing, or an exec of an inode that a process holds open for writing. A ``#!`` script is
neither: the interpreter is the executed image and the script is a file it reads, so a script
reports no holders even while it runs - see the article for what that does to an in-place edit.

The limit is the reader's, not the file's: a process may open another process's ``maps`` and
``fd`` only when both run as the same user or the reader holds privilege, so a deploy that runs
as one user and a service that runs as another can be refused with ``EACCES``. A refused entry is
counted, never treated as "holds nothing", because that would turn permission into a false "not
busy": a diagnosis with ``complete`` False says what it could not read.
"""

from __future__ import annotations
import errno
import os
import pathlib
from dataclasses import dataclass

PROC = pathlib.Path("/proc")
WRITE_BITS = {1, 2}
DENIED = {errno.EACCES, errno.EPERM}


@dataclass(frozen=True)
class Diagnosis:
    """What the kernel's process table says about one path, and whether it would refuse."""

    path: str
    inode: int | None
    device: int | None
    exists: bool
    mapped_by: tuple[int, ...] = ()
    open_for_write_by: tuple[int, ...] = ()
    scanned: int = 0
    unreadable: tuple[int, ...] = ()

    @property
    def busy(self) -> bool:
        """True when a write open would be refused, or an exec of this inode refused."""
        return bool(self.mapped_by or self.open_for_write_by)

    @property
    def complete(self) -> bool:
        """False when some process could not be read, so a quiet answer is not proof."""
        return not self.unreadable

    @property
    def holders(self) -> tuple[int, ...]:
        """Every process that is executing the inode or holding it open for writing."""
        return tuple(sorted(set(self.mapped_by) | set(self.open_for_write_by)))

    def __str__(self) -> str:
        if not self.exists:
            return f"{self.path}: no such file"
        if self.busy:
            line = (f"{self.path}: inode {self.inode} mapped by {list(self.mapped_by)} "
                    f"and open for writing by {list(self.open_for_write_by)}")
        elif not self.complete:
            line = (f"{self.path}: inode {self.inode} held by none of the {self.scanned} "
                    f"processes readable here")
        else:
            line = f"{self.path}: inode {self.inode} held by no process among the " \
                   f"{self.scanned} readable"
        if not self.complete:
            line += f"; {len(self.unreadable)} process entries could not be read"
        return line


def diagnose(path: os.PathLike | str) -> Diagnosis:
    """Read the process table and report who holds this inode. Opens nothing for writing."""
    shown = os.fspath(path)
    try:
        info = os.stat(shown)
    except FileNotFoundError:
        return Diagnosis(shown, None, None, False)
    if not _is_regular(info):
        return Diagnosis(shown, info.st_ino, info.st_dev, True)
    mapped: list[int] = []
    writers: list[int] = []
    unreadable: list[int] = []
    pids = _pids()
    for pid in pids:
        found = _maps(pid, info)
        if found is None:
            unreadable.append(pid)
            continue
        if found:
            mapped.append(pid)
            continue
        found = _writes(pid, info)
        if found is None:
            unreadable.append(pid)
        elif found:
            writers.append(pid)
    return Diagnosis(shown, info.st_ino, info.st_dev, True, tuple(mapped), tuple(writers),
                     len(pids), tuple(unreadable))


def _is_regular(info: os.stat_result) -> bool:
    import stat

    return stat.S_ISREG(info.st_mode)


def _pids() -> list[int]:
    """Every numeric entry in /proc that this user may look at."""
    try:
        return [int(entry.name) for entry in PROC.iterdir() if entry.name.isdigit()]
    except OSError:
        return []


def _maps(pid: int, info: os.stat_result) -> bool | None:
    """True when the process maps the file; None when its table may not be read by this user."""
    device = f"{os.major(info.st_dev):02x}:{os.minor(info.st_dev):02x}"
    inode = str(info.st_ino)
    try:
        lines = (PROC / str(pid) / "maps").read_text(errors="replace").splitlines()
    except OSError as exc:
        return None if exc.errno in DENIED else False
    for line in lines:
        fields = line.split(maxsplit=5)
        if len(fields) < 5:
            continue
        if fields[3] == device and fields[4] == inode:
            return True
    return False


def _writes(pid: int, info: os.stat_result) -> bool | None:
    """True when the process holds a descriptor open for writing; None when it may not be read."""
    base = PROC / str(pid) / "fd"
    try:
        names = os.listdir(base)
    except OSError as exc:
        return None if exc.errno in DENIED else False
    for name in names:
        try:
            held = os.stat(base / name)
        except OSError:
            continue
        if held.st_ino != info.st_ino or held.st_dev != info.st_dev:
            continue
        try:
            flags = _flags(pid, name)
        except OSError as exc:
            if exc.errno in DENIED:
                return None
            continue
        if flags in WRITE_BITS:
            return True
    return False


def _flags(pid: int, name: str) -> int | None:
    """The access mode of one descriptor, from its ``fdinfo`` flags field."""
    text = (PROC / str(pid) / "fdinfo" / name).read_text(errors="replace")
    for line in text.splitlines():
        if line.startswith("flags:"):
            try:
                return int(line.split(":", 1)[1].strip(), 8) & 3
            except ValueError:
                return None
    return None

Those two entries are not the reader’s to open. /proc/<pid>/maps and /proc/<pid>/fd describe a process, not a file, and the kernel lets a reader into another process’s entries only when both run as the same user or the reader holds privilege (root, or CAP_SYS_PTRACE); the check that decides it, ptrace_may_access in the kernel’s own source, refuses with EACCES, errno 13. The number was measured on the one refusal this host can produce – a file this reader may not open, refused in 5 of 5 attempts – and the process case below is that rule carried to /proc, not a second user’s process observed: this host lists none to observe. On this host the same boundary hides them one step earlier: /proc is mounted with hidepid=invisible, so another user’s processes do not appear in the listing at all, and no counter can count what the listing does not contain.

So the package separates the two states. A process whose entries are refused is kept in unreadable, complete turns False, and the quiet line reads “held by none of the N processes readable here; M process entries could not be read”, adding that a quiet answer there is not proof. Without a refusal the same answer names how many processes it read, so the count is always visible. The stand-in /proc measured the split: one readable holder, one process whose maps could not be opened and one whose fd directory could not be listed gave busy: yes from the readable holder and kept the other 2 in unreadable, with complete False; a stand-in holding only the unreadable process gave busy: no and complete False, naming the 1 process it could not read – the false negative, made visible instead of silent; and a stand-in with one readable holder gave complete True. All three answered the same way in 5 runs of 5.

The rule that follows is one line: run the diagnosis as the user that runs the service, or with privilege enough to read it, and if neither is possible, read a quiet answer as “nothing I could see holds it” and compare the deploy user with the service user once, at install time. What the diagnosis must never do is turn a refusal into a zero.

The planner no longer chooses between shapes, because the measurement leaves one shape standing: it checks the two facts that can stop a deploy before it starts – a target that is a directory, a directory that cannot be written – and otherwise returns the rename with the sentence that goes into the log.

The replacement is a rename with the boring parts done properly: a temporary sibling, flushed and synced, carrying the target’s mode, removed if anything fails. Because the temporary file is a sibling, the rename cannot cross a mount, so there is no fallback path that gives up the name. The limits are the ones section 7 lists: mode bits only, and a symlink path replaced as a link.

"""Replacing a file by name, so a running process never has to be written to.

``atomic_replace`` writes the new bytes to a temporary file beside the target, flushes and
syncs them, gives the temporary file the target's mode, and renames it over the target. The
temporary file is a sibling by default, so the rename stays inside one directory and one
filesystem; a source file on another mount is read into that sibling first, which is what keeps
the final step a rename however the new bytes arrived.

There is no in-place path and no remove-then-write path here, on purpose. Both work on a running
binary, and both make the name point at an incomplete file while the bytes are written: this host
saw the source of the new bytes at zero bytes and part-way through in every run that used them
(article section 8). A crash inside that window leaves a broken executable under the name.
"""

from __future__ import annotations
import itertools
import os
import pathlib
import shutil

_SEQUENCE = itertools.count(1)


def staged_path(target: os.PathLike | str) -> pathlib.Path:
    """A name for the new bytes: a sibling of the target, unique per process and per call."""
    path = pathlib.Path(target)
    return path.parent / f".{path.name}.new-{os.getpid()}-{next(_SEQUENCE)}"


def atomic_replace(target: os.PathLike | str, payload: bytes | None = None, *,
                   source: os.PathLike | str | None = None, mode: int | None = None,
                   sync: bool = True) -> pathlib.Path:
    """Replace ``target`` with ``payload`` or ``source``, without writing to its inode."""
    if (payload is None) == (source is None):
        raise ValueError("give exactly one of payload and source")
    path = pathlib.Path(target)
    if mode is None:
        try:
            mode = path.stat().st_mode & 0o7777
        except FileNotFoundError:
            mode = 0o755
    temporary = staged_path(path)
    try:
        if source is not None:
            with open(source, "rb") as reader, open(temporary, "wb") as writer:
                shutil.copyfileobj(reader, writer)
                writer.flush()
                if sync:
                    os.fsync(writer.fileno())
        else:
            with open(temporary, "wb") as writer:
                writer.write(payload or b"")
                writer.flush()
                if sync:
                    os.fsync(writer.fileno())
        os.chmod(temporary, mode)
        os.replace(temporary, path)
        if sync:
            _sync_directory(path.parent)
        return path
    except BaseException:
        try:
            temporary.unlink()
        except FileNotFoundError:
            pass
        raise


def _sync_directory(directory: pathlib.Path) -> None:
    """Make the rename durable; not every platform allows opening a directory."""
    try:
        descriptor = os.open(directory, os.O_RDONLY)
    except OSError:
        return
    try:
        os.fsync(descriptor)
    except OSError:
        pass
    finally:
        os.close(descriptor)
What the package was asked to doWhat it didSame in every run
deploy to a running binaryatomic-replace; busy before: yesyes
deploy to an idle binaryatomic-replace; busy before: noyes
deploy from another filesystem while runningatomic-replace; old bytes keptyes
deploy through a symbolic link while the target runsatomic-replace; the link itself replacedyes
diagnose a running binarybusy: yes; 0.35 msyes
diagnose a running shebang scriptbusy: no; no holdersyes
dry run that has to name the holdernamed the processyes
Table 14: the package against real processes, 5 runs per arm.

The first four rows are one strategy applied to four situations; the fourth shows section 7’s limit in practice – the running process kept its inode, and the name at the symlink path became a regular file. The diagnosis row is 0.35 ms to find the process that maps the inode, cheap enough for every deploy. The script row reports no holder, because a script has none: the package will rename a running script, which is right, but nothing forces the caller to. The last row is the log line, and the whole deploy took 30.18 ms as a median, including the diagnosis, the copy, the sync and the rename.

10. At 3 a.m.: Wait, Replace, or Stop

The error rarely arrives alone. The deploy has to decide, in order, whether the file is busy, whether it can replace the name, how long to wait, and when to stop. The measured wait below is what a retry loop actually pays, at three polling intervals, against a process with about a third of a second left to live. A deploy that replaces the name does not need it; a deploy that must write in place does.

Retry intervalWait before the write succeededWorst of fiveWait / interval
1 ms2.32 ms3.27 ms2.32x
5 ms6.34 ms6.50 ms1.27x
20 ms21.56 ms21.78 ms1.08x
Table 15: the wait after a process exit at three polling intervals, 5 runs each. Every run had the same process lifetime.

The wait tracks the interval and not the process: at 1 ms the median wait was 2.32 ms, at 20 ms it was 21.56 ms, and the ratio stayed between 1.1 and 2.3 across the three. A retry that samples every few milliseconds therefore costs a few milliseconds – the price is bounded by the interval, which is the useful thing to tune.

  1. Diagnose first, without writing. Read /proc/<pid>/maps and the open descriptors; that answer tells a log line who holds the file, and it cannot cause the failure it is looking for.
  2. Replace the name. Stage the new bytes beside the target on the same filesystem, sync them, and rename. The measured rename kept the running process on its old inode in every run and cost a metadata operation rather than a copy.
  3. Never stage on another mount. The temporary file belongs in the target’s directory, whatever mount the new bytes come from, because that is what keeps the last step a rename. Section 8 shows what the tools that give up the name leave behind.
  4. Wait only if you must write in place. Then retry ETXTBSY alone, with a few milliseconds between attempts, and let every other error reach the log at once.
  5. Stop at a deadline you chose before the incident, not one the loop discovers. A process that has not exited in a minute is a different problem than a busy file.
  6. Keep the old inode until the process is gone. The bytes stay readable through /proc/<pid>/exe and the file is marked deleted only after the last reference goes, which is a useful property to test in a staging deploy.
  • Not answered here: a network filesystem that caches writes, a container runtime that rewrites execve, a vendor kernel with a patch, and a Windows or macOS host all behave differently enough to need their own measurement.
  • What to measure next: the shutdown time of the service being replaced, because the wait is the process’s life and nothing else.

The error’s name reads like a disk problem and it is a lifetime problem: the bytes of an executing file are in use, so rename the file, keep the inode, and the error is gone without a retry at all – with two habits around it, a descriptor closed before any fork that may outlive it (section 4) and the owner, label and capabilities set on the staged file before the name moves onto it (section 7).

Frequently asked questions

Why does the error say text file busy when the file is a binary?

The name is older than the case most people meet it in: a file with execute permission that is being executed is denied to writers, and the message has said Text file busy since long before containers made it common. The error number is the reliable part – ETXTBSY, errno 26 – whether the executed file is a binary or a script’s interpreter.

Is it safe to delete a running binary?

Yes: unlink worked 5 times out of 5 while the file ran, the process kept the old bytes, and /proc/<pid>/exe ended in (deleted) with the original hash. What is not safe is deleting the name and failing to create the new file: a restart then has nothing to exec.

Does a rename ever fail on a running binary?

Not within one filesystem: 100 renames replaced a name whose inode was executing, each into a fresh process, and every one succeeded while the process kept its old bytes. A rename changes a directory entry; the lock lives on the inode the entry used to point at, so the two never touch – and the price does not rise because the inode is running. A rename cannot cross a mount, which is EXDEV and nothing to do with the file being busy; and it carries the mode bits but not the owner, the extended attributes, the SELinux label, the capabilities or the other hard links, so those go on the staged file before the rename and not after it.

Is it safe to rewrite a script that is still running?

Only if you know how its interpreter reads source, and a rename removes the question. The kernel never locks the script, so the write is allowed. bash executed 101 old commands and then 99 new ones when its 5,012-byte script was rewritten 0.30 s into the run. dash is not a whole-file reader either: it ran all 200 old commands of that 5 KB script because the whole file fit in its first read, and at 12,012 bytes and above it ran the 327 commands of that first read and then the new text. CPython ran only the program it had compiled, and truncation ended a bash run early with status 0. Replace the name and every run keeps the file it opened.

Does install replace a running binary atomically?

No. It removes the target and creates a new file under the name, which is why it never meets ETXTBSY: the name was seen at zero bytes in 3 of 3 runs while the payload was written, and the inode changed every time. cp -f and cp --remove-destination behave the same way. Use a temporary file and a rename when the name must always point at a complete file.

Why did cp -f work when cp did not?

Because the force path is a fallback, not a stronger write: when the first open fails with ETXTBSY, cp removes the destination and creates it again, which is a new inode. It worked 5 of 5 times while the plain form was refused every time. Against an idle file the first open succeeds instead, and then it truncates in place: the inode did not even change in the measured runs. Either way the name can be short while the bytes are written.

What about a container that mounts the binary read-only?

Then the error is different – a read-only filesystem gives EROFS, not ETXTBSY, though that is the platform’s rule and not something this host measured – and no retry will help. The package’s diagnosis separates the two because it reads the process table and the descriptor flags, never the error text.

How do I know which inode the running process is using?

Read /proc/<pid>/maps and look for the path; the field before it is the inode, and on this host it equalled the file’s own inode in every run. /proc/<pid>/exe is the other view, ending in (deleted) once the name is gone. Both are readable without privilege for your own processes, and only for those: another user’s entries answer EACCES unless you are root or hold CAP_SYS_PTRACE.

Why does the diagnosis say the file is not busy when it is?

Because it could not read the process that holds it. The two entries it reads belong to the process, so a deploy user that differs from the service user is refused them, and a tool that treats a refusal as “holds nothing” reports busy: no about a running file. The package counts those processes instead: the diagnosis keeps them in unreadable, sets complete to False, and the log line says how many entries could not be read. On a host mounted hidepid=invisible the processes are not listed at all and cannot be counted, so the number of processes the answer was built from is the honest part of a quiet line.

Is there a signal or a timeout that ends the lock?

No. The window is the process’s life, measured at 1200.8 ms for a 1.20 s process and tracking the two shorter lifetimes the same way. Terminating the process releases it at once, and a graceful shutdown extends it by exactly as long as the shutdown takes; the retry interval is the only part a deploy controls.

Take the next step

TechBobby Engineering writes runbooks from measured failures: every measured number here came from one of the 9 probes in this article’s tree, run on the host described at the top of this page.

Appendix: The Probes Behind Sections 4 to 9

Each fold below is one probe, printed exactly as it ran, and these five carry every number in sections 4 to 9 – the script sizes of section 5 are the last arms of Probe 05, and the stand-in /proc of section 9 is the last arms of Probe 09. The four probes behind sections 1 to 3 and 6 – host facts, open modes, the window and inodes – measure the same way. The tree behind them is 9 probes, 6 package modules and 6 test files.

Probe 04 – the exec side, what a child inherits, and the fork-to-exec window 04_exec.py
"""Probe 04 - the other direction: a file open for writing cannot be executed.

The first group starts the same binary by fork and execv and reports the error number the
child came back with. What differs is who holds a write descriptor on the file while the exec
runs: this process, an unrelated process, an inherited descriptor, or nobody.

The second group separates inheritance from parentage. It opens a write descriptor, spawns a
helper that waits, then closes the descriptor in the parent, and only then lets the helper
exec the file. Each spawn mode (``close_fds`` on and off, ``pass_fds``, an inheritable
descriptor) decides whether the helper still holds the descriptor when it calls exec.

The third group is the race the flag does not cover: a descriptor marked close-on-exec, a
child forked from another thread that has not exec'd yet, and an exec attempt from a third
party in between. Close-on-exec closes at exec, not at fork, so the copy in the child keeps
the file busy for as long as the child takes to reach its own exec.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import shutil
import statistics
import subprocess
import sys
import tempfile
import threading
import time
import warnings

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "04_exec.json"
SOURCE = "/bin/sleep"
REPEATS = 5
HOLD_SECONDS = 0.4


def fresh(directory: pathlib.Path) -> pathlib.Path:
    target = directory / "tool.bin"
    if target.exists():
        target.unlink()
    shutil.copyfile(SOURCE, target)
    os.chmod(target, 0o755)
    return target


def try_exec(path: pathlib.Path) -> tuple[int | None, str]:
    """Attempt execv in a child; return (errno the child reported, its own message)."""
    read_end, write_end = os.pipe()
    pid = os.fork()
    if pid == 0:                                    # pragma: no cover - child process
        os.close(read_end)
        try:
            os.execv(str(path), [str(path), "0.05"])
        except OSError as exc:
            os.write(write_end, f"{exc.errno}\n{exc.strerror}".encode())
            os._exit(99)
        os._exit(0)
    os.close(write_end)
    with os.fdopen(read_end, "rb") as handle:
        said = handle.read().decode().strip()
    _, status = os.waitpid(pid, 0)
    if not said:
        return None, f"exit {status >> 8}"
    lines = said.splitlines()
    return int(lines[0]), lines[1] if len(lines) > 1 else ""


def held_by_other(path: pathlib.Path) -> subprocess.Popen:
    """A separate process that opens the file for writing and keeps the descriptor."""
    code = ("import os,sys,time\n"
            "fd=os.open(sys.argv[1], os.O_WRONLY)\n"
            "print('open', flush=True)\n"
            "time.sleep(float(sys.argv[2]))\n"
            "os.close(fd)\n")
    process = subprocess.Popen([sys.executable, "-c", code, str(path), str(HOLD_SECONDS)],
                               stdout=subprocess.PIPE, text=True)
    assert process.stdout is not None
    process.stdout.readline()
    return process


ARMS = [
    "nothing open",
    "read-only fd held here",
    "write fd held here, closed before exec",
    "write fd held here through exec",
    "read-write fd held here",
    "append fd held here",
    "write fd held by another process",
    "write fd through a hard link",
    "write fd held here, released before exec",
]


def one_attempt(directory: pathlib.Path, arm: str) -> tuple[int | None, str]:
    target = fresh(directory)
    fd: int | None = None
    other: subprocess.Popen | None = None
    try:
        if arm == "nothing open":
            pass
        elif arm == "read-only fd held here":
            fd = os.open(target, os.O_RDONLY)
        elif arm in ("write fd held here, closed before exec",
                     "write fd held here, released before exec"):
            fd = os.open(target, os.O_WRONLY)
            os.close(fd)
            fd = None
        elif arm == "write fd held here through exec":
            fd = os.open(target, os.O_WRONLY)
        elif arm == "read-write fd held here":
            fd = os.open(target, os.O_RDWR)
        elif arm == "append fd held here":
            fd = os.open(target, os.O_APPEND | os.O_WRONLY)
        elif arm == "write fd held by another process":
            other = held_by_other(target)
        elif arm == "write fd through a hard link":
            link = target.with_suffix(".link")
            if link.exists():
                link.unlink()
            os.link(target, link)
            fd = os.open(link, os.O_WRONLY)
        else:
            raise SystemExit(f"unknown arm {arm}")
        return try_exec(target)
    finally:
        if fd is not None:
            os.close(fd)
        if other is not None:
            other.wait(timeout=5)


CHILD = """import json, os, sys, time

target, gate, report = sys.argv[1:4]
while not os.path.exists(gate):
    time.sleep(0.001)
held = []
for name in os.listdir("/proc/self/fd"):
    try:
        link = os.readlink("/proc/self/fd/" + name)
    except OSError:
        continue
    if link == target:
        held.append(int(name))
with open(report, "w") as handle:
    json.dump({"held": len(held)}, handle)
try:
    os.execv(target, [target, "0.05"])
except OSError as exc:
    with open(report, "w") as handle:
        json.dump({"held": len(held), "errno": exc.errno}, handle)
    os._exit(99)
"""


def spawn_attempt(directory: pathlib.Path, arm: str) -> dict:
    """Spawn a helper, close the descriptor here, then let the helper exec the file."""
    target = fresh(directory)
    gate = directory / "gate"
    report = directory / "child.json"
    child = directory / "child.py"
    child.write_text(CHILD, encoding="utf-8")
    for path in (gate, report):
        if path.exists():
            path.unlink()
    options: dict = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
    fd = os.open(target, os.O_RDONLY if arm == "read-only fd passed to the helper" else os.O_WRONLY)
    if arm == "inheritable fd, close_fds=False":
        os.set_inheritable(fd, True)
    if "pass_fds" in arm or "passed to the helper" in arm:
        options["pass_fds"] = (fd,)
    if arm == "close_fds=False, descriptor close-on-exec" or arm.startswith("inheritable"):
        options["close_fds"] = False
    helper = subprocess.Popen([sys.executable, str(child), str(target), str(gate), str(report)],
                              **options)
    if arm != "write fd held here through the exec":
        os.close(fd)
        fd = -1
    gate.write_text("go", encoding="utf-8")
    code = helper.wait(timeout=10)
    if fd >= 0:
        os.close(fd)
    said = json.loads(report.read_text(encoding="utf-8")) if report.exists() else {}
    return {"held_by_child": said.get("held"), "errno": said.get("errno"),
            "child_exit": code, "ran": code == 0}


SPAWN_ARMS = [
    "no descriptor, close_fds=True",
    "write fd held here through the exec",
    "write fd, close_fds=True, parent closes",
    "write fd passed with pass_fds, parent closes",
    "close_fds=False, descriptor close-on-exec",
    "inheritable fd, close_fds=False",
    "read-only fd passed to the helper",
]

RACE_DELAY = 0.30
RACE_ARMS = (
    ("write fd, close-on-exec, child parked 0.30 s", True, RACE_DELAY, False),
    ("no descriptor, child parked 0.30 s", False, RACE_DELAY, False),
    ("write fd, close-on-exec, child parked 0.02 s", True, 0.02, False),
    ("write fd, close-on-exec, child execs the target itself", True, RACE_DELAY, True),
)


def fd_flags(fd: int) -> int | None:
    """The open file description's flags, in octal, from this process's own fdinfo."""
    try:
        text = pathlib.Path(f"/proc/self/fdinfo/{fd}").read_text(errors="replace")
    except OSError:
        return None
    for line in text.splitlines():
        if line.startswith("flags:"):
            return int(line.split(":", 1)[1].strip(), 8)
    return None


def fd_open(fd: int) -> bool:
    return pathlib.Path(f"/proc/self/fd/{fd}").exists()


def is_alive(pid: int) -> bool:
    """True until the child is a zombie; /proc is the only process table here."""
    try:
        state = pathlib.Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0]
    except OSError:
        return False
    return state != "Z"


def fork_helper(fd: int, delay: float, self_exec: pathlib.Path | None
                ) -> tuple[int, dict, threading.Event, dict, int]:
    """Fork a helper from a second thread; it reports what it holds, parks, then execs.

    The fork runs in a thread so the descriptor and the fork are owned by different threads,
    which is the shape a threaded deploy has: one thread writes the file, another starts work.
    The child announces the moment it is ready to exec and then waits for one byte from the
    parent, so every exec attempt counted by the caller happens while the child is still
    parked between fork and exec - the window the flag does not close.
    """
    read_end, write_end = os.pipe()
    go_read, go_write = os.pipe()
    holder: dict[str, int] = {}
    gate = threading.Event()
    said: dict = {}

    def worker() -> None:                               # pragma: no cover - forks
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            pid = os.fork()
        if pid == 0:
            try:
                os.close(read_end)
                os.close(go_write)
                report = {"fd_present": fd_open(fd), "flags": fd_flags(fd),
                          "fd_number": fd}
                os.write(write_end, (json.dumps(report) + "\n").encode())
                time.sleep(delay)
                os.write(write_end, b"exec\n")
                os.read(go_read, 1)
                target = self_exec if self_exec is not None else pathlib.Path("/bin/true")
                try:
                    os.execv(str(target), [str(target), "0.05"])
                except OSError as exc:
                    os.write(write_end, (json.dumps({"errno": exc.errno}) + "\n").encode())
            finally:
                os._exit(0)
        holder["pid"] = pid

    def reader() -> None:
        with os.fdopen(read_end, "rb") as handle:
            first = handle.readline().decode().strip()
            said.update(json.loads(first) if first else {})
            for line in handle:
                text = line.decode().strip()
                if text == "exec":
                    gate.set()
                elif text:
                    said.update(json.loads(text))

    thread = threading.Thread(target=worker)
    thread.start()
    thread.join()
    os.close(write_end)
    pumping = threading.Thread(target=reader, daemon=True)
    pumping.start()
    return holder["pid"], said, gate, {"thread": pumping}, go_write


def race_attempt(directory: pathlib.Path, hold_fd: bool, delay: float,
                 self_exec: bool) -> dict:
    """Hold a close-on-exec write descriptor, fork a waiting child, and exec from here."""
    target = fresh(directory)
    fd = os.open(target, os.O_WRONLY) if hold_fd else -1
    flags = fd_flags(fd) if hold_fd else None
    pid, report, gate, extra, go = fork_helper(fd, delay, target if self_exec else None)
    if hold_fd:
        os.close(fd)
    attempts = refused = 0
    errnos: set[int] = set()
    started = time.perf_counter()
    while not gate.is_set():
        value, _ = try_exec(target)
        attempts += 1
        if value is not None:
            refused += 1
            errnos.add(value)
        time.sleep(0.002)
    window_ms = (time.perf_counter() - started) * 1000
    os.write(go, b"g")
    os.close(go)
    os.waitpid(pid, 0)
    extra["thread"].join(timeout=5)
    after, _ = try_exec(target)
    return {"attempts": attempts, "refused": refused,
            "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
            "child_window_ms": window_ms, "child_fd_present": report.get("fd_present"),
            "child_flags_octal": f"{report.get('flags'):#o}" if report.get("flags") else None,
            "child_exec_errno": report.get("errno"),
            "close_on_exec": bool(flags and flags & os.O_CLOEXEC),
            "first_exec_after_window": after}


def main() -> None:
    directory = pathlib.Path(tempfile.mkdtemp(prefix="p04-", dir=HERE.parent / "scratch"))
    arms = []
    for arm in ARMS:
        results = [one_attempt(directory, arm) for _ in range(REPEATS)]
        errnos = {value for value, _ in results if value is not None}
        arms.append({
            "label": arm,
            "attempts": REPEATS,
            "succeeded": sum(1 for value, _ in results if value is None),
            "failed": sum(1 for value, _ in results if value is not None),
            "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
            "message": results[0][1],
            "stable": len({value is None for value, _ in results}) == 1,
        })
    # How many execs a writer's presence refuses, at a 2 ms cadence for half a second.
    target = fresh(directory)
    writer = held_by_other(target)
    refused = total = 0
    deadline = time.perf_counter() + HOLD_SECONDS / 2
    while time.perf_counter() < deadline:
        value, _ = try_exec(target)
        total += 1
        refused += value is not None
        time.sleep(0.002)
    writer.wait(timeout=5)
    immediate = [try_exec(target)[0] for _ in range(REPEATS)]
    spawns = []
    for arm in SPAWN_ARMS:
        results = [spawn_attempt(directory, arm) for _ in range(REPEATS)]
        errnos = {result["errno"] for result in results if result["errno"] is not None}
        spawns.append({
            "label": arm,
            "attempts": REPEATS,
            "ran": sum(1 for result in results if result["ran"]),
            "refused": sum(1 for result in results if not result["ran"]),
            "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
            "held_by_child": results[0]["held_by_child"],
            "stable": len({(result["ran"], result["held_by_child"]) for result in results}) == 1,
        })
    race = []
    for label, hold_fd, delay, self_exec in RACE_ARMS:
        runs = [race_attempt(directory, hold_fd, delay, self_exec) for _ in range(REPEATS)]
        race.append({
            "label": label,
            "attempts": REPEATS,
            "hold_fd": hold_fd,
            "delay_s": delay,
            "close_on_exec": runs[0]["close_on_exec"],
            "child_fd_present": sum(1 for run in runs if run["child_fd_present"]),
            "child_flags_octal": runs[0]["child_flags_octal"],
            "exec_attempts": sum(run["attempts"] for run in runs),
            "exec_refused": sum(run["refused"] for run in runs),
            "errno": runs[0]["errno"],
            "window_ms_median": statistics.median(run["child_window_ms"] for run in runs),
            "child_exec_refused": sum(1 for run in runs if run["child_exec_errno"] == 26),
            "child_exec_errno": runs[0]["child_exec_errno"],
            "ran_after": sum(1 for run in runs if run["first_exec_after_window"] is None),
        })
    shutil.rmtree(directory, ignore_errors=True)
    payload = {
        "repeats": REPEATS,
        "hold_seconds": HOLD_SECONDS,
        "arms": arms,
        "refused_error": errno.ETXTBSY,
        "all_failures_are_etxtbsy": all(arm["errno"] in (None, errno.ETXTBSY) for arm in arms),
        "every_arm_was_stable": all(arm["stable"] for arm in arms),
        "contention": {"attempts": total, "refused": refused,
                       "refused_pct": refused / total * 100 if total else 0.0},
        "first_exec_after_release": {"attempts": REPEATS,
                                     "succeeded": sum(1 for value in immediate if value is None)},
        "spawns": spawns,
        "every_spawn_arm_was_stable": all(arm["stable"] for arm in spawns),
        "race": race,
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    for arm in arms:
        print(f"{arm['label']:42s} ok {arm['succeeded']}/{arm['attempts']} "
              f"failed {arm['failed']}/{arm['attempts']} errno {arm['errno']} {arm['message'][:40]}")
    print("contention:", payload["contention"])
    print("after release:", payload["first_exec_after_release"])
    for arm in spawns:
        print(f"{arm['label']:48s} ran {arm['ran']}/{arm['attempts']} "
              f"held {arm['held_by_child']} errno {arm['errno']}")
    for arm in race:
        print(f"{arm['label']:52s} attempts {arm['exec_attempts']:4d} "
              f"refused {arm['exec_refused']:4d} errno {arm['errno']} "
              f"cloexec {arm['close_on_exec']} child-fd {arm['child_fd_present']}/"
              f"{arm['attempts']} window {arm['window_ms_median']:.0f} ms")


if __name__ == "__main__":
    main()
Probe 05 – scripts, bash against dash at four sizes, and rewriting one while it runs 05_script.py
"""Probe 05 - a script is not the file the kernel locks.

The same tests are pointed at a compiled binary and at three ways of running a text file:
a shell script through its #! line, a Python script through its #! line, and a Python
script handed to the interpreter by name. The rewrite arms then overwrite a script in
place while it runs, with the shell named explicitly (bash, and dash for the 5 KB
control), and record which text the process executed afterwards.

The last three arms take the dash rewrite past that 5 KB control - 12,012, 16,012 and
37,512 bytes - because a single size cannot show a boundary. Every command block is 25
bytes, so the command the output switches at multiplies back into the byte offset the
interpreter had read to, and the offset came out the same at all three sizes.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import shutil
import statistics
import subprocess
import sys
import tempfile
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "05_script.json"
SOURCE = "/bin/sleep"
INTERPRETER = "/bin/dash"
REPEATS = 5
PYTHON = os.path.realpath(sys.executable)

SHELL_SCRIPT = "#!/bin/sh\nsleep 0.6\n"
PY_SCRIPT = f"#!{PYTHON}\nimport time\ntime.sleep(0.6)\n"
RUN_SECONDS = 0.6


def fresh_elf(directory: pathlib.Path) -> pathlib.Path:
    target = directory / "tool.bin"
    if target.exists():
        target.unlink()
    shutil.copyfile(SOURCE, target)
    os.chmod(target, 0o755)
    return target


def script(directory: pathlib.Path, name: str, text: str) -> pathlib.Path:
    target = directory / name
    target.write_text(text, encoding="utf-8")
    os.chmod(target, 0o755)
    return target


def start(argv: list[str]) -> subprocess.Popen:
    process = subprocess.Popen(argv)
    time.sleep(0.12)
    return process


def write_attempt(path: pathlib.Path) -> tuple[bool, int | None]:
    try:
        handle = open(path, "r+b")
        handle.close()
        return True, None
    except OSError as exc:
        return False, exc.errno


def exe_of(pid: int) -> str:
    try:
        return os.readlink(f"/proc/{pid}/exe")
    except OSError as exc:
        return f"error {exc.errno}"


def maps_containing(pid: int, path: pathlib.Path) -> bool:
    try:
        text = pathlib.Path(f"/proc/{pid}/maps").read_text()
    except OSError:
        return False
    return str(path) in text


def try_exec(path: pathlib.Path) -> int | None:
    read_end, write_end = os.pipe()
    pid = os.fork()
    if pid == 0:                                    # pragma: no cover - child process
        os.close(read_end)
        try:
            os.execv(str(path), [str(path)])
        except OSError as exc:
            os.write(write_end, str(exc.errno).encode())
            os._exit(99)
        os._exit(0)
    os.close(write_end)
    with os.fdopen(read_end, "rb") as handle:
        said = handle.read().decode().strip()
    os.waitpid(pid, 0)
    return int(said) if said else None


def marker_arm(directory: pathlib.Path) -> dict:
    """Rewrite a running Python script; the old text should keep producing its marker."""
    first = directory / "marker_a.txt"
    second = directory / "marker_b.txt"
    for path in (first, second):
        if path.exists():
            path.unlink()
    target = script(directory, "loop.py",
                    f"#!{PYTHON}\nimport pathlib, time\nfor _ in range(60):\n"
                    f"    pathlib.Path({str(first)!r}).write_text('a')\n"
                    f"    time.sleep(0.02)\n")
    process = start([str(target)])
    time.sleep(0.15)
    written, error = write_attempt(target)
    target.write_text(f"#!{PYTHON}\nimport pathlib, time\nfor _ in range(60):\n"
                      f"    pathlib.Path({str(second)!r}).write_text('b')\n"
                      f"    time.sleep(0.02)\n", encoding="utf-8")
    process.wait(timeout=10)
    return {"write_allowed": written, "errno": error,
            "old_marker": first.exists(), "new_marker": second.exists()}


PY_LOOP = ("import time\nfor _ in range(200):\n    print('{mark}')\n    time.sleep(0.002)\n")


def shell_loop(count: int, sleep: float, mark: str, shell: str) -> str:
    lines = [f"#!{shell}"]
    for _ in range(count):
        lines.append(f"printf '{mark}\\n'")
        if sleep:
            lines.append(f"sleep {sleep}")
    return "\n".join(lines) + "\n"


def rewrite_arm(directory: pathlib.Path, label: str, count: int, sleep: float,
                truncate: bool = False, python: bool = False,
                shell: str = "/bin/bash") -> dict:
    """Rewrite a running script in place and watch which text keeps running."""
    if python:
        target = script(directory, "loop.py", PY_LOOP.format(mark="A"))
        argv = [PYTHON, str(target)]
        text_a = target.read_text(encoding="utf-8")
        interpreter = PYTHON
    else:
        target = script(directory, "loop.sh", shell_loop(count, sleep, "A", shell))
        argv = [shell, str(target)]
        text_a = target.read_text(encoding="utf-8")
        interpreter = shell
    started = time.perf_counter()
    process = subprocess.Popen(argv, stdout=subprocess.PIPE, text=True)
    time.sleep(0.30)
    # The process has to still be running for the write to land mid-run; the record says so.
    alive = process.poll() is None
    allowed, error = write_attempt(target)
    written = time.perf_counter()
    if truncate:
        with open(target, "r+b") as handle:
            handle.truncate(10)
            handle.flush()
            os.fsync(handle.fileno())
    elif python:
        target.write_text(PY_LOOP.format(mark="B"), encoding="utf-8")
    else:
        with open(target, "r+b") as handle:
            handle.write(shell_loop(count, sleep, "B", shell).encode())
            handle.flush()
            os.fsync(handle.fileno())
    out, _ = process.communicate(timeout=120)
    marks = out.split()
    # The command whose marker came from the rewritten text: everything after it did too.
    first_new = next((index for index, mark in enumerate(marks, start=1) if mark == "B"), None)
    read_to = None if python else (SHEBANG_BYTES + (first_new - 1) * BLOCK_BYTES
                                   if first_new else len(text_a.encode()))
    return {"label": label, "bytes": len(text_a), "commands": count,
            "write_allowed": allowed, "errno": error, "interpreter": interpreter,
            "alive_at_write": alive, "write_at_ms": (written - started) * 1000,
            "run_ms": (time.perf_counter() - started) * 1000,
            "old_text_ran": out.count("A"), "new_text_ran": out.count("B"),
            "switch_at_command": first_new, "read_to_bytes": read_to,
            "ordered": first_new is not None and marks[first_new:] == ["B"] * len(marks[first_new:]),
            "exit": process.returncode, "truncated": truncate}


def version_of(argv: list[str]) -> str:
    try:
        output = subprocess.run(argv, capture_output=True, text=True, timeout=10)
    except OSError as exc:
        return f"error {exc.errno}"
    return (output.stdout or output.stderr).splitlines()[0] if (output.stdout or output.stderr) else ""


BASH = "/bin/bash"
DASH = "/bin/dash"
TRUNCATED_BYTES = 10
BLOCK_BYTES = len("printf 'A\\n'") + 1 + len("sleep 0.002") + 1
SHEBANG_BYTES = len(f"#!{DASH}\n")
REWRITE_ARMS = (
    ("bash script, 127 bytes", 5, 0.1, False, False, BASH),
    ("bash script, 5,012 bytes", 200, 0.002, False, False, BASH),
    ("dash script, 5,012 bytes", 200, 0.002, False, False, DASH),
    ("bash script truncated to 10 bytes", 200, 0.002, True, False, BASH),
    ("CPython script", 200, 0.002, False, True, BASH),
)
# The sizes above the 5 KB control, each a whole number of 25-byte command blocks after the
# 12-byte #! line, so the command the switch lands on is a byte offset as well as a count.
DASH_BUFFER_ARMS = (
    ("dash script, 12,012 bytes", 480),
    ("dash script, 16,012 bytes", 640),
    ("dash script, 37,512 bytes", 1500),
)


def main() -> None:
    directory = pathlib.Path(tempfile.mkdtemp(prefix="p05-", dir=HERE.parent / "scratch"))
    arms = []

    def record(label: str, target: pathlib.Path, argv: list[str]) -> None:
        allowed = refused = 0
        errnos: set[int] = set()
        exes: set[str] = set()
        mapped = 0
        for _ in range(REPEATS):
            process = start(argv)
            exes.add(exe_of(process.pid))
            ok, error = write_attempt(target)
            mapped += maps_containing(process.pid, target)
            process.wait()
            if ok:
                allowed += 1
            else:
                refused += 1
                if error is not None:
                    errnos.add(error)
        arms.append({"label": label, "write_allowed": allowed, "write_refused": refused,
                     "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
                     "exe": sorted(exes)[0] if len(exes) == 1 else sorted(exes),
                     "mapped_in_maps": mapped, "attempts": REPEATS})

    elf = fresh_elf(directory)
    record("ELF, running", elf, [str(elf), "0.6"])

    shell = script(directory, "job.sh", SHELL_SCRIPT)
    record("shebang /bin/sh, running", shell, [str(shell)])

    py = script(directory, "job.py", PY_SCRIPT)
    record("shebang python, running", py, [str(py)])

    py2 = script(directory, "job2.py", PY_SCRIPT)
    record("python3 script.py, running", py2, [PYTHON, str(py2)])

    interp = directory / "interp.bin"
    if interp.exists():
        interp.unlink()
    shutil.copyfile(INTERPRETER, interp)
    os.chmod(interp, 0o755)
    record("copy of the script's interpreter, running", interp,
           [str(interp), "-c", "sleep 0.6"])

    exec_arms = []
    for label, path in (("ELF open for writing, exec attempted", fresh_elf(directory)),
                        ("shebang script open for writing, exec attempted",
                         script(directory, "waited.sh", "#!/bin/sh\nexit 0\n"))):
        errnos = set()
        for _ in range(REPEATS):
            fd = os.open(path, os.O_WRONLY)
            try:
                value = try_exec(path)
            finally:
                os.close(fd)
            errnos.add(value)
        exec_arms.append({"label": label, "attempts": REPEATS,
                          "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
                          "refused": sum(1 for value in errnos if value is not None) and REPEATS})

    markers = [marker_arm(directory) for _ in range(REPEATS)]
    rewrites = []
    for label, count, sleep, truncate, python, shell in REWRITE_ARMS:
        runs = [rewrite_arm(directory, label, count, sleep, truncate, python, shell)
                for _ in range(REPEATS)]
        rewrites.append({
            "label": label,
            "bytes": runs[0]["bytes"],
            "commands": runs[0]["commands"],
            "attempts": REPEATS,
            "interpreter": runs[0]["interpreter"],
            "alive_at_write": sum(1 for run in runs if run["alive_at_write"]),
            "write_at_ms": statistics.median(run["write_at_ms"] for run in runs),
            "run_ms": statistics.median(run["run_ms"] for run in runs),
            "old_text_ran": statistics.median(run["old_text_ran"] for run in runs),
            "new_text_ran": statistics.median(run["new_text_ran"] for run in runs),
            "runs_with_new_text": sum(1 for run in runs if run["new_text_ran"] > 0),
            "runs_with_old_text": sum(1 for run in runs if run["old_text_ran"] > 0),
            "write_allowed": sum(1 for run in runs if run["write_allowed"]),
            "exit_zero": sum(1 for run in runs if run["exit"] == 0),
        })
    buffer_arms = []
    for label, count in DASH_BUFFER_ARMS:
        runs = [rewrite_arm(directory, label, count, 0.002, False, False, DASH)
                for _ in range(REPEATS)]
        buffer_arms.append({
            "label": label,
            "size": runs[0]["bytes"],
            "commands": runs[0]["commands"],
            "attempts": REPEATS,
            "old_text_ran": statistics.median(run["old_text_ran"] for run in runs),
            "new_text_ran": statistics.median(run["new_text_ran"] for run in runs),
            "switch_at_command": statistics.median(run["switch_at_command"] for run in runs),
            "read_to_bytes": statistics.median(run["read_to_bytes"] for run in runs),
            "read_to_bytes_min": min(run["read_to_bytes"] for run in runs),
            "read_to_bytes_max": max(run["read_to_bytes"] for run in runs),
            "runs_with_new_text": sum(1 for run in runs if run["new_text_ran"] > 0),
            "runs_with_old_text": sum(1 for run in runs if run["old_text_ran"] > 0),
            "runs_ordered": sum(1 for run in runs if run["ordered"]),
            "write_allowed": sum(1 for run in runs if run["write_allowed"]),
            "alive_at_write": sum(1 for run in runs if run["alive_at_write"]),
            "exit_zero": sum(1 for run in runs if run["exit"] == 0),
        })
    shutil.rmtree(directory, ignore_errors=True)
    payload = {
        "repeats": REPEATS,
        "python": PYTHON,
        "arms": arms,
        "exec_arms": exec_arms,
        "marker_runs": markers,
        "rewrites": rewrites,
        "dash_buffer": {
            "repeats": REPEATS,
            "block_bytes": BLOCK_BYTES,
            "shebang_bytes": SHEBANG_BYTES,
            "arms": buffer_arms,
            # The byte dash had read to is the same at every size, which is what a fixed
            # first read means - and it is what the 5 KB control never reached.
            "first_read_bytes_median": statistics.median(arm["read_to_bytes"] for arm in buffer_arms),
            "first_read_bytes_min": min(arm["read_to_bytes_min"] for arm in buffer_arms),
            "first_read_bytes_max": max(arm["read_to_bytes_max"] for arm in buffer_arms),
            "old_commands_median": statistics.median(arm["old_text_ran"] for arm in buffer_arms),
            "switch_was_ordered": all(arm["runs_ordered"] == REPEATS for arm in buffer_arms),
            "every_arm_saw_new_text": all(arm["runs_with_new_text"] == REPEATS
                                          for arm in buffer_arms),
            "every_arm_kept_a_prefix": all(arm["runs_with_old_text"] == REPEATS
                                           for arm in buffer_arms),
        },
        "script_writes_allowed": all(arm["write_allowed"] == REPEATS for arm in arms
                                     if "running" in arm["label"] and "ELF" not in arm["label"]
                                     and "interpreter" not in arm["label"]),
        "elf_write_refused": next(arm["write_refused"] for arm in arms
                                  if arm["label"] == "ELF, running"),
        "interpreter_write_refused": next(arm["write_refused"] for arm in arms
                                          if arm["label"] == "copy of the script's interpreter, running"),
        "script_not_the_exe": all(not str(arm["exe"]).endswith(("job.sh", "job.py", "job2.py"))
                                  for arm in arms if "running" in arm["label"]
                                  and "ELF" not in arm["label"]),
        "old_text_kept_running": all(run["old_marker"] and not run["new_marker"] for run in markers),
        "errtxtbsy": errno.ETXTBSY,
        "shells": {
            "bash_path": BASH,
            "bash": version_of([BASH, "--version"]),
            "dash_path": DASH,
            "dash": "no version string; /bin/dash is this host's /bin/sh",
            "sh_link": os.path.realpath("/bin/sh"),
        },
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    for arm in arms:
        print(f"{arm['label']:38s} allowed {arm['write_allowed']}/{arm['attempts']} "
              f"refused {arm['write_refused']} errno {arm['errno']} exe {arm['exe']} "
              f"mapped {arm['mapped_in_maps']}")
    for arm in exec_arms:
        print(f"{arm['label']:44s} errno {arm['errno']}")
    print("markers:", markers)
    for arm in rewrites:
        print(f"{arm['label']:36s} bytes {arm['bytes']:6d} old {arm['old_text_ran']:6.1f} "
              f"new {arm['new_text_ran']:6.1f} runs-with-new {arm['runs_with_new_text']}/"
              f"{arm['attempts']} write allowed {arm['write_allowed']} "
              f"alive-at-write {arm['alive_at_write']}/{arm['attempts']} "
              f"run {arm['run_ms']:.0f} ms")
    print("script writes allowed:", payload["script_writes_allowed"],
          "old text kept running:", payload["old_text_kept_running"])
    for arm in buffer_arms:
        print(f"{arm['label']:26s} bytes {arm['size']:6d} commands {arm['commands']:5d} "
              f"old {arm['old_text_ran']:6.0f} new {arm['new_text_ran']:6.0f} "
              f"read-to {arm['read_to_bytes']:6.0f} B "
              f"({arm['read_to_bytes_min']:.0f}-{arm['read_to_bytes_max']:.0f}) "
              f"ordered {arm['runs_ordered']}/{arm['attempts']}")
    print("dash first read:", payload["dash_buffer"]["first_read_bytes_median"], "bytes",
          "| old commands:", payload["dash_buffer"]["old_commands_median"])


if __name__ == "__main__":
    main()
Probe 06 – the replacement shapes, what they cost, and the wait 06_deploy.py
"""Probe 06 - the deploy shapes that work, what a running process keeps, and what each costs.

Two questions a deploy script asks: which replacement of a running binary succeeds, and how
long a retry has to wait for the lock to clear. The answer to the first is timed on a small
binary and on a large file, because a rename should not care about size and a copy should.
"""
from __future__ import annotations

import errno
import hashlib
import json
import os
import pathlib
import shutil
import statistics
import subprocess
import tempfile
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "06_deploy.json"
SOURCE = "/bin/sleep"
SPARE = "/bin/true"
REPEATS = 5
BLOCK = 20
SIZES = (43432, 12_000_000)
INTERVALS = (0.001, 0.005, 0.020)


def digest(path: pathlib.Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def mapped(pid: int, inode: int) -> bool:
    """True when this process has a mapping of that inode (the binary, not a data file)."""
    try:
        text = pathlib.Path(f"/proc/{pid}/maps").read_text(errors="replace")
    except OSError:
        return False
    return any(line.split()[4] == str(inode) for line in text.splitlines()
               if len(line.split()) >= 5)


def fresh(directory: pathlib.Path, name: str = "tool.bin") -> pathlib.Path:
    target = directory / name
    if target.exists():
        target.unlink()
    shutil.copyfile(SOURCE, target)
    os.chmod(target, 0o755)
    return target


def start(target: pathlib.Path, seconds: str = "0.60") -> subprocess.Popen:
    process = subprocess.Popen([str(target), seconds])
    time.sleep(0.08)
    return process


def in_place(target: pathlib.Path, payload: bytes) -> tuple[bool, int | None]:
    try:
        with open(target, "wb") as handle:
            handle.write(payload)
        return True, None
    except OSError as exc:
        return False, exc.errno


def via_temp(target: pathlib.Path, payload: bytes) -> bool:
    temp = target.with_name(f".{target.name}.new")
    with open(temp, "wb") as handle:
        handle.write(payload)
        handle.flush()
        os.fsync(handle.fileno())
    os.chmod(temp, 0o755)
    os.replace(temp, target)
    return True


def via_unlink(target: pathlib.Path, payload: bytes) -> bool:
    target.unlink()
    with open(target, "wb") as handle:
        handle.write(payload)
    os.chmod(target, 0o755)
    return True


def floor_ms(values: list[float]) -> dict:
    return {"median": statistics.median(values), "min": min(values), "max": max(values)}


def time_cost(base: str, size: int) -> dict:
    """Time the three shapes on one filesystem; a rename should ignore the size."""
    payload = b"\0" * size
    work = pathlib.Path(tempfile.mkdtemp(prefix="cost-", dir=base))
    target = work / "payload.bin"
    rename_blocks, write_rename_blocks, copy_blocks = [], [], []
    for _ in range(REPEATS):
        rename_times, write_times, copy_times = [], [], []
        for index in range(BLOCK):
            temp = work / f"payload.{index}.new"
            temp.write_bytes(payload)
            started = time.perf_counter()
            os.replace(temp, target)
            rename_times.append((time.perf_counter() - started) * 1000)
        for index in range(BLOCK):
            temp = work / f"write.{index}.new"
            started = time.perf_counter()
            with open(temp, "wb") as handle:
                handle.write(payload)
                handle.flush()
                os.fsync(handle.fileno())
            os.replace(temp, target)
            write_times.append((time.perf_counter() - started) * 1000)
        for _ in range(BLOCK):
            started = time.perf_counter()
            with open(target, "wb") as handle:
                handle.write(payload)
            copy_times.append((time.perf_counter() - started) * 1000)
        rename_blocks.append(statistics.median(rename_times))
        write_rename_blocks.append(statistics.median(write_times))
        copy_blocks.append(statistics.median(copy_times))
    shutil.rmtree(work, ignore_errors=True)
    return {
        "fs": "tmpfs" if base == "/tmp" else "virtiofs (this workspace)",
        "size": size,
        "rename": {"blocks": rename_blocks, **floor_ms(rename_blocks)},
        "write_fsync_rename": {"blocks": write_rename_blocks, **floor_ms(write_rename_blocks)},
        "plain_write": {"blocks": copy_blocks, **floor_ms(copy_blocks)},
    }


def rename_while_running(directory: pathlib.Path) -> dict:
    """Time renames of a name whose inode a process is executing, every iteration.

    The earlier version of this measurement renamed once into a running file and then
    ninety-nine times into an idle one, so its median described an idle rename. This one
    gives every rename its own process: a fresh copy of the binary is started, the rename
    waits until that process maps the copy's inode, the rename replaces the name, and the
    process is then checked for survival and for the bytes it is still executing.
    """
    payload = pathlib.Path(SOURCE).read_bytes()
    blocks: list[float] = []
    verified = survived_runs = old_bytes_runs = 0
    total = 0
    wait_ms: list[float] = []
    for _ in range(REPEATS):
        times: list[float] = []
        for index in range(BLOCK):
            target = fresh(directory)
            inode = os.stat(target).st_ino
            process = subprocess.Popen([str(target), "4.0"])
            waited = time.perf_counter()
            while not mapped(process.pid, inode):
                if process.poll() is not None or time.perf_counter() - waited > 2.0:
                    raise SystemExit("the process never mapped the new copy")
                time.sleep(0.0005)
            wait_ms.append((time.perf_counter() - waited) * 1000)
            before = digest(pathlib.Path(f"/proc/{process.pid}/exe"))
            temp = directory / f"live.{index}.new"
            temp.write_bytes(payload)
            if mapped(process.pid, inode):
                verified += 1
            started = time.perf_counter()
            os.replace(temp, target)
            times.append((time.perf_counter() - started) * 1000)
            total += 1
            alive = process.poll() is None
            survived_runs += alive
            old_bytes_runs += alive and digest(pathlib.Path(f"/proc/{process.pid}/exe")) == before
            process.terminate()
            process.wait(timeout=10)
        blocks.append(statistics.median(times))
    return {"median": statistics.median(blocks), "min": min(blocks), "max": max(blocks),
            "blocks": blocks, "size": len(payload), "renames": total,
            "verified_running": verified, "process_survived": survived_runs,
            "old_bytes_served": old_bytes_runs,
            "verify_wait_ms_median": statistics.median(wait_ms)}


def retry_latency(directory: pathlib.Path, interval: float) -> dict:
    target = fresh(directory)
    process = start(target, "0.30")
    exit_seen = None
    attempts = 0
    refused = 0
    while True:
        attempts += 1
        try:
            handle = os.open(target, os.O_WRONLY)
            os.close(handle)
            if exit_seen is not None:
                break
        except OSError as exc:
            if exc.errno != errno.ETXTBSY:
                raise
            refused += 1
        if exit_seen is None and process.poll() is not None:
            exit_seen = time.perf_counter()
        if exit_seen is not None and time.perf_counter() - exit_seen > 1.0:
            raise SystemExit("the lock did not clear")
        time.sleep(interval)
    latency = (time.perf_counter() - exit_seen) * 1000
    process.wait()
    return {"interval_ms": interval * 1000, "attempts": attempts, "refused": refused,
            "latency_ms": latency}


def main() -> None:
    directory = pathlib.Path(tempfile.mkdtemp(prefix="p06-", dir=HERE.parent / "scratch"))
    arms = []
    for label, operation in (("in-place write", in_place), ("temp file and rename", via_temp),
                             ("unlink and recreate", via_unlink)):
        worked = failed = 0
        errnos: set[int] = set()
        survivors = 0
        deleted = 0
        kept_old = 0
        inode_changed = 0
        for _ in range(REPEATS):
            target = fresh(directory)
            before = digest(target)
            inode_before = os.stat(target).st_ino
            process = start(target)
            payload = pathlib.Path(SPARE).read_bytes()
            if operation is in_place:
                ok, error = operation(target, payload)
            else:
                ok, error = operation(target, payload), None
            if ok:
                worked += 1
                inode_changed += os.stat(target).st_ino != inode_before
            else:
                failed += 1
                if error is not None:
                    errnos.add(error)
            # The process columns are about the process, not about the write: a refused write
            # leaves it running on its old bytes too, which is what the reader needs to see.
            if process.poll() is None:
                survivors += 1
                exe = pathlib.Path(f"/proc/{process.pid}/exe")
                deleted += str(exe.readlink()).endswith("(deleted)")
                kept_old += digest(exe) == before
            process.wait()
        arms.append({"label": label, "worked": worked, "failed": failed,
                     "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
                     "process_survived": survivors, "exe_marked_deleted": deleted,
                     "old_bytes_still_served": kept_old, "inode_changed": inode_changed,
                     "attempts": REPEATS})

    costs = [time_cost(base, size) for base in ("/tmp", str(HERE.parent / "scratch"))
             for size in SIZES]
    live_rename = rename_while_running(directory)
    retries = [{"interval_ms": interval * 1000,
                "runs": [retry_latency(directory, interval) for _ in range(REPEATS)]}
               for interval in INTERVALS]
    for group in retries:
        for run in group["runs"]:
            run.pop("attempts")
        group["latency_median_ms"] = statistics.median(run["latency_ms"] for run in group["runs"])
        group["latency_max_ms"] = max(run["latency_ms"] for run in group["runs"])
    shutil.rmtree(directory, ignore_errors=True)
    payload = {
        "repeats": REPEATS,
        "block": BLOCK,
        "sizes": list(SIZES),
        "arms": arms,
        "costs": costs,
        "live_rename": live_rename,
        "retries": retries,
        "in_place_refused": next(arm["failed"] for arm in arms if arm["label"] == "in-place write"),
        "replace_kept_the_process": all(arm["process_survived"] == REPEATS for arm in arms
                                        if arm["label"] != "in-place write"),
        "rename_is_cheaper_than_the_write": all(
            cost["rename"]["median"] < cost["write_fsync_rename"]["median"] for cost in costs),
        "all_refusals_etxtbsy": all(arm["errno"] in (None, errno.ETXTBSY) for arm in arms),
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    for arm in arms:
        print(f"{arm['label']:22s} worked {arm['worked']}/{arm['attempts']} errno {arm['errno']} "
              f"alive {arm['process_survived']} deleted {arm['exe_marked_deleted']} "
              f"old {arm['old_bytes_still_served']} inode {arm['inode_changed']}")
    for cost in costs:
        print(f"{cost['fs']:28s} size {cost['size']:>9,}: rename {cost['rename']['median']:.3f} ms "
              f"write+fsync+rename {cost['write_fsync_rename']['median']:.3f} ms "
              f"plain write {cost['plain_write']['median']:.3f} ms")
    print(f"rename while a process runs: median {live_rename['median']:.3f} ms "
          f"({live_rename['min']:.3f}-{live_rename['max']:.3f}), "
          f"size {live_rename['size']:,}, renames {live_rename['renames']}, "
          f"verified running {live_rename['verified_running']}, "
          f"survived {live_rename['process_survived']}, "
          f"old bytes {live_rename['old_bytes_served']}")
    for group in retries:
        print(f"retry {group['interval_ms']:.0f} ms: latency median "
              f"{group['latency_median_ms']:.2f} ms max {group['latency_max_ms']:.2f} ms")


if __name__ == "__main__":
    main()
Probe 08 – thirteen shell commands, their output, and the name while they write 08_tools.py
"""Probe 08 - what the shell tools print and return when the file is busy.

The same replacement is tried with the commands a deploy script actually uses, and the exact
message and exit status are recorded, because a runbook that says "cp fails" is less useful
than one that says what the line looks like.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import shutil
import subprocess
import tempfile
import threading
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "08_tools.json"
SOURCE = "/bin/sleep"
REPEATS = 5

ARMS = [
    ("cp", ["cp", SOURCE, "{target}"]),
    ("cp -f", ["cp", "-f", SOURCE, "{target}"]),
    ("cp --remove-destination", ["cp", "--remove-destination", SOURCE, "{target}"]),
    ("install -m 755", ["install", "-m", "755", SOURCE, "{target}"]),
    ("dd", ["dd", f"if={SOURCE}", "of={target}", "conv=notrunc"]),
    ("tee", ["sh", "-c", f"cat {SOURCE} | tee {{target}} > /dev/null"]),
    ("truncate -s 0", ["truncate", "-s", "0", "{target}"]),
    ("sh -c 'printf x > file'", ["sh", "-c", "printf x > {target}"]),
    ("sed -i", ["sed", "-i", "s/sleep/sleeping/", "{target}"]),
    ("touch", ["touch", "{target}"]),
    ("chmod 755", ["chmod", "755", "{target}"]),
    ("mv (same directory)", ["sh", "-c", "mv {spare} {target}"]),
    ("mv (from the read-only system mount)", ["mv", SOURCE, "{target}"]),
]


def fresh(directory: pathlib.Path) -> pathlib.Path:
    target = directory / "tool.bin"
    if target.exists():
        target.unlink()
    shutil.copyfile(SOURCE, target)
    os.chmod(target, 0o755)
    spare = directory / "spare.bin"
    if spare.exists():
        spare.unlink()
    shutil.copyfile(SOURCE, spare)
    os.chmod(spare, 0o755)
    return target


# A second question about the same tools: while the bytes are copied, does the name show the
# new file before it is complete? A rename cannot: the name points at the old inode or the new
# one, both complete. An unlink-then-write can, and that is what a reader execs in between.
GAP_SIZE = 8 * 1024 * 1024
GAP_SOURCE = pathlib.Path("/tmp") / f"p08-gap-{os.getpid()}.bin"
GAP_ARMS = [
    ("install -m 755", ["install", "-m", "755", str(GAP_SOURCE), "{target}"]),
    ("cp -f", ["cp", "-f", str(GAP_SOURCE), "{target}"]),
    ("cp --remove-destination", ["cp", "--remove-destination", str(GAP_SOURCE), "{target}"]),
    ("mv (from another mount)", ["mv", "-f", str(GAP_SOURCE), "{target}"]),
    ("sed -i", ["sed", "-i", "s/1/2/g", "{target}"]),
]


class Watcher(threading.Thread):
    """Poll the name while a command replaces it, and count what a reader would have seen."""

    def __init__(self, path: pathlib.Path, size: int) -> None:
        super().__init__(daemon=True)
        self.path = path
        self.size = size
        self.stop = False
        self.absent = 0
        self.partial = 0
        self.smallest = None
        self.polls = 0

    def run(self) -> None:
        while not self.stop:
            self.polls += 1
            try:
                found = os.stat(self.path).st_size
            except FileNotFoundError:
                self.absent += 1
                continue
            if found != self.size:
                self.partial += 1
                self.smallest = found if self.smallest is None else min(self.smallest, found)


def gap_arm(directory: pathlib.Path, label: str, argv: list[str]) -> dict:
    GAP_SOURCE.write_bytes(b"0" * GAP_SIZE + b"\n")
    expected = GAP_SIZE + 1
    target = directory / "gap.bin"
    if target.exists():
        target.unlink()
    target.write_bytes(b"1" * GAP_SIZE + b"\n")
    inode_before = os.stat(target).st_ino
    watcher = Watcher(target, expected)
    watcher.start()
    time.sleep(0.02)
    done = subprocess.run([part.format(target=str(target)) for part in argv],
                          capture_output=True, text=True)
    time.sleep(0.02)
    watcher.stop = True
    watcher.join()
    after = os.stat(target).st_ino if target.exists() else None
    return {"label": label, "returncode": done.returncode, "polls": watcher.polls,
            "absent": watcher.absent, "partial": watcher.partial,
            "smallest": watcher.smallest, "inode_changed": after is not None and after != inode_before,
            "final": target.stat().st_size if target.exists() else None}


def gap_rename(directory: pathlib.Path) -> dict:
    """The control: a temporary file beside the target, renamed over it."""
    GAP_SOURCE.write_bytes(b"0" * GAP_SIZE + b"\n")
    expected = GAP_SIZE + 1
    target = directory / "gap.bin"
    if target.exists():
        target.unlink()
    target.write_bytes(b"1" * GAP_SIZE + b"\n")
    inode_before = os.stat(target).st_ino
    temp = directory / "gap.new"
    shutil.copyfile(GAP_SOURCE, temp)
    watcher = Watcher(target, expected)
    watcher.start()
    time.sleep(0.02)
    os.replace(temp, target)
    time.sleep(0.02)
    watcher.stop = True
    watcher.join()
    return {"label": "temp file and rename", "returncode": 0, "polls": watcher.polls,
            "absent": watcher.absent, "partial": watcher.partial, "smallest": watcher.smallest,
            "inode_changed": os.stat(target).st_ino != inode_before,
            "final": target.stat().st_size}


def main() -> None:
    directory = pathlib.Path(tempfile.mkdtemp(prefix="p08-", dir=HERE.parent / "scratch"))
    arms = []
    for label, template in ARMS:
        results = []
        for _ in range(REPEATS):
            target = fresh(directory)
            inode_before = os.stat(target).st_ino
            spare = directory / "spare.bin"
            argv = [part.format(target=str(target), spare=str(spare)) for part in template]
            process = subprocess.Popen([str(target), "0.45"])
            time.sleep(0.08)
            done = subprocess.run(argv, capture_output=True, text=True)
            alive = process.poll() is None
            process.wait()
            message = (done.stderr or done.stdout).strip().splitlines()
            replaced = (target.exists() and os.stat(target).st_ino != inode_before
                        and target.read_bytes() == pathlib.Path(SOURCE).read_bytes())
            results.append({"returncode": done.returncode,
                            "message": message[0] if message else "",
                            "process_alive": alive,
                            "name_replaced": replaced,
                            "text_file_busy": "Text file busy" in (done.stderr + done.stdout)})
        codes = {result["returncode"] for result in results}
        busy = sum(result["text_file_busy"] for result in results)
        arms.append({"label": label, "attempts": REPEATS, "returncodes": sorted(codes),
                     "text_file_busy": busy,
                     "name_replaced": sum(result["name_replaced"] for result in results),
                     "message": results[0]["message"],
                     "stable": len(codes) == 1 and len({result["message"] for result in results}) == 1})
    gaps = [gap_arm(directory, label, argv) for label, argv in GAP_ARMS for _ in range(3)]
    gaps.append(gap_rename(directory))
    gaps.append(gap_rename(directory))
    GAP_SOURCE.unlink(missing_ok=True)
    shutil.rmtree(directory, ignore_errors=True)
    payload = {
        "repeats": REPEATS,
        "arms": arms,
        "failed_tools": [arm["label"] for arm in arms if arm["text_file_busy"] == REPEATS],
        "worked_tools": [arm["label"] for arm in arms
                         if arm["text_file_busy"] == 0 and arm["returncodes"] == [0]],
        "replaced_tools": [arm["label"] for arm in arms
                           if arm["text_file_busy"] == 0 and arm["name_replaced"] == REPEATS
                           and 0 not in arm["returncodes"]],
        "failed_otherwise": [arm["label"] for arm in arms
                             if arm["text_file_busy"] == 0 and 0 not in arm["returncodes"]
                             and arm["name_replaced"] < REPEATS],
        "every_arm_stable": all(arm["stable"] for arm in arms),
        "gaps": gaps,
        "etxtbsy": errno.ETXTBSY,
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    for arm in arms:
        print(f"{arm['label']:40s} rc {arm['returncodes']} busy {arm['text_file_busy']}/{REPEATS} "
              f"| {arm['message'][:78]}")
    for row in gaps:
        print(f"{row['label']:26s} rc {row['returncode']:2d} polls {row['polls']:6d} "
              f"absent {row['absent']:5d} partial {row['partial']:6d} smallest {row['smallest']} "
              f"inode changed {row['inode_changed']}")


if __name__ == "__main__":
    main()
Probe 09 – the package against real processes, and a stand-in /proc that refuses it 09_library.py
"""Probe 09 - the package against the behaviour probes 02 to 08 measured.

The unit tests prove the functions do what their docstrings say; this probe proves the
package's behaviour matches what this host actually does with a file that is being executed:
the diagnosis finds the running process, the deploy replaces the name and leaves the process on
its old inode, and nothing the package does opens the target for writing.

The last three arms answer the question the real process table cannot on this host. The package
reads two per-process entries, ``/proc/<pid>/maps`` and ``/proc/<pid>/fd``, which a reader may
open only for its own processes or with privilege; the kernel's check for that, ``ptrace_may_access``,
refuses with ``EACCES``. Where the deploy user and the service user
differ, those entries are refused. This host mounts ``/proc`` with ``hidepid=invisible``, so
another user's processes are not in the listing to try, and the refusal is measured on a
stand-in ``/proc`` tree instead - one readable holder, one process whose ``maps`` is refused,
one whose ``fd`` is refused, and a tree with nothing readable at all, which is the shape a
false "not busy" takes.
"""
from __future__ import annotations

import errno
import json
import os
import pathlib
import shutil
import statistics
import subprocess
import sys
import tempfile
import time

HERE = pathlib.Path(__file__).resolve().parent
OUT = HERE.parent / "results" / "09_library.json"
sys.path.insert(0, str(HERE.parent / "module"))

from deployguard import deploy, diagnose  # noqa: E402
import deployguard.probe as probe  # noqa: E402

SOURCE = "/bin/sleep"
REPEATS = 5
STANDIN_BYTES = 64


def device_field(st_dev: int) -> str:
    return f"{os.major(st_dev):02x}:{os.minor(st_dev):02x}"


def build_tree(root: pathlib.Path, device: str, st_ino: int, arms: list[str]) -> pathlib.Path:
    """A stand-in /proc: one directory per process, holding a maps file and an fd directory."""
    proc = root / "proc"
    proc.mkdir(parents=True)
    for index, kind in enumerate(arms, start=1):
        base = proc / str(1000 + index)
        base.mkdir()
        maps, descriptor = base / "maps", base / "fd"
        if kind == "maps-denied":
            maps.write_text("")
            os.chmod(maps, 0o000)
        elif kind == "fd-denied":
            maps.write_text(f"7f00e000-7f00f000 r--p 00000000 {device} 9999 /usr/bin/sleep\n")
            descriptor.mkdir()
            (descriptor / "3").write_text("")
            os.chmod(descriptor, 0o000)
        elif kind == "holder":
            maps.write_text(f"7f00e000-7f00f000 r-xp 00000000 {device} {st_ino} /srv/app/tool\n")
            descriptor.mkdir()
            (base / "fdinfo").mkdir()
            (base / "fdinfo" / "4").write_text("pos:\t0\nflags:\t0102\nmnt_id:\t28\n")
            os.symlink("/srv/app/tool", descriptor / "4")
        else:                                       # a process that holds nothing
            maps.write_text(f"7f00e000-7f00f000 r--p 00000000 {device} 4242 /lib/libc.so.6\n")
            descriptor.mkdir()
    return proc


def run_against(proc: pathlib.Path, target: pathlib.Path) -> dict:
    """Ask the package about ``target`` while it reads the stand-in tree instead of /proc."""
    original = probe.PROC
    probe.PROC = proc
    try:
        found = diagnose(target)
    finally:
        probe.PROC = original
    return {"busy": found.busy, "complete": found.complete, "exists": found.exists,
            "scanned": found.scanned, "unreadable": list(found.unreadable),
            "mapped_by": list(found.mapped_by),
            "open_for_write_by": list(found.open_for_write_by), "line": str(found)}


def mount_options() -> dict:
    """The /proc mount and its hidepid setting, as /proc/mounts states them."""
    for line in pathlib.Path("/proc/mounts").read_text().splitlines():
        fields = line.split()
        if len(fields) > 3 and fields[1] == "/proc":
            options = fields[3].split(",")
            hidepid = next((option for option in options if option.startswith("hidepid=")), None)
            return {"source": fields[0], "type": fields[2], "options": fields[3],
                    "hidepid": hidepid.split("=", 1)[1] if hidepid else "0 (not set)"}
    return {"source": None, "type": None, "options": "not listed", "hidepid": "not listed"}


def access_rule(directory: pathlib.Path) -> dict:
    """A file this reader may not open answers EACCES, which is the whole rule in one call."""
    blocked = directory / "sealed"
    blocked.write_bytes(b"x")
    os.chmod(blocked, 0o000)
    errnos: set[int] = set()
    for _ in range(REPEATS):
        try:
            blocked.open("rb").close()
        except OSError as exc:
            errnos.add(exc.errno)
    os.chmod(blocked, 0o600)
    blocked.unlink()
    return {"attempts": REPEATS, "errno": sorted(errnos)[0] if len(errnos) == 1 else None,
            "always_denied": len(errnos) == 1}


def fresh(directory: pathlib.Path) -> pathlib.Path:
    target = directory / "tool.bin"
    if target.exists():
        target.unlink()
    shutil.copyfile(SOURCE, target)
    os.chmod(target, 0o755)
    return target


def start(target: pathlib.Path, seconds: str = "0.60") -> subprocess.Popen:
    process = subprocess.Popen([str(target), seconds])
    time.sleep(0.08)
    return process


def arm(label: str, run) -> dict:                    # noqa: ANN001 - a local closure
    results = [run() for _ in range(REPEATS)]
    keys = {key for result in results for key, value in result.items()
            if isinstance(value, (bool, int, str, type(None)))}
    timed = {"elapsed_ms", "diagnosis_ms"}
    stable = len({json.dumps({key: result.get(key) for key in keys - timed}, sort_keys=True)
                  for result in results}) == 1
    return {"label": label, "attempts": REPEATS, "stable": stable,
            "first": results[0], "results": results}


def main() -> None:
    directory = pathlib.Path(tempfile.mkdtemp(prefix="p09-", dir=HERE.parent / "scratch"))

    def deploy_running() -> dict:
        target = fresh(directory)
        process = start(target)
        before = target.read_bytes()
        started = time.perf_counter()
        result = deploy(target, b"#!/bin/sh\nexit 0\n", mode=0o755)
        elapsed = (time.perf_counter() - started) * 1000
        served = pathlib.Path(f"/proc/{process.pid}/exe").read_bytes()
        alive = process.poll() is None
        process.wait()
        return {"strategy": result.plan.strategy.value, "replaced": result.replaced,
                "busy_before": result.diagnosis.busy,
                "holder_found": process.pid in result.diagnosis.mapped_by,
                "process_alive": alive, "old_bytes_kept": served == before,
                "elapsed_ms": round(elapsed, 2)}

    def deploy_idle() -> dict:
        target = fresh(directory)
        result = deploy(target, b"payload", mode=0o755)
        return {"strategy": result.plan.strategy.value, "replaced": result.replaced,
                "busy_before": result.diagnosis.busy}

    def deploy_cross() -> dict:
        """A source on another mount: the copy lands in a sibling file, so the rename stays put."""
        target = fresh(directory)
        process = start(target)
        before = pathlib.Path(f"/proc/{process.pid}/exe").read_bytes()
        source = pathlib.Path("/tmp") / f"p09-{os.getpid()}-payload.bin"
        source.write_bytes(b"cross payload")
        result = deploy(target, source=source)
        source.unlink(missing_ok=True)
        alive = process.poll() is None
        served = pathlib.Path(f"/proc/{process.pid}/exe").read_bytes() if alive else b""
        process.wait()
        return {"strategy": result.plan.strategy.value, "replaced": result.replaced,
                "process_alive": alive, "old_bytes_kept": served == before,
                "bytes": target.read_bytes().decode()}

    def deploy_symlink() -> dict:
        """The running file is reached through a link; the link is what gets replaced."""
        real = fresh(directory)
        link = directory / "current"
        if link.is_symlink() or link.exists():
            link.unlink()
        os.symlink(real.name, link)
        process = start(real)
        before = pathlib.Path(f"/proc/{process.pid}/exe").read_bytes()
        result = deploy(link, b"link payload", mode=0o755)
        alive = process.poll() is None
        served = pathlib.Path(f"/proc/{process.pid}/exe").read_bytes() if alive else b""
        process.wait()
        return {"strategy": result.plan.strategy.value, "replaced": result.replaced,
                "link_still_a_link": link.is_symlink(), "process_alive": alive,
                "old_bytes_kept": served == before, "bytes": link.read_bytes().decode()}

    def diagnosis_cost() -> dict:
        target = fresh(directory)
        process = start(target, "1.0")
        timings = []
        for _ in range(20):
            started = time.perf_counter()
            found = diagnose(target)
            timings.append((time.perf_counter() - started) * 1000)
        process.wait()
        return {"busy": found.busy, "holder_found": bool(found.mapped_by),
                "diagnosis_ms": round(statistics.median(timings), 2),
                "diagnosis_max_ms": round(max(timings), 2)}

    def script_probe() -> dict:
        target = directory / "job.sh"
        target.write_text("#!/bin/sh\nsleep 0.4\n", encoding="utf-8")
        os.chmod(target, 0o755)
        process = subprocess.Popen([str(target)])
        time.sleep(0.08)
        found = diagnose(target)
        process.wait()
        return {"busy": found.busy, "holders": len(found.holders)}

    def dry_run_line() -> dict:
        target = fresh(directory)
        process = start(target)
        result = deploy(target, b"payload", dry_run=True)
        line = result.summary()
        process.wait()
        return {"names_the_pid": str(process.pid) in line, "replaced": result.replaced,
                "has_strategy": "atomic-replace" in line}

    arms = [
        arm("deploy to a running binary", deploy_running),
        arm("deploy to an idle binary", deploy_idle),
        arm("deploy from another filesystem while running", deploy_cross),
        arm("deploy through a symbolic link while the target runs", deploy_symlink),
        arm("diagnose a running binary", diagnosis_cost),
        arm("diagnose a running shebang script", script_probe),
        arm("dry run names the holder", dry_run_line),
    ]

    # The stand-in trees: the refusal the real table cannot show on this host.
    standin_target = directory / "standin.bin"
    standin_target.write_bytes(b"\x7fELF" + b"\0" * STANDIN_BYTES)
    os.chmod(standin_target, 0o755)
    info = standin_target.stat()
    device = device_field(info.st_dev)

    def standin(kind: str, layout: list[str]) -> dict:
        if kind not in trees:
            trees[kind] = build_tree(directory / f"proc-{kind}", device, info.st_ino, layout)
        return run_against(trees[kind], standin_target)

    trees: dict[str, pathlib.Path] = {}
    standin_arms = [
        arm("stand-in /proc: readable holder beside two refused entries",
            lambda: standin("mixed", ["holder", "maps-denied", "fd-denied"])),
        arm("stand-in /proc: only a refused process",
            lambda: standin("denied-only", ["maps-denied"])),
        arm("stand-in /proc: one readable holder",
            lambda: standin("readable", ["holder"])),
    ]
    mixed, denied, readable = (entry["first"] for entry in standin_arms)
    rule = access_rule(directory)
    mount = mount_options()
    for path in sorted(directory.rglob("*"), reverse=True):
        try:                                        # the refused entries are mode 000
            path.chmod(0o700)
        except OSError:
            pass
    shutil.rmtree(directory, ignore_errors=True)
    payload = {
        "repeats": REPEATS,
        "arms": arms,
        "every_arm_stable": all(entry["stable"] for entry in arms),
        "atomic_strategy_used": arms[0]["first"]["strategy"] == "atomic-replace",
        "idle_also_atomic": arms[1]["first"]["strategy"] == "atomic-replace",
        "cross_source_stayed_atomic": arms[2]["first"]["strategy"] == "atomic-replace",
        "symlink_replaced_not_followed": (arms[3]["first"]["strategy"] == "atomic-replace"
                                          and not arms[3]["first"]["link_still_a_link"]),
        "running_process_kept_old_bytes": all(result["old_bytes_kept"]
                                              for result in arms[0]["results"]),
        "cross_source_kept_old_bytes": all(result["old_bytes_kept"]
                                           for result in arms[2]["results"]),
        "diagnosis_median_ms": statistics.median(result["diagnosis_ms"]
                                                 for result in arms[4]["results"]),
        "diagnosis_found_the_holder": all(result["holder_found"] for result in arms[4]["results"]),
        "script_reports_no_holder": all(not result["busy"] for result in arms[5]["results"]),
        "deploy_median_ms": statistics.median(result["elapsed_ms"] for result in arms[0]["results"]),
        "dry_run_named_the_pid": all(result["names_the_pid"] for result in arms[6]["results"]),
        "busy_error_number": errno.ETXTBSY,
        "standin": {
            "bytes": STANDIN_BYTES + 4,
            "errno": {"EACCES": errno.EACCES, "ENOENT": errno.ENOENT},
            "mount": mount,
            "access_rule": rule,
            "arms": standin_arms,
            "mixed_found_the_holder": mixed["busy"],
            "mixed_reported_the_skipped": len(mixed["unreadable"]),
            "mixed_was_flagged_incomplete": not mixed["complete"],
            "denied_only_said_not_busy": not denied["busy"],
            "denied_only_was_flagged_incomplete": not denied["complete"],
            "denied_only_named_the_pid": len(denied["unreadable"]),
            "readable_was_complete": readable["complete"],
            "readable_saw_the_writer": readable["open_for_write_by"] != [],
            "every_arm_stable": all(entry["stable"] for entry in standin_arms),
        },
    }
    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
    for entry in arms:
        print(f"{entry['label']:48s} stable {entry['stable']} {entry['first']}")
    for entry in standin_arms:
        print(f"{entry['label']:58s} stable {entry['stable']} {entry['first']}")
    print("mount:", mount, "| access rule:", rule)


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.