Capstone: Crash-Safe Binary Log
In-place record overwrites corrupt both old and new values on power loss, while CRC32-only WAL headers replay stale transactions when preallocated log segments are recycled. In this capstone lesson you will synthesize O_CLOEXEC, branchless IEEE 802.3 CRC32 + 64-bit seq WAL framing, fdatasync(), ftruncate() crash healing, and lock-free pread() indexing.
What you'll learn
- Construct self-describing binary Write-Ahead Log frames with magic bytes, 64-bit
seqepochs, lengths, and IEEECRC32. - Implement startup crash-recovery scanning that detects torn or corrupt tail frames and heals the log via
ftruncate(). - Serve lock-free latest-key reads via an in-memory offset index and stateless
pread()without moving the append cursor.
Why In-Place Updates Corrupt State & CRC32 Alone Fails Recycled Logs
Imagine an embedded power-controller key-value store that updates "vcore" from "1150mV" (6 bytes) to "1200mV_boost" (12 bytes) by overwriting records in place inside a flat binary file. If input power drops halfway through that write(), the sector on flash contains half of the new record spliced onto adjacent keys—destroying both the uncommitted update and previously committed state! Switching to an append-only log with a CRC32 checksum fixes torn writes on fresh files, yet a subtler bug strikes as soon as the engine recycles preallocated WAL segments without zero-wiping 4 MiB of flash: right after committing 3 new frames (105 bytes), the recycled sector at offset 105 still holds an intact, valid-CRC32 frame from yesterday's epoch ("vcore=900mV!")—which a naive CRC32-only scanner happily replays on boot!
Production storage engines (SQLite WAL, RocksDB, etcd Raft logs) solve both hazards by uniting every primitive from Modules 1–6 inside an append-only Write-Ahead Log (WAL) sealed by reflected IEEE 802.3 CRC32 + a strictly monotonic 64-bit sequence/epoch counter (seq).
note: A crash-safe Write-Ahead Log is like an aircraft flight recorder tape sealed frame-by-frame with sequence numbers and checksum stamps: if power cuts mid-frame, recovery inspectors snip off the broken tail frame cleanly and read any earlier frame by exact byte offset without moving the recording head.
Where it stops working: Snipping physical tape requires hand splicing, whereas ftruncate() updates inode->i_size atomically in the filesystem while leaving concurrent pread() readers completely lock-free at earlier offsets.
definition (Write-Ahead Log (WAL), Reflected CRC32 & Monotonic Epoch): Write-Ahead Log (WAL): Originated in the ARIES recovery architecture (Mohan et al.), an append-only binary log where mutations append immutable frames flushed via fdatasync() before acknowledgment, startup recovery truncates uncommitted crash tails via ftruncate(), and point queries read latest committed offsets via stateless pread(). Reflected IEEE 802.3 CRC32 (0xEDB88320U) & Monotonic seq: Processes bits Least-Significant-Bit (LSB)-first over [seq, klen, vlen, key, val] to detect bit-rot and torn writes, while h.seq == expected_seq stops recovery deterministically at recycled-sector boundaries.
One Layer Down: 24-Byte Frame Geometry & Branchless GF(2) CRC32 Math
Each WAL record begins with an ABI-locked 24-byte header (struct wal_hdr: uint32_t magic, crc32, klen, vlen; uint64_t seq;, _Static_assert(sizeof(struct wal_hdr) == 24) with zero compiler padding) followed by klen key bytes and vlen value bytes, giving total size frame_bytes = 24 + klen + vlen. Computing IEEE 802.3 CRC32 bit-by-bit in C without a branch (if (crc & 1)) avoids branch-misprediction stalls on embedded ARMv7 pipelines. Using two's-complement negation on unsigned uint32_t, -(crc & 1U) evaluates to 0xFFFFFFFFU when bit 0 is 1 and 0x00000000U when bit 0 is 0, yielding the branchless step crc_next = (crc >> 1) ^ (0xEDB88320U & -(crc & 1U)). Initializing c = 0xFFFFFFFFU and inverting ~c at completion ensures leading and trailing 0x00 bytes alter the checksum!
| Course Module Synthesized | Exact Primitive Inside WAL Engine | Storage Invariant Enforced | ||
|---|---|---|---|---|
m01 — Types & ABI | <stdint.h>, _Static_assert(sizeof == 24), unsigned -(crc & 1U) | Zero UB; identical binary frame on ARMv7 & x86-64 | ||
m02 — Unbuffered I/O | `O_RDWR \ | O_CREAT \ | O_CLOEXEC, write_all()` retry loop | Leak-safe handle; immune to EINTR & short writes |
m03 — VFS & fstat | fstat(fd, &st) logical st_size, saved_errno cleanup | Bounds recovery scan to exact inode byte size | ||
m04 — Atomicity & Resize | Stateless pread() index reads + ftruncate(fd, valid_off) | Lock-free concurrent GETs + atomic torn-tail heal | ||
m05 — Safe Diagnostics | Bounded key/value length caps + %lld / PRIu64 reports | Zero stack overruns on corrupted length headers | ||
m06 — Durability | fdatasync(fd) per commit + fsync(dir_fd) on creation | Committed frames survive power loss & SIGKILL |
Figure 6.3. ABI-locked 24-byte CRC32+seq WAL frame layout, recycled-tail ftruncate() crash healing, and lock-free pread() indexing.
- Step 1. Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().
- Step 2. Replay sequentially from offset 0 checking WAL_MAGIC, h.seq == exp_seq, subtraction bounds, and CRC32.
- Step 3. Snip stale recycled frames or torn crash tails via ftruncate(fd, off) + fdatasync(fd) + lseek(fd, off, SEEK_SET).
- Step 4. Serve latest committed values concurrently via stateless pread() while writer_fpos remains parked at EOF.
Figure 6.3b. Seal immutable WAL frames with branchless CRC32 + monotonic seq, flush via fdatasync(), heal crash tails with ftruncate() + lseek(), and read lock-free via pread().
Startup Recovery State Machine & Cursor Resynchronization
Walk through the four validation gates executed at byte offset off during startup recovery (exp_seq starting at 1): (1) off + 24 <= st.st_size and pread_full(fd, &h, 24, off) == 24; (2) h.magic == WAL_MAGIC, h.seq == exp_seq, bounded h.klen/h.vlen, and off + 24 + h.klen + h.vlen <= st.st_size; (3) pread_full() of key and val succeeds and frame_crc(...) == h.crc32; (4) on any failure, stop at off, call ftruncate(fd, off) + fdatasync(fd) to snip the torn or stale tail, and call lseek(fd, off, SEEK_SET) so subsequent appends start cleanly at off!
Building Mini-WAL Commit, Stale-Epoch Guard, Healing & pread Lookup
Save mini_wal_demo.c below. It wraps writes in write_all() + fdatasync() + initial /tmp directory fsync(), commits three monotonic mutations (seq=1..3: vcore=1150mV, pll_hz=1200M, vcore=1200mV, 105 bytes total), injects a recycled-sector stale frame with a valid CRC32 but stale seq=1 (vcore=900mV!, 140 bytes) plus 5 torn garbage bytes (145 bytes), runs startup recovery to heal the log back to 105 bytes via ftruncate(), and serves "vcore" (1200mV) via stateless pread() while writer_fpos stays at 105!
learner@ksa:~/gl-c01/m06-l03$ bat -H 23 -H 49 -H 95 -H 115 mini_wal_demo.c File: mini_wal_demo.c #define _FILE_OFFSET_BITS 64 #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #define WAL_MAGIC 0x4B57414CU struct wal_hdr { uint32_t magic, crc32, klen, vlen; uint64_t seq; }; _Static_assert(sizeof(struct wal_hdr) == 24, "WAL header ABI"); static uint32_t crc32_step(uint32_t crc, const void *buf, size_t len) { const uint8_t *p = (const uint8_t *)buf; for (size_t i = 0; i < len; i++) { crc ^= p[i]; for (int b = 0; b < 8; b++) { crc = (crc >> 1) ^ (0xEDB88320U & (-(crc & 1U))); } } return crc; } static uint32_t frame_crc(uint64_t seq, uint32_t kl, uint32_t vl, const char *k, const char *v) { uint32_t c = 0xFFFFFFFFU; c = crc32_step(c, &seq, sizeof(seq)); c = crc32_step(c, &kl, sizeof(kl)); c = crc32_step(c, &vl, sizeof(vl)); c = crc32_step(c, k, kl); c = crc32_step(c, v, vl); return ~c; } static int write_all(int fd, const void *buf, size_t len) { const uint8_t *p = (const uint8_t *)buf; size_t done = 0U; while (done < len) { ssize_t n = write(fd, p + done, len - done); if (n < 0) { if (errno == EINTR) continue; return -1; } done += (size_t)n; } return 0; } static int wal_put(int fd, uint64_t seq, const char *k, const char *v) { uint32_t kl = (uint32_t)strlen(k), vl = (uint32_t)strlen(v); struct wal_hdr h = {WAL_MAGIC, frame_crc(seq, kl, vl, k, v), kl, vl, seq}; uint8_t frame[128]; size_t tot = sizeof(h) + kl + vl; if (tot > sizeof(frame)) return -1; memcpy(frame, &h, sizeof(h)); memcpy(frame + sizeof(h), k, kl); memcpy(frame + sizeof(h) + kl, v, vl); if (lseek(fd, 0, SEEK_END) < 0 || write_all(fd, frame, tot) < 0) { return -1; } return fdatasync(fd); } int main(void) { const char *path = "/tmp/ksa_m06_l03.wal"; int fd = open(path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); int dfd = open("/tmp", O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (fd < 0 || dfd < 0 || fsync(dfd) < 0) return 1; (void)close(dfd); if (wal_put(fd, 1ULL, "vcore", "1150mV") < 0 || wal_put(fd, 2ULL, "pll_hz", "1200M") < 0 || wal_put(fd, 3ULL, "vcore", "1200mV") < 0) { return 1; } off_t clean_sz = lseek(fd, 0, SEEK_END); if (wal_put(fd, 1ULL, "vcore", "900mV!") < 0 || write_all(fd, "TORN!", 5U) < 0) { return 1; } off_t crashed_sz = lseek(fd, 0, SEEK_END); struct stat st; if (fstat(fd, &st) < 0) return 1; off_t off = 0, vcore_off = -1; uint32_t vcore_len = 0U, valid_recs = 0U; uint64_t exp_seq = 1ULL; while (off + (off_t)sizeof(struct wal_hdr) <= st.st_size) { struct wal_hdr h; char kbuf[32], vbuf[64]; if (pread(fd, &h, sizeof(h), off) != (ssize_t)sizeof(h)) break; off_t hsz = (off_t)sizeof(h); if (h.magic != WAL_MAGIC || h.seq != exp_seq || h.klen >= sizeof(kbuf) || h.vlen >= sizeof(vbuf) || (off_t)(h.klen + h.vlen) > st.st_size - off - hsz) { break; } if (pread(fd, kbuf, h.klen, off + hsz) != (ssize_t)h.klen || pread(fd, vbuf, h.vlen, off + hsz + (off_t)h.klen) != (ssize_t)h.vlen) { break; } if (frame_crc(h.seq, h.klen, h.vlen, kbuf, vbuf) != h.crc32) break; kbuf[h.klen] = '\0'; if (strcmp(kbuf, "vcore") == 0) { vcore_off = off + hsz + (off_t)h.klen; vcore_len = h.vlen; } valid_recs++; exp_seq++; off += hsz + (off_t)h.klen + (off_t)h.vlen; } if (off < st.st_size && (ftruncate(fd, off) < 0 || fdatasync(fd) < 0)) return 1; if (lseek(fd, off, SEEK_SET) < 0) return 1; char latest[64] = {0}; if (vcore_off < 0 || pread(fd, latest, vcore_len, vcore_off) != (ssize_t)vcore_len) { return 1; } off_t writer_fpos = lseek(fd, 0, SEEK_CUR); (void)close(fd); (void)unlink(path); printf("wal_recovery: clean=%lld crashed=%lld healed=%lld recs=%u\n", (long long)clean_sz, (long long)crashed_sz, (long long)off, valid_recs); printf("wal_lookup: vcore=%s writer_fpos=%lld\n", latest, (long long)writer_fpos); return 0; }- Branchless reflected IEEE 802.3 CRC32 step: -(crc & 1U) masks 0xEDB88320U without conditional branch mispredictions.
- Include seq, klen, vlen, key, and val inside frame_crc() and finish with fdatasync(fd) before acknowledging wal_put().
- Checking h.seq != exp_seq rejects intact valid-CRC frames left in recycled WAL sectors; ftruncate(fd, off) heals the tail.
Verifying Crash-Tail Healing, Stateless pread Lookup & Lab 6
Compile and execute mini_wal_demo: verify clean=105, crashed=145, healed=105 (recs=3), and vcore=1200mV with writer_fpos=105 untouched! Then complete the full capstone project in lab_m06_durable_wal.
learner@ksa:~/gl-c01/m06-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror mini_wal_demo.c -o mini_wal_demolearner@ksa:~/gl-c01/m06-l03./mini_wal_demowal_recovery: clean=105 crashed=145 healed=105 recs=3wal_lookup: vcore=1200mV writer_fpos=105learner@ksa:~/gl-c01/m06-l03test ! -e /tmp/ksa_m06_l03.wal && rm -f mini_wal_demolearner@ksa:~/gl-c01/m06-l03→ open standalone lab workbench
1. Motivation
Every production embedded database, OTA boot-state manager, and distributed consensus log (SQLite WAL, RocksDB, etcd, U-Boot redundant environment) confronts the same physical law: power can vanish mid-sector at any microsecond. Overwriting records in place destroys committed state, calling fclose(fp) without fflush(fp) + fdatasync(fileno(fp)) leaves acknowledged commits in volatile DRAM, and reading with stateful read() clobbers concurrent cursors. In this capstone project, you will synthesize all six modules of GL-C01 into durable_wal, a crash-consistent IEEE 802.3 CRC32 Write-Ahead Log and key-value engine.
2. Learning Objectives
- Commit length-prefixed, IEEE 802.3
CRC32-protected binary frames via the complete two-stage durability barrier (fwrite->fflush->fdatasync(fileno(fp))-> single-ownerfclose, plus parent-directoryfsyncon initial creation). - Recover crashed logs deterministically by scanning frames from offset
0via statelesspread(), detecting torn headers, torn payloads, or single-bitCRC32corruptions, and healing the file viaftruncate(fd, valid_offset)+fdatasync(fd). - Serve log-structured latest-wins
getqueries viapread()while provingstruct file.f_posremains untouched at0.
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+),#define _POSIX_C_SOURCE 200809Land#define _FILE_OFFSET_BITS 64. - Target Board Portability (
ARMv7Cortex-A7): The16-bytestruct wal_hdr(magic,crc32,key_len,val_len), branchless reflected0xEDB88320UCRC32, andpread/ftruncate/fdatasynccalls behave identically on embeddedARMv7ext4/f2fspartitions (wherefdatasync()flushes the eMMC controller cache).
4. Required Software & Hardware
- Software Toolchain:
gcc(-std=c11 -Wall -Wextra -Werror),strace,dd/python3(for fault-injection corruption tests), and/bin/sh. - Hardware: Standard Linux host environment (
tmpfsor NVMe/SSD filesystem).
5. Complete Executable Commands
Run from labs/lab_m06_durable_wal/:
learner@ksa:~/gl-c01/m06-l03$ bat script.sh File: script.sh # 1. Compile the capstone WAL engine with strict C11 warning flags gcc -std=c11 -O2 -Wall -Wextra -Werror files/durable_wal.c -o /tmp/durable_wal rm -f /tmp/engine.wal # 2. Commit three mutations (including an update to boot.mode) and verify latest-wins GET /tmp/durable_wal append /tmp/engine.wal boot.mode primary /tmp/durable_wal append /tmp/engine.wal vcore_mv 1200 /tmp/durable_wal append /tmp/engine.wal boot.mode fallback /tmp/durable_wal get /tmp/engine.wal boot.mode # 3. Inject a 9-byte torn power-loss tail and verify ftruncate() heals back to 95 bytes! printf 'TORN_TAIL' >> /tmp/engine.wal /tmp/durable_wal recover /tmp/engine.wal /tmp/durable_wal get /tmp/engine.wal boot.mode # 4. Trace exact fflush -> write -> fdatasync -> close syscall sequence on append strace -e trace=openat,write,fdatasync,fsync,close /tmp/durable_wal append /tmp/engine.wal watchdog on # 5. Clean up and run the full TAP 13 fault-injection suite rm -f /tmp/durable_wal /tmp/engine.wal sh check.sh*Why each command runs:* Step 2 appends immutable frames (32 + 30 + 33 = 95 bytes) and verifies "boot.mode" resolves to "fallback" with f_pos=0; Step 3 simulates an interrupted write (104 bytes) and proves recover heals 104 -> 95 (valid_records=3); Step 4 proves fflush() issues write() before fdatasync() and fclose() closes fd once; and Step 5 executes all TAP 13 checks including mid-payload CRC32 bit-flip injection.
6. Annotated Source Code (starter/ Flaws vs files/ Reference)
Flawed Baseline (starter/durable_wal.c)
- Zero durability & fake checksum (
append): Writescrc32 = 0U, omitsO_CLOEXEC, and omitsfflush()+fdatasync()+ parent directoryfsync(). - No-op
recover: Printsst.st_sizewithout reading headers, recomputingCRC32, or callingftruncate(). - Stateful first-match
get: Usesread()(advancingf_posto32) and returns on the first matching key ("primary") instead of scanning toEOFfor latest-wins ("fallback").
Warning-Clean Reference (files/durable_wal.c)
- Branchless IEEE 802.3
CRC32(crc32_update/compute_frame_crc): Computesuint32_t mask = -(crc & 1U); crc = (crc >> 1) ^ (0xEDB88320U & mask);over[key_len, val_len, key, val](including lengths inside the checksum envelope!). - Two-Stage Commit + Dir Sync (
cmd_append): OpensO_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC(0644), transfers ownership tofdopen(fd, "wb"), runsfwrite->fflush(fp)->fdatasync(fileno(fp))-> singlefclose(fp), and callssync_parent_dir(wal_path)when creating a brand-new WAL file. - Stateless Recovery & Lookup (
cmd_recover,cmd_get): Usespread_exact()fromoff = 0, validatesWAL_MAGIC, bounds (1 <= key_len <= 64,val_len <= 256), full payload availability, andexpect_crc == hdr.crc32, heals mismatches viaftruncate(fd, valid_off) + fdatasync(fd), and updateslatest_valacross all valid frames whilelseek(fd, 0, SEEK_CUR)stays0!
7. Expected Output
learner@ksa:~/gl-c01/m06-l03$ bat listing.txt File: listing.txt $ ./durable_wal append engine.wal boot.mode primary && ./durable_wal append engine.wal boot.mode fallback && ./durable_wal get engine.wal boot.mode COMMIT key=boot.mode bytes=32 COMMIT key=boot.mode bytes=33 VALUE fallback f_pos=0 $ sh check.sh TAP version 13 1..5 ok 1 - builds with -std=c11 -Wall -Wextra and no warnings ok 2 - flushes and fdatasyncs 3 CRC32-framed WAL commits (95 bytes) ok 3 - scans WAL statelessly via pread leaving f_pos=0 with latest-wins semantics ok 4 - truncates torn power-loss tail back to last valid frame boundary ok 5 - detects CRC32 payload corruption, truncates bad frame, and keeps prior commits # pass 5/58. Explanation of Observed Behavior
Look at Test 5 inside check.sh: after three committed frames (95 bytes), a 4th 40-byte frame (135 bytes total) has 1 bit flipped inside its value payload. During recover, pread_exact() reads frames 1..3 (valid_off advances 0 -> 32 -> 62 -> 95); at valid_off = 95, compute_frame_crc() mismatches hdr.crc32, breaking out of the scan loop at valid_off = 95. ftruncate(fd, 95) + fdatasync(fd) then snips the corrupted 40-byte tail atomically on storage while all 3 earlier committed frames remain 100% intact!
9. Experiment Variations
- Single-Write Coalescing Optimization: Coalesce
[hdr, key, val]into one stackuint8_t frame[16 + KEY_CAP + VAL_CAP]buffer beforefwrite()(or usewritev()), confirming understracethatfflush(fp)already coalesces the threefwrite()calls into onewrite()syscall thanks to_IOFBF! - Header Length Bit-Flip Test: Flip
1bit insidehdr.key_len(changing5to37within<= 64) on a 4th frame and verify that includingkey_leninsidecompute_frame_crc()catches the corruption even if95 + 16 + 37 <= st_size. - 256-entry
CRC32Lookup Table: Precompute auint32_t crc_tab[256]table inside an__attribute__((constructor))orstatic constarray (1table lookup per byte instead of8bit loops) and compare CPU throughput on1 MiBpayloads.
10. Performance Measurements
Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 paired append + get durable CLI commits):
| Metric | Measured Host (x86_64 Linux 6.12) | Target Board Expectation (ARMv7 Cortex-A7 Industrial eMMC) |
|---|---|---|
Durable append + get (p50 / p95 / p99) | 3,346.2 us / 5,287.6 us / 5,400.4 us | ~14,000–24,000 us CLI (1.5–6.0 ms per hardware eMMC fdatasync barrier) |
Syscalls per existing-WAL append | 1 openat + 1 write + 1 fdatasync + 1 close | Identical 4-syscall commit path |
Stateless get cursor mutation (f_pos) | 0 -> 0 (pread64 only) | 0 -> 0 (pread64 only) |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
EBADF or crashed fd in multithreaded test | Called close(fd) after fclose(fp) on fp = fdopen(fd, "wb") | Let fclose(fp) close fd once; only close(fd) if fdopen() returned NULL |
fdatasync runs while WAL file on disk is still 0 bytes | Called fdatasync(fileno(fp)) before fflush(fp) | Always call fflush(fp) first, then fdatasync(fileno(fp)) |
get returns "primary" instead of "fallback" | Returned immediately on first key match instead of scanning to EOF | Keep updating latest_val until the scan reaches the end of valid frames |
get prints f_pos=95 instead of f_pos=0 | Used stateful read()/fread() instead of pread() | Read headers and payloads exclusively via pread_exact() |
12. Guided Questions
- Why does
cmd_append()checkint existed = (stat(wal_path, &before_st) == 0);and callsync_parent_dir(wal_path)when!existed?
- *Hint 1:* Does
fdatasync(fileno(fp))sync the parent directory's dentry table? - *Hint 2:* What happens on sudden power loss right after creating
engine.walifengine.wal's blocks are on NVMe media but the parent directory's new"engine.wal" -> st_inoentry was still in volatile DRAM?
- Why does
cmd_append()combineO_APPENDonopen()withfdopen(fd, "wb")?
- *Hint 1:* When
fflush(fp)drains theRing 3buffer via a singlewrite(fd, buf, frame_len)syscall (frame_len <= 336bytes), what lock doesO_APPENDacquire insideRing 0? - *Hint 2:* Why would two separate
write()syscalls (header inwrite #1, payload inwrite #2) break multi-processO_APPENDatomicity without_IOFBFcoalescing them into a singlewrite()?
13. Independent Challenges
- Near Transfer — Monotonic
64-Bit Epoch Header & Tombstone Deletes (del <wal_path> <key>): Upgradestruct wal_hdrto24bytes by addinguint64_t seq(1, 2, ..., verified duringrecoverto block stale recycled-segment frames as inm06-l03) anduint32_t tombstone(0xFFFFFFFFUval_lensentinel) sodelremoves keys cleanly without in-place mutation. - Far Transfer — Crash-Safe WAL Compaction (
compact <wal_path>): Implement atomic log compaction using directory-pinnedopenat(..., "wal.compact.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644), writing only live non-deleted keys, committing viafflush+fdatasync+ checkedfclose, swapping viarenameat(), and hardening viafsync(dir_fd).
14. Solutions & Explanations
- Guided Question 1:
fdatasync(fd)only persistsfd's own data blocks and size metadata; syncing the parent directory (fsync(dfd)) on initial creation commits the directory entry so the newly created WAL file cannot vanish across power loss. - Guided Question 2: Because
_IOFBFcoalesces the16-byte header,<= 64-byte key, and<= 256-byte value (<= 336bytes<< BUFSIZ) into onewrite()syscall insidefflush(fp),O_APPENDpositionski_pos = i_sizeand copies the entire frame atomically underinode->i_rwsem!
Run locally in your terminal and check off each verification milestone.
Not started
Full-Course Synthesis & Bridge to GL-C02
Trace how every layer in mini_wal_demo reinforced the others: O_CLOEXEC prevented handle leaks, subtraction bounds (off_t)(h.klen + h.vlen) > st.st_size - off - hsz prevented signed off_t overflow UB, h.seq == exp_seq caught the recycled stale frame even though its CRC32 was valid, ftruncate(fd, off) + lseek(fd, off, SEEK_SET) healed both i_size and f_pos, and pread() served "1200mV" without disturbing the writer cursor!
Next in the Series — GL-C02: Filesystems, Signals, Processes & Threads: Later: In Course 2 (GL-C02: linux-c-proc-threads), you will build on these VFS descriptor and durability foundations to master directory trees (opendir/readdir, statx), asynchronous POSIX signals (sigaction, signal masks), multi-process execution (fork, execve, waitpid), and pthread mutex/condvar concurrency!
Guided Practice: Adding Tombstone (DELETE) Records to an Append-Only WAL
How do append-only WAL engines delete a key like "pll_hz" without erasing or mutating earlier frames in place?
- Step 1 (Encode a tombstone sentinel): Reserve
vlen == UINT32_MAX(with0payload value bytes on disk,frame_bytes = 24 + klen) or a 1-bitopflag inside the header covered byframe_crc(). - Step 2 (Update the in-memory offset index): During sequential replay in
main(), whenever a valid tombstone frame for"pll_hz"arrives, set its index entry toval_off = -1(deleted), soGETreturnsENOENTwhile historical frames remain immutable!
Independent Practice: Atomic WAL Log Compaction (compact_wal_at)
Over months of updates, an append-only WAL accumulates superseded frames. Write a C11 compaction routine int compact_wal_at(int dfd, const char *wal_name) that replays wal_name to build the live latest-key map, writes only live keys (seq = 1..K) into a fresh exclusive staging file via openat(dfd, "wal.compact.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644), flushes via fdatasync(tfd) + checked close(tfd), atomically swaps via renameat(dfd, "wal.compact.tmp", dfd, wal_name), and commits fsync(dfd).
Common Production Pitfalls
warning: Symptom: Computing a WAL frame's CRC32 over key and val bytes while excluding klen, vlen, and seq lets a corrupted length field shift frame boundaries or trigger gigabyte malloc() calls! Root Cause: Unchecksummed header lengths allow bit-flips in klen/vlen to reinterpret payload bytes as adjacent headers. Fix: Enforce strict upper caps on klen and vlen before reading payloads, and include seq, klen, vlen, key, and val inside the CRC32 envelope.
warning: Symptom: After ftruncate(fd, valid_off) heals a 145-byte crashed WAL back to 105 bytes, the next write() (on a non-O_APPEND handle) injects a 40-byte zero hole at [105..144]! Root Cause: ftruncate() updates inode->i_size to 105 without moving struct file.f_pos down from 145. Fix: Call lseek(fd, valid_off, SEEK_SET) immediately after ftruncate() (or write via O_APPEND / explicit pwrite() offsets).
Knowledge Check
Key takeaways
- A crash-safe Write-Ahead Log unites
O_CLOEXEChandle hygiene, binary length-prefixedCRC32framing,fdatasync()+ directoryfsync()barriers,ftruncate()torn-tail healing, and statelesspread()indexed reads. - Reflected IEEE 802.3
CRC32(0xEDB88320U) processes bitsLSB-first using the branchless mask-(crc & 1U)over[seq, klen, vlen, key, val], while monotonic 64-bitseqprevents stale recycled blocks from replaying. - Append-only immutable frames replace in-place overwrites with sequential tail appends, enabling lock-free
pread()lookups on committed offsets. - With Linux file I/O, VFS descriptor tables,
stdiocodecs, and two-layer durability mastered inGL-C01, you are ready for filesystems, signals, processes, and threads inGL-C02.