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.

25 minfree previewLinux 6.12C11glibc 2.39→ module 6 lab
What you'll learn
  • Construct self-describing binary Write-Ahead Log frames with magic bytes, 64-bit seq epochs, lengths, and IEEE CRC32.
  • 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 SynthesizedExact Primitive Inside WAL EngineStorage 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 loopLeak-safe handle; immune to EINTR & short writes
m03 — VFS & fstatfstat(fd, &st) logical st_size, saved_errno cleanupBounds recovery scan to exact inode byte size
m04 — Atomicity & ResizeStateless pread() index reads + ftruncate(fd, valid_off)Lock-free concurrent GETs + atomic torn-tail heal
m05 — Safe DiagnosticsBounded key/value length caps + %lld / PRIu64 reportsZero stack overruns on corrupted length headers
m06 — Durabilityfdatasync(fd) per commit + fsync(dir_fd) on creationCommitted frames survive power loss & SIGKILL
fig_m06_l03_arch.svg — ABI-locked 24-byte CRC32+seq WAL frame layout,…

Figure 6.3. ABI-locked 24-byte CRC32+seq WAL frame layout, recycled-tail ftruncate() crash healing, and lock-free pread() indexing.

step_m06_l03.svg — Seal immutable WAL frames with branchless CRC32 +…step 1/4
  1. Step 1. Seal [seq, klen, vlen, key, val] inside a 24-byte header with branchless CRC32 and commit via write_all() + fdatasync().
  2. Step 2. Replay sequentially from offset 0 checking WAL_MAGIC, h.seq == exp_seq, subtraction bounds, and CRC32.
  3. Step 3. Snip stale recycled frames or torn crash tails via ftruncate(fd, off) + fdatasync(fd) + lseek(fd, off, SEEK_SET).
  4. 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
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;    }
  1. Branchless reflected IEEE 802.3 CRC32 step: -(crc & 1U) masks 0xEDB88320U without conditional branch mispredictions.
  2. Include seq, klen, vlen, key, and val inside frame_crc() and finish with fdatasync(fd) before acknowledging wal_put().
  3. 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-l03
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

Lab 6 Capstone: Crash-Consistent CRC32 Write-Ahead Log & KV Engine

env: host

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

  1. Commit length-prefixed, IEEE 802.3 CRC32-protected binary frames via the complete two-stage durability barrier (fwrite -> fflush -> fdatasync(fileno(fp)) -> single-owner fclose, plus parent-directory fsync on initial creation).
  2. Recover crashed logs deterministically by scanning frames from offset 0 via stateless pread(), detecting torn headers, torn payloads, or single-bit CRC32 corruptions, and healing the file via ftruncate(fd, valid_offset) + fdatasync(fd).
  3. Serve log-structured latest-wins get queries via pread() while proving struct file.f_pos remains untouched at 0.

3. Environment Requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+), #define _POSIX_C_SOURCE 200809L and #define _FILE_OFFSET_BITS 64.
  • Target Board Portability (ARMv7 Cortex-A7): The 16-byte struct wal_hdr (magic, crc32, key_len, val_len), branchless reflected 0xEDB88320U CRC32, and pread/ftruncate/fdatasync calls behave identically on embedded ARMv7 ext4/f2fs partitions (where fdatasync() 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 (tmpfs or NVMe/SSD filesystem).

5. Complete Executable Commands

Run from labs/lab_m06_durable_wal/:

learner@ksa: ~/gl-c01/m06-l03
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)

  1. Zero durability & fake checksum (append): Writes crc32 = 0U, omits O_CLOEXEC, and omits fflush() + fdatasync() + parent directory fsync().
  2. No-op recover: Prints st.st_size without reading headers, recomputing CRC32, or calling ftruncate().
  3. Stateful first-match get: Uses read() (advancing f_pos to 32) and returns on the first matching key ("primary") instead of scanning to EOF for latest-wins ("fallback").

Warning-Clean Reference (files/durable_wal.c)

  • Branchless IEEE 802.3 CRC32 (crc32_update / compute_frame_crc): Computes uint32_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): Opens O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC (0644), transfers ownership to fdopen(fd, "wb"), runs fwrite -> fflush(fp) -> fdatasync(fileno(fp)) -> single fclose(fp), and calls sync_parent_dir(wal_path) when creating a brand-new WAL file.
  • Stateless Recovery & Lookup (cmd_recover, cmd_get): Uses pread_exact() from off = 0, validates WAL_MAGIC, bounds (1 <= key_len <= 64, val_len <= 256), full payload availability, and expect_crc == hdr.crc32, heals mismatches via ftruncate(fd, valid_off) + fdatasync(fd), and updates latest_val across all valid frames while lseek(fd, 0, SEEK_CUR) stays 0!

7. Expected Output

learner@ksa: ~/gl-c01/m06-l03
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/5

