EXDEV errno 18: Cross-Device rename, link, mv and a Safe Fallback

Dark cover headed 'Invalid cross-device link': errno 18, 7 of 9 rename calls refused across devices, a 32 MiB image that took 32 MiB to copy and 4 KiB to stage, and 88 passing tests

TL;DR

  • rename(2) and link(2) answer EXDEV (errno 18) whenever the two names sit on different mounted filesystems: 7 of 9 rename calls here were refused, and the 2 that worked were the same-device controls.
  • A device number is not a disk, and not a promise either: /tmp is 0:47 and /usr is 0:23 in one image, a rename into the read-only /usr answered EXDEV while a create there answered EROFS, and two mount points can share one number – so the move attempts the rename and falls back on the kernel’s answer, not on the number.
  • shutil.move falls back to copy-then-unlink: the bytes arrive, the inode does not, a 64 MiB image that occupied 4 MiB on its source leaves 64 MiB of blocks on the destination, and 86% of a reader’s polls saw the file half-written.
  • A staged copy in the destination‘s own directory keeps the last step inside one device: 0 of 616 reader polls saw an intermediate size, and the source is removed only after the copy is verified.

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

What you sawWhy it happenedChange this
OSError: [Errno 18] Invalid cross-device link at the very last line of an atomic writeThe temporary file was created in /tmp and renamed onto a volumeCreate the temporary file in the target’s own directory: tempfile.mkstemp(dir=target_dir)
A move left the old file in place and a new one beside itThe tree was copied, then the source’s removal was refusedFix the ownership or mode, or move with a tool that keeps the source until the copy is verified; here the source kept its 2 files and the destination held another 2
A 32 MiB image that used 4 KiB of blocks became 32 MiB on diskThe copy wrote the holes as zerosCopy with a sparse-aware loop, cp --sparse=auto or mv, which keep the holes the source reports
Readers saw an empty or half-sized file during the moveThe copy was written straight to the final nameCopy to a temporary name in the destination’s directory, then rename over it
The file arrived without its user xattr or labelThe destination filesystem answered ENOTSUP (95) for the attributeAsk the destination first: getfattr after the copy, and reapply the label when the target is a different filesystem type
Renaming a directory onto a non-empty one answered 17 on one mount and 39 on anotherThe filesystem chooses between EEXIST and ENOTEMPTY for one conditionTreat both as “the target is not empty”; do not branch on the number alone
A rename into a read-only mount answered 18, not 30The mount boundary is checked before permission to writeAttempt the rename first: EXDEV means the mount was checked before the mode, so look at the mount, not the permission bits
The same physical disk still gives EXDEV, and a bind mount does notA bind mount shares its source’s device number; a subvolume, overlay or tmpfs answers a number of its own. The kernel compares mount points, not just numbersAttempt the rename first and fall back on EXDEV; log st_dev as the prediction only, because a bind mount makes an equal number wrong – the staged copy in Section 9 works that way
link() fails where rename() worksA hard link is a second name for one inode, so it cannot cross devices at allCopy and rename; there is no hard-link fallback across devices
A directory move stopped half wayThe tree was being written into the destination nameA staged directory inside the destination, renamed in one step, keeps the destination name empty until the tree is complete; verify the file count before the rename
mv /tmp/app.db /data/app.db fails inside a container/tmp belongs to the image layer and /data is a volumeWrite the temporary file under the volume: same device, one rename
EXDEV arrives only under load, never in testsTests write the temporary file next to the fixture, production writes it to /tmpAssert the plan and the fallback: a test that makes the rename answer EXDEV proves the staged path without needing a second device, and a test that only compares st_dev cannot see a bind mount
Table 1: Each row is a condition measured on this host (Sections 2 to 8) or a documented kernel rule (Section 10); the fix column is the one this page implements in Section 9.

1. What errno 18 says, and what it does not

The error is not about disk space, permissions or a closed file. It is about the one operation a rename performs: unlinking a name from one directory and linking the same inode into another. Both directories have to be on one mounted filesystem, because the kernel updates two directory entries in one operation and a filesystem only knows how to do that inside itself. man 2 rename puts the condition in one line for EXDEV: “oldpath and newpath are not on the same mounted filesystem”. man 2 link repeats it for the same reason, because a hard link is the second half of that operation.

What the message does not say is what to do. It arrives from os.rename, os.replace, Path.rename, shutil.move (which swallows it and copies), and from link(), and in each case the caller is holding a value that is perfectly valid on the destination device. The fallback is always the same shape: build the destination’s content first, somewhere on the destination, and make the name change last.

"""Where a path lives: the one fact that decides whether a move can be a rename."""

from __future__ import annotations
import os


def device_of(path: str | os.PathLike[str]) -> int:
    """The ``st_dev`` of the entry ``path``, or of its nearest ancestor that exists.

    A caller checks a destination that does not exist yet - a file a service is about to
    write - so the answer has to come from the directory it would live in, not from the
    file. Walking up also covers ``a/b/c`` on a mount whose parent is another device:
    the answer changes exactly where the mount is.

    The final component is answered by ``lstat``, not ``stat``: a rename moves the entry
    itself, so a symlink is compared by the device its name lives on, never by the device
    its target happens to sit on.
    """
    current = os.path.abspath(os.fspath(path))
    while True:
        try:
            return os.lstat(current).st_dev
        except FileNotFoundError:
            parent = os.path.dirname(current)
            if parent == current:
                raise
            current = parent


def same_device(source: str | os.PathLike[str], target: str | os.PathLike[str]) -> bool:
    """True when a directory entry can be moved between the two without copying bytes."""
    return device_of(source) == device_of(target)


def describe(device: int) -> str:
    """``major:minor``, the form ``stat -c %d`` and the mount table use."""
    major = os.major(device)
    minor = os.minor(device)
    return f"{major}:{minor}"

device_of is the whole diagnostic. It answers for a path that does not exist yet – the destination file a service is about to create – by walking up to the nearest directory that does, which is exactly the directory the new name would be created in. The interesting consequence is in the next section: two paths inside the same directory tree can answer differently, and that answer, not the hardware, decides.

2. The device census: one host, four devices

Here is the host this page measured on: Linux 6.12.118-guest-1.1, CPython 3.12.16, uid 1000, file descriptors 1,024 soft and 4,096 hard. Four paths that a service might use as a working directory live on four different devices, and only one of them is a disk in any physical sense.

Pathst_devFilesystemReported sizeRenames with /tmp
/workspace0:36virtiofs8 EiB (host-reported)EXDEV
/tmp0:47tmpfs128 MiBsame device
/dev/shm0:45tmpfs64 MiBEXDEV
/usr0:23overlay (read-only)read-only image layerEXDEV
Table 2: Four paths, four devices. The size column is what statvfs reported, including the host’s synthetic total for virtiofs; the last column is the measured answer of a rename from /tmp.

The last two rows are the interesting ones. /tmp and /dev/shm are both tmpfs, both memory, and still refuse a rename between them. /usr is the read-only overlay this container runs from, and a rename into it answers EXDEV – not EROFS – because the mount check comes first. Writing a new file there does answer EROFS (30), which is how the two conditions can be told apart after the fact:

CallAnswerWhat the kernel checked first
rename("/tmp/x", "/usr/bin/x")EXDEV 18Are both directories on one mounted filesystem? No, so stop.
open("/usr/bin/new", "wb")EROFS 30The mount is read-only.
rename("/tmp/x", "/tmp/y")successOne filesystem: the entry moves.
Table 3: The order of the checks, measured. A page that says “EXDEV means permission denied” or “EXDEV means read-only” has the order backwards.

A device number is not a mount, and the difference is the trap this page corrects in itself. Two mount points can answer the same st_dev, and this host already has the shape: the mount table shows /bin as a mount of /usr/bin and /lib as a mount of /usr/lib, all on 0:23, so /usr and /bin are two mount points of one device. The kernel compares the mount points, not the numbers, so a rename between two such paths is refused with EXDEV even though both names report one device. Equal st_dev is therefore an early answer, never a permission.

The refusal itself could not be run on that pair, because the mounts the runtime made are read-only, and a writable bind mount of our own needs mount(2): a user and mount namespace is refused (unshare exits 1, “Operation not permitted”) and mount --bind answers “must be superuser” with exit 32. So the measured half is the mount table, and the refusal is rename(2)‘s documented rule rather than a run on this host. Section 9 stops depending on the prediction for exactly that reason: the rename is attempted, and EXDEV starts the fallback.

device_of and stat -c %d answer the same question on this host for all four paths; the shell form is worth knowing because a deployment script may have no interpreter, and the number it prints is the same st_dev that Table 2 shows as major:minor, in decimal.

stat -c '%d %n' /tmp /workspace /dev/shm /usr
python3 -c 'import os,sys; print(os.stat(sys.argv[1]).st_dev)' /tmp

3. One error, nine calls: every object kind refused

A first guess is that errno 18 depends on what is being moved – that files move and directories do not, or that symlinks are special. The matrix says otherwise: every object type is refused, and what decides is the pair of directories. 7 of the 9 calls were refused, and the only 2 that succeeded were the same-device controls.

Object movedFrom -> toAnswerSource keptSame inode at the target
regular file, 4 KiB/workspace -> /workspacesuccessnoyes
regular file, 4 KiB/tmp -> /tmpsuccessnoyes
regular file, 4 KiB/workspace -> /tmpEXDEV 18yesn/a
regular file, 4 KiB/workspace -> /dev/shmEXDEV 18yesn/a
empty directory/workspace -> /tmpEXDEV 18yesn/a
directory holding a file/workspace -> /tmpEXDEV 18yesn/a
symbolic link/workspace -> /tmpEXDEV 18yesn/a
fifo/workspace -> /tmpEXDEV 18yesn/a
os.replace over an existing file/workspace -> /tmpEXDEV 18yesn/a
Table 4: Nine calls, five repeats each, identical every time. On a refusal the source is still there and the destination name was never created – except in the last row, where the destination kept the content it already had; on a success the source name is gone and the inode at the target is the one that was moved.

The last row matters for atomic-write code, because os.replace is the call that is supposed to never fail for an ordinary destination: it replaces whatever is there, in one step. Across a device boundary it does not even get that far – the existing destination file is left untouched and the temporary file stays where it was, which is exactly the leak Section 8 measures.

A fifo is worth its own row because it shows what is really being moved. The kernel is not carrying an object anywhere; it is moving a directory entry. The fifo has no content at all, and it is still refused, because its name cannot move.

4. What a rename keeps that a copy has to reproduce

Once the move has to copy, every property that a directory entry used to carry for free becomes something the copy has to re-create. Three of them are cheap and survive shutil.move; four do not survive, and one of those fails silently.

PropertySame-device renameCross-device copyMeasured on
contentsuntouchedbyte-identicaldigest comparison, Section 9
inodepreservednew inodest_ino before and after
mode, including setuidpreservedpreserved (setuid kept)0o640 and 0o4755
mtimepreservedpreservedos.utime, then st_mtime
user xattrpreserveddropped when the destination refuses itENOTSUP 95 on the destination
holesnothing to reproducewritten as zerosst_blocks after the copy
name visible only when completeyesnoreader polls, Section 6
Table 5: Each row was measured on this host; the cross-device column is what shutil.move does, not what a careful implementation could do.

The xattr row is the silent one. On this host the source was a tmpfs file with a user.p40 attribute, the destination was the virtiofs mount, and the move reported success: no exception, the file is there, the contents are right. Reading the attribute afterwards answered errno 95, because that filesystem does not store user attributes at all. A copy routine cannot report what a filesystem cannot hold, so the only defence is to ask afterwards, or to know the destination’s type before the move.

The hole row is the expensive one and it gets its own measurements in Section 6. Here it is enough to see the shape: a 64 MiB image with one 4 KiB write in it occupied 4 MiB on the source and 64 MiB on the destination after the move.

5. What shutil.move does once rename has refused

The standard library documents the fallback in one sentence: “If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dst using copy_function and then removed”. It does not catch EXDEV specifically: any OSError from the rename sends it to the copy path, which is why a permission problem on the destination turns into a second attempt and a different errno.

ConditionResultDetail measured here
4 KiB file, across devicessuccess11.7 ms median, inode changed, mode and mtime kept
4 KiB file, same devicesuccess8.9 ms median, inode preserved
directory tree with a relative symlinksuccess3 entries in 48.7 ms, the link stayed a link
destination directory without a write bitEACCES 13source kept, destination never created
tree whose removal is refusedEACCES 13source kept and a second copy at the destination
64 MiB sparse imagesuccess64 MiB of blocks on the destination for that image
source is itself a symlinksuccessmoved as a link; the target string kept
user xattr, destination refuses itsuccess (silently)attribute gone, read-back ENOTSUP 95
a reader polling during the movesuccess170 of 197 polls saw the file incomplete
Table 6: Nine conditions, five repeats each. The last row is Section 6’s whole subject: the move is correct when it returns, and wrong while it runs.
from __future__ import annotations
import os
import shutil
import threading
import time
import probelib

DENSE = 32 << 20


def run_file_cross() -> dict:
    root = probelib.fresh("e04_file")
    source = probelib.write(root / "payload.bin", 4096, b"a")
    os.utime(source, (1_700_000_000, 1_700_000_000))
    os.chmod(source, 0o640)
    before = os.stat(source)
    target = probelib.fresh_tmp("e04_file") / "payload.bin"
    started = time.perf_counter()
    _, error = probelib.try_call(lambda: shutil.move(str(source), str(target)))
    after = os.stat(target)
    return {"errno": error["errno"], "name": error["name"],
            "ms": probelib.ms(started), "source_gone": not source.exists(),
            "dest_size": after.st_size, "inode_changed": after.st_ino != before.st_ino,
            "mode_preserved": (after.st_mode & 0o7777) == (before.st_mode & 0o7777),
            "mtime_preserved": int(after.st_mtime) == int(before.st_mtime)}


def run_reader_visibility() -> dict:
    """Poll the destination while shutil.move copies, the way a web server would."""
    root = probelib.fresh("e04_reader")
    source = probelib.write(root / "payload.bin", DENSE, b"r")
    target = probelib.fresh_tmp("e04_reader") / "payload.bin"
    seen: list[int] = []
    stop = threading.Event()

    def watch() -> None:
        while not stop.is_set():
            try:
                seen.append(target.stat().st_size)
            except OSError:
                seen.append(-1)
            time.sleep(0.0005)

    watcher = threading.Thread(target=watch, daemon=True)
    watcher.start()
    _, error = probelib.try_call(lambda: shutil.move(str(source), str(target)))
    stop.set()
    watcher.join(timeout=5)
    partial = [size for size in seen if 0 <= size < DENSE]
    return {"errno": error["errno"], "name": error["name"], "observations": len(seen),
            "partial_observations": len(partial),
            "distinct_partial_sizes": len(set(partial)),
            "last_size": target.stat().st_size if target.exists() else -1}

Both functions above are the probe, printed whole: the first moves a file across the boundary and reads back the inode, the mode and the mtime; the second starts a thread that polls the destination every half millisecond while the move runs, and keeps every size it sees. The numbers in Table 6 come from those two functions; Table 7’s come from the copy probe in Section 6.

6. Two silent costs: the holes and the half-written name

Both costs are silent in the same way: the call returns success and the data is correct when the move finishes. One shows up later, as disk usage that does not go back down; the other shows up during the move, in another process, as a file that is momentarily empty.

Sparse copying is decided by the source filesystem, not by the tool. SEEK_DATA and SEEK_HOLE let a copy ask where the real data is; the tmpfs mount answers with the one 4 KiB extent and nothing else, and the virtiofs mount answers that the whole 32 MiB is data. So the same hole-aware loop that copies 4 KiB from a tmpfs source copies the whole file – correctly – from a virtiofs source.

Copy methodSource filesystemBlocks on the destinationTimeData read
shutil.copyfilevirtiofs32 MiB69.0 mswhole file (one extent)
hole-aware loopvirtiofs32 MiB74.0 ms33,554,432 B
cp --sparse=autovirtiofs32 MiB78.3 mswhole file
cp --sparse=nevervirtiofs32 MiB76.4 mswhole file
mvvirtiofs32 MiB81.1 mswhole file
shutil.copyfiletmpfs32 MiB5.94 mswhole file
hole-aware looptmpfs4 KiB0.02 ms4 KiB
cp --sparse=autotmpfs4 KiB1.01 msone extent
cp --sparse=nevertmpfs32 MiB8.0 mswhole file
mvtmpfs4 KiB0.89 msone extent
Table 7: The same 32 MiB sparse image, five ways of copying it, from two source filesystems onto a destination that reports its blocks honestly. The rows that stay sparse are the ones where the tool asked, and the source could answer.

The two cheap rows are worth reading together. On a tmpfs source the hole-aware loop reads 4 KiB and finishes in under 0.02 ms, 8,192 times fewer bytes than the 32 MiB that copyfile writes. On the dense file this probe measures beside the 32 MiB sparse one – 16 MiB of data, five repeats each, source and destination both on the tmpfs mount the probe recorded for this pair – the same loop costs 27% more time at the median than copyfile: 5.9 ms (5.6–6.1 ms) against 4.7 ms (4.5–5.3 ms).

That gap is not the price of asking. The dense file is one data extent, so the loop makes 2 lseek calls in all – two syscalls for the whole file, not one per chunk – and the figure is the same on every repeat. What differs is how the bytes travel. shutil.copyfile in CPython 3.12.16 on this host has shutil._USE_CP_SENDFILE set to yes, and the probe counted 2 sendfile calls that moved all 16 MiB inside the kernel. The loop reads the file into a Python bytes object 16 times and writes each piece back, so every byte is copied through user space twice – once by read, once by write – before the length is set with truncate and the handle is closed. The bytes that land are the same bytes in both columns; the round trip is what the loop pays for staying portable. The probe also ran the control: with copyfile‘s kernel path switched off, the same copy runs through its own 64 KiB user-space buffer in 5.1 ms (5.0–5.4 ms), so the kernel path accounts for part of the gap here and the loop’s per-chunk work for the rest – one shared host’s median, not a constant, and the reason the loop in Section 9 asks before it copies, falls back to a plain copy when the source cannot answer, and reports which of the two it did.

"""Copying a file while keeping the holes the source filesystem reports.

A cross-device move has no choice but to copy bytes. Which bytes is a decision: a 32 MiB
image with one 4 KiB write in it costs 4 KiB to copy when ``SEEK_DATA`` can name the data, and
32 MiB when it cannot. The source filesystem answers that question, so the answer is measured
per copy rather than assumed - and when it cannot answer at all, the copy says so and copies
every byte instead of writing a file full of holes.
"""

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

CHUNK = 1 << 20


class _SeekDataUnsupported(Exception):
    """The source's filesystem does not answer ``SEEK_DATA``: copy the whole file instead."""


@dataclass(frozen=True)
class CopyStats:
    """What the copy actually did, so the caller can log it rather than guess."""

    logical_bytes: int
    data_bytes: int
    extents: int
    holes_known: bool = True

    @property
    def hole_bytes(self) -> int:
        return self.logical_bytes - self.data_bytes


def _extents(handle: int, size: int):
    """Yield ``(start, end)`` for each region the filesystem reports as data.

    ``SEEK_DATA`` answers ``ENXIO`` when no data follows the offset, which is how a file that
    is entirely a hole ends: no extents, and the destination is still given its full length.
    Any other refusal means the filesystem cannot answer the question at all, which is not
    the same statement as "there are no holes" and must not be reported as one.
    """
    if not hasattr(os, "SEEK_DATA") or not hasattr(os, "SEEK_HOLE"):
        raise _SeekDataUnsupported("this platform has no SEEK_DATA")
    offset = 0
    while offset < size:
        try:
            start = os.lseek(handle, offset, os.SEEK_DATA)
        except OSError as exc:
            if exc.errno == errno.ENXIO:
                return
            raise _SeekDataUnsupported(str(exc)) from exc
        end = os.lseek(handle, start, os.SEEK_HOLE)
        yield start, end
        offset = end


def copy_sparse(source: str | os.PathLike[str], target: str | os.PathLike[str]) -> CopyStats:
    """Copy only the data extents, then give the target the source's length.

    When the source cannot name its data, every byte is copied and ``holes_known`` is
    ``False``: the destination is correct either way, and the caller can tell which copy it
    paid for.
    """
    handle = os.open(source, os.O_RDONLY)
    try:
        size = os.fstat(handle).st_size
        try:
            spans = list(_extents(handle, size))
        except _SeekDataUnsupported:
            spans = None
    finally:
        os.close(handle)
    if spans is None:
        shutil.copyfile(source, target)
        return CopyStats(logical_bytes=size, data_bytes=size, extents=0, holes_known=False)
    copied = 0
    with open(source, "rb") as reader, open(target, "wb") as writer:
        for start, end in spans:
            reader.seek(start)
            writer.seek(start)
            remaining = end - start
            while remaining > 0:
                chunk = reader.read(min(CHUNK, remaining))
                if not chunk:
                    break
                writer.write(chunk)
                copied += len(chunk)
                remaining -= len(chunk)
        writer.truncate(size)
        writer.flush()
    return CopyStats(logical_bytes=size, data_bytes=copied, extents=len(spans))

The second cost is the window in which the destination name exists and the content does not. shutil.move copies to the final name, so a reader that opens the file while the copy runs gets whatever has arrived so far. The probe polls the destination on a thread and records every size it sees; the table below is the count of polls that were neither the old file nor the finished one.

How the destination was writtenPollsSaw an intermediate sizeDistinct sizes
shutil.move, destination did not exist197170 (86%)45
shutil.move, replacing an existing file12422
os.replace of a file staged in the same directory70500
safemove.move, staged and verified61600
Table 8: Polls on a thread every fraction of a millisecond, across five repeats. A zero is not a promise about every filesystem; it is what a rename inside one device gives, because the new name appears with the new content already behind it.

7. The errno answers around it

EXDEV is easy to mistake for one of its neighbours when the message is read without the condition. Every row below was produced on this host by constructing the condition, so the table can be used as a lookup: the number a call returns says which check failed.

AnswerCondition that produced itNote
EXDEV 18either name is on another mounted filesystemfiles, directories, symlinks, fifos, os.replace
EEXIST 17link() onto an existing namealso the answer for a directory onto a non-empty one, on virtiofs
ENOTEMPTY 39a directory onto a non-empty one, on tmpfsone condition, two numbers, depending on the filesystem
EISDIR 21a file renamed onto a directorythe target is the wrong kind
ENOTDIR 20a path component that is a filethe parent is not a directory
EINVAL 22a directory renamed into itselfthe move would detach the tree it is inside
ENAMETOOLONG 36a name of 300 charactersthe limit is per component
ELOOP 40a path through a symlink loopthe resolver gave up
EACCES 13a destination directory with no write bitpermission, not device
EROFS 30creating a name in a read-only mountchecked after the device
EPERM 1link() to a directorythe kernel never allows it
ENOTSUP 95a user xattr on a filesystem that has nonesilent after a copy
Table 9: Twelve answers, each from its own constructed condition. The first two rows are the ones a cross-device bug produces; the rest are what a wrong diagnosis produces instead.

The EEXIST row is the one that breaks error-handling code. man 2 rename lists ENOTEMPTY for “newpath is a nonempty directory”, and this host’s tmpfs returns it; the virtiofs mount returns EEXIST for the same call. Code that catches only errno.ENOTEMPTY therefore treats the same condition as a hard failure on one mount and a handled case on another, with no change to the program.

8. Choose the temporary file’s directory, not the filename

A temporary file created without a directory is the shortest route to EXDEV: it is renamed onto a path that turns out to be another device. “If dir is not None, the file will be created in that directory” – and when the argument is omitted, that directory is the system temporary directory, which in a container is usually a different mount from the data volume it is about to feed.

Where the temp file was madeLast stepAnswerLeft behind
the target’s own directoryos.replacesuccessnothing
/tmpos.replace to /workspaceEXDEV 18the temporary file, still there
/dev/shmos.replace to /workspaceEXDEV 18the temporary file, still there
/tmpos.link to /workspaceEXDEV 18the temporary file, still there
the target’s own directory, then fsync the file and the directoryos.replacesuccessnothing
NamedTemporaryFile(delete=True)os.replace to /workspaceEXDEV 18nothing, and no target either
Table 10: Six placements, five repeats each. The last row is the quiet failure: the context manager deletes the temporary file on the way out, so the data is gone and the exception is the only evidence it ever existed.

The leak is worth naming because it is not an error path. os.replace raises, the caller logs and retries, and the 8,388,608-byte temporary file stays in /tmp; on a service that retries every minute, that is the temporary directory filling up at the rate of the payload. The measurement recorded 1 file left behind per failed attempt, with the target untouched.

The fix is one function: the temporary file is created in target_dir, the copy is checked against the source’s digest, and only then does os.replace give it the destination’s name – a rename that stays on one device however far apart the two names were. Section 9 prints that module whole, with the plan that decides when to take this path.

9. safemove: the fallback as a module

The rule from Section 8 is small enough to hold in one function, and it is worth holding in one place rather than in every writer. safemove answers four questions before it touches a byte: are the two paths on one device, is the source a symlink, is it a directory, and does the destination name have to change in one step. The answer is a value, so a service can log it, assert on it in a test, and refuse to write when it is not what it expected – and it is advice, because Section 2 showed that two mounts can share one device number. The move asks the kernel for the rename first and applies the plan only when the answer is EXDEV.

"""The fallback plan for one move, written down before any byte is touched.

The plan is advice, not a promise. It reads ``st_dev`` and the source's type, and the move
still asks the kernel first with one ``os.replace``, because two mount points can share a
device number - a bind mount, a subvolume view, an overlay's lower layer - and a rename
between them is refused with ``EXDEV`` all the same. What the plan decides is the shape of the
fallback: one rename, a staged copy, or a link re-created under the target's name.
"""
from __future__ import annotations

import os
import stat
from dataclasses import dataclass

from .device import same_device


@dataclass(frozen=True)
class Plan:
    """What a move of one path will attempt, what it falls back to, and why.

    ``method`` is the first attempt (``rename``, ``copy`` or ``link``), ``staged`` says the
    fallback builds its copy beside the target rather than at its name, ``atomic_replace``
    says the published name changes in one step, and ``same_device`` is the prediction the
    plan was built from.
    """

    method: str
    staged: bool
    atomic_replace: bool
    reason: str
    same_device: bool


def choose(source: str | os.PathLike[str], target: str | os.PathLike[str],
           must_be_atomic: bool = True) -> Plan:
    """Decide the fallback for moving ``source`` onto ``target``.

    ``same_device`` is recorded because it is the answer a caller usually wants to assert,
    but the kernel has the last word: ``move()`` attempts ``os.replace`` first and applies
    this plan only when that attempt answers ``EXDEV``. A plan that says ``rename`` on one
    device is therefore a prediction, not a permission.
    """
    info = os.lstat(source)
    one_device = same_device(source, target)
    if one_device:
        if must_be_atomic:
            return Plan("rename", False, True,
                        "one device: the kernel moves the entry itself, and an EXDEV would "
                        "still be staged rather than shown to readers",
                        one_device)
        return Plan("rename", False, False,
                    "one device: the kernel moves the entry itself; an EXDEV falls back to "
                    "an in-place copy, because the name need not change in one step",
                    one_device)
    if stat.S_ISLNK(info.st_mode):
        if must_be_atomic:
            return Plan("link", True, True,
                        "two devices: recreate the link in the target's own directory, "
                        "then rename it into place - the target string moves, not the file",
                        one_device)
        return Plan("link", False, False,
                    "two devices and an in-place name taken: the link is created at the name",
                    one_device)
    if must_be_atomic:
        return Plan("copy", True, True,
                    "two devices: copy into the target's own directory, then rename over it",
                    one_device)
    return Plan("copy", False, False,
                "two devices and an in-place name taken: readers can see the copy grow",
                one_device)

choose therefore predicts; move decides. The prediction is kept because it is what a test can assert without a second device, and because a caller that needs the destination’s name to change in one step has to know before the copy starts. What it is not is a permission slip: the plan that says rename on one device is escalated to a staged copy the moment the kernel refuses – unless the caller passed must_be_atomic=False, in which case the plan already said the name may be taken in place and the fallback is the reader-visible copy, reported with staged=False.

"""Moving a path across a device boundary without leaving a half-written name behind.

The kernel refuses ``rename`` between two devices with ``EXDEV``, and everything a runbook
needs to say about that error follows from one rule: a name can only change on the device that
holds it. So the move asks the kernel first - one ``os.replace`` - and treats a plan built from
``st_dev`` as advice, not a promise, because two mount points can share a device number and a
rename between them is refused all the same. When the answer is ``EXDEV``, the copy is built
under a temporary name *in the destination's directory*, made durable, and given the
destination's name with a rename that stays inside that one device.
"""
from __future__ import annotations

import errno
import os
import shutil
import tempfile
import time
from dataclasses import dataclass

from .copy import CopyStats, copy_file, digest, fsync_directory, fsync_file
from .policy import Plan, choose

STAGING_PREFIX = ".safemove-"


@dataclass(frozen=True)
class MoveReport:
    """What the move did, in the same terms the plan promised, plus whether the plan held."""

    source: str
    target: str
    method: str
    staged: bool
    ms: float
    logical_bytes: int
    data_bytes: int
    extents: int
    files: int
    verified: bool
    fsyncs: int
    fell_back: bool

    @property
    def copied_bytes(self) -> int:
        return self.data_bytes if self.method == "copy" else 0


def _remove_quietly(path: str) -> None:
    """Undo a staging path after a failure; the caller's error is the one that matters."""
    try:
        if os.path.isdir(path) and not os.path.islink(path):
            shutil.rmtree(path)
        else:
            os.unlink(path)
    except OSError:
        pass


def _is_tree(path: str) -> bool:
    return os.path.isdir(path) and not os.path.islink(path)


def _holds_names(path: str) -> bool:
    """True when ``path`` is a directory that already holds entries other than . and .."""
    if os.path.islink(path) or not os.path.isdir(path):
        return False
    try:
        with os.scandir(path) as entries:
            return next(entries, None) is not None
    except OSError:
        return False


def _refuse_a_target_of_the_wrong_kind(target: str, tree: bool) -> None:
    """Refuse a destination whose type cannot receive this source, before a byte is copied.

    ``rename(2)`` answers ``EISDIR`` when the new name is a directory and the old name is not,
    and ``ENOTDIR`` when the old name is a directory and the new name is not; a staged copy
    would meet exactly the same two refusals at its last step, after writing every byte to a
    staging name it then has to throw away. So the check is made where the destination is
    already known, and the errno is the one the direct rename would have given.
    """
    if not os.path.lexists(target):
        return
    directory = os.path.isdir(target) and not os.path.islink(target)
    if tree and not directory:
        raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), target)
    if not tree and directory:
        raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), target)


def _tree_counts(path: str) -> tuple[int, int]:
    """Directories and files under ``path``, symlinks counted as files, the walk not following them."""
    directories = files = 0
    for _, names, filenames in os.walk(path):
        directories += len(names)
        files += len(filenames)
    return directories, files


def _fsync_tree(root: str) -> int:
    """fsync every regular file under ``root``; a symlink has no bytes of its own to sync."""
    count = 0
    for current, _, names in os.walk(root):
        for name in names:
            path = os.path.join(current, name)
            if os.path.islink(path):
                continue
            fsync_file(path)
            count += 1
    return count


def _stage_file(source: str, target_dir: str, verify: bool,
                do_fsync: bool) -> tuple[CopyStats, bool, int, str]:
    """Copy into a temporary name beside the target and prove the copy before publishing it."""
    handle, staging = tempfile.mkstemp(dir=target_dir, prefix=STAGING_PREFIX)
    os.close(handle)
    try:
        stats = copy_file(source, staging)
        fsyncs = 0
        if do_fsync:
            fsync_file(staging)
            fsyncs += 1
        verified = False
        if verify:
            verified = (digest(source) == digest(staging)
                        and os.path.getsize(source) == os.path.getsize(staging))
            if not verified:
                raise OSError(0, "the copy does not match its source")
        return stats, verified, fsyncs, staging
    except BaseException:
        _remove_quietly(staging)
        raise


def move(source: str | os.PathLike[str], target: str | os.PathLike[str], *,
         verify: bool = True, do_fsync: bool = True, must_be_atomic: bool = True) -> MoveReport:
    """Move ``source`` to ``target``, on one device or across two.

    The rename is attempted first and unconditionally. ``EXDEV`` is the one refusal that
    starts the fallback; every other errno belongs to the caller's own paths and is raised
    untouched. The plan is consulted only to choose the shape of that fallback.
    """
    source = os.fspath(source)
    target = os.fspath(target)
    plan = choose(source, target, must_be_atomic=must_be_atomic)
    started = time.perf_counter()
    link = os.path.islink(source)
    tree = _is_tree(source)
    logical = 0 if (link or tree) else os.path.getsize(source)
    target_dir = os.path.dirname(os.path.abspath(target)) or "."

    # st_dev says what the kernel will probably do, not what it must do: two mount points of
    # one filesystem answer one device number and a rename between them is refused anyway.
    # One syscall settles it, so the kernel gets the first word.
    try:
        os.replace(source, target)
    except OSError as exc:
        if exc.errno != errno.EXDEV:
            raise
        return _fall_back(source, target, target_dir, plan, link, tree, logical,
                          verify, do_fsync, started)

    fsyncs = 0
    if do_fsync:
        fsync_directory(target_dir)
        fsyncs = 1
    elapsed = (time.perf_counter() - started) * 1000
    return MoveReport(source, target, "rename", False, elapsed, logical, 0, 0,
                      1, True, fsyncs, False)


def _fall_back(source: str, target: str, target_dir: str, plan: Plan, link: bool, tree: bool,
               logical: int, verify: bool, do_fsync: bool, started: float) -> MoveReport:
    """The plan, applied after the kernel refused the direct rename with ``EXDEV``.

    A plan that promised a rename is escalated to a staged copy only when the caller asked
    for the destination's name to change in one step: the kernel has just said the two names
    are on different devices, whatever their device numbers were, and a staged copy is the
    only way to keep that promise. With ``must_be_atomic=False`` the plan already said the
    name may be taken in place, so the fallback copies in place and ``staged`` stays false -
    the report then describes the move the policy allowed, not a stricter one.

    A tree is checked against its destination before a byte is copied. A rename can land on a
    name that holds nothing or on an empty directory. A directory holding entries is refused
    here with ``ENOTEMPTY`` - the errno the direct rename in :func:`move` gets from the kernel
    on one device, or ``EEXIST`` on a filesystem that prefers it - instead of copying the whole
    tree into a staging name that the last rename could only refuse. So a tree move never
    merges into a destination that already has entries, and the caller keeps its source.

    The destination's kind is checked in the same place and for the same reason: a directory
    standing where a file's name must go is ``EISDIR``, and a file or a symlink standing where
    a tree's name must go is ``ENOTDIR`` - both refused before the copy rather than after it.
    """
    _refuse_a_target_of_the_wrong_kind(target, tree)
    if tree and _holds_names(target):
        raise OSError(errno.ENOTEMPTY, os.strerror(errno.ENOTEMPTY), target)
    staged = plan.staged or (plan.method == "rename" and plan.atomic_replace)
    if link:
        return _move_link(source, target, target_dir, staged, do_fsync, started)
    if tree:
        if staged:
            return _move_tree(source, target, target_dir, do_fsync, started, verify)
        return _copy_in_place(source, target, logical, True, do_fsync, started, verify)
    if not staged:
        return _copy_in_place(source, target, logical, False, do_fsync, started, verify)
    stats, verified, fsyncs, staging = _stage_file(source, target_dir, verify, do_fsync)
    try:
        os.replace(staging, target)
        if do_fsync:
            fsync_directory(target_dir)
            fsyncs += 1
        os.unlink(source)
    except BaseException:
        _remove_quietly(staging)
        raise
    elapsed = (time.perf_counter() - started) * 1000
    return MoveReport(source, target, "copy", True, elapsed, stats.logical_bytes,
                      stats.data_bytes, stats.extents, 1, verified, fsyncs, True)


def _move_link(source: str, target: str, target_dir: str, staged: bool, do_fsync: bool,
               started: float) -> MoveReport:
    """Recreate the link under the target's name: a link has no bytes to copy or to verify."""
    if not staged:
        os.symlink(os.readlink(source), target)
        fsyncs = 0
        if do_fsync:
            fsync_directory(target_dir)
            fsyncs = 1
        os.unlink(source)
        elapsed = (time.perf_counter() - started) * 1000
        return MoveReport(source, target, "link", False, elapsed, 0, 0, 0, 1, True, fsyncs,
                          True)
    handle, staging = tempfile.mkstemp(dir=target_dir, prefix=STAGING_PREFIX)
    os.close(handle)
    os.unlink(staging)
    fsyncs = 0
    try:
        os.symlink(os.readlink(source), staging)
        os.replace(staging, target)
        if do_fsync:
            fsync_directory(target_dir)
            fsyncs = 1
        os.unlink(source)
    except BaseException:
        _remove_quietly(staging)
        raise
    elapsed = (time.perf_counter() - started) * 1000
    return MoveReport(source, target, "link", True, elapsed, 0, 0, 0, 1, True, fsyncs, True)


def _copy_in_place(source: str, target: str, logical: int, tree: bool, do_fsync: bool,
                   started: float, verify: bool) -> MoveReport:
    """The reader-visible path: copy straight to the destination name, then drop the source.

    Readers can see this copy grow, because there is no rename to hide it behind. The bytes
    are still made durable before the source is removed - ``fsync`` on the copy and then on
    the directory that holds its name - so the same rule as the staged path applies here,
    one file at a time and one directory at the end.
    """
    target_dir = os.path.dirname(os.path.abspath(target)) or "."
    if tree:
        shutil.copytree(source, target, symlinks=True, dirs_exist_ok=True,
                        copy_function=copy_file)
        verified = not verify or _tree_counts(source) == _tree_counts(target)
        if not verified:
            raise OSError(0, "the copy does not match its source")
        files = _tree_counts(source)[1]
        fsyncs = 0
        if do_fsync:
            fsyncs = _fsync_tree(target) + 1
            fsync_directory(target_dir)
        shutil.rmtree(source)
        elapsed = (time.perf_counter() - started) * 1000
        return MoveReport(source, target, "copy", False, elapsed, logical, logical, files,
                          files, verified, fsyncs, True)
    stats = copy_file(source, target)
    verified = False
    if verify:
        verified = (digest(source) == digest(target)
                    and os.path.getsize(source) == os.path.getsize(target))
        if not verified:
            raise OSError(0, "the copy does not match its source")
    fsyncs = 0
    if do_fsync:
        fsync_file(target)
        fsync_directory(target_dir)
        fsyncs = 2
    os.unlink(source)
    elapsed = (time.perf_counter() - started) * 1000
    return MoveReport(source, target, "copy", False, elapsed, stats.logical_bytes,
                      stats.data_bytes, stats.extents, 1, verified, fsyncs, True)


def _move_tree(source: str, target: str, target_dir: str, do_fsync: bool,
               started: float, verify: bool) -> MoveReport:
    """Stage a whole tree beside its destination, then publish it with one rename."""
    staging = tempfile.mkdtemp(dir=target_dir, prefix=STAGING_PREFIX)
    try:
        shutil.copytree(source, staging, symlinks=True, dirs_exist_ok=True,
                        copy_function=copy_file)
        expected = _tree_counts(source)
        verified = _tree_counts(staging) == expected
        if verify and not verified:
            raise OSError(0, "the copy does not match its source")
        fsyncs = 0
        if do_fsync:
            fsyncs = _fsync_tree(staging)
        os.replace(staging, target)
        if do_fsync:
            fsync_directory(target_dir)
            fsyncs += 1
    except BaseException:
        _remove_quietly(staging)
        raise
    files = 0
    logical = 0
    for root, _, names in os.walk(source):
        for name in names:
            path = os.path.join(root, name)
            files += 1
            if not os.path.islink(path):
                logical += os.path.getsize(path)
    shutil.rmtree(source)
    elapsed = (time.perf_counter() - started) * 1000
    return MoveReport(source, target, "copy", True, elapsed, logical, logical, files, files,
                      verified, fsyncs, True)

The move is one attempt and one fallback. The rename is tried first, unconditionally, and EXDEV is the only refusal that starts the fallback – every other errno belongs to the caller’s own paths and is raised untouched, so a locked directory still answers EACCES at the first step instead of after a wasted copy. On the fallback the file is copied into a temporary name in the destination‘s own directory, made durable, verified against the source’s digest, and only then renamed over the destination; the source is unlinked last. A caller that passed must_be_atomic=False gets the shape its plan described instead: the copy is written straight to the destination’s name for readers to see grow, fsync runs on the copy and then on its directory before the source is unlinked, and the report says staged=False. A directory takes the same shape – staged when the name has to change in one step, copied in place when it need not – with its count checked against the source either way and its destination refused before the first byte when it already holds entries, because the rename that publishes a tree can only land on an empty name: ENOTEMPTY here, the refusal the direct rename gives on one device (or EEXIST, where that is the one the filesystem prefers), taken before a copy that would be thrown away. The destination’s kind is refused in the same place and for the same reason: a directory standing where a file’s name must go answers EISDIR, and a file or a symlink standing where a tree’s name must go answers ENOTDIR – both before the copy, not after it. A symlink is re-created as a link rather than followed: the entry moves, the file it points at stays where it is. The copy asks the source for its data extents, so a sparse image stays sparse where the source can say where its holes are.

MoveTime, median (min-max of 5)RateWhat it did
4 KiB, one device8.1 ms (7.5–8.4 ms)–one rename and a directory fsync, no copy
4 KiB, across devices11.1 ms (10.4–11.4 ms)–staged copy, verify, rename, two fsyncs
8 MiB dense, across devices61.4 ms (31.8–68.2 ms)130 MiB/shole-aware copy of a file with no holes
4 MiB sparse from tmpfs139.4 ms (130.3–166.7 ms)–4,096 B copied, 1 extent
4 MiB sparse from virtiofs40.3 ms (38.6–42.8 ms)–4,194,304 B copied, 1 extent: the whole file
symlink, across devices6.1 ms (5.9–6.3 ms)–the link re-created with its target string, no bytes copied
directory of 40 files, across devices496.2 ms (489.3–548.5 ms)–12.4 ms per file at the median, 41 fsyncs
sha256 of the 8 MiB payload26.4 ms (11.6–26.6 ms)–303 MiB/s of hashing
Table 11: The package under the same probes as the standard library. Each time is the median of five repeats with the min-max range beside it, because this is a shared host and a single number would hide how much it moves. Every row but the last times the whole safemove.move call it names – the rename attempt, the staged copy with both verification digests, the rename and the unlink of the source – so the dense rate is a rate that verifies, not a bare copy; the last row times two digest reads of the same 8 MiB payload, halved for the per-digest figure. The per-file figure is the median total divided by the file count.

The widest range in the table is the densest condition, and the five repeats behind it are not one spread: the 8 MiB move is 61.4 ms (31.8–68.2 ms), but 3 runs sit at 61.4 ms or above and 2 at or below 33.0 ms, so the median is the slow group’s lowest number, not the middle of the range. The destination is host-backed virtiofs, and a write there pays for whatever else the host is doing; the median is the figure to quote and the range is what that run may return.

Two rows read backwards until the destination is taken into account. The move that copies 4 MiB from virtiofs finishes in 40.3 ms, while the move that copies 4,096 B from tmpfs takes 139.4 ms; both end on the same two devices, in opposite directions, and the slower one is writing to virtiofs. Table 12 times the same moves phase by phase: the copy phase carries most of both, and the paragraph after the table takes that phase apart, because “the copy” is not one syscall.

Phasetmpfs source, virtiofs destinationvirtiofs source, tmpfs destination
create the staging name7.69 ms0.07 ms
copy the data extents103.4 ms20.6 ms
fsync the staging file1.95 ms0.01 ms
digest the source3.4 ms6.3 ms
digest the staging file18.8 ms3.6 ms
rename over the destination5.22 ms0.01 ms
fsync the directory, unlink the source1.93 ms5.10 ms
the whole move, measured140.7 ms (131.7–147.5 ms)35.5 ms (34.6–37.9 ms)
blocks the destination holds afterwards1.00 MiB4.00 MiB
Table 12: The two sparse rows of Table 11, timed phase by phase, five repeats each; the total row carries its min-max range too. The copy phase is the whole of copy_sparse – the extents written at their offsets, the file’s length set with truncate, and the handle closed – not the data bytes alone. This is a second five-run measurement of the same conditions, so its total can differ from Table 11’s by a few percent, and the phases are separate medians that need not add up to it.

The reversal is the destination, not the data, and the copy phase of Table 12 is where it is charged. Its three operations were each timed alone in one probe – the length taken with truncate, the 4 KiB extent written at its offset, and the handle closed after both – with the open called before the timer started, so its cost is inside none of them. A 4 MiB length costs 9.8 ms on virtiofs; in memory the same call returns in 0.00 ms. The 4 KiB write that makes the copy’s one extent returns in 0.08 ms on virtiofs and 0.00 ms in memory, and closing that handle costs 16.2 ms on virtiofs, and in memory it costs nothing measurable (0.00 ms): on the host-backed destination the close, not the write, is where the cost of the block it allocated is paid. A dense 4 MiB copy runs at 57 MiB/s into virtiofs against 154 MiB/s into memory.

Those three prices are the destination’s, and they account for part of the copy row of Table 12 – 26.1 ms of the 103.4 ms the copy phase spends putting 4,096 B into virtiofs, or 25% of it – three separate medians, a decomposition of the cause rather than a sum that has to balance. The other three quarters – the opens on both sides, the read of the source, the metadata copystat writes, whatever the host’s backend adds – were not timed apart, so this page does not divide them and does not name the largest. The copy saved bytes to read and write; it did not take away the destination’s price of laying a file down, and that price is why the 4 MiB copied out of virtiofs takes 20.6 ms while the 4,096 B copied into it takes 103.4 ms.

The same discipline fits in a shell script when the writer is not Python. The block below is the whole rule with coreutils: create the staging name in the destination’s directory, copy with the source’s holes, sync, rename inside that device, and remove the source last. It was run as printed, on the two devices in Table 2.

src=/workspace/work/post40/scratch/demo/app.db
dst_dir=/tmp/p40/demo
mkdir -p "$(dirname "$src")" "$dst_dir"
head -c 4096 /dev/zero > "$src"
stage="$(mktemp "$dst_dir/.stage.XXXXXX")"
cp --sparse=auto "$src" "$stage" && sync "$stage" \
  && mv -f "$stage" "$dst_dir/app.db" && rm -f "$src"
stat -c '%s %b' "$dst_dir/app.db"

The verification is not free and it is not optional in this design: it is the only thing that turns “the copy returned” into “the source can be removed”. It is also a page-cache verification – the digest reads the copy back on the same host after fsync, so it proves what the kernel will serve, not what the platter holds, and Scope and Limits says exactly what that leaves untested. The suite that pins the behaviour is 88 tests across 5 files (905 lines), and it covers the failure paths that matter here: a locked destination, a failed verification, a tree whose source cannot be removed, a symlink that must stay a link, and a plan that cannot be edited by accident.

from __future__ import annotations
import os
import pytest
import importlib
from safemove.move import STAGING_PREFIX, move

move_module = importlib.import_module("safemove.move")


def staging_left(directory) -> list[str]:
    return [name for name in os.listdir(directory) if name.startswith(STAGING_PREFIX)]


def test_a_locked_destination_leaves_no_staging_name(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    locked = there / "locked"
    locked.mkdir()
    locked.chmod(0o500)
    try:
        with pytest.raises(OSError):
            move(source, locked / "moved.bin")
        assert staging_left(locked) == []
    finally:
        locked.chmod(0o700)


def test_a_failed_verification_keeps_the_source(tmp_path, there, monkeypatch):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 2048)
    monkeypatch.setattr(move_module, "digest",
                        lambda path: "0" * 64 if path.endswith("a.bin") else "1" * 64)
    with pytest.raises(OSError):
        move(source, there / "moved.bin")
    assert source.exists()
    assert not (there / "moved.bin").exists()
    assert staging_left(there) == []

10. In production: containers, volumes and network mounts

None of this is exotic. The rule from Section 2 – a name can only change on the mount that holds it – maps directly onto the places where a service keeps its state and its scratch space, and the table below is the mapping that follows from it. Nothing in this table was measured on this host; the measured part is the rule, and the deployments are where the rule bites.

Where the code runsWhy the two names are on different devicesWhat to change
Docker, /tmp to a volume/tmp is in the image’s writable layer; the volume is its own mountcreate the temporary file under the volume
Compose or Swarm bind mountthe host directory is mounted into the container; the mount shares the host’s device number, so a prediction of one device can still be wrongsame rule: temporary file beside the target
Kubernetes emptyDir plus a PVCthe pod-scoped directory and the claim are separate mountsstage in the claim, not in /tmp
Kubernetes ConfigMap or Secret mountthe mount is read-only and separate; renames out of it answer EXDEV or EROFScopy out, never rename out
overlay root filesystemthe container root is an overlay of layersrename of a directory that lives in a lower layer may be refused; write to a volume
NFS or CIFS mountthe network filesystem is its own device, and a rename across a mount boundary may be refused even where a number says otherwisecompare st_dev and the mount’s source, then attempt the rename
CI workspacethe checkout is usually a bind mount into the job container, so the test’s device numbers are the host’s, not production’sa same-device prediction in a test can still be refused in production
Table 13: The deployment shapes where a temporary directory and a data directory are two devices. Each row is the rule from Section 2 applied to one platform, not a measurement of that platform.

The checklist this page adds up to, in the order to apply it:

  1. Attempt the rename first, and keep st_dev as the prediction you log rather than the condition you branch on: one os.stat call answers it – 0:36 against 0:47 on this host – and even that answer is only advice, because two mounts can share a number, so EXDEV is what decides.
  2. Create the temporary file in the destination’s directory, never in the system temporary directory, so the last rename stays inside one device – and refuse a destination directory that already holds entries before copying, because that rename can only land on an empty name: ENOTEMPTY, or EEXIST on a filesystem that answers 17 for the same condition, and both mean the same thing. Check the destination’s kind in the same step: a file cannot land on a directory (EISDIR) and a tree cannot land on a file or a symlink (ENOTDIR), so refuse either before the first byte.
  3. Copy with a loop that asks SEEK_DATA for the extents, and keep the file’s length with truncate when the source reports holes; fall back to a plain copy when it does not.
  4. Verify the copy – size and digest – before the source is removed, because a successful copy is not the same statement as a correct one.
  5. fsync the file, rename, then fsync the directory: a rename that is not durable is a name that can come back as the old one after a crash.
  6. Unlink the source last, and treat a refusal there (EACCES, EBUSY) as a duplicate rather than a failed move, because both copies now exist.
  7. Expect a tree to be more than one rename, and count the window that opens after the last one: the tree is published by a single rename, but the source is then deleted entry by entry, so a crash there leaves the destination complete and the source partly gone – finish the delete rather than running the move again, because the source is no longer the tree whose count the destination was verified against.

Scope and Limits

What this page measured, and what it deliberately did not:

  • Linux only. Every errno, mount answer and timing here comes from Linux 6.12.118-guest-1.1 with CPython 3.12.16, uid 1000, on one host, five repeats per condition. Windows answers EXDEV from MoveFileEx in its own way and macOS has its own rename semantics; neither was run.
  • Not covered by the module. Reflink clones (FICLONE) are not attempted even where the filesystem supports them; a tree whose files are hard links to each other is copied as one file per name, so the tree’s internal links are not preserved; ownership, ACLs and SELinux labels are not copied – the copy keeps mode and times, and restoring the rest is the caller’s job.
  • The verification is a page-cache verification. The digest is taken after fsync by reading the file back on the same host, and that read may be answered from the page cache. It proves the copy as the kernel will serve it, not the bytes on the platter: neither POSIX_FADV_DONTNEED nor O_DIRECT is used, and a power-loss test after fsync was not run. A device that lies about its cache is outside what this check can see.
  • Timings are one host’s. virtiofs is host-backed and tmpfs is memory on this machine; the ratios in Section 9 are a direction, not a constant to quote for another machine.

Questions This Page Answers

Does EXDEV mean the disk is full?

No. A full disk answers ENOSPC 28; EXDEV is 18, a different number and a different check. EXDEV says the two names are on different mounted filesystems, and it can arrive with both devices almost empty.

Why does a rename fail between two directories in the same tree?

Because a mount inside that tree is a device boundary. On this host /tmp (0:47) and /usr (0:23) look like ordinary directories and are two mounts, so a rename between them is refused even though the pages are in one container.

Is os.replace atomic across devices?

No. Across devices it fails with EXDEV before changing anything: the destination keeps its old content and the temporary file stays where it was. Atomicity is available only inside one device, which is why the temporary file has to live beside its destination.

Does shutil.move raise EXDEV?

Not normally. The standard library falls back to a copy: “Otherwise, src is copied to dst using copy_function and then removed”. The exception is raised only if the copy also fails, and then the errno belongs to the copy’s failure, not to the rename’s.

How do I make a cross-device move atomic?

A staged copy in the destination’s own directory, with the digest checked to verify it before the rename, makes the move atomic: the rename is then a same-device operation, so readers see the old file or the new one and nothing between, and the source is unlinked after it.

Why did my sparse file grow to its full size?

The copy wrote the holes as zeros. A hole-aware copy asks SEEK_DATA and SEEK_HOLE where the data is, copies only those extents, and restores the length with truncate; on this host that turns 32 MiB of writes into 4 KiB for the same image.

Which filesystems report holes?

Not all of them, and the copy inherits the answer. On this host the tmpfs source named one 4 KiB extent in a 32 MiB image, and the virtiofs source reported the whole file as data, so the same loop copied every byte from it.

Why did the moved file lose its xattr or its SELinux label?

The destination filesystem does not store it: the copy reports success and the attribute is gone, because the destination answers ENOTSUP (95) for the attribute. Read it back after the move, or know the destination’s type before the move.

Why did renaming onto a non-empty directory answer 17 here and 39 elsewhere?

The condition is the same and the number is the filesystem’s choice: this host’s tmpfs answered ENOTEMPTY 39 and its virtiofs mount answered EEXIST 17 for the same call. Handle both when the condition is “the target directory is not empty”.

Can a hard link cross a device?

No. A hard link is a second name for one inode, and an inode belongs to one filesystem; link(2) answers EXDEV for the same reason rename(2) does, and there is no fallback that keeps the semantics.

How do I tell whether two paths are on one device, before writing anything?

Compare st_dev of the two directories, using the nearest existing ancestor of a path that does not exist yet. In Python that is os.stat(path).st_dev after walking up – or os.lstat on the entry itself when it is a symlink; in a shell it is stat -c %d on both directories. Then attempt the rename anyway: a bind mount shares its source’s device number, so equal numbers are not a promise, and EXDEV is the answer that decides.

Do I have to copy a directory tree by hand to move it across devices?

Not by hand. A tree is copied into a staging directory inside the destination, its count checked against the source, and the whole tree published with one rename, so the destination name stays empty until the tree is complete; on one device the same tree moves with a single os.replace.

Going further

TechBobby Engineering writes runbooks from measured failures: every number here was read from a record a probe wrote, not typed in. The package, its tests and the harness are printed in full in the appendix; the numbered probes are not. Each figure carries the size and repeat count it was taken at, so a reader can rerun the same probe, on the one host described at the top of this page.

Appendix: The Package, Its Tests, and the Harness

Each fold below is one file, printed character for character as it ran on the host in Section 2: the rest of the package, its tests, the harness every five-repeat run went through, and the example that prints a plan for three paths without moving anything. policy.py and move.py, the two files the page is about, are printed whole in Section 9 and are not repeated here. The numbered probes that wrote each record are not folded here either, and the tables that map the rule onto deployments rather than measure them say so in their captions.

The package’s public names __init__.py
"""Move a path across devices so that its destination name is never half-written.

``safemove.move`` takes the same arguments as ``shutil.move`` and adds the three things a
service needs from a cross-device move: the copy is staged in the destination's own directory,
it is verified against the source before the source is dropped, and the destination name
changes in one rename. ``safemove.choose`` returns that plan without touching anything.
"""
from __future__ import annotations

from .copy import CopyStats, copy_file, copy_sparse, digest
from .device import describe, device_of, same_device
from .move import MoveReport, move
from .policy import Plan, choose

__all__ = ["CopyStats", "MoveReport", "Plan", "choose", "copy_file", "copy_sparse", "describe",
           "device_of", "digest", "move", "same_device"]
Which device a path lives on device.py
"""Where a path lives: the one fact that decides whether a move can be a rename."""
from __future__ import annotations

import os


def device_of(path: str | os.PathLike[str]) -> int:
    """The ``st_dev`` of the entry ``path``, or of its nearest ancestor that exists.

    A caller checks a destination that does not exist yet - a file a service is about to
    write - so the answer has to come from the directory it would live in, not from the
    file. Walking up also covers ``a/b/c`` on a mount whose parent is another device:
    the answer changes exactly where the mount is.

    The final component is answered by ``lstat``, not ``stat``: a rename moves the entry
    itself, so a symlink is compared by the device its name lives on, never by the device
    its target happens to sit on.
    """
    current = os.path.abspath(os.fspath(path))
    while True:
        try:
            return os.lstat(current).st_dev
        except FileNotFoundError:
            parent = os.path.dirname(current)
            if parent == current:
                raise
            current = parent


def same_device(source: str | os.PathLike[str], target: str | os.PathLike[str]) -> bool:
    """True when a directory entry can be moved between the two without copying bytes."""
    return device_of(source) == device_of(target)


def describe(device: int) -> str:
    """``major:minor``, the form ``stat -c %d`` and the mount table use."""
    major = os.major(device)
    minor = os.minor(device)
    return f"{major}:{minor}"
Hole-aware copy, fsync, digest copy.py
"""Copying a file while keeping the holes the source filesystem reports.

A cross-device move has no choice but to copy bytes. Which bytes is a decision: a 32 MiB
image with one 4 KiB write in it costs 4 KiB to copy when ``SEEK_DATA`` can name the data, and
32 MiB when it cannot. The source filesystem answers that question, so the answer is measured
per copy rather than assumed - and when it cannot answer at all, the copy says so and copies
every byte instead of writing a file full of holes.
"""
from __future__ import annotations

import errno
import hashlib
import os
import shutil
from dataclasses import dataclass

CHUNK = 1 << 20


class _SeekDataUnsupported(Exception):
    """The source's filesystem does not answer ``SEEK_DATA``: copy the whole file instead."""


@dataclass(frozen=True)
class CopyStats:
    """What the copy actually did, so the caller can log it rather than guess."""

    logical_bytes: int
    data_bytes: int
    extents: int
    holes_known: bool = True

    @property
    def hole_bytes(self) -> int:
        return self.logical_bytes - self.data_bytes


def _extents(handle: int, size: int):
    """Yield ``(start, end)`` for each region the filesystem reports as data.

    ``SEEK_DATA`` answers ``ENXIO`` when no data follows the offset, which is how a file that
    is entirely a hole ends: no extents, and the destination is still given its full length.
    Any other refusal means the filesystem cannot answer the question at all, which is not
    the same statement as "there are no holes" and must not be reported as one.
    """
    if not hasattr(os, "SEEK_DATA") or not hasattr(os, "SEEK_HOLE"):
        raise _SeekDataUnsupported("this platform has no SEEK_DATA")
    offset = 0
    while offset < size:
        try:
            start = os.lseek(handle, offset, os.SEEK_DATA)
        except OSError as exc:
            if exc.errno == errno.ENXIO:
                return
            raise _SeekDataUnsupported(str(exc)) from exc
        end = os.lseek(handle, start, os.SEEK_HOLE)
        yield start, end
        offset = end


def copy_sparse(source: str | os.PathLike[str], target: str | os.PathLike[str]) -> CopyStats:
    """Copy only the data extents, then give the target the source's length.

    When the source cannot name its data, every byte is copied and ``holes_known`` is
    ``False``: the destination is correct either way, and the caller can tell which copy it
    paid for.
    """
    handle = os.open(source, os.O_RDONLY)
    try:
        size = os.fstat(handle).st_size
        try:
            spans = list(_extents(handle, size))
        except _SeekDataUnsupported:
            spans = None
    finally:
        os.close(handle)
    if spans is None:
        shutil.copyfile(source, target)
        return CopyStats(logical_bytes=size, data_bytes=size, extents=0, holes_known=False)
    copied = 0
    with open(source, "rb") as reader, open(target, "wb") as writer:
        for start, end in spans:
            reader.seek(start)
            writer.seek(start)
            remaining = end - start
            while remaining > 0:
                chunk = reader.read(min(CHUNK, remaining))
                if not chunk:
                    break
                writer.write(chunk)
                copied += len(chunk)
                remaining -= len(chunk)
        writer.truncate(size)
        writer.flush()
    return CopyStats(logical_bytes=size, data_bytes=copied, extents=len(spans))


def copy_file(source: str | os.PathLike[str], target: str | os.PathLike[str],
              sparse: bool = True) -> CopyStats:
    """Copy a file, its mode and its times; sparse copies keep the holes the source reports."""
    if sparse:
        stats = copy_sparse(source, target)
    else:
        shutil.copyfile(source, target)
        stats = CopyStats(logical_bytes=os.path.getsize(target),
                          data_bytes=os.path.getsize(target), extents=1, holes_known=False)
    shutil.copystat(source, target)
    return stats


def fsync_file(path: str | os.PathLike[str]) -> None:
    """Make the file's own bytes durable before its name is published."""
    handle = os.open(path, os.O_RDONLY)
    try:
        os.fsync(handle)
    finally:
        os.close(handle)


def fsync_directory(path: str | os.PathLike[str]) -> None:
    """Make the new name durable: on Linux the rename is only crash-safe after this."""
    handle = os.open(path, os.O_RDONLY)
    try:
        os.fsync(handle)
    finally:
        os.close(handle)


def digest(path: str | os.PathLike[str]) -> str:
    """sha256 of a file's contents, used to prove the copy before the source is dropped."""
    hasher = hashlib.sha256()
    with open(path, "rb") as handle:
        for block in iter(lambda: handle.read(CHUNK), b""):
            hasher.update(block)
    return hasher.hexdigest()
Two devices, a sparse file and a tree conftest.py
"""Fixtures: a directory on one device, and one on another, when the host has two."""
from __future__ import annotations

import os
import pathlib
import shutil
import tempfile

import pytest

from safemove import device_of

SECOND_DEVICE = pathlib.Path("/workspace/work/post40/scratch/pytest")


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


@pytest.fixture()
def there() -> pathlib.Path:
    """A fresh directory on a different device from ``tmp_path``, or a skip on a one-device host."""
    SECOND_DEVICE.mkdir(parents=True, exist_ok=True)
    if device_of(SECOND_DEVICE) == device_of("/tmp"):
        pytest.skip("the host has only one device to test with")
    path = pathlib.Path(tempfile.mkdtemp(dir=SECOND_DEVICE, prefix="case-"))
    yield path
    shutil.rmtree(path, ignore_errors=True)


@pytest.fixture()
def sparse_file(tmp_path: pathlib.Path):
    """A 4 MiB file whose only data is one 4 KiB write in the middle."""

    def make(name: str = "disk.img", size: int = 4 << 20, data_at: int | None = None):
        path = tmp_path / name
        with open(path, "wb") as handle:
            handle.truncate(size)
            handle.seek(size // 2 if data_at is None else data_at)
            handle.write(b"data" * 1024)
        return path

    return make


@pytest.fixture()
def tree(tmp_path: pathlib.Path):
    """A small tree with a subdirectory and a relative symlink."""

    def make(name: str = "tree") -> pathlib.Path:
        root = tmp_path / name
        (root / "sub").mkdir(parents=True)
        (root / "sub" / "inside.txt").write_bytes(b"inside")
        os.symlink("../sub/inside.txt", root / "link")
        return root

    return make
Device answers for paths that do not exist test_device.py
"""``device_of`` answers for paths that do not exist yet, which is the case that matters."""
from __future__ import annotations

import os

from safemove.device import describe, device_of, same_device


def test_existing_directory_reports_its_own_device(tmp_path):
    assert device_of(tmp_path) == os.stat(tmp_path).st_dev


def test_missing_file_reports_the_directory_it_would_live_in(tmp_path):
    assert device_of(tmp_path / "not-yet.json") == os.stat(tmp_path).st_dev


def test_missing_parents_are_walked_until_one_exists(tmp_path):
    deep = tmp_path / "a" / "b" / "c" / "file.bin"
    assert device_of(deep) == os.stat(tmp_path).st_dev


def test_two_paths_in_one_directory_share_a_device(tmp_path):
    assert same_device(tmp_path / "a", tmp_path / "b")


def test_the_root_always_answers(tmp_path):
    assert isinstance(device_of("/"), int)


def test_relative_paths_are_resolved(tmp_path, monkeypatch):
    monkeypatch.chdir(tmp_path)
    assert device_of("relative.bin") == os.stat(tmp_path).st_dev


def test_a_destination_that_does_not_exist_yet_is_compared_by_its_directory(tmp_path):
    assert same_device(tmp_path / "existing.bin", tmp_path / "new" / "name.bin")


def test_two_devices_are_told_apart(there):
    assert not same_device("/tmp", there)


def test_describe_prints_the_mount_table_form(tmp_path):
    major, minor = describe(device_of(tmp_path)).split(":")
    assert (int(major), int(minor)) == (os.major(os.stat(tmp_path).st_dev),
                                        os.minor(os.stat(tmp_path).st_dev))


def test_device_of_a_symlink_answers_for_the_link_not_its_target(tmp_path):
    """A rename moves the entry, so a link is compared by the device its name lives on."""
    os.symlink("/dev/shm", tmp_path / "link")
    assert device_of(tmp_path / "link") == os.stat(tmp_path).st_dev


def test_a_link_to_another_device_is_not_called_same_device(tmp_path, there):
    payload = there / "payload.bin"
    payload.write_bytes(b"x")
    os.symlink(payload, tmp_path / "link")
    assert not same_device(tmp_path / "link", there / "moved.bin")
Copies keep the shape of the holes test_copy.py
"""The copy has to keep what the source had, including the shape of its holes."""
from __future__ import annotations

import errno
import hashlib
import os

import pytest

from safemove.copy import (CopyStats, copy_file, copy_sparse, digest, fsync_directory,
                           fsync_file)


def test_copy_file_moves_the_bytes(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 100)
    target = tmp_path / "b.bin"
    copy_file(source, target)
    assert target.read_bytes() == source.read_bytes()


def test_copy_file_reports_the_logical_size(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 5000)
    stats = copy_file(source, tmp_path / "b.bin")
    assert stats.logical_bytes == 5000


def test_a_dense_copy_has_no_hole(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 5000)
    stats = copy_file(source, tmp_path / "b.bin")
    assert stats.hole_bytes == 0


def test_a_sparse_copy_counts_only_its_data(sparse_file, tmp_path):
    source = sparse_file(size=4 << 20)
    stats = copy_file(source, tmp_path / "copy.img")
    assert stats.data_bytes == 4096
    assert stats.extents == 1


def test_a_sparse_copy_keeps_the_length(sparse_file, tmp_path):
    source = sparse_file(size=4 << 20)
    copy_file(source, tmp_path / "copy.img")
    assert os.path.getsize(tmp_path / "copy.img") == 4 << 20


def test_a_sparse_copy_keeps_the_hole_on_disk(sparse_file, tmp_path):
    source = sparse_file(size=4 << 20)
    copy_file(source, tmp_path / "copy.img")
    assert os.stat(tmp_path / "copy.img").st_blocks * 512 < 64 * 1024


def test_an_all_hole_file_copies_without_extents(tmp_path):
    source = tmp_path / "hole.img"
    with open(source, "wb") as handle:
        handle.truncate(1 << 20)
    stats = copy_sparse(source, tmp_path / "copy.img")
    assert stats.extents == 0
    assert stats.data_bytes == 0
    assert stats.logical_bytes == 1 << 20


def test_data_larger_than_one_chunk_is_copied_whole(tmp_path):
    source = tmp_path / "big.bin"
    source.write_bytes(bytes(range(256)) * 8192)
    stats = copy_sparse(source, tmp_path / "copy.bin")
    assert stats.data_bytes == 2 << 20
    assert digest(source) == digest(tmp_path / "copy.bin")


def test_copy_file_keeps_the_mode(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    os.chmod(source, 0o640)
    copy_file(source, tmp_path / "b.bin")
    assert (os.stat(tmp_path / "b.bin").st_mode & 0o777) == 0o640


def test_copy_file_keeps_the_mtime(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    os.utime(source, (1_600_000_000, 1_600_000_000))
    copy_file(source, tmp_path / "b.bin")
    assert int(os.stat(tmp_path / "b.bin").st_mtime) == 1_600_000_000


def test_copy_file_without_sparse_writes_every_byte(sparse_file, tmp_path):
    source = sparse_file(size=1 << 20)
    stats = copy_file(source, tmp_path / "copy.img", sparse=False)
    assert stats.data_bytes == 1 << 20
    assert stats.extents == 1


def test_copy_file_reports_a_missing_source(tmp_path):
    with pytest.raises(FileNotFoundError):
        copy_file(tmp_path / "nope", tmp_path / "copy")


def test_digest_matches_hashlib(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"abc" * 1000)
    assert digest(source) == hashlib.sha256(b"abc" * 1000).hexdigest()


def test_digest_tells_two_files_apart(tmp_path):
    (tmp_path / "a.bin").write_bytes(b"one")
    (tmp_path / "b.bin").write_bytes(b"two")
    assert digest(tmp_path / "a.bin") != digest(tmp_path / "b.bin")


def test_fsync_file_accepts_a_written_file(tmp_path):
    path = tmp_path / "a.bin"
    path.write_bytes(b"x")
    fsync_file(path)


def test_fsync_directory_accepts_a_directory(tmp_path):
    fsync_directory(tmp_path)


def test_stats_hole_bytes_is_the_difference():
    stats = CopyStats(logical_bytes=100, data_bytes=40, extents=2)
    assert stats.hole_bytes == 60


def test_a_sparse_copy_reports_that_it_knew_the_holes(sparse_file, tmp_path):
    stats = copy_file(sparse_file(size=4 << 20), tmp_path / "copy.img")
    assert stats.holes_known is True


def test_a_copy_that_could_not_ask_reports_it(tmp_path, monkeypatch):
    """A filesystem that cannot answer SEEK_DATA must give a whole copy, not a file of holes."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 1000)
    real_lseek = os.lseek

    def no_seek_data(handle, offset, whence):
        if whence == os.SEEK_DATA:
            raise OSError(errno.EINVAL, "Invalid argument")
        return real_lseek(handle, offset, whence)

    monkeypatch.setattr(os, "lseek", no_seek_data)
    stats = copy_sparse(source, tmp_path / "b.bin")
    assert (tmp_path / "b.bin").read_bytes() == source.read_bytes()
    assert stats.data_bytes == stats.logical_bytes == 7000
    assert stats.holes_known is False
Same device, two devices, and a refused rename in the middle test_move.py
"""One move, three cases: same device, two devices, two devices with a failure in the middle."""
from __future__ import annotations

import errno
import os

import pytest

import importlib

from safemove.move import STAGING_PREFIX, move

move_module = importlib.import_module("safemove.move")


def staging_left(directory) -> list[str]:
    return [name for name in os.listdir(directory) if name.startswith(STAGING_PREFIX)]


def test_a_same_device_move_keeps_the_inode(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    before = os.stat(source).st_ino
    report = move(source, tmp_path / "b.bin")
    assert report.method == "rename"
    assert os.stat(tmp_path / "b.bin").st_ino == before


def test_a_same_device_move_removes_the_source(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    move(source, tmp_path / "b.bin")
    assert not source.exists()


def test_a_cross_device_move_copies_the_bytes(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 100)
    report = move(source, there / "moved.bin")
    assert (there / "moved.bin").read_bytes() == b"payload" * 100
    assert report.method == "copy"


def test_a_cross_device_move_is_staged(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert move(source, there / "moved.bin").staged is True


def test_a_cross_device_move_verifies_the_copy(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 4096)
    assert move(source, there / "moved.bin").verified is True


def test_a_cross_device_move_leaves_no_staging_name(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    move(source, there / "moved.bin")
    assert staging_left(there) == []


def test_a_cross_device_move_removes_the_source(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    move(source, there / "moved.bin")
    assert not source.exists()


def test_a_cross_device_move_keeps_the_mode(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    os.chmod(source, 0o600)
    move(source, there / "moved.bin")
    assert (os.stat(there / "moved.bin").st_mode & 0o777) == 0o600


def test_a_cross_device_move_counts_only_the_data_it_copied(tmp_path, there, sparse_file):
    source = sparse_file(size=4 << 20)
    report = move(source, there / "disk.img")
    assert report.data_bytes == 4096
    assert report.logical_bytes == 4 << 20


def test_a_cross_device_move_of_a_tree_keeps_every_file(tmp_path, there, tree):
    source = tree()
    report = move(source, there / "tree")
    assert (there / "tree" / "sub" / "inside.txt").read_bytes() == b"inside"
    assert report.files == 2


def test_a_cross_device_tree_move_keeps_a_symlink_a_symlink(tmp_path, there, tree):
    source = tree()
    move(source, there / "tree")
    assert os.path.islink(there / "tree" / "link")
    assert os.readlink(there / "tree" / "link") == "../sub/inside.txt"


def test_a_cross_device_tree_move_removes_the_source(tmp_path, there, tree):
    source = tree()
    move(source, there / "tree")
    assert not source.exists()


def test_a_cross_device_move_onto_an_existing_file_replaces_it(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"new")
    (there / "moved.bin").write_bytes(b"old")
    move(source, there / "moved.bin")
    assert (there / "moved.bin").read_bytes() == b"new"


def test_a_locked_destination_directory_leaves_the_source_alone(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    locked = there / "locked"
    locked.mkdir()
    locked.chmod(0o500)
    try:
        with pytest.raises(OSError) as raised:
            move(source, locked / "moved.bin")
    finally:
        locked.chmod(0o700)
    assert raised.value.errno == errno.EACCES
    assert source.exists()


def test_a_locked_destination_leaves_no_staging_name(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    locked = there / "locked"
    locked.mkdir()
    locked.chmod(0o500)
    try:
        with pytest.raises(OSError):
            move(source, locked / "moved.bin")
        assert staging_left(locked) == []
    finally:
        locked.chmod(0o700)


def test_a_failed_verification_keeps_the_source(tmp_path, there, monkeypatch):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 2048)
    monkeypatch.setattr(move_module, "digest",
                        lambda path: "0" * 64 if path.endswith("a.bin") else "1" * 64)
    with pytest.raises(OSError):
        move(source, there / "moved.bin")
    assert source.exists()
    assert not (there / "moved.bin").exists()
    assert staging_left(there) == []


def test_without_verification_the_move_still_runs(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 16)
    report = move(source, there / "moved.bin", verify=False)
    assert report.verified is False
    assert (there / "moved.bin").read_bytes() == b"x" * 16


def test_without_fsync_the_move_reports_no_sync(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 16)
    report = move(source, there / "moved.bin", do_fsync=False)
    assert report.fsyncs == 0


def test_with_fsync_the_move_syncs_the_file_and_the_directory(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 16)
    report = move(source, there / "moved.bin")
    assert report.fsyncs == 2


def test_an_in_place_copy_is_not_staged(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 32)
    report = move(source, there / "moved.bin", must_be_atomic=False)
    assert report.staged is False
    assert (there / "moved.bin").read_bytes() == b"x" * 32


def test_an_in_place_copy_fsyncs_the_file_and_the_directory(tmp_path, there, monkeypatch):
    """The reader-visible path is still durable: fsync the copy, then the directory."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 1024)
    calls: list[int] = []
    real_fsync = move_module.os.fsync

    def counted(handle: int) -> None:
        calls.append(handle)
        real_fsync(handle)

    monkeypatch.setattr(move_module.os, "fsync", counted)
    report = move(source, there / "moved.bin", must_be_atomic=False)
    assert report.staged is False
    assert report.fsyncs == 2
    assert len(calls) == 2
    assert (there / "moved.bin").read_bytes() == b"x" * 1024


def test_an_in_place_copy_without_fsync_reports_no_sync(tmp_path, there, monkeypatch):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 16)
    calls: list[int] = []
    real_fsync = move_module.os.fsync

    def counted(handle: int) -> None:
        calls.append(handle)
        real_fsync(handle)

    monkeypatch.setattr(move_module.os, "fsync", counted)
    report = move(source, there / "moved.bin", must_be_atomic=False, do_fsync=False)
    assert report.fsyncs == 0
    assert calls == []


def test_an_in_place_tree_copy_fsyncs_every_file_and_the_directory(tmp_path, there, tree):
    """Two entries in the tree, one of them a symlink: one file fsync, then the directory."""
    report = move(tree(), there / "tree", must_be_atomic=False)
    assert report.staged is False
    assert report.files == 2
    assert report.fsyncs == 2
    assert (there / "tree" / "sub" / "inside.txt").read_bytes() == b"inside"


def test_a_refused_rename_without_atomicity_stays_in_place(tmp_path, monkeypatch):
    """must_be_atomic=False is a policy about the fallback too: no staged copy is built."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 100)
    assert move_module.choose(source, tmp_path / "b.bin",
                              must_be_atomic=False).atomic_replace is False
    real_replace = move_module.os.replace

    def refuse_the_direct_rename(src, dst):
        if str(src) == str(source):
            raise OSError(errno.EXDEV, "Invalid cross-device link")
        return real_replace(src, dst)

    monkeypatch.setattr(move_module.os, "replace", refuse_the_direct_rename)
    report = move(source, tmp_path / "b.bin", must_be_atomic=False)
    assert report.method == "copy"
    assert report.staged is False
    assert report.fell_back is True
    assert report.fsyncs == 2
    assert (tmp_path / "b.bin").read_bytes() == b"payload" * 100
    assert not source.exists()
    assert staging_left(tmp_path) == []


def test_a_refused_rename_of_a_symlink_without_atomicity_creates_it_at_the_name(tmp_path,
                                                                               monkeypatch):
    payload = tmp_path / "payload.bin"
    payload.write_bytes(b"x")
    link = tmp_path / "link"
    os.symlink(payload, link)
    real_replace = move_module.os.replace

    def refuse_the_direct_rename(src, dst):
        if str(src) == str(link):
            raise OSError(errno.EXDEV, "Invalid cross-device link")
        return real_replace(src, dst)

    monkeypatch.setattr(move_module.os, "replace", refuse_the_direct_rename)
    report = move(link, tmp_path / "moved", must_be_atomic=False)
    assert report.method == "link"
    assert report.staged is False
    assert report.fell_back is True
    assert os.readlink(tmp_path / "moved") == str(payload)
    assert not os.path.lexists(link)


def test_a_missing_source_is_reported_as_such(tmp_path, there):
    with pytest.raises(FileNotFoundError):
        move(tmp_path / "nope", there / "moved.bin")


def test_a_rename_reports_no_copied_bytes(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 32)
    assert move(source, tmp_path / "b.bin").copied_bytes == 0


def test_a_copy_reports_the_bytes_it_copied(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 32)
    assert move(source, there / "moved.bin").copied_bytes == 32


def test_a_move_reports_its_duration(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert move(source, tmp_path / "b.bin").ms > 0


def test_a_same_device_move_fsyncs_the_new_name(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert move(source, tmp_path / "b.bin").fsyncs == 1


def test_an_empty_file_is_still_one_file(tmp_path):
    source = tmp_path / "empty.bin"
    source.write_bytes(b"")
    assert move(source, tmp_path / "moved.bin").files == 1


def test_a_cross_device_move_of_a_symlink_keeps_it_a_link(tmp_path, there):
    payload = tmp_path / "payload.bin"
    payload.write_bytes(b"x")
    link = tmp_path / "link"
    os.symlink(payload, link)
    report = move(link, there / "link")
    assert report.method == "link"
    assert os.path.islink(there / "link")
    assert os.readlink(there / "link") == str(payload)
    assert not os.path.lexists(link)


def test_a_cross_device_move_of_a_dangling_symlink_keeps_the_string(tmp_path, there):
    link = tmp_path / "dangling"
    os.symlink("../gone/away", link)
    move(link, there / "dangling")
    assert os.readlink(there / "dangling") == "../gone/away"
    assert not os.path.lexists(link)


def test_a_cross_device_tree_move_verifies_the_count(tmp_path, there, tree):
    assert move(tree(), there / "tree").verified is True


def test_a_refused_rename_falls_back_to_a_staged_copy(tmp_path, monkeypatch):
    """A same-device plan is advice: when the kernel answers EXDEV, the move stages anyway."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 100)
    assert move_module.choose(source, tmp_path / "b.bin").same_device is True
    real_replace = move_module.os.replace

    def refuse_the_direct_rename(src, dst):
        if str(src) == str(source):
            raise OSError(errno.EXDEV, "Invalid cross-device link")
        return real_replace(src, dst)

    monkeypatch.setattr(move_module.os, "replace", refuse_the_direct_rename)
    report = move(source, tmp_path / "b.bin")
    assert report.method == "copy"
    assert report.staged is True
    assert report.fell_back is True
    assert (tmp_path / "b.bin").read_bytes() == b"payload" * 100
    assert not source.exists()
    assert staging_left(tmp_path) == []


def test_an_ordinary_rename_does_not_claim_a_fallback(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert move(source, tmp_path / "b.bin").fell_back is False


def test_a_refused_rename_of_a_symlink_falls_back_to_a_link(tmp_path, monkeypatch):
    payload = tmp_path / "payload.bin"
    payload.write_bytes(b"x")
    link = tmp_path / "link"
    os.symlink(payload, link)
    real_replace = move_module.os.replace

    def refuse_the_direct_rename(src, dst):
        if str(src) == str(link):
            raise OSError(errno.EXDEV, "Invalid cross-device link")
        return real_replace(src, dst)

    monkeypatch.setattr(move_module.os, "replace", refuse_the_direct_rename)
    report = move(link, tmp_path / "moved")
    assert report.method == "link"
    assert report.fell_back is True
    assert os.path.islink(tmp_path / "moved")
    assert os.readlink(tmp_path / "moved") == str(payload)
    assert not os.path.lexists(link)
    assert staging_left(tmp_path) == []


def test_a_cross_device_tree_move_onto_a_non_empty_directory_is_refused_before_the_copy(
        tmp_path, there, tree):
    """The last rename can only land on an empty name, so the refusal comes before the copy."""
    source = tree()
    target = there / "target"
    target.mkdir()
    (target / "kept.txt").write_bytes(b"kept")
    with pytest.raises(OSError) as raised:
        move(source, target)
    assert raised.value.errno == errno.ENOTEMPTY
    assert staging_left(there) == []
    assert (there / "target" / "kept.txt").read_bytes() == b"kept"
    assert not (there / "target" / "sub").exists()
    assert (source / "sub" / "inside.txt").read_bytes() == b"inside"


def test_a_cross_device_tree_move_onto_an_empty_directory_lands(tmp_path, there, tree):
    """An empty directory is a name a rename can replace, so it is not a refusal."""
    target = there / "target"
    target.mkdir()
    report = move(tree(), target)
    assert report.staged is True
    assert (target / "sub" / "inside.txt").read_bytes() == b"inside"


def test_a_cross_device_in_place_tree_move_onto_a_non_empty_directory_is_refused(
        tmp_path, there, tree):
    """A tree move never merges into a destination that already holds entries."""
    source = tree()
    target = there / "target"
    target.mkdir()
    (target / "kept.txt").write_bytes(b"kept")
    with pytest.raises(OSError) as raised:
        move(source, target, must_be_atomic=False)
    assert raised.value.errno == errno.ENOTEMPTY
    assert (target / "kept.txt").read_bytes() == b"kept"
    assert not (target / "sub").exists()
    assert (source / "sub" / "inside.txt").read_bytes() == b"inside"


def refuse_the_direct_rename(monkeypatch, source) -> None:
    """Make the kernel answer EXDEV for the first call only: that is the fallback's entry point."""
    real_replace = move_module.os.replace
    wanted = str(source)

    def refuse(src, dst):
        if str(src) == wanted:
            raise OSError(errno.EXDEV, "Invalid cross-device link")
        return real_replace(src, dst)

    monkeypatch.setattr(move_module.os, "replace", refuse)


def count_copies(monkeypatch) -> list[str]:
    """Record every call into the copy, so a refusal that copies first is visible as a copy."""
    copied: list[str] = []
    real_copy = move_module.copy_file

    def counted(source, target, *args, **kwargs):
        copied.append(str(source))
        return real_copy(source, target, *args, **kwargs)

    monkeypatch.setattr(move_module, "copy_file", counted)
    return copied


def test_a_cross_device_file_move_onto_a_directory_is_refused_before_the_copy(
        tmp_path, there, monkeypatch):
    """rename(2) answers EISDIR for this pair, so the fallback must not copy first and fail last."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"payload" * 100)
    target = there / "taken"
    target.mkdir()
    refuse_the_direct_rename(monkeypatch, source)
    copied = count_copies(monkeypatch)
    with pytest.raises(IsADirectoryError) as raised:
        move(source, target)
    assert raised.value.errno == errno.EISDIR
    assert copied == []
    assert staging_left(there) == []
    assert source.read_bytes() == b"payload" * 100
    assert target.is_dir() and list(target.iterdir()) == []


def test_a_cross_device_file_move_onto_a_directory_is_refused_in_place_too(
        tmp_path, there, monkeypatch):
    """The reader-visible path takes the same pre-check: no partial copy into a wrong target."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"x" * 64)
    target = there / "taken"
    target.mkdir()
    refuse_the_direct_rename(monkeypatch, source)
    copied = count_copies(monkeypatch)
    with pytest.raises(IsADirectoryError) as raised:
        move(source, target, must_be_atomic=False)
    assert raised.value.errno == errno.EISDIR
    assert copied == []
    assert source.exists()
    assert list(target.iterdir()) == []


def test_a_cross_device_tree_move_onto_a_file_is_refused_before_the_copy(
        tmp_path, there, tree, monkeypatch):
    """A directory onto a file is ENOTDIR, and the file keeps every byte of itself."""
    source = tree()
    target = there / "taken"
    target.write_bytes(b"kept")
    refuse_the_direct_rename(monkeypatch, source)
    copied = count_copies(monkeypatch)
    with pytest.raises(NotADirectoryError) as raised:
        move(source, target)
    assert raised.value.errno == errno.ENOTDIR
    assert copied == []
    assert staging_left(there) == []
    assert target.read_bytes() == b"kept"
    assert (source / "sub" / "inside.txt").read_bytes() == b"inside"


def test_a_cross_device_tree_move_onto_a_symlink_is_refused_before_the_copy(
        tmp_path, there, tree, monkeypatch):
    """A symlink is not a directory either: the tree move answers ENOTDIR, not a merge."""
    source = tree()
    target = there / "taken"
    os.symlink(tmp_path / "elsewhere", target)
    refuse_the_direct_rename(monkeypatch, source)
    copied = count_copies(monkeypatch)
    with pytest.raises(NotADirectoryError) as raised:
        move(source, target)
    assert raised.value.errno == errno.ENOTDIR
    assert copied == []
    assert staging_left(there) == []
    assert os.path.islink(target)
    assert os.readlink(target) == str(tmp_path / "elsewhere")
    assert (source / "sub" / "inside.txt").read_bytes() == b"inside"


def test_a_same_device_file_move_onto_a_directory_is_refused_by_the_kernel(tmp_path):
    """One device: the direct rename gives EISDIR itself, so both paths answer the same errno."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    target = tmp_path / "taken"
    target.mkdir()
    with pytest.raises(IsADirectoryError) as raised:
        move(source, target)
    assert raised.value.errno == errno.EISDIR
    assert source.exists()


def test_a_move_onto_a_non_empty_directory_is_refused(tmp_path):
    source = tmp_path / "tree"
    source.mkdir()
    target = tmp_path / "target"
    target.mkdir()
    (target / "kept.txt").write_bytes(b"kept")
    with pytest.raises(OSError) as raised:
        move(source, target)
    assert raised.value.errno in (errno.EEXIST, errno.ENOTEMPTY)
The plan as a value test_policy.py
"""The plan is a value: it can be printed, compared and tested without moving anything."""
from __future__ import annotations

import dataclasses
import os

import pytest

import safemove


def test_a_file_on_one_device_plans_a_rename(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    plan = safemove.choose(source, tmp_path / "b.bin")
    assert plan.method == "rename"
    assert plan.staged is False


def test_a_file_across_devices_plans_a_staged_copy(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    plan = safemove.choose(source, there / "b.bin")
    assert plan.method == "copy"
    assert plan.staged is True


def test_a_directory_across_devices_plans_a_staged_copy(tmp_path, there, tree):
    plan = safemove.choose(tree(), there / "tree")
    assert plan.method == "copy"
    assert plan.atomic_replace is True


def test_a_plan_always_replaces_atomically(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    plan = safemove.choose(source, there / "b.bin")
    assert plan.atomic_replace is True


def test_an_in_place_copy_is_reported_as_such(tmp_path, there):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    plan = safemove.choose(source, there / "b.bin", must_be_atomic=False)
    assert plan.staged is False


def test_a_same_device_plan_without_atomicity_says_the_name_may_be_taken_in_place(tmp_path):
    """The one-device plan follows must_be_atomic too: a refused rename copies in place."""
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert safemove.choose(source, tmp_path / "b.bin").atomic_replace is True
    plan = safemove.choose(source, tmp_path / "b.bin", must_be_atomic=False)
    assert plan.method == "rename"
    assert plan.staged is False
    assert plan.atomic_replace is False
    assert "in-place" in plan.reason


def test_every_plan_carries_its_reason(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    assert safemove.choose(source, tmp_path / "b.bin").reason


def test_a_missing_source_cannot_be_planned(tmp_path, there):
    with pytest.raises(FileNotFoundError):
        safemove.choose(tmp_path / "nope", there / "b.bin")


def test_a_plan_is_immutable(tmp_path):
    source = tmp_path / "a.bin"
    source.write_bytes(b"x")
    plan = safemove.choose(source, tmp_path / "b.bin")
    with pytest.raises(dataclasses.FrozenInstanceError):
        plan.method = "copy"


def test_the_package_exposes_the_public_names():
    for name in ("move", "choose", "Plan", "MoveReport", "same_device", "device_of"):
        assert hasattr(safemove, name)


def test_a_symlink_across_devices_plans_a_recreated_link(tmp_path, there):
    payload = tmp_path / "payload.bin"
    payload.write_bytes(b"x")
    link = tmp_path / "link"
    os.symlink(payload, link)
    plan = safemove.choose(link, there / "link")
    assert plan.method == "link"
    assert plan.staged is True
    assert "link" in plan.reason


def test_a_symlink_is_planned_by_its_own_device_not_its_targets(tmp_path, there):
    """The link lives beside the destination; only the file it points at lives elsewhere."""
    payload = there / "payload.bin"
    payload.write_bytes(b"x")
    link = tmp_path / "link"
    os.symlink(payload, link)
    assert safemove.choose(link, tmp_path / "moved").method == "rename"
The harness: five repeats, median, min-max probelib.py
"""The harness every probe in this tree uses: five repeats, one JSON record per arm.

A probe never prints a number for the page. It writes ``results/NN_name.json`` and the page
reads the file, so a figure that was not recorded cannot be quoted. Each arm keeps every run,
the median with its min-max range, and whether all runs agreed, because the runbook's claim is
about what this host does every time, not once.
"""
from __future__ import annotations

import json
import os
import pathlib
import statistics
import time

HERE = pathlib.Path(__file__).resolve().parent
WORK = HERE.parent
RESULTS = WORK / "results"
SCRATCH = pathlib.Path("/workspace/work/post40/scratch")
TMP = pathlib.Path("/tmp/p40")
REPEATS = 5


def summarize(values: list) -> dict:
    """median with min-max, the shape every table cell in the page uses."""
    numbers = [value for value in values if isinstance(value, (int, float))]
    if not numbers:
        return {"median": 0, "min": 0, "max": 0}
    return {"median": statistics.median(numbers), "min": min(numbers), "max": max(numbers)}


def arm(label: str, run_once, repeats: int = REPEATS) -> dict:
    """Run one condition ``repeats`` times and keep everything it returned."""
    runs: list[dict] = []
    for _ in range(repeats):
        runs.append(run_once())
    keys = [key for key in runs[0] if isinstance(runs[0][key], (int, float))
            and not isinstance(runs[0][key], bool)]
    summary = {key: summarize([run[key] for run in runs]) for key in keys}
    identical = all({k: v for k, v in run.items()} == {k: v for k, v in runs[0].items()}
                    for run in runs[1:])
    return {"label": label, "runs": runs, "summary": summary, "identical": identical}


def errno_of(exc: OSError) -> dict:
    return {"errno": exc.errno or 0, "name": errno_name(exc.errno), "message": exc.strerror}


def errno_name(number: int | None) -> str:
    import errno as errno_module
    if not number:
        return "OK"
    for name in dir(errno_module):
        if name.startswith("E") and getattr(errno_module, name) == number:
            return name
    return f"errno {number}"


def try_call(function):
    """Return (result, error-dict) without raising, so an arm can carry a failure."""
    try:
        return function(), {"errno": 0, "name": "OK", "message": ""}
    except OSError as exc:
        return None, errno_of(exc)


def allocated(path) -> int:
    """Bytes the filesystem actually holds for a path, as st_blocks counts them."""
    return os.stat(path).st_blocks * 512


def fresh(*parts: str) -> pathlib.Path:
    """An empty directory under the tree's scratch space."""
    path = SCRATCH.joinpath(*parts)
    if path.exists():
        remove_tree(path)
    path.mkdir(parents=True)
    return path


def fresh_tmp(*parts: str) -> pathlib.Path:
    path = TMP.joinpath(*parts)
    if path.exists():
        remove_tree(path)
    path.mkdir(parents=True)
    return path


def remove_tree(path) -> None:
    """Delete a tree that may contain read-only directories made by a probe."""
    path = pathlib.Path(path)
    if not path.exists():
        return
    for root, directories, files in os.walk(path):
        for name in directories:
            os.chmod(os.path.join(root, name), 0o700)
        for name in files:
            try:
                os.unlink(os.path.join(root, name))
            except OSError:
                pass
    for root, directories, _ in os.walk(path, topdown=False):
        for name in directories:
            try:
                os.rmdir(os.path.join(root, name))
            except OSError:
                pass
    try:
        path.rmdir()
    except OSError:
        pass


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


def sparse(path, size: int, at: int = 0, payload: bytes = b"data") -> pathlib.Path:
    """A file of ``size`` bytes whose only real data sits at offset ``at``."""
    path = pathlib.Path(path)
    with open(path, "wb") as handle:
        handle.truncate(size)
        handle.seek(at)
        handle.write(payload)
    return path


def ms(start: float) -> float:
    return (time.perf_counter() - start) * 1000


def emit(name: str, payload: dict) -> None:
    RESULTS.mkdir(parents=True, exist_ok=True)
    target = RESULTS / f"{name}.json"
    target.write_text(json.dumps(payload, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
    print("wrote", target, "arms:", len(payload.get("arms", [])))


def record(arms: list[dict], notes: dict | None = None) -> dict:
    return {"repeats": REPEATS, "arms": arms, "notes": notes or {}}
The plan for three paths show_plan.py
#!/usr/bin/env python3
"""Print the plan for three moves without moving anything.

Run it on the host that raised EXDEV: the first line is the pair of devices, and the three
plans show where the fallback is chosen and where the destination is still one rename away.
"""
from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "module"))

import safemove  # noqa: E402

CASES = [
    ("same directory", "/workspace/work/post40/scratch/plan/src.bin",
     "/workspace/work/post40/scratch/plan/dst.bin"),
    ("across devices", "/workspace/work/post40/scratch/plan/src.bin", "/tmp/p40/plan/dst.bin"),
    ("across devices, no atomic name", "/workspace/work/post40/scratch/plan/src.bin",
     "/tmp/p40/plan/dst.bin"),
]


def main() -> None:
    source = CASES[0][1]
    os.makedirs(os.path.dirname(source), exist_ok=True)
    with open(source, "wb") as handle:
        handle.write(b"plan")
    print("source device", safemove.describe(safemove.device_of(source)))
    print("target device", safemove.describe(safemove.device_of("/tmp/p40/plan")))
    for label, src, dst in CASES:
        plan = safemove.choose(src, dst, must_be_atomic="no atomic" not in label)
        print(f"{label:32s} method={plan.method:7s} staged={plan.staged!s:5s} "
              f"atomic={plan.atomic_replace!s:5s} {plan.reason}")


if __name__ == "__main__":
    main()

Related runbooks: ENOSPC errno 28: full blocks, full inodes, and deleted files still open – the refusal a deploy log reports as a permission problem, and the filesystem family this page belongs to; EACCES errno 13: the bit, the directory, and the chmod that ends it – the same nine bits, read from the other side.


Keep reading

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