Lab 6: Crash-Consistent CRC32 Write-Ahead Log & KV Engine
Master kernel page-cache writeback barriers (fsync, fdatasync, directory sync), sector-aligned O_DIRECT DMA, user-space setvbuf/fflush/fdopen ownership rules, and synthesize a crash-safe CRC32 Write-Ahead Log storage engine.
Prerequisites in this module
What ./check.sh verifies
- Clean C11 build with
-std=c11 -Wall -Wextra -Werrorand zero warnings. - Runtime behavior, exit status, and output match the automated
./check.shassertions.
step 1/15 · inspect starter files and specification
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.
learner@ksa:~/gl-c01/lab-m06ls -lastarter/durable_wal.clearner@ksa:~/gl-c01/lab-m06starter: starter/durable_wal.c
learner@ksa:~/gl-c01/lab-m06$ bat starter/durable_wal.c File: starter/durable_wal.c #define _POSIX_C_SOURCE 200809L #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> enum { WAL_MAGIC = 0x4B57414CU, KEY_CAP = 64, VAL_CAP = 256 }; struct wal_hdr { uint32_t magic; uint32_t crc32; uint32_t key_len; uint32_t val_len; }; /* * STARTER BASELINE (contains intentional durability & recovery bugs): * 1. append leaves crc32 = 0 and omits fflush() + fdatasync() durability barrier. * 2. recover never validates CRC32 or repairs torn tail frames with ftruncate(). * 3. get uses stateful read(), mutating f_pos and stopping on the first match. */ int main(int argc, char **argv) { if (argc < 3) return 2; if (strcmp(argv[1], "append") == 0 && argc == 5) { FILE *fp = fopen(argv[2], "ab"); if (!fp) return 1; struct wal_hdr h = {WAL_MAGIC, 0U, (uint32_t)strlen(argv[3]), (uint32_t)strlen(argv[4])}; fwrite(&h, sizeof(h), 1, fp); fwrite(argv[3], 1, h.key_len, fp); fwrite(argv[4], 1, h.val_len, fp); fclose(fp); printf("COMMIT key=%s bytes=%u\n", argv[3], (unsigned)(sizeof(h) + h.key_len + h.val_len)); return 0; } if (strcmp(argv[1], "recover") == 0 && argc == 3) { struct stat st; if (stat(argv[2], &st) < 0) return 1; printf("RECOVER valid_records=0 truncated_from=%lld to=%lld\n", (long long)st.st_size, (long long)st.st_size); return 0; } if (strcmp(argv[1], "get") == 0 && argc == 4) { int fd = open(argv[2], O_RDONLY); if (fd < 0) return 1; struct wal_hdr h; char k[KEY_CAP + 1]; char v[VAL_CAP + 1]; while (read(fd, &h, sizeof(h)) == (ssize_t)sizeof(h)) { if (h.key_len > KEY_CAP || h.val_len > VAL_CAP) break; if (read(fd, k, h.key_len) != (ssize_t)h.key_len) break; if (read(fd, v, h.val_len) != (ssize_t)h.val_len) break; k[h.key_len] = '\0'; v[h.val_len] = '\0'; if (strcmp(k, argv[3]) == 0) { off_t cur = lseek(fd, 0, SEEK_CUR); close(fd); printf("VALUE %s f_pos=%lld\n", v, (long long)cur); return 0; } } close(fd); printf("NOT_FOUND\n"); return 1; } return 2; }step 2/15 · 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.
step 3/15 · 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).
step 4/15 · 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).
step 5/15 · 5. complete executable commands
Run from labs/lab_m06_durable_wal/:
learner@ksa:~/gl-c01/lab-m06$ 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.
step 6/15 · 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!
step 7/15 · 7. expected output
learner@ksa:~/gl-c01/lab-m06$ 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/5step 8/15 · 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!
step 9/15 · 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.
step 10/15 · 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) |
step 11/15 · 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() |
step 12/15 · 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()?
step 13/15 · 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).
step 14/15 · 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!
step 15/15 · run verification and inspect output
Run the verification command and confirm the output matches the expected contract.
learner@ksa:~/gl-c01/lab-m06./durable_wal append engine.wal boot.mode primary && ./durable_wal append engine.wal boot.mode fallback && ./durable_wal get engine.wal boot.modelearner@ksa:~/gl-c01/lab-m06COMMIT key=boot.mode bytes=32COMMIT key=boot.mode bytes=33VALUE fallback f_pos=0Progressive hints & solution
hint 1
Compare starter/durable_wal.c against the module lessons. Focus first on: Clean C11 build with -std=c11 -Wall -Wextra -Werror and zero warnings.
hint 2
Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.
solution
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/durable_wal.c
learner@ksa:~/gl-c01/lab-m06$ bat files/durable_wal.c File: files/durable_wal.c #define _POSIX_C_SOURCE 200809L #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> enum { WAL_MAGIC = 0x4B57414CU, KEY_CAP = 64, VAL_CAP = 256 }; struct wal_hdr { uint32_t magic; uint32_t crc32; uint32_t key_len; uint32_t val_len; }; static uint32_t crc32_update(uint32_t crc, const void *data, size_t len) { const uint8_t *p = (const uint8_t *)data; for (size_t i = 0; i < len; i++) { crc ^= (uint32_t)p[i]; for (int b = 0; b < 8; b++) { uint32_t mask = -(crc & 1U); crc = (crc >> 1) ^ (0xEDB88320U & mask); } } return crc; } static uint32_t compute_frame_crc(uint32_t klen, uint32_t vlen, const void *key, const void *val) { uint32_t crc = 0xFFFFFFFFU; crc = crc32_update(crc, &klen, sizeof(klen)); crc = crc32_update(crc, &vlen, sizeof(vlen)); crc = crc32_update(crc, key, klen); crc = crc32_update(crc, val, vlen); return crc ^ 0xFFFFFFFFU; } static ssize_t pread_exact(int fd, void *buf, size_t len, off_t off) { uint8_t *p = (uint8_t *)buf; size_t done = 0; while (done < len) { ssize_t n = pread(fd, p + done, len - done, off + (off_t)done); if (n < 0) { if (errno == EINTR) continue; return -1; } if (n == 0) break; done += (size_t)n; } return (ssize_t)done; } static void sync_parent_dir(const char *path) { char dir_buf[512]; const char *slash = strrchr(path, '/'); if (!slash) { snprintf(dir_buf, sizeof(dir_buf), "."); } else if (slash == path) { snprintf(dir_buf, sizeof(dir_buf), "/"); } else { size_t dlen = (size_t)(slash - path); if (dlen >= sizeof(dir_buf)) return; memcpy(dir_buf, path, dlen); dir_buf[dlen] = '\0'; } int dfd = open(dir_buf, O_RDONLY | O_CLOEXEC); if (dfd >= 0) { (void)fsync(dfd); close(dfd); } } static int cmd_append(const char *wal_path, const char *key, const char *val) { size_t klen = strlen(key); size_t vlen = strlen(val); if (klen == 0 || klen > KEY_CAP || vlen > VAL_CAP) return 1; struct stat before_st; int existed = (stat(wal_path, &before_st) == 0); int fd = open(wal_path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644); if (fd < 0) return 1; FILE *fp = fdopen(fd, "wb"); if (!fp) { close(fd); return 1; } struct wal_hdr hdr; hdr.magic = WAL_MAGIC; hdr.key_len = (uint32_t)klen; hdr.val_len = (uint32_t)vlen; hdr.crc32 = compute_frame_crc(hdr.key_len, hdr.val_len, key, val); if (fwrite(&hdr, sizeof(hdr), 1, fp) != 1 || fwrite(key, 1, klen, fp) != klen || (vlen > 0 && fwrite(val, 1, vlen, fp) != vlen)) { fclose(fp); return 1; } if (fflush(fp) != 0) { fclose(fp); return 1; } if (fdatasync(fileno(fp)) < 0) { fclose(fp); return 1; } if (fclose(fp) != 0) return 1; if (!existed) { sync_parent_dir(wal_path); } size_t total = sizeof(hdr) + klen + vlen; printf("COMMIT key=%s bytes=%zu\n", key, total); return 0; } static int cmd_recover(const char *wal_path) { int fd = open(wal_path, O_RDWR | O_CREAT | O_CLOEXEC, 0644); if (fd < 0) return 1; struct stat st; if (fstat(fd, &st) < 0) { close(fd); return 1; } off_t orig_size = st.st_size; off_t valid_off = 0; size_t valid_records = 0; for (;;) { struct wal_hdr hdr; ssize_t hn = pread_exact(fd, &hdr, sizeof(hdr), valid_off); if (hn < 0) { close(fd); return 1; } if (hn == 0) break; if ((size_t)hn < sizeof(hdr)) break; if (hdr.magic != WAL_MAGIC || hdr.key_len == 0 || hdr.key_len > KEY_CAP || hdr.val_len > VAL_CAP) { break; } uint8_t kbuf[KEY_CAP]; uint8_t vbuf[VAL_CAP]; ssize_t kn = pread_exact(fd, kbuf, hdr.key_len, valid_off + (off_t)sizeof(hdr)); if (kn != (ssize_t)hdr.key_len) break; ssize_t vn = pread_exact(fd, vbuf, hdr.val_len, valid_off + (off_t)sizeof(hdr) + (off_t)hdr.key_len); if (vn != (ssize_t)hdr.val_len) break; uint32_t expect_crc = compute_frame_crc(hdr.key_len, hdr.val_len, kbuf, vbuf); if (expect_crc != hdr.crc32) break; valid_off += (off_t)(sizeof(hdr) + hdr.key_len + hdr.val_len); valid_records++; } if (orig_size != valid_off) { if (ftruncate(fd, valid_off) < 0 || fdatasync(fd) < 0) { close(fd); return 1; } } close(fd); printf("RECOVER valid_records=%zu truncated_from=%lld to=%lld\n", valid_records, (long long)orig_size, (long long)valid_off); return 0; } static int cmd_get(const char *wal_path, const char *target_key) { size_t tklen = strlen(target_key); if (tklen == 0 || tklen > KEY_CAP) return 1; int fd = open(wal_path, O_RDONLY | O_CLOEXEC); if (fd < 0) return 1; off_t off = 0; int found = 0; char latest_val[VAL_CAP + 1]; latest_val[0] = '\0'; for (;;) { struct wal_hdr hdr; ssize_t hn = pread_exact(fd, &hdr, sizeof(hdr), off); if (hn <= 0 || (size_t)hn < sizeof(hdr)) break; if (hdr.magic != WAL_MAGIC || hdr.key_len == 0 || hdr.key_len > KEY_CAP || hdr.val_len > VAL_CAP) { break; } char kbuf[KEY_CAP + 1]; char vbuf[VAL_CAP + 1]; if (pread_exact(fd, kbuf, hdr.key_len, off + (off_t)sizeof(hdr)) != (ssize_t)hdr.key_len) { break; } if (pread_exact(fd, vbuf, hdr.val_len, off + (off_t)sizeof(hdr) + (off_t)hdr.key_len) != (ssize_t)hdr.val_len) { break; } if (compute_frame_crc(hdr.key_len, hdr.val_len, kbuf, vbuf) != hdr.crc32) { break; } kbuf[hdr.key_len] = '\0'; vbuf[hdr.val_len] = '\0'; if (hdr.key_len == tklen && memcmp(kbuf, target_key, tklen) == 0) { memcpy(latest_val, vbuf, hdr.val_len + 1); found = 1; } off += (off_t)(sizeof(hdr) + hdr.key_len + hdr.val_len); } off_t cur = lseek(fd, 0, SEEK_CUR); close(fd); if (cur != 0) return 1; if (!found) { printf("NOT_FOUND\n"); return 1; } printf("VALUE %s f_pos=%lld\n", latest_val, (long long)cur); return 0; } int main(int argc, char **argv) { if (argc < 3) return 2; if (strcmp(argv[1], "append") == 0 && argc == 5) { return cmd_append(argv[2], argv[3], argv[4]); } if (strcmp(argv[1], "recover") == 0 && argc == 3) { return cmd_recover(argv[2]); } if (strcmp(argv[1], "get") == 0 && argc == 4) { return cmd_get(argv[2], argv[3]); } return 2; }Run the check
From labs/lab_m06_durable_wal/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:
learner@ksa:~/gl-c01/lab-m06./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 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 semanticsok 4 - truncates torn power-loss tail back to last valid frame boundaryok 5 - detects CRC32 payload corruption, truncates bad frame, and keeps prior commits# pass 5/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
learner@ksa:~/gl-c01/lab-m06./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - flushes and fdatasyncs 3 CRC32-framed WAL commits (95 bytes)not ok 3 - scans WAL statelessly via pread leaving f_pos=0 with latest-wins semantics --- message: 'get returned VALUE primary f_pos=32 , expected VALUE fallback f_pos=0' hint: 'scan records with pread() so f_pos stays 0 and keep updating match until EOF' ...not ok 4 - truncates torn power-loss tail back to last valid frame boundary --- message: 'recover= RECOVER valid_records=0 truncated_from=104 to=104 after_bytes=104 (expected 95)' hint: 'ftruncate(fd, last_valid_offset) and fdatasync(fd) when a trailing header or payload is incomplete' ...not ok 5 - detects CRC32 payload corruption, truncates bad frame, and keeps prior commits --- message: 'recover= RECOVER valid_records=0 truncated_from=135 to=135 after=135 survive= VALUE 30 f_pos=62' hint: 'recompute CRC32 over key+value bytes and ftruncate() at the corrupt frame offset' ...# pass 2/5note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....
inspect harness: check.sh
learner@ksa:~/gl-c01/lab-m06$ bat check.sh File: check.sh #!/bin/sh set -u PASS=0 TOTAL=5 tap_ok() { PASS=$((PASS + 1)) printf 'ok %s - %s\n' "$1" "$2" } tap_not_ok() { msg=$(printf '%s' "$3" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") hnt=$(printf '%s' "$4" | tr "\n\r'" " " | sed "s/ */ /g; s/^ //; s/ \$//") printf 'not ok %s - %s\n' "$1" "$2" printf ' ---\n' printf " message: '%s'\n" "$msg" printf " hint: '%s'\n" "$hnt" printf ' ...\n' } printf 'TAP version 13\n' printf '1..%s\n' "$TOTAL" WORK="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_m06.XXXXXX")" trap 'rm -rf "$WORK"' EXIT BUILT=0 if [ ! -f files/durable_wal.c ]; then tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "missing files/durable_wal.c" \ "place your implementation in files/durable_wal.c" elif gcc -std=c11 -Wall -Wextra -Werror files/durable_wal.c -o "$WORK/durable_wal" 2>"$WORK/gcc.err"; then BUILT=1 tap_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" else tap_not_ok 1 "builds with -std=c11 -Wall -Wextra and no warnings" \ "gcc failed: $(cat "$WORK/gcc.err")" \ "fix all C11 warnings and errors in files/durable_wal.c" fi WAL="$WORK/engine.wal" C1="" C3="" CLEAN_BYTES=0 if [ "$BUILT" -eq 1 ]; then C1="$(timeout 3 "$WORK/durable_wal" append "$WAL" "boot.mode" "primary" 2>/dev/null || true)" timeout 3 "$WORK/durable_wal" append "$WAL" "watchdog.sec" "30" >/dev/null 2>&1 || true C3="$(timeout 3 "$WORK/durable_wal" append "$WAL" "boot.mode" "fallback" 2>/dev/null || true)" [ -f "$WAL" ] && CLEAN_BYTES="$(wc -c < "$WAL" | tr -d ' ')" fi if [ "$C1" = "COMMIT key=boot.mode bytes=32" ] && [ "$C3" = "COMMIT key=boot.mode bytes=33" ] && [ "$CLEAN_BYTES" = "95" ]; then tap_ok 2 "flushes and fdatasyncs 3 CRC32-framed WAL commits (95 bytes)" else tap_not_ok 2 "flushes and fdatasyncs 3 CRC32-framed WAL commits (95 bytes)" \ "c1='${C1:-empty}' c3='${C3:-empty}' wal_bytes=${CLEAN_BYTES} (expected 95)" \ "call fflush(fp) before fdatasync(fileno(fp)) so user-space stdio buffers reach the kernel" fi G_LATEST="" if [ "$BUILT" -eq 1 ] && [ -f "$WAL" ]; then G_LATEST="$(timeout 3 "$WORK/durable_wal" get "$WAL" "boot.mode" 2>/dev/null || true)" fi if [ "$G_LATEST" = "VALUE fallback f_pos=0" ]; then tap_ok 3 "scans WAL statelessly via pread leaving f_pos=0 with latest-wins semantics" else tap_not_ok 3 "scans WAL statelessly via pread leaving f_pos=0 with latest-wins semantics" \ "get returned '${G_LATEST:-empty}', expected 'VALUE fallback f_pos=0'" \ "scan records with pread() so f_pos stays 0 and keep updating match until EOF" fi REC_TORN="" AFTER_TORN=0 TORN_BYTES=0 if [ "$BUILT" -eq 1 ] && [ -f "$WAL" ]; then printf 'TORN_TAIL' >> "$WAL" TORN_BYTES="$(wc -c < "$WAL" | tr -d ' ')" REC_TORN="$(timeout 3 "$WORK/durable_wal" recover "$WAL" 2>/dev/null || true)" AFTER_TORN="$(wc -c < "$WAL" | tr -d ' ')" fi if [ "$TORN_BYTES" -gt 0 ] && [ "$REC_TORN" = "RECOVER valid_records=3 truncated_from=${TORN_BYTES} to=95" ] && [ "$AFTER_TORN" = "95" ]; then tap_ok 4 "truncates torn power-loss tail back to last valid frame boundary" else tap_not_ok 4 "truncates torn power-loss tail back to last valid frame boundary" \ "recover='${REC_TORN:-empty}' after_bytes=${AFTER_TORN} (expected 95)" \ "ftruncate(fd, last_valid_offset) and fdatasync(fd) when a trailing header or payload is incomplete" fi REC_CRC="" AFTER_CRC=0 CORR_SIZE=0 G_SURVIVE="" CORR_GONE=0 if [ "$BUILT" -eq 1 ] && [ -f "$WAL" ]; then timeout 3 "$WORK/durable_wal" append "$WAL" "psu.rail" "12000mV" >/dev/null 2>&1 || true CORR_SIZE="$(wc -c < "$WAL" | tr -d ' ')" if [ "$CORR_SIZE" -gt 95 ]; then printf 'X' | dd of="$WAL" bs=1 seek=$((CORR_SIZE - 1)) conv=notrunc status=none 2>/dev/null || true fi REC_CRC="$(timeout 3 "$WORK/durable_wal" recover "$WAL" 2>/dev/null || true)" AFTER_CRC="$(wc -c < "$WAL" | tr -d ' ')" if ! timeout 3 "$WORK/durable_wal" get "$WAL" "psu.rail" >/dev/null 2>&1; then CORR_GONE=1 fi G_SURVIVE="$(timeout 3 "$WORK/durable_wal" get "$WAL" "watchdog.sec" 2>/dev/null || true)" fi if [ "$CORR_SIZE" -gt 95 ] && [ "$REC_CRC" = "RECOVER valid_records=3 truncated_from=${CORR_SIZE} to=95" ] && [ "$AFTER_CRC" = "95" ] && [ "$CORR_GONE" -eq 1 ] && [ "$G_SURVIVE" = "VALUE 30 f_pos=0" ]; then tap_ok 5 "detects CRC32 payload corruption, truncates bad frame, and keeps prior commits" else tap_not_ok 5 "detects CRC32 payload corruption, truncates bad frame, and keeps prior commits" \ "recover='${REC_CRC:-empty}' after=${AFTER_CRC} survive='${G_SURVIVE:-empty}'" \ "recompute CRC32 over key+value bytes and ftruncate() at the corrupt frame offset" fi printf '# pass %s/%s\n' "$PASS" "$TOTAL" [ "$PASS" -eq "$TOTAL" ]Definition of done
Verification checklist
status: 0/3 checks verified
Troubleshooting
Compiler fails under -Werror on sign conversion or unused args
Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.
./check.sh reports missing files in files/
Invoke ./check.sh from inside labs/lab_m06_durable_wal/ so relative paths to files/ resolve directly.