8. 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

  1. Single-Write Coalescing Optimization: Coalesce [hdr, key, val] into one stack uint8_t frame[16 + KEY_CAP + VAL_CAP] buffer before fwrite() (or use writev()), confirming under strace that fflush(fp) already coalesces the three fwrite() calls into one write() syscall thanks to _IOFBF!
  2. Header Length Bit-Flip Test: Flip 1 bit inside hdr.key_len (changing 5 to 37 within <= 64) on a 4th frame and verify that including key_len inside compute_frame_crc() catches the corruption even if 95 + 16 + 37 <= st_size.
  3. 256-entry CRC32 Lookup Table: Precompute a uint32_t crc_tab[256] table inside an __attribute__((constructor)) or static const array (1 table lookup per byte instead of 8 bit loops) and compare CPU throughput on 1 MiB payloads.

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):

MetricMeasured 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 append1 openat + 1 write + 1 fdatasync + 1 closeIdentical 4-syscall commit path
Stateless get cursor mutation (f_pos)0 -> 0 (pread64 only)0 -> 0 (pread64 only)

11. Troubleshooting

SymptomRoot CauseFix
EBADF or crashed fd in multithreaded testCalled 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 bytesCalled 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 EOFKeep updating latest_val until the scan reaches the end of valid frames
get prints f_pos=95 instead of f_pos=0Used stateful read()/fread() instead of pread()Read headers and payloads exclusively via pread_exact()

12. Guided Questions

  1. Why does cmd_append() check int existed = (stat(wal_path, &before_st) == 0); and call sync_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.wal if engine.wal's blocks are on NVMe media but the parent directory's new "engine.wal" -> st_ino entry was still in volatile DRAM?
  1. Why does cmd_append() combine O_APPEND on open() with fdopen(fd, "wb")?
  • *Hint 1:* When fflush(fp) drains the Ring 3 buffer via a single write(fd, buf, frame_len) syscall (frame_len <= 336 bytes), what lock does O_APPEND acquire inside Ring 0?
  • *Hint 2:* Why would two separate write() syscalls (header in write #1, payload in write #2) break multi-process O_APPEND atomicity without _IOFBF coalescing them into a single write()?

13. Independent Challenges

  1. Near Transfer — Monotonic 64-Bit Epoch Header & Tombstone Deletes (del <wal_path> <key>): Upgrade struct wal_hdr to 24 bytes by adding uint64_t seq (1, 2, ..., verified during recover to block stale recycled-segment frames as in m06-l03) and uint32_t tombstone (0xFFFFFFFFU val_len sentinel) so del removes keys cleanly without in-place mutation.
  2. Far Transfer — Crash-Safe WAL Compaction (compact <wal_path>): Implement atomic log compaction using directory-pinned openat(..., "wal.compact.tmp", O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644), writing only live non-deleted keys, committing via fflush + fdatasync + checked fclose, swapping via renameat(), and hardening via fsync(dir_fd).

14. Solutions & Explanations

  • Guided Question 1: fdatasync(fd) only persists fd'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 _IOFBF coalesces the 16-byte header, <= 64-byte key, and <= 256-byte value (<= 336 bytes << BUFSIZ) into one write() syscall inside fflush(fp), O_APPEND positions ki_pos = i_size and copies the entire frame atomically under inode->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?

  1. Step 1 (Encode a tombstone sentinel): Reserve vlen == UINT32_MAX (with 0 payload value bytes on disk, frame_bytes = 24 + klen) or a 1-bit op flag inside the header covered by frame_crc().
  2. 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 to val_off = -1 (deleted), so GET returns ENOENT while 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

quiz · 1 of 4

During startup recovery of an append-only WAL, the scanner verifies 3 intact frames ending at byte 105, followed by 11 bytes of a 4th frame cut short by a power outage. What is the exact recovery action?

quiz · 2 of 4

Why does sequential replay of an append-only WAL from offset 0 to valid_off support key updates ("vcore" changing from "1150mV" to "1200mV") without mutating earlier bytes in place?

quiz · 3 of 4

(Review from earlier lesson) Why can reader threads execute pread(fd, buf, vlen, val_off) concurrently on the WAL descriptor while a writer appends new frames at the tail?

quiz · 4 of 4

Why do production WAL engines that recycle preallocated log segments pair reflected IEEE 802.3 CRC32 (0xEDB88320U & -(crc & 1U)) with a strictly monotonic 64-bit seq header field?

Key takeaways

  • A crash-safe Write-Ahead Log unites O_CLOEXEC handle hygiene, binary length-prefixed CRC32 framing, fdatasync() + directory fsync() barriers, ftruncate() torn-tail healing, and stateless pread() indexed reads.
  • Reflected IEEE 802.3 CRC32 (0xEDB88320U) processes bits LSB-first using the branchless mask -(crc & 1U) over [seq, klen, vlen, key, val], while monotonic 64-bit seq prevents 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, stdio codecs, and two-layer durability mastered in GL-C01, you are ready for filesystems, signals, processes, and threads in GL-C02.
Progress is saved on this device.
up next · module 6 labLab: Crash-Consistent CRC32 Write-Ahead Log & KV Engine (90 min)
→ module 6 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure