Unit 4 of 12 · about 4 hours · explain, implement
Torn, truncated and reordered writes and crash-consistent metadata publication
Disks write sectors, not your records. Any multi-sector update can land partially, and only an ordered publication protocol makes the partial state detectable.
You'll be able to
- Enumerate crash states for torn, truncated and reordered writes at sector and file granularity.
- Implement atomic metadata publication with write-ahead records, checksums and a synced rename.
- Explain when full-page images are needed and what turns them off safely.
Covers
Read
In this order, only the parts listed
0 of 3 done
- OSTEP journaling crash scenariosOperating Systems: Three Easy Pieces - Crash Consistency and Data Integrity
Chapter 42, Section 42.3: the five-block journal transaction, the torn-transaction garbage-block example, and the checksum fix that lets the whole transaction issue at once
- OSTEP misdirected and lost writesOperating Systems: Three Easy Pieces - Crash Consistency and Data Integrity
Chapter 45, Sections 45.5 and 45.6: Misdirected Writes and Lost Writes, with the read-back verification discussion
- PostgreSQL torn pages and full-page imagesPostgreSQL 18 Documentation - WAL Configuration and Internals
Section 28.1, Reliability: the sector-tear paragraph with the 8 KiB page over 512-byte sectors, and the full-page-image paragraph including the
full_page_writescondition
Focus on
- A torn write lands some sectors of one page. A truncated write lands a prefix of a multi-block transaction. A reordered write lands a later block before an earlier one.
- Publication is journal first with a transaction-end marker and checksum, then checkpoint to final locations, then a synced rename or manifest swap that flips the visible state at once.
- A matching begin and end marker is not enough when the disk reorders internally. The checksum over the transaction body is what exposes the garbage middle block.
- PostgreSQL writes full page images after each checkpoint because a torn 8 KiB page cannot be repaired from per-tuple WAL records alone. ZFS-like stacks that prevent partial writes may disable it; ordinary stacks must not.
Common mistakes · 3
- Assuming an 8 KiB page write is atomic because one call issued it. The drive writes 512-byte sectors, and power can fail between any two of them.
- Treating
renameas durable without syncing the directory. The new name is visible but not yet crash-safe. - Disabling
full_page_writesfor speed on a plain filesystem. Without page images, a torn page has no repair source during REDO.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.The journal holds TxB, I, B, garbage and TxE with matching IDs. Is this transaction valid?Answer
No. Matching IDs without a body checksum cannot expose a reordered middle block. Recovery must reject it by checksum, not accept it by markers.
2.What distinguishes a truncated transaction from a torn page?Answer
Truncation cuts a multi-block transaction short, so the end marker or checksum is missing or wrong. A tear corrupts the middle of one page while its framing looks complete.
3.Why does the publication protocol sync the directory after renaming a new segment file?Answer
The rename changes a directory, not the file. Until the directory itself is synced, a crash can lose the name even though the file contents are durable.
4.When is turning off
full_page_writessafe?AnswerOnly when the layer below provably prevents partial page writes, such as a copy-on-write filesystem. Otherwise recovery cannot repair torn pages.
Practice
- Building Distributed Systems TH-2: Implement WAL Recovery on Startup
Task TH-2, Implement WAL Recovery on Startup: half-written tail handling
This is a free drill graded in the browser after login. Reproduce the torn-tail case in your local log and keep the local crash schedule as evidence.
You're done when
You enumerate all three crash outcomes for a journal transaction and your local log discards the torn tail on every injected schedule.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 more in the section
- PostgreSQL 18 Documentation - WAL Configuration and InternalsPostgreSQL Global Development Group · support
Read "WAL Configuration" (checkpoints and the redo point crash recovery starts from), "WAL Internals" and "Reliability" for the official, versioned statement of the write-ahead and durability contract.
- Operating Systems: Three Easy Pieces - Crash Consistency and Data IntegrityRemzi and Andrea Arpaci-Dusseau · required
Read Chapter 42 (FSCK and journaling: the crash scenarios, data and metadata journaling and their write order) and Chapter 45 (data integrity: checksums, misdirected and lost writes, scrubbing; https://pages.cs.wisc.edu/~remzi/OSTEP/file-integrity.pdf). Turn each crash scenario into an injection point in your store.
Also in this section
- CMU 15-445 - Storage, Index and Recovery SequenceCarnegie Mellon Database Group · primary
Follow Fall 2025 lectures 3 to 10 and 21 to 22. Do the BusTub projects from tag v20251119-2025fall (https://github.com/cmu-db/bustub/tree/v20251119-2025fall): P1 (ARC replacer, disk scheduler and buffer pool manager) and P2 (B+ tree with a leaf tombstone buffer), with P0 (Count-Min Sketch) as the C++ warm-up. Tests ship with a
DISABLED_prefix to remove, and GCC 15 needs-DCMAKE_CXX_FLAGS="-include cstdint"at configure time. Use the storage and recovery homework for WAL reasoning, and keep C++ scope bounded to storage and recovery. - Hypothesis - Stateful TestingHypothesis · support
Use
RuleBasedStateMachinewith rules, bundles and invariants to drive your store and a dictionary model with the same random operation sequences, and check the machine catches a planted bug before trusting a pass. - DDIA 2e - Chapter 4 Storage and RetrievalMartin Kleppmann and Chris Riccomini · required
Read "Storage and Indexing for OLTP" (log-structured storage, B-trees, their comparison and secondary indexes) and "Data Storage for Analytics" (column-oriented storage). Its Bloom filter, tombstone and write-ahead log coverage is brief, so take those from OSTEP and The Internals of PostgreSQL. Build a workload decision table, then connect each claim to a measurement from your small store.
- Building Distributed Systems - The Logger and IndexesBuild Distributed Systems · optional
Only the first three tasks are free (a write-ahead log, its recovery and log segments). Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.
- HLD Handbook - Storage Engines and Data StructuresHLD Handbook · required
Read Part 0 data structures plus Part 4 storage engines and OLTP versus OLAP. Use its exercises for comparison, while the CMU project and local fault tests remain the implementation evidence.
- The Internals of PostgreSQL - Buffer Manager, WAL and RecoveryHironobu Suzuki · support
Read Chapter 1 Sections 1.2 to 1.4 (heap pages and tuples), Chapter 8 (buffer manager and dirty-page flushing) and Chapter 9 Sections 9.1 to 9.8 (WAL segments, XLOG records, checkpoints and recovery). Compare each mechanism with your simplified store. The site is revised often, so note the date you read it.
- ARIES: A Transaction Recovery Method (Mohan et al., 1992)ACM TODS (Stanford course copy) · support
Read the introduction, the overview and restart processing (analysis, redo by repeating history, undo) and the page LSN rule. The rest is 1992 storage detail beyond this section.
- Build Your Own RedisBuild Your Own · optional
Use the persistence and data-structure portions only if a second implementation is needed to cement parsing, indexing or append-log behavior. Do not replace the crash-tested stage artifact with tutorial completion.
- Replicated Log and Stream Processor - Storage SliceRoadmap-Final · support
Implement checksummed segments, indexes, acknowledgement states, recovery, retention and atomic metadata changes. Preserve every crash schedule and corrupted artifact needed to reproduce a failure.
- Apache Parquet File FormatApache Software Foundation · support
Read the File Format layout (row groups, column chunks, footer metadata) and the Page Index page (ColumnIndex and OffsetIndex with per-page min and max values for page skipping). Use it only for file layout and skipping; it does not cover table metadata or catalogs.
- Linux man-pages: fsyncLinux man-pages project · support
Read the DESCRIPTION for what
fsyncandfdatasyncguarantee and the directory-sync requirement for new file names, and the ERRORS section for what anEIOfrom write-back can refer to.