torch.save returning and your checkpoint surviving a crash, and between read() and the bytes arriving: devices, the VFS, the page cache, writeback, fsync, journaling, direct I/O, network file systems and checkpoint files. Measured on a Linux 5.10 VM, kernel source quoted with line numbers. A child page of Topic: operating-systems. Data as of October 2026. Reading: 43 min, plus 19 in closed details.Returned is not durable. write() and torch.save return once the bytes are in kernel memory, the page cache; the kernel moves them to the device later, in its own order and on its own schedule. What a crash can leave is decided only by fsync (of the file, and of its directory) and rename; what a read costs is decided by whether the page cache and readahead can serve it.
write() returns at the page cache: 1.4 us. The 4 KiB is copied into a cached page, which is marked dirty. The device has received nothing.sync_file_range returns when the device acknowledges: 161 us. The page went through the block layer to the drive, which acknowledges from its volatile cache. No metadata, no cache flush.fdatasync pushes the data to stable media: 393 us. A cache flush gets it past the device cache. An overwrite changes neither the size nor the block map, so there is no journal commit; the new modification time stays in memory.fsync also commits the metadata: 1,305 us. The inode's change (the new time) goes through a journal commit as well, a second ordered write and flush (section 5).write and sync_file_range are lost although both calls returned; fdatasync keeps the data and loses only the time stamp; fsync keeps everything.Fig. 1: the layers your bytes cross, top to bottom (the page cache is sections 3 and 4, the block layer and the device cache section 1, the media section 5); orange is the data, purple the file's metadata change. Medians of 1,000 overwrites of one 4 KiB record on ext4 measured; fsync needs a journal commit, fdatasync on an overwrite does not (section 5).
| Call | When it returns, what is guaranteed | Cost here measured |
|---|---|---|
write() | the bytes are in the page cache; other processes can read them; nothing is on the device | 1.4 us |
fsync(fd) | the file's data and its metadata (size, block map, times) are on stable storage, device cache flushed | 1,305 us |
fdatasync(fd) | the data, plus only the metadata needed to read it back (size, block map); not the times | 393 us |
sync_file_range() | the pages were sent to the device; no metadata, no device cache flush: not durable | 161 us |
rename(tmp, final) | atomic for every reader now; durable only after the next journal commit or an fsync of the directory | part of the protocol (section 6) |
fsync(dir_fd) | the directory's entries (names created, renamed, removed) are durable | 2.3 ms (after a rename) |
Medians of 1,000 overwrites of one 4 KiB record of a preallocated file on ext4 (section 5 has appends and the 99th percentiles); the directory fsync is from the 256 MiB checkpoint runs of section 10.
You need: file descriptors and system calls (Processes and the system-call API, section 7) and the page cache as memory that is reclaimed and counted against containers (Virtual memory). The root Topic: operating-systems section 7 gives the intuition (returned is not durable, and the four-step safe checkpoint); this page is the mechanism, measured.
torch.save returned (section 4).ckpt.pt.tmp, fsync it, rename it over ckpt.pt, fsync the directory; and never overwrite the last good checkpoint in place. It cost 365 ms against 263 ms for the plain save (section 6)..metadata before renaming the new one in, and never fsyncs the directory: save each step to a new directory (section 10).fsync fails, the data is gone: the kernel may already have dropped the dirty pages. Rewrite the checkpoint from memory; never retry the fsync and carry on (section 5).Docker Desktop's Linux VM on an Apple M1 laptop (Linux 5.10.104-linuxkit, arm64, 5 CPUs, about 10 GB), October 2026, image kb-os-lab:1 (the root's lab image: fio 3.33, strace 6.1, e2fsprogs 1.47, PyTorch 2.14.1 CPU). Files were written to /data, an anonymous Docker volume: a directory on the VM's ext4 disk (data=ordered, commit=5, delayed allocation), with no overlay file system in between. Containers were not privileged. The disk is virtual: a virtio block device backed by a file on the laptop's SSD, which macOS caches, so device reads and flushes here are faster than on a real NVMe drive and cold reads are inflated; the ratios between methods carry over, the absolute numbers do not. Things that need privileges, a real crash, NVMe hardware, a network file system or a GPU are taught from primary sources and tagged not run here. Labels: measured ran here; source read from kernel source or documentation. Kernel source is quoted at v5.10 with line numbers. Scripts and raw outputs: src/exp/ and src/raw/ in the repository.
| OSTEP chapter | Here | What this page adds |
|---|---|---|
| 36 I/O Devices; 37 Hard Disk Drives; 44 Flash-based SSDs | 1 | NVMe queues and doorbells, blk-mq, schedulers, queue depth measured; device write caches, FLUSH and FUA |
| 39 Files and Directories | 2, 5, 6 | the VFS objects, fsync family semantics, rename and directory fsync |
| 40 File System Implementation; 41 Locality and FFS | 2, 3 | a real ext4 inode and extent tree, block groups, readahead's window measured |
| 42 Crash Consistency: FSCK and Journaling; 43 Log-structured File Systems | 6, 7 | jbd2, ext4's data modes, delayed allocation, application-level crash states; copy-on-write file systems in brief |
| 45 Data Integrity and Protection | 5 | fsync error reporting (errseq_t), fsyncgate |
| 49 Sun's Network File System | 9 | close-to-open in Linux's NFS client; object stores and FUSE mounts |
OSTEP is free at pages.cs.wisc.edu/~remzi/OSTEP. Read 39, 40 and 42 alongside sections 2, 5 to 7 here.
A storage device keeps data without power, but it is thousands of times slower than memory, works in blocks rather than bytes, and usually has its own volatile cache. Everything above it exists to hide those three facts; every durability bug forgets one of them.
A device serves many requests in parallel, so more in flight buys throughput until it saturates; after that, each extra request only waits longer. A DataLoader that reads one sample at a time from one thread runs at QD 1, the top bar. More workers, prefetching or asynchronous I/O move it down the chart.
fio, O_DIRECT (no page cache, section 8) on a 1 GiB file, 5 s per point. Queue depth (QD) is how many requests are in flight at once.
QD 1 to 64: throughput x5.1, mean latency x14.4. Little's law (requests in flight = throughput x latency) at QD 64: 64 / 1,152.6 us = 55,527 per second, against 54,723 measured (+1.5%). The virtual disk reports itself as rotational: 1, which it is not; read the shape, not the absolute numbers.
A file system describes an I/O as a bio (direction, starting sector, list of memory pages); bios that touch neighbouring sectors merge into a request. Since Linux 3.13 the block layer is blk-mq: each CPU puts requests in its own software queue, which feeds one of the device's hardware queues (kernel docs: blk-mq). On NVMe, the interface modern SSDs speak over PCIe, each hardware queue is a submission and completion queue pair in host memory: the driver writes a command and rings a doorbell register; the drive fetches it by DMA, does the work, posts a completion and raises an interrupt. The specification allows up to 65,535 I/O queue pairs of up to 65,536 entries each (NVM Express base specification).
This VM's disk as the kernel reports it: 5 CPUs, scheduler none, 5 hardware queues (one per CPU), up to 256 requests per queue, at most 1,280 KiB per request measured. The NVMe part is from the specification not run here (this disk is virtio).
Two erase blocks of four pages each illustrative; real blocks hold hundreds of pages. Mechanism and typical times from OSTEP ch. 44.
Flash is read and written in pages of a few KiB but erased only in much larger erase blocks, and a page cannot be rewritten before its block is erased. The flash translation layer (FTL) inside the drive therefore writes every update to a fresh page, remaps it, and garbage-collects old blocks in the background; the extra internal writes are write amplification. Typical times for SLC flash: read about 25 us, program (write) 200 to 300 us, erase 1.5 to 2 ms (OSTEP ch. 44).
The device's cache. Most drives acknowledge a write once it is in their internal DRAM. If power fails before it reaches flash or platter, the write is lost although the drive said "done". The kernel has two tools for this (kernel docs: writeback cache control): a cache flush (REQ_PREFLUSH: "flush the volatile cache before this I/O") and FUA, Force Unit Access (REQ_FUA: "this write completes only once it is on stable storage"). A file system's fsync ends with one of them: that, not the write, is the red line in the hero figure.
Hard disks. A spinning platter and a moving arm: a random read waits for the arm to move (seek) and the platter to turn (rotation), several milliseconds, so a few hundred random reads per second; sequential reads are fast because nothing moves. OSTEP ch. 37 works the numbers.
Plugging and schedulers. A thread may plug its queue while it submits a batch, so the batch is merged before it is sent. An optional I/O scheduler may reorder requests: none, mq-deadline (bounds how long a request waits), kyber (latency targets) or bfq (fair shares between processes). For fast NVMe drives none is the usual choice because reordering costs more than it saves.
TRIM. A discard (TRIM on SATA, Deallocate on NVMe) tells the drive which blocks a deleted file freed, so its garbage collector stops copying dead data. ext4 can send discards at every delete (mount option discard) or you run fstrim periodically. This VM mounts its disk nodiscard and runs a small service that calls /sbin/fstrim /var/lib/docker after deletes (seen in the VM's process list with docker run --pid host ... ps) measured.
This disk reports a write-back cache and no FUA support, so the kernel emulates FUA with a write followed by a full flush. A drive that wrongly reports write through, or firmware that ignores flushes, silently breaks every guarantee on this page; only power-cut tests can find that. What the kernel believes about this disk:
lsblk -o NAME,SIZE,ROTA,SCHED,MOUNTPOINT and cat /sys/block/nvme0n1/queue/{scheduler,nr_requests,max_sectors_kb,read_ahead_kb,write_cache}iostat -x 1: per device, r/s w/s (requests per second), rkB/s, r_await (average ms per read, queueing included), aqu-sz (average queue depth), %util (time with at least one request in flight; near 100% does not mean saturated on a device that serves many requests in parallel)cat /proc/diskstats: the raw counters behind iostat; in a cgroup v2 container, cat /sys/fs/cgroup/io.stat gives your container's own rbytes wbytes rios wios (used for every device count on this page)cat /sys/fs/cgroup/io.max: a bandwidth or IOPS limit; the root's Debug lab case "Slow storage: workers sleep in D state on page faults" (Debug lab) throttles reads to 1 MiB/s this wayReading the counters. You seldom tune the block layer, but you read it. "The disk is at 100% util" on iostat while r/s keeps rising with more workers means the device still has room; a large r_await with a small aqu-sz means each request is slow (a remote or throttled device), not that you are queueing.
Programs want named files with sizes, owners and times, and they want the same open, read, write to work on ext4, XFS, tmpfs, NFS or /proc. The VFS (virtual file system switch) gives every file system one set of objects and calls to implement (kernel docs: VFS). Below, mke2fs built a 64 MiB ext4 file system inside an ordinary file and debugfs (which reads the image directly, so no mount and no privileges) copied in a 3,000,000-byte "checkpoint" and a small file with two names measured. The figure is that real image seen through the kernel's objects.
Four objects. The superblock, one per mounted file system: its type, block size, and the operations on its inodes (struct super_block, fs.h line 1416). The inode, one per file whatever its names: type, permissions, owner, size, times, link count, where its data lives, and an address_space (line 451) holding that file's pages in the page cache. The dentry, one per name in a path, cached: "the name ckpt.pt in directory X is inode 13"; a negative dentry caches "this name does not exist". The file, one per open(): offset, open flags, pointers to dentry and inode; file descriptors index a per-process table of these (Processes and the system-call API section 7 draws the three tables).
Names are not files. A directory is itself a file whose content is a table of (name, inode number). A hard link is a second entry for the same inode (hello.txt and hardlink.txt are both inode 14, Links: 2); a symbolic link is a small file containing a path. The inode is freed when its link count is zero and no process has it open, so deleting a checkpoint that a running process still holds open frees no space until it closes; lsof +L1 lists such deleted-but-open files.
Extents. Inode 13's data is one extent: logical blocks 0 to 732 stored in physical blocks 2066 to 2798, contiguous. That is 733 blocks of 4,096 bytes, the fewest that hold 3,000,000 bytes (3,000,000 / 4,096 = 732.4), and Blockcount: 5864 counts the same space in 512-byte sectors (733 x 8). ext2 and ext3 listed every block number; an extent says "start, length" once, so a large file costs ext4 almost no metadata. ext4 also groups inodes and their data into block groups so a file's inode sits near its data (OSTEP ch. 41 credits the idea to FFS). The journal (section 7) is itself an inode, 4 MiB here.
Inode numbers, link counts and the extent are copied from the debugfs output (in the closed block below). struct file, struct dentry and struct inode are the kernel's objects (include/linux/fs.h lines 916 and 610, include/linux/dcache.h line 89, v5.10).
Every small file pays for a path lookup, an inode, a directory entry, a share of a journal transaction and its own block allocation; every cold read of one is at least one device request that readahead (section 3) cannot merge with its neighbours. On a network file system each open and stat is also a round trip to a server (section 9), so the gap grows from tens to thousands of times.
Orange: 10,240 files of 4 KiB; blue: one file of 40 MiB, on ext4 measured. Creating the small files took 7.2x as long, reading them warm 10.6x, cold 56x. Cold means each file's pages were dropped with posix_fadvise(DONTNEED) after an fsync.
Read it from the bottom up: the directory out is a table (ckpt.pt is inode 13; hello.txt and hardlink.txt are inode 14), inode 13's EXTENTS line is the extent, and the journal is an inode of its own.
Path lookup. open("/data/out/ckpt.pt") walks the path one component at a time, looking each name up in the dentry cache and asking the file system only on a miss (fs/namei.c). The root's Syscall tracer shows import torch making hundreds of newfstatat calls that fail with ENOENT: Python searching its path. Each failure leaves a negative dentry, so the second import is cheap.
stat file (inode number, links, size, blocks, times); ls -li (inode numbers)df -h (space) and df -i (inodes: a file system can run out of inodes with free space left, the small-files failure)filefrag -v file (extents of a file on a mounted ext4 or XFS); debugfs -R "stat <13>" imagelsof +L1 (deleted files still open, still using space)A device request has a large fixed cost; programs often read 4 KiB at a time, and often read the same file again (every epoch). Two answers: keep what was read in memory, the page cache, and when a program reads sequentially, fetch the next pages before it asks, readahead. How the page cache competes for memory and is reclaimed is Virtual memory's; this section is how data gets into it.
measured A cold 8 MiB file read 4 KiB at a time; after every read() the script read the container's io.stat, so each device request and its size is visible. Predict first: with a 128 KiB (32-page) maximum window, how many device requests do 512 sequential 4 KiB reads cost? Then watch Fig. 2.
posix_fadvise(DONTNEED): nothing is cached. The maximum window is 32 pages (128 KiB).get_init_ra_size(1) = 4: pages 0 to 3 in one request, the program waits for it. Page 1 carries the readahead mark.POSIX_FADV_SEQUENTIAL the window doubles to 64 pages and the same reads cost 13 requests. With readahead off, or at random offsets, every read is its own request: 64 reads, 64 requests.Fig. 2: sequential reads cost few requests because each window is fetched one window ahead. Page 0 is front left, 16 pages to a row. Blue tiles are pages in the page cache, orange the windows fetched in the current step (streaming up from the device in front), dashed outlines pages not yet read; the dark glow is the page the latest read() asked for. Measured: 512 sequential reads cost 20 requests (572 pages) by default and 13 requests (636 pages) with POSIX_FADV_SEQUENTIAL; readahead off and random offsets cost one request per read. Defaults reproduce the measurement independently: the two source rules below predict every request of both sequential runs. Times are this VM's: the "device" is macOS's cache of the disk file.
With readahead on, the window grew 4, 8, 16, 32 pages and then stayed at the 32-page maximum, each requested one window ahead of the reader, so most reads never waited for the device. With readahead off the same reads cost one request each. Random reads get no readahead: the kernel only predicts sequential access, and the measured random case fetched exactly one page per read.
The rule, from mm/readahead.c source (v5.10). First window, get_init_ra_size (line 311): round the request up to a power of two, then x4 if it is at most 1/32 of the maximum, x2 if at most 1/4, else the maximum. Each later window, get_next_ra_size (line 329): x4 while under 1/16 of the maximum, then x2, capped at the maximum. The maximum is read_ahead_kb (128 KiB here, 32 pages); posix_fadvise(POSIX_FADV_SEQUENTIAL) doubles it for that open file (mm/fadvise.c line 92) and POSIX_FADV_RANDOM turns readahead off (line 88).
The root's Debug lab case "The first epoch is slower than the rest: cold and warm page cache" measured a 512 MiB shard at 858 MiB/s cold against 3,831 MiB/s warm, and readahead off at 16,384 requests for 64 MiB against 516 with it on. On this VM "cold" still means "in macOS's cache of the virtual disk file": on a real local NVMe drive the cold number would be lower, and on a network file system much lower. Here the cold small-files read of section 2 was 56 times slower than reading the same 40 MiB as one file.
source read(fd, buf, 4096) reaches ext4's ext4_file_read_iter, which calls the generic generic_file_buffered_read (mm/filemap.c line 2185, v5.10). For each page of the request it looks the page up in the file's address_space. A hit is a memory copy. A miss calls page_cache_sync_readahead (line 2235), which decides how much to fetch, allocates the pages, builds bios and submits them; the reader then sleeps until its page is unlocked. That sleep is the D state with wait channel wait_on_page_bit_common that the root's Debug lab case "Slow storage: workers sleep in D state on page faults" caught on a throttled disk. A page that carries the PG_readahead mark triggers page_cache_async_readahead (line 2247): the next window is fetched while the program is still reading the current one.
cat /sys/block/DEV/queue/read_ahead_kb, change with blockdev --setra SECTORS /dev/DEV (root; network file systems have their own, e.g. NFS's read_ahead_kb under /sys/class/bdi/).posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL | RANDOM | WILLNEED | DONTNEED), from Python os.posix_fadvise (posix_fadvise(2)); WILLNEED starts reading a range now; DONTNEED drops a file's clean pages (how this page made files cold without root).madvise(MADV_SEQUENTIAL | MADV_RANDOM | MADV_WILLNEED); Virtual memory measured random rows through mmap fetching 13x more than they used, and MADV_RANDOM cutting it to 3.4x.fincore file (util-linux); whole system: free -m (buff/cache), grep -E "^(Cached|Dirty|Writeback):" /proc/meminfo; your container: grep -E "^file " /sys/fs/cgroup/memory.stat.If every write() waited for the device, a checkpoint written in 4 KiB pieces would pay a device round trip for each. So write() copies the bytes into the cached page, marks it dirty (changed in memory, not yet on the device) and returns. Per-device flusher threads (kernel workers named kworker/u*:*-flush-*) write dirty pages back for one of three reasons (vm sysctl docs; mm/page-writeback.c lines 74 to 109):
dirty_writeback_centisecs (500, so 5 s) the flusher wakes and writes data that has been dirty longer than dirty_expire_centisecs (3000, so 30 s).dirty_background_ratio (10%) of dirtyable memory (free memory plus file pages that could be reclaimed, not total RAM: global_dirtyable_memory, line 362), the flusher writes everything, whatever its age.dirty_ratio (20%) the writing process itself is paused in balance_dirty_pages (line 1555, the pause at line 1795) so it cannot dirty memory faster than the device drains it. This is dirty throttling: write() becomes slow without any error.With cgroup v2 each memory cgroup is also its own writeback domain, with thresholds scaled to its memory, so a container with a 1.5 GB limit is throttled long before the machine is (cgroup v2 docs, Writeback). measured Each run in Fig. 3 and the chart below it wrote a file into a fresh container (limit 1,500 MB) and sampled its memory.stat (dirty and under-writeback page cache) and io.stat (bytes the device received) every 100 ms.
wb_over_bg_thresh, not traced; see the question below).dirty_expire_centisecs, 30 s, found at a 5-second wake-up) would send it. The other three primed runs left after 7.7, 18.0 and 0.4 s: when is not a promise.Fig. 3: each lane's 16 tiles are sixteenths of what that run wrote: orange dirty in the page cache, blue received by the device (memory.stat and io.stat every 100 ms) measured. Time is seconds after the first sample that saw the write.
wb_over_bg_thresh (mm/page-writeback.c line 1960) also compares this writeback domain's dirty pages with its share of the background threshold, a share proportional to how much it recently wrote back. A brand-new container has almost no share, so even 16 MiB counts as "over its threshold" and is written in the background. After the container had just written and synced 1 GiB (the "primed" runs), it had a share, and the same 16 MiB waited between 0.4 and 30 s as that share decayed. We could not trace the flusher here (that needs privileges), so treat the explanation as the likely one, not a proven one. The lesson does not depend on it: when dirty data reaches the device is not a promise you can use. Only fsync is.torch.save returned. Killing the process does not lose it (the dirty pages belong to the kernel); only a kernel crash, a power loss or a VM or node being killed does.balance_dirty_pages while the container's dirty data hovered at the domain's limits. A loop that saves a large checkpoint synchronously stalls the same way; a background writer thread moves the stall off the training thread but does not remove it.source write() on ext4 runs generic_perform_write (mm/filemap.c line 3288, v5.10): for each page, ext4_da_write_begin (fs/ext4/inode.c line 2934) finds or creates the page in the cache and reserves space without choosing disk blocks (delayed allocation, section 7), the bytes are copied in, the page is marked dirty, and balance_dirty_pages_ratelimited (line 3365) checks whether this writer has dirtied too much. Then write() returns. Nothing has touched the device.
On this VM the kernel computed a background threshold of MiB and a hard threshold of MiB VM-wide (/proc/vmstat) measured.
grep -E "^(Dirty|Writeback):" /proc/meminfo (machine), grep -E "file_(dirty|writeback)" /sys/fs/cgroup/memory.stat (container), cat /proc/PID/wchan (a writer in balance_dirty_pages is being throttled), grep -E "nr_dirty(_background)?_threshold" /proc/vmstat.vm.dirty_background_bytes and vm.dirty_bytes set absolute limits instead of ratios, which is saner on machines with hundreds of GB of RAM where 20% is far more than a device can drain in seconds.fsync what must survive (section 5); for a long streaming write, start writeback early with sync_file_range(SYNC_FILE_RANGE_WRITE) on each finished chunk and fdatasync once at the end, which keeps dirty data and the final fsync small.This also explains the root's Debug lab "fsync" case, where 256 MiB was clean 5 s later: a fresh container's writeback domain is over its share at once.
A checkpoint, a database log or a "this checkpoint is complete" marker must survive a crash, so the program needs a call that returns only when the data is on stable storage, and it must know exactly what that call covers. fsync(fd) covers the file's data and all its metadata, then a device cache flush ("This includes writing through or flushing a disk cache if present", fsync(2)); not the directory entry that names the file. fdatasync(fd) covers the data plus only the metadata "needed in order to allow a subsequent data retrieval to be correctly handled": size and block map yes, modification time no. sync_file_range only starts or waits for writeback of a byte range; the kernel's own comment: "there are no guarantees here that the data will be available on disk after a crash" (fs/sync.c lines 351 to 355, v5.10).
source ext4_sync_file (fs/ext4/fsync.c line 129, v5.10) does three things in order: write the file's dirty pages and wait; wait for the journal transaction that last changed what this call covers; flush the device cache. Fig. 4 follows one 4 KiB overwrite through each call; pick a call, then compare the measured costs.
file_write_and_wait_range (called from ext4_sync_file): the dirty page becomes a bio and goes through blk-mq to the driver.write_cache: write back). A power cut now still loses it.ext4_fsync_journal (line 104): this inode last changed in the running transaction (i_sync_tid), so jbd2 must commit it: journal blocks, then the commit block.REQ_PREFLUSH | REQ_FUA (fs/jbd2/commit.c line 157): the device flushes its cache, so the data page and the journal reach stable media.i_datasync_tid (line 109): an overwrite changed nothing data retrieval needs (size and block map unchanged), and that transaction committed long ago, so there is nothing to wait for. The mtime change stays in the running transaction.needs_barrier is set, so ext4_sync_file sends a cache flush (line 177): the data page reaches stable media.SYNC_FILE_RANGE_WRITE starts writeback of the range.WAIT_BEFORE | WRITE | WAIT_AFTER waited for writeback only: no journal commit, no cache flush. The kernel's own comment says there are "no guarantees here that the data will be available on disk after a crash" (fs/sync.c line 355).Fig. 4: fsync pays for a journal commit that fdatasync skips on an overwrite; sync_file_range never reaches the media. Orange is the data page, purple the inode change; only what reaches the bottom block survives a power cut. Order from fs/ext4/fsync.c (v5.10), whole-call times measured.
fallocate) and overwriting it is how databases make fdatasync cheap.1,000 records each; median and 99th percentile in microseconds. "Append" grows the file (size changes every time); "overwrite" rewrites a preallocated, already-synced file (only data and times change). tmpfs keeps files only in memory, so it has nothing to flush.
Log scale. On an overwrite, fdatasync cost 3.3x less than fsync (393 against 1,305 us); on an append only 1.3x less (997 against 1,265 us). sync_file_range is cheaper because it flushes nothing and commits nothing: it is not a durability call. On tmpfs every call costs about a microsecond.
Two descriptors on one file: A (the checkpoint writer) and B (another process, say a log shipper). Sequence from the LWN article and lib/errseq.c; simplified to one page.
A device error during writeback is reported to the next fsync. Before Linux 4.13 the error could reach one caller only and the failed pages were marked clean, so a second fsync returned success with the data lost: the PostgreSQL "fsyncgate" story in the root's section 7. Since 4.13 the kernel records writeback errors in an errseq_t, a counter plus error code that "allow[s] any number of 'subscribers' to tell whether it has changed since a previous point where it was sampled" (lib/errseq.c lines 8 to 10, v5.10), so every file descriptor open at the time sees the error once (LWN, Improved block-layer error handling). The pages may still be gone.
AS_EIO) is set on the file's mapping.errseq_t value it last saw: A and B both sampled counter 0 at open.The rule: a failed fsync means that file's recent writes are lost; rewrite it from memory, or abort. With delayed allocation, running out of space can also surface only at fsync or close rather than at write, so check both: Python's f.close() raises OSError if the underlying close fails.
| Call | Covers | Source |
|---|---|---|
open(..., O_DSYNC) / O_SYNC | every write() behaves as if followed by fdatasync / fsync | open(2) |
syncfs(fd), sync() | everything dirty on one file system, or on all of them; heavy, and in a shared machine you wait for other people's data too | sync(2) |
source The journal wait is ext4_fsync_journal (line 104): for fdatasync it waits only for the transaction that last changed what data retrieval needs (i_datasync_tid against i_sync_tid, line 109), and if that already committed there is nothing to wait for. It goes through ext4_fc_commit (line 115), a full journal commit unless the newer "fast commit" feature was enabled when the file system was created (a feature flag that needs privileges to read on this VM). The flush is blkdev_issue_flush (line 177).
strace -f -e trace=fsync,fdatasync,sync_file_range,rename,renameat -p PID, or strace -c for totals.fsync makes data durable, not an update atomic: a crash in the middle of rewriting ckpt.pt leaves a file that is partly new, partly old or partly missing, and the previous good checkpoint is already destroyed. The fix is to build the new version under another name and switch in one step. rename: "If newpath already exists, it will be atomically replaced, so that there is no point at which another process attempting to access newpath will find it missing" (rename(2)). Atomic for readers now; durable only once the directory change is committed, which is what an fsync of the directory forces: "Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed" (fsync(2)).
ckpt.pt to inode A, on disk and in its cached copy.ckpt.pt.tmp. A new inode B under a new name, only in memory: its 256 MiB is dirty in the page cache. ckpt.pt is untouched.fsync the temporary file: 111 ms. B's data and inode reach the disk. A crash now still finds A under ckpt.pt; B may be left without a name, which is litter, not damage.rename over ckpt.pt. In memory the name now points at B, at once for every reader. The directory on disk still says A: a crash now brings back the old checkpoint, which is still a good one.fsync the directory: 2.3 ms. The new entry reaches the disk and A's space is freed. Old or new at every point, and now new for good. The whole protocol took 365 ms against 263 ms for the plain save.Fig. 5: the safe save of the running job's checkpoint, from its trace (below); POSIX guarantees only, ext4 adds ordering (the crash lab). Times are the 256 MiB runs of section 10 measured.
measured The running job's checkpoint written two ways, under strace -f -y, keeping only calls on the checkpoint directory (shown as DIR), with runs of writes folded into one line:
The plain save opens the existing ckpt.pt with O_TRUNC: the old checkpoint is thrown away at the first system call, and the new one exists only in the page cache until writeback. The safe version never touches ckpt.pt until a complete, durable new file exists; renameat is the single switch; the directory fsync makes the switch durable.
The crash lab runs every protocol on this page through a crash at each point. Pick a protocol, then step the crash point: the left pane is what every file system promises, the right what this VM's ext4 adds. Call sequences from the real traces above and in section 10; the last protocol is our fix (DCP into a new directory plus the two directory fsyncs DCP does not make). A model with the rules in the closed block below, not a crash test: no power was cut. ALICE (Pillai et al., OSDI 2014) checks real applications the same way.
Across all protocols: plain torch.save loses the checkpoint at 3 of 4 crash points; fsync in place at 2 of 5; tmp then rename without fsync at 1 of 5 under POSIX only (0 on this ext4); tmp, fsync, rename, fsync(dir) at 0 of 7; DCP saving into the same directory at 10 of 11; DCP into a new step directory plus parent fsync at 0 of 13.
POSIX only. Durable: a file's data and its own metadata after an fsync of that file returns (fsync(2)); a directory's entries (create, rename, unlink, mkdir) after an fsync of that directory. Everything else may or may not have reached the disk, independently (each name change is atomic in itself, rename(2)). File data not yet synced may be absent, cut short, fully there, or (for a file rewritten in place without truncation persisting) a mix of old and new.
ext4 as configured here. Name and size changes go through one journal and reach the disk in order, so after a crash some prefix of them is there. An fsync of anything commits the whole running transaction, so every earlier name change is durable after it (fs/ext4/fsync.c, ext4_fsync_journal). File data is written by writeback or fsync; with delayed allocation, a file whose data was not yet written has size 0 or a shorter size after a crash, never garbage (data=ordered). auto_da_alloc: renaming over an existing file, or closing a file that was truncated, starts writing its data, and the commit that records a later name change waits for it (fs/ext4/namei.c lines 3782 to 3783, fs/ext4/file.c lines 140 to 143, ext4 docs).
Simplifications: the crash happens at some moment after the listed step and before the next; device caches honour flushes; one writer; a DCP checkpoint "loads" if its .metadata and shard come from the same save.
ckpt.pt.tmp, or a new step_000200/ directory). Never open the last good checkpoint for writing.flush() Python's buffer, then os.fsync(f.fileno()) every file you wrote.os.replace(tmp, final) (a rename), or for a directory of shards, write a small "complete" marker last.os.fsync a descriptor of the directory that holds the name you changed (open it O_RDONLY).torch.save(state, "ckpt.pt.tmp"); os.replace("ckpt.pt.tmp", "ckpt.pt") with no fsync at all, on ext4 with default options. The machine loses power 2 seconds later. What can the restarted job find at ckpt.pt?commit=5), so after 2 s it may not be on disk yet: the old checkpoint is still there. If it did commit, auto_da_alloc made ext4 push the new data out first, so the new file is complete. On XFS, btrfs or a network file system, or with noauto_da_alloc, the empty-file outcome is back. The crash lab above shows both models.Pillai and colleagues recorded the system calls of eleven widely used systems ("databases, key-value stores, version control systems, distributed systems, and virtualization software") and computed every state a crash could leave under the guarantees file systems actually give. They found "a total of 60 vulnerabilities, many of which lead to severe consequences" (All File Systems Are Not Created Equal, OSDI 2014). The answer depends on the file system and its mount options: code that is safe on one can corrupt on another.
source ext4 carries a heuristic for the most common unsafe pattern, born from the 2009 zero-length-files story in the root's section 7: with the default auto_da_alloc mount option (this VM has it), renaming a file over an existing one makes ext4 allocate and start writing the source file's delayed data first (fs/ext4/namei.c lines 3782 to 3783, ext4_alloc_da_blocks), and closing a file that had been truncated to zero does the same (fs/ext4/file.c lines 140 to 143). With data=ordered, the commit that records the rename then waits for that data. So on ext4, write-then-rename without fsync usually ends with old or new rather than an empty file; but the rename is still not durable until the next commit, the heuristic exists only on ext4, and the ext4 documentation introduces it as help for "broken applications" that replace files without fsync(), providing "roughly the same level of guarantees as ext3" (ext4 docs, auto_da_alloc). Write the fsyncs.
renameat2 flags. RENAME_NOREPLACE fails instead of overwriting (two writers cannot clobber each other); RENAME_EXCHANGE swaps two names atomically (rename(2)). Rename is atomic only within one file system, so the temporary file goes in the same directory.
O_TMPFILE + linkat. Create a file with no name at all, write and fsync it, then give it a name with linkat: it can never be seen half-written, and a crash leaves no .tmp litter (open(2), O_TMPFILE). linkat will not replace an existing name, so it suits "write once" files such as shards.
Creating, growing or renaming a file changes several blocks (the inode, a free-block bitmap, the directory). A crash between them leaves the file system's own structures inconsistent. ext4 hands the fix to a generic journaling layer, jbd2: every operation that changes metadata opens a handle on the current running transaction, many operations share one transaction, and the transaction is committed (its blocks written to the journal, then a commit block) when it is 5 seconds old (JBD2_DEFAULT_MAX_COMMIT_AGE, include/linux/jbd2.h line 48, v5.10; the commit=5 mount option), when the journal fills, or when someone's fsync needs it. After a crash, mount replays committed transactions and discards incomplete ones: seconds, not the full scan of fsck. The root's OS simulators tab crashes such an update at every block write; Fig. 6 is the order ext4 really uses; pick a data mode.
Fig. 6: one commit, step by step: in ordered mode the data reaches home before the metadata that points to it is committed. One transaction holding a new file's inode, its directory entry and a bitmap block (orange), plus the file's 4 data blocks (blue; grey with a red edge where a block still holds stale contents). Order from fs/jbd2/commit.c and the ext4 documentation; "Crash now" is what replay finds.
The journal always covers metadata; the data= mount option decides what happens to file data:
| Mode | File data | After a crash (ext4 docs) |
|---|---|---|
data=journal | written to the journal too, then in place | "bringing both data and metadata into a consistent state"; slowest for most workloads (every byte written twice) |
data=ordered (default, this VM) | "All data are forced directly out to the main file system prior to its metadata being committed to the journal" | a file's metadata never points at blocks with stale contents; recently written data may be missing, never garbage |
data=writeback | "Data ordering is not preserved" | "incorrect data [can] appear in files which were written shortly before the crash"; the same level as "XFS and JFS in its default mode - metadata journaling" |
Delayed allocation (delalloc, on here) is why ordered mode does not make your file complete. ext4 chooses disk blocks at writeback, not at write(), when it knows how big the file is, which gives large contiguous extents (the single extent of section 2). Until then there are no blocks to order, so the journal can commit a new file's name and size while its data is still only in memory: the zero-length files of 2009, and the reason for the auto_da_alloc heuristic of section 6.
Barriers. A commit block must not reach the media before the blocks it commits, so jbd2 writes it with a cache flush and FUA (REQ_PREFLUSH | REQ_FUA, fs/jbd2/commit.c line 157, v5.10; section 1) unless mounted barrier=0 (this VM: barrier, the default). Turning barriers off on a drive with a volatile cache trades crash safety for speed; never do it for a checkpoint volume.
When it bites in ML: through its defaults. A 5-second window in which renames and new names are not durable; ordered mode that keeps the file system sane but does not make your file complete; and different file systems on different clusters (ext4 locally, XFS on the big array, something else over the network) making "it worked on my machine" checkpoint code unsafe elsewhere.
measured This VM's journal since boot (/proc/fs/jbd2/vda1-8/info, readable from an unprivileged container; the disk is shared by every container on the VM):
Transactions here commit far more often than every 5 s (a transaction ran 158 ms on average) because 36,364 of the 36,654 commits were requested, by fsync calls from the containers sharing this disk; each commit logged about 11 journal blocks and took about 2.4 ms. Later the committed blocks are written to their real places (a checkpoint, in journaling's sense) and that journal space is reused.
XFS, common on large local arrays, journals metadata only, with a design ("delayed logging") that batches many changes into each log write (kernel docs: XFS delayed logging). Do not count on ext4's auto_da_alloc rename rule there or anywhere else: the fsync rules of section 6 are what every file system promises to honour. not run here (the kernel knows XFS, but mounting needs privileges)
Copy-on-write file systems (btrfs, ZFS) never overwrite a block in place: a change writes new blocks and new copies of every tree node above them, up to a new root, and the commit is the single write that switches to the new root. The file system is always consistent with no journal replay, and snapshots cost almost nothing (keep the old root). OSTEP ch. 43 develops the same idea as the log-structured file system. Durability of your file still needs fsync. not run here
findmnt -no OPTIONS /path or cat /proc/fs/ext4/DEV/options: data mode, commit interval, barrier, delalloc, auto_da_alloccat /proc/fs/jbd2/DEV-8/info: commits, average commit timedumpe2fs -h /dev/DEV (features, journal size), xfs_info /mountA database's write-ahead log is the same idea one level up, inside the database's own files: Storage engines and indexes owns it.
The page cache is a bargain for data you read twice and for small writes, but a training job also streams data it reads once (a dataset bigger than RAM) and writes data it will not read back (a checkpoint). Copying that through the cache costs a memory copy per byte, evicts useful pages, and creates the dirty throttling of section 4. Two tools: skip the cache, and keep many requests in flight from one thread.
O_DIRECT asks the kernel to move data by DMA straight between your buffer and the device (open(2), O_DIRECT). The price is alignment: the buffer address, the length and the file offset must be multiples of the device's logical block size (512 bytes here), or the call fails measured:
O_DIRECT is not durable. It skips the page cache, not the device's cache, and does not commit metadata such as a new file size. In the fio runs below, adding fdatasync after each direct 4 KiB write cut the rate from 12,706 to 6,270 writes per second.
Buffered I/O copies once by CPU into the page cache, and the device later moves it by DMA. O_DIRECT moves it by DMA between your (aligned) buffer and the device. GPUDirect Storage moves it between GPU memory and storage, with no bounce buffer through the CPU not run here. None of the three flushes the device's cache: durability still needs fdatasync.
When to use it. Checkpoint writers and data loaders that manage their own buffers use it to keep the page cache for what matters and make throughput predictable; GPUDirect Storage requires it. Not for small reads you will repeat (no caching, no readahead), nor from Python on unaligned bytes objects (use an aligned buffer, e.g. mmap.mmap(-1, n), which is page aligned).
The direct sequential numbers are far above any single NVMe drive's because macOS serves the VM's disk file from its own cache; read the relations (direct sequential at queue depth 8 beats buffered single-threaded writes; random 4 KiB costs the same either way when nothing is cached), not the absolute values.
Asynchronous I/O. A plain read blocks the thread, so one thread has one request in flight: queue depth 1 in section 1. libaio (io_submit, io_getevents) is truly asynchronous only with O_DIRECT. io_uring (Linux 5.1+) shares two ring buffers between program and kernel: the program writes submission entries and reads completion entries, often with no system call per I/O (io_uring(7)); Concurrency owns the ring design and the event loops built on it. Here fio's io_uring engine ran 51,050 reads per second at queue depth 16, against 48,455 with libaio measured, once a memory-lock limit was raised:
measured On this 5.10 kernel, fio's io_uring engine first failed with Cannot allocate memory: the rings are charged to RLIMIT_MEMLOCK unless the process has CAP_IPC_LOCK (fs/io_uring.c lines 7869, 9273 and 9335, v5.10), and the container's default limit is 64 KiB (the same limit the Virtual memory page met for pinned memory). Even root is short of it: on 5.10 that limit is counted per user ID, so every container running as UID 0 shares one 64 KiB budget across the whole VM, and the BPF programs runc attaches are charged to it too (Containers and isolation measures it). With docker run --ulimit memlock=-1:-1 it ran:
tmpfs has no device to DMA to, so on this kernel it refuses O_DIRECT at open. Linux 6.1 added STATX_DIOALIGN to statx to ask a file for its exact alignment rules (statx(2)) not run here.
On a cluster the dataset and the checkpoint directory usually live on a server, a parallel file system or an object store, and each keeps a different subset of the local guarantees above. Nothing in this section ran here (no network storage in the VM) not run here; it is taught from each system's own documentation. How those systems are built and sized (Lustre's servers and striping, object stores, staging, bandwidth) is Storage and data movement's; this section is the semantics a checkpoint writer depends on.
NFS: close-to-open. One server exports a file system; clients cache data and attributes. Linux's client gives close-to-open consistency: at open it revalidates with the server, and "when the application closes the file, the NFS client writes back any pending changes to the file so that the next opener can view the changes. This also gives the NFS client an opportunity to report write errors to the application via the return code from close(2)" (nfs(5)). fsync asks the server to commit the data to its own stable storage (the COMMIT procedure of RFC 1813).
COMPLETE marker file. A restarted job on another node sees the marker. Is every shard guaranteed to be readable there?Time runs down. Rank 7 writes a shard, rank 0 writes the marker after a barrier, and a restarted job on node B reads them. The ordering that matters is across ranks: the marker is written only after every rank has closed (or fsynced) its shard. Per nfs(5); the message names are NFSv3's.
Check the return value of close: on NFS that is where write errors appear. And many small files cost a network round trip each for open and stat.
Object stores and FUSE mounts have no rename and no fsync in the local sense, so "write then rename" becomes "upload under a new key, then write a small pointer or marker object last": a checkpoint is complete when its marker exists. Code that relies on os.replace, on appending, or on rewriting part of a file fails or behaves differently on such mounts; read each mount's semantics page before pointing a checkpoint writer at it.
| System | How it works | What changes for you |
|---|---|---|
| Lustre (and GPFS, WekaFS, ...) | Metadata servers hold names and directories; file data is striped over many object storage targets. How it is built, striped and sized is Storage and data movement's. | Big files spread over many targets are fast; metadata is the shared bottleneck, so millions of small files, or thousands of ranks calling stat at start-up, slow the whole cluster. |
| Object stores (S3, GCS, Azure Blob) | Objects are written whole (or in multipart uploads) and appear atomically when the upload completes; S3 has given "strong read-after-write consistency" for all applications since December 2020 (AWS, 2020-12). There is no rename and no fsync. Since August 2024 a PUT can carry If-None-Match to fail rather than overwrite an existing key (AWS, 2024-08). | New key, marker last. A conditional write keeps two jobs from overwriting each other's checkpoint. |
| FUSE mounts of object stores (Mountpoint for S3, gcsfuse, s3fs) | A user-space process implements the file system calls on top of the object API. Mountpoint, for example, writes "sequentially from a single client at a time", uploads asynchronously, and on general-purpose buckets "does not emulate operations like rename"; "if your application needs to guarantee that a new file has been uploaded to S3, it should call fsync on the file before closing it" (Mountpoint semantics). | No os.replace, no appends, no partial rewrites; fsync before close. |
| GPUDirect Storage | "enables a direct data path for direct memory access (DMA) transfers between GPU memory and storage, which avoids a bounce buffer through the CPU" (GDS overview). Programs use the cuFile API; its reference guide's examples open the file with O_DIRECT before registering it (cuFile API reference). | Skips the page cache and pinned host memory entirely (section 8's rules apply: alignment, and durability still needs a sync). Worth it when host memory bandwidth or CPU copies limit checkpoint or data loading speed on GPU servers with supported NVMe or network storage. |
The running example, scaled up. The root's job saves a 0.28 MB state. Here the same write paths save a 256 MiB state (), five times each on ext4, plus PyTorch's distributed checkpoint (DCP) in three settings and its asynchronous save. "Dirty after" is how much of the checkpoint was still only in memory when the call returned. measured
torch.save writes a zip archive: a pickle of the object structure plus one record per tensor storage. Given a path, it opens the file itself (O_WRONLY|O_CREAT|O_TRUNC in the trace of section 6), writes and closes: no fsync, and the old file's contents are discarded at open. Loading needs the zip's central directory, written last; a file cut short anywhere fails to load, the error the root's Debug lab case "Disk full mid-checkpoint: a cryptic error and a destroyed checkpoint" shows (failed finding central directory).
Medians of 5 runs (min and max in src/raw/ckpt_time.txt). fsync added 86 ms to a 263 ms save; the full safe protocol 102 ms, of which the directory fsync was 2.3 ms. Four writer threads made DCP faster than one. On this VM the device absorbs 256 MiB in about a tenth of a second; a device that writes 250 MB/s (an illustrative cloud-volume rate) would need 268 MB / 250 MB/s = about 1.1 s for the same fsync.
torch.distributed.checkpoint source PyTorch 2.14.1 (the version in this image, git 5c48869), torch/distributed/checkpoint/filesystem.py. Every rank writes its own files, named __{rank}_{n}.distcp, one per writer thread (thread_count); with sync_files=True (the default) each is flushed and fsynced before closing (lines 470 to 474). Then the coordinator rank, in finish (line 762), writes the global .metadata.tmp, fsyncs it (lines 779 to 783), deletes any existing .metadata (line 796) and renames the temporary file into place (line 798). It never fsyncs a directory. The traced save, overwriting an existing checkpoint directory:
openat(..., O_TRUNC), so the old checkpoint is gone at the first call. Between unlinkat(.metadata) and the moment the rename is durable (the next journal commit, up to 5 s on ext4), a crash leaves a directory with no .metadata, which DCP cannot load: no checkpoint at all. And because the directory is never fsynced, even after dcp.save has returned a crash can bring back the old .metadata next to the new, fsynced shard: a checkpoint whose metadata and data come from different saves. With a new directory per step there is nothing to delete or truncate, and a crash can only lose the step being written. This is what torchtitan does ("Standardized checkpoint path, e.g. checkpoints/step-100", torchtitan base.py line 379). Add an fsync of the parent directory after the save so the new directory's name is durable too, and treat a step directory without .metadata as incomplete. This is our reading of the source and the trace, shown as states in the crash lab (pick the two DCP protocols); it is not a reported incident.Asynchronous saves. dcp.async_save first stages the state (copies tensors to CPU memory), returns a future, and writes in the background, so training continues during the slow part. Here it blocked training for 66 ms of a 501 ms save. Two costs remain: a second copy of the state in host memory while it is written, and the writes still compete for the device and the dirty-page budget (section 4), so a step that runs during the background write can be slower.
step-000200/); each rank writes and fsyncs its own shard; barrier; one rank writes the metadata or a COMPLETE marker, fsyncs it, then fsyncs the step directory and its parent.shutil.disk_usage); handle OSError from write, fsync and close as "this checkpoint failed".Given a file object instead of a path, torch.save writes into it and leaves flushing, syncing and renaming to you: that is how the safe protocol of section 6 wraps it. CheckFreq describes the same split as async_save, a quick in-memory "snapshot" and a background "persist", and chooses how often to checkpoint from measured costs (CheckFreq, FAST 2021).
Mohan and colleagues measured nine models on production servers at Microsoft and found that "in many cases, DNN training time is dominated by data stall time: time spent waiting for data to be fetched and preprocessed" (Analyzing and Mitigating Data Stalls in DNN Training, VLDB 2021). The storage half of that is this page's mechanisms; dataset formats, sharding and loader prefetch are Storage and loading at scale's.
D with wait channel wait_on_page_bit_common or io_schedule wait for storage; high system time with many small read calls is the root's Debug lab case "High system time: millions of tiny reads"; iostat -x shows whether the device is busy.| Mistake | What happens | Fix |
|---|---|---|
torch.save(state, "ckpt.pt") over the last good checkpoint | the old file is truncated at open; a crash or full disk before the end leaves nothing loadable | temporary name, fsync, rename, fsync the directory (6) |
| "It returned, so it is saved" | the data sits dirty in the page cache for seconds; a node crash loses it | fsync before you rely on it (4, 5) |
| fsync of the file but not of the directory | after a crash the new name may be missing although the data is on disk | open the directory and fsync it after the rename |
| Retrying a failed fsync | the retry can succeed with the data already dropped | treat the file as lost; write it again from memory |
Ignoring the return of close | on NFS and with delayed allocation, write errors and ENOSPC can surface there | let f.close() raise; do not swallow OSError |
| DCP saves into the same directory every time | old shards truncated first, .metadata deleted before the new one is renamed in | one directory per step; fsync the parent (10) |
| Millions of small files on a shared file system | metadata servers saturate; cold reads one request each | shards; sequential reads; stage locally (2, 11) |
| Benchmarking a loader once, or twice | the first run times the disk, the second times RAM | say which; evict with posix_fadvise(DONTNEED) or measure both (3) |
%util at 100% means the disk is saturated | not on devices that serve many requests at once | look at throughput and latency against queue depth (1) |
| Assuming rename works everywhere | object stores have none; FUSE mounts may reject it | new keys plus a marker written last (9) |
| Deleting old checkpoints to free space while a process holds them open | no space is freed until the process closes them | lsof +L1; close or restart the holder (2) |
write() guarantee when it returns, and what does fsync() add?write guarantees the bytes are in the kernel's page cache: visible to every process on this machine, but only in memory. fsync returns when the file's data and metadata have reached stable storage, including flushing the device's volatile cache. It does not cover the directory entry naming the file; that needs an fsync of the directory.rename it over the target (atomic for readers: they see old or new), then fsync the directory so the rename survives a crash. Same directory, because rename is atomic only within one file system. Alternatives: O_TMPFILE plus linkat for new names, renameat2(RENAME_EXCHANGE) to swap.auto_da_alloc forces allocation on rename-over-existing and truncate-then-close to cover the common unsafe patterns, but the portable fix is fsync.balance_dirty_pages pauses the writer so it cannot outrun the device. /proc/PID/wchan shows balance_dirty_pages; Dirty and Writeback in /proc/meminfo stay high. Fixes: accept device speed, write in a background thread, use dirty_bytes limits, start writeback early with sync_file_range, or O_DIRECT.read_ahead_kb, and triggers the next window asynchronously from a marked page. It does nothing for random access, which is why random small reads cost one device request each and why datasets are stored as sequential shards.io.max limit or a smaller memory limit (less cache); and whether workers sit in state D (ps -eo stat,wchan).Links checked on 5 October 2026; knowledge base links updated 24 October 2026. Times are estimates for the part worth reading. Suggested order: this page's Reading tab (the crash lab is in section 6) with OSTEP chapters 39, 40 and 42 beside it; then the ALICE paper and the ext4 and writeback documentation for whatever you are debugging.
Section 7 is the intuition for this page, with an animation of one write's journey and the 2009 ext4 and 2018 fsyncgate stories; the running job is followed through the whole OS.
On the root page: crash consistency at the block level (inode, bitmap, data block) with no journal, data journaling and ordered journaling, checked against OSTEP's homework. This page's crash lab (Reading section 6) is the same question one level up, at the system calls.
On the root page: buffered against unbuffered writes, and the running job's checkpoint write paths in its full trace.
On the root page, the storage cases: "Disk full mid-checkpoint: a cryptic error and a destroyed checkpoint", "write() returned, but the data is not on disk yet: fsync", "The first epoch is slower than the rest: cold and warm page cache", "Slow storage: workers sleep in D state on page faults", "High system time: millions of tiny reads".
File descriptors and their three tables, pipes, O_CLOEXEC, the system call mechanism and its cost.
The context switch measured, CFS read live from /proc, EEVDF as a simulator, affinity, NUMA and cgroup CPU quotas and throttling.
The page cache from the memory side: reclaim, mmap of datasets and weights (random rows, read amplification, MADV_RANDOM), memory cgroups counting page cache.
glibc's malloc in depth, fragmentation measured, jemalloc, tcmalloc and mimalloc on the same job, pymalloc, and PyTorch's CPU and CUDA allocators.
Event-driven I/O: epoll, io_uring's rings, and the event loops (asyncio, tokio, libuv) built on them.
cgroups v2 in depth, including the io controller (io.max, io.stat) used for every device count here, and overlayfs.
virtio, the paravirtual disk this page measured, and the path from a CUDA call to the GPU.
Write-ahead logs: the journal's idea inside a database, and why databases preallocate and use fdatasync or O_DIRECT. Part of the Databases topic.
Dataset formats, shards, streaming and loader prefetch: section 11's mechanisms turned into a data pipeline.
Checkpoint strategies and recovery designs built on top of the write protocols here.
What a sharded checkpoint contains and how ranks save it.
Parallel file systems, object storage and checkpoint I/O at cluster scale.
Where torch.distributed.checkpoint and the DataLoader sit in PyTorch.
Pages and mmap as a C++ program meets them, measured on an M1.
Devices, disks, files and directories, file system implementation, FFS, journaling, LFS, SSDs, integrity. Chapter 42 is the core of sections 7 and 8.
The ALICE study: application update protocols, file system persistence properties, 60 vulnerabilities. The crash lab in Reading section 6 is a small version of its method.
A readable tour of the research on file consistency and error handling, with the surprising results.
fsyncgate, and the errseq_t error reporting that changed what a failed fsync means.
The data modes and mount options, the dirty-page knobs, FLUSH and FUA, the multi-queue block layer, the VFS objects.
The functions this page cites by line: readahead sizing, the background threshold check, ext4's fsync, sync_file_range's warning.
save, async_save, FileSystemWriter options; the finish method read in section 11.
Checkpointing often and cheaply with a snapshot and persist split; where training time goes when input is the bottleneck.
The guarantees of the storage a cluster gives you, each from its own documentation.
The benchmark tool used here; read "I/O depth" and "direct" before trusting any storage benchmark.