瀏覽代碼

release: 2.21.6 - the WAL reader resynchronises past a damaged record (bug fix, server only)

- replay skips a record that does not frame, checksum or parse and resumes at
  the next valid one, instead of abandoning the rest of the file (one damaged
  record cost a production replay 160,261 intact ones)
- open()'s max-sequence scan uses the same reader, so damage in the current
  file can no longer make new appends reuse sequence numbers
- open() cuts a torn tail before appending after it

Tests: test_snapshot_durability (six damage cases on real WAL files).
Without the resync, 49 of 199 entries replay.
fszontagh 6 天之前
父節點
當前提交
4d0803cb78

+ 21 - 0
CHANGELOG.md

@@ -12,6 +12,27 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
 
+## 2.21.6 - 2026-11-20 (bug fix, server only)
+
+### Fixed
+- **[server]** ⚠ A damaged WAL record no longer costs the rest of its file.
+  Replay stopped at the first record it could not read: one damaged record (the
+  2.21.5 flush race) made a production replay skip 160,261 intact records
+  behind it. The reader now resynchronises. From a record that does not frame,
+  checksum or parse, it scans forward to the next offset holding a valid
+  record (plausible length, op type, a sequence above the last good one, then
+  the checksum and a full parse), continues from there, and counts what it
+  skipped (`... N skipped past, B bytes` in the per-file line).
+- **[server]** The WAL's open scan (which finds the highest sequence number)
+  had the same fail-stop. Damage in the current file made it stop early, and
+  new writes then reused sequence numbers already on disk. It now uses the
+  same resynchronising reader.
+- **[server]** After a crash mid-write, the next process appended after the
+  half-written record, leaving a damaged record in the middle of the file.
+  Opening the WAL now cuts such a torn tail (bytes after the last valid record
+  that no resync can parse) before appending (`WAL: cut a torn tail of N
+  byte(s)`, WARN).
+
 ## 2.21.5 - 2026-11-20 (bug fix, server only)
 
 ### Fixed

文件差異過大導致無法顯示
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.21.5
+2.21.6

+ 3 - 7
docs/ROADMAP.md

@@ -432,13 +432,9 @@ service. Report, then an operator decision per row.
 
 **Cause found and fixed in 2.21.5:** `WriteAheadLog::sync()` flushed the stream
 without the write lock, and the race damaged one record in a production WAL
-file. Replay stops at a damaged record, so 160,261 intact records behind it
-were never applied (see CLAUDE.md v2.21.5). **Still open: a resynchronising
-reader.** On an unreadable record, scan forward for the next offset whose
-length, sequence (above the last good one), op type and checksum all hold, and
-continue from there, logging what was skipped. The same applies to `open()`'s
-max-sequence scan: a damaged CURRENT file would make it stop early and new
-appends reuse sequence numbers, which a later replay would mis-order.
+file. **The amplifier is fixed in 2.21.6:** the reader resynchronises past a
+damaged record, `open()`'s max-sequence scan uses the same reader, and a torn
+tail is cut before appending. Closed.
 
 **Also open, a surface for a stalled snapshot.** A snapshot failing every two
 minutes for two weeks logged 16,586 ERROR lines and nobody read them. Expose

+ 7 - 0
docs/integration-guide.md

@@ -2715,6 +2715,13 @@ unreadable, sequences go backwards, or fewer bytes were read than the file
 holds. Before 2.21.4 all of these were skipped without a trace. Report any
 such WARN.
 
+**A damaged record costs only itself (2.21.6+).** Up to 2.21.5 replay stopped
+at the first record it could not read, so every record behind it in that file
+was lost. Now the reader skips the damaged bytes, resumes at the next valid
+record, and says so in the file's line (`... 1 unreadable (...; 1 skipped
+past, 587 bytes)`). After a crash mid-write the half-written last record is
+cut before new writes are appended (`WAL: cut a torn tail of N byte(s)`).
+
 **Memory behind disk after a replay (2.21.4+; use 2.21.5).** If a replay
 applies fewer entries than it should, memory keeps older versions of rows that
 LMDB has newer copies of. Reads are still right, because they are served from

+ 10 - 5
service/src/persistence/persistence_manager.cpp

@@ -217,6 +217,11 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
             outcome.failureReason = "Failed to open WAL for replay";
             return false;
         }
+        if (const uint64_t cut = wal_->lastOpenTruncatedBytes()) {
+            spdlog::warn("WAL: cut a torn tail of {} byte(s) from {} (a record a crash left "
+                         "half-written; appending after it would damage the file)",
+                         cut, "wal-current.log");
+        }
         // v2.11.0 T12 review (I1) — track every (collection, id) applied as
         // INSERT/UPDATE/UPSERT during this replay, deduplicated, so it can be
         // explicitly re-mirrored to LMDB once replay finishes. Erased again
@@ -298,13 +303,13 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
                                  f.outOfOrder > 0;
             const std::string line = fmt::format(
                 "WAL file {}: {} applied, {} already in the snapshot, {} unreadable "
-                "({} checksum, first at byte {}), {} out of sequence order, "
-                "sequences {}-{}, read {} of {} bytes{}",
+                "({} checksum, first at byte {}; {} skipped past, {} bytes), "
+                "{} out of sequence order, sequences {}-{}, read {} of {} bytes{}",
                 f.path.filename().string(), f.applied, f.atOrBelow, f.unreadable,
-                f.checksumFailures, f.firstUnreadableOffset, f.outOfOrder,
-                f.firstSequence, f.lastSequence, f.bytesRead, f.fileBytes,
+                f.checksumFailures, f.firstUnreadableOffset, f.resynced, f.skippedBytes,
+                f.outOfOrder, f.firstSequence, f.lastSequence, f.bytesRead, f.fileBytes,
                 !f.headerReadable ? " (HEADER UNREADABLE, file skipped)"
-                : endedEarly      ? " (ended early: a torn or zeroed record)" : "");
+                : endedEarly      ? " (a torn tail after the last valid record)" : "");
             if (suspect) spdlog::warn("{}", line); else spdlog::info("{}", line);
         }
 

+ 143 - 76
service/src/persistence/wal.cpp

@@ -9,6 +9,8 @@
 #include <sstream>
 
 #include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
 #include <unistd.h>
 
 namespace smartbotic::database {
@@ -333,33 +335,24 @@ bool WriteAheadLog::open() {
         return false;
     }
 
-    // Find existing WAL files and determine highest sequence
+    // Find existing WAL files and determine highest sequence.
+    // v2.21.6 - through scanFile: the old loop stopped at the first record it
+    // could not read, so damage in the current file made the sequence too low
+    // and new appends reused sequence numbers already on disk.
     auto walFiles = getWalFiles();
-    if (!walFiles.empty()) {
-        // Read the last file to get the highest sequence
-        for (auto it = walFiles.rbegin(); it != walFiles.rend(); ++it) {
-            std::ifstream file(*it, std::ios::binary);
-            if (!file) continue;
-
-            auto header = readHeader(file);
-            if (!header) continue;
-
-            // Read entries to find highest sequence
-            while (file) {
-                uint32_t length;
-                file.read(reinterpret_cast<char*>(&length), 4);
-                if (!file || length == 0) break;
-
-                std::vector<uint8_t> entryData(length + 4);
-                std::memcpy(entryData.data(), &length, 4);
-                file.read(reinterpret_cast<char*>(entryData.data() + 4), length);
-                if (!file) break;
-
-                auto entry = WalEntry::deserialize(entryData);
-                if (entry && entry->sequence > sequence_.load()) {
-                    sequence_.store(entry->sequence);
-                }
-            }
+    lastOpenTruncatedBytes_ = 0;
+    for (const auto& path : walFiles) {
+        ReplayFileStats stats;
+        scanFile(path, [this](const WalEntry& entry) {
+            if (entry.sequence > sequence_.load()) sequence_.store(entry.sequence);
+        }, stats);
+        // A torn tail of the file appends go to (a crash mid-write): appending
+        // after it would leave a damaged record in the middle of the file.
+        // Cut it at the end of the last valid record.
+        if (path == currentFilePath() && stats.headerReadable && stats.bytesRead < stats.fileBytes) {
+            std::error_code rec;
+            std::filesystem::resize_file(path, stats.bytesRead, rec);
+            if (!rec) lastOpenTruncatedBytes_ = stats.fileBytes - stats.bytesRead;
         }
     }
 
@@ -740,67 +733,141 @@ void WriteAheadLog::writeHeader() {
     currentFile_.flush();
 }
 
-uint64_t WriteAheadLog::replayFile(const std::filesystem::path& path, uint64_t fromSequence,
-                                    const std::function<void(const WalEntry&)>& callback,
-                                    ReplayFileStats& stats) {
+namespace {
+// seq, timestamp, op, collection len, id len, data flag, options flag, crc
+constexpr uint32_t kMinRecordBody = 8 + 8 + 1 + 2 + 2 + 1 + 1 + 4;
+constexpr uint32_t kMaxRecordBody = 1u << 30;
+// A resync candidate's sequence must lie within this distance above the last
+// good one: a cheap filter before the checksum, generous enough for any WAL.
+constexpr uint64_t kMaxSequenceGap = 100'000'000ULL;
+
+uint32_t le32(const uint8_t* p) {
+    return static_cast<uint32_t>(p[0]) | static_cast<uint32_t>(p[1]) << 8 |
+           static_cast<uint32_t>(p[2]) << 16 | static_cast<uint32_t>(p[3]) << 24;
+}
+uint64_t le64(const uint8_t* p) {
+    uint64_t v = 0;
+    for (int i = 7; i >= 0; --i) v = (v << 8) | p[i];
+    return v;
+}
+
+// The record at `off` if it frames, checksums and parses; nullopt otherwise.
+std::optional<WalEntry> recordAt(const uint8_t* base, uint64_t size, uint64_t off,
+                                 uint32_t& lenOut) {
+    if (off + 4 > size) return std::nullopt;
+    const uint32_t len = le32(base + off);
+    if (len < kMinRecordBody || len > kMaxRecordBody || off + 4 + len > size) return std::nullopt;
+    std::vector<uint8_t> rec(base + off, base + off + 4 + len);
+    auto e = WalEntry::deserialize(rec);
+    if (e) lenOut = len;
+    return e;
+}
+
+// Read-only mapping of a whole file, unmapped on scope exit.
+struct MappedFile {
+    const uint8_t* data = nullptr;
+    uint64_t size = 0;
+    explicit MappedFile(const std::filesystem::path& path) {
+        const int fd = ::open(path.c_str(), O_RDONLY);
+        if (fd < 0) return;
+        struct stat st {};
+        if (::fstat(fd, &st) == 0 && st.st_size > 0) {
+            void* p = ::mmap(nullptr, static_cast<size_t>(st.st_size), PROT_READ, MAP_PRIVATE, fd, 0);
+            if (p != MAP_FAILED) {
+                data = static_cast<const uint8_t*>(p);
+                size = static_cast<uint64_t>(st.st_size);
+            }
+        }
+        ::close(fd);
+    }
+    ~MappedFile() {
+        if (data) ::munmap(const_cast<uint8_t*>(data), static_cast<size_t>(size));
+    }
+    MappedFile(const MappedFile&) = delete;
+    MappedFile& operator=(const MappedFile&) = delete;
+};
+}  // namespace
+
+// v2.21.6 - the one reader of a WAL file, for replay() and open() alike.
+//
+// It used to stop at the first record it could not read: a production file
+// had ONE damaged record (the 2.21.5 flush race) and the 160,261 intact
+// records behind it were never applied. Now a record that does not frame,
+// checksum or parse starts a resync: the scan moves forward a byte at a time
+// to the next offset holding a record that does - a plausible length, an op
+// type in range and a sequence above the last good one (cheap filters), then
+// the checksum and a full parse, which a random offset passes with
+// negligible probability. What was skipped is counted. Bytes after the last
+// valid record that no resync can parse (a torn tail) end the file;
+// `stats.bytesRead` is then the end of the last valid record.
+void WriteAheadLog::scanFile(const std::filesystem::path& path,
+                             const std::function<void(const WalEntry&)>& onEntry,
+                             ReplayFileStats& stats) {
+    MappedFile f(path);
     std::error_code size_ec;
     stats.fileBytes = std::filesystem::file_size(path, size_ec);
-    std::ifstream file(path, std::ios::binary);
-    if (!file) {
+    if (!f.data || f.size < sizeof(Header) || std::memcmp(f.data, "CALWAL01", 8) != 0) {
         stats.headerReadable = false;
-        return 0;
+        return;
     }
+    const uint64_t start = le64(f.data + 8);
+    uint64_t floor = start > 0 ? start - 1 : 0;   // sequences here are above it
+    uint64_t off = sizeof(Header);
+    stats.bytesRead = off;
+
+    while (off < f.size) {
+        uint32_t len = 0;
+        if (auto e = recordAt(f.data, f.size, off, len)) {
+            if (stats.firstSequence == 0) stats.firstSequence = e->sequence;
+            else if (e->sequence <= stats.lastSequence) ++stats.outOfOrder;
+            stats.lastSequence = e->sequence;
+            if (e->sequence > floor) floor = e->sequence;
+            onEntry(*e);
+            off += 4 + static_cast<uint64_t>(len);
+            stats.bytesRead = off;
+            continue;
+        }
 
-    auto header = readHeader(file);
-    if (!header) {
-        stats.headerReadable = false;
-        return 0;
+        // Damaged at `off`.
+        ++stats.unreadable;
+        if (stats.firstUnreadableOffset == 0) stats.firstUnreadableOffset = off;
+        if (off + 4 <= f.size) {
+            const uint32_t l = le32(f.data + off);
+            if (l >= kMinRecordBody && l <= kMaxRecordBody && off + 4 + l <= f.size &&
+                le32(f.data + off + l) != crc32::calculate(f.data + off + 4, l - 4)) {
+                ++stats.checksumFailures;
+            }
+        }
+        uint64_t c = off + 1;
+        bool found = false;
+        for (; c + 4 + kMinRecordBody <= f.size; ++c) {
+            const uint8_t op = f.data[c + 4 + 16];
+            if (op < static_cast<uint8_t>(WalOpType::INSERT) ||
+                op > static_cast<uint8_t>(WalOpType::VEC_DELETE)) continue;
+            const uint64_t seq = le64(f.data + c + 4);
+            if (seq <= floor || seq > floor + kMaxSequenceGap) continue;
+            uint32_t l2 = 0;
+            if (recordAt(f.data, f.size, c, l2)) { found = true; break; }
+        }
+        if (!found) break;   // nothing valid follows: a torn tail
+        stats.skippedBytes += c - off;
+        ++stats.resynced;
+        off = c;
     }
-    stats.bytesRead = static_cast<uint64_t>(file.tellg());
+}
 
+uint64_t WriteAheadLog::replayFile(const std::filesystem::path& path, uint64_t fromSequence,
+                                    const std::function<void(const WalEntry&)>& callback,
+                                    ReplayFileStats& stats) {
     uint64_t count = 0;
-
-    while (file) {
-        // Read entry length
-        uint32_t length;
-        file.read(reinterpret_cast<char*>(&length), 4);
-        if (!file || length == 0) break;
-
-        // Read entry data
-        std::vector<uint8_t> entryData(length + 4);
-        std::memcpy(entryData.data(), &length, 4);
-        file.read(reinterpret_cast<char*>(entryData.data() + 4), length);
-        if (!file) break;
-        const uint64_t entryOffset = stats.bytesRead;
-        stats.bytesRead += 4 + static_cast<uint64_t>(length);
-
-        // Deserialize and invoke callback
-        auto entry = WalEntry::deserialize(entryData);
-        if (!entry) {
-            ++stats.unreadable;
-            if (stats.firstUnreadableOffset == 0) stats.firstUnreadableOffset = entryOffset;
-            if (length >= 4) {
-                uint32_t stored = 0;
-                for (int i = 0; i < 4; ++i) {
-                    stored |= static_cast<uint32_t>(entryData[entryData.size() - 4 + i]) << (i * 8);
-                }
-                if (stored != crc32::calculate(entryData.data() + 4, length - 4)) {
-                    ++stats.checksumFailures;
-                }
-            }
-            continue;
-        }
-        if (stats.firstSequence == 0) stats.firstSequence = entry->sequence;
-        else if (entry->sequence <= stats.lastSequence) ++stats.outOfOrder;
-        stats.lastSequence = entry->sequence;
-        if (entry->sequence > fromSequence) {
-            callback(*entry);
-            count++;
+    scanFile(path, [&](const WalEntry& entry) {
+        if (entry.sequence > fromSequence) {
+            callback(entry);
+            ++count;
         } else {
             ++stats.atOrBelow;
         }
-    }
-
+    }, stats);
     stats.applied = count;
     return count;
 }

+ 11 - 0
service/src/persistence/wal.hpp

@@ -135,6 +135,8 @@ public:
         uint64_t checksumFailures = 0;   // of `unreadable`
         uint64_t firstUnreadableOffset = 0;  // byte offset, 0 = none
         uint64_t outOfOrder = 0;     // sequence not above the previous entry's
+        uint64_t resynced = 0;       // v2.21.6: damaged regions skipped, reading resumed
+        uint64_t skippedBytes = 0;   // bytes in those regions
         uint64_t firstSequence = 0;  // of readable entries, 0 = none
         uint64_t lastSequence = 0;
         uint64_t bytesRead = 0;      // header + every entry read
@@ -142,6 +144,9 @@ public:
     };
     std::vector<ReplayFileStats> lastReplayStats() const;
 
+    /** v2.21.6 - bytes of a torn tail the last open() cut from the current file. */
+    uint64_t lastOpenTruncatedBytes() const { return lastOpenTruncatedBytes_; }
+
     /**
      * Get the current sequence number.
      */
@@ -243,6 +248,11 @@ private:
     // fsync the current file by path (std::ofstream has no fd); no lock.
     void fsyncCurrentFile();
 
+    // v2.21.6 - every valid record of a file, resynchronising past damage.
+    static void scanFile(const std::filesystem::path& path,
+                         const std::function<void(const WalEntry&)>& onEntry,
+                         ReplayFileStats& stats);
+
     // Read entries from a file
     uint64_t replayFile(const std::filesystem::path& path, uint64_t fromSequence,
                         const std::function<void(const WalEntry&)>& callback,
@@ -251,6 +261,7 @@ private:
     // document's read, replication), so the record is guarded.
     mutable std::mutex replayStatsMutex_;
     std::vector<ReplayFileStats> lastReplayStats_;
+    uint64_t lastOpenTruncatedBytes_ = 0;
 
     Config config_;
     std::atomic<bool> isOpen_{false};

+ 172 - 0
tests/test_snapshot_durability.cpp

@@ -21,10 +21,12 @@
 #include <cassert>
 #include <chrono>
 #include <cstdint>
+#include <cstring>
 #include <filesystem>
 #include <fstream>
 #include <iostream>
 #include <nlohmann/json.hpp>
+#include <set>
 #include <thread>
 #include <unistd.h>  // getpid
 #include <unordered_set>
@@ -336,6 +338,175 @@ void test_wal_append_races_sync() {
     std::cout << "PASS: WAL entries survive appends racing sync()\n";
 }
 
+// v2.21.6 - the WAL reader resynchronises past a damaged record instead of
+// abandoning the rest of the file (a production file lost 160,261 intact
+// records behind one damaged one). Each case damages a real WAL file and
+// checks exactly which entries come back.
+namespace walresync {
+using smartbotic::database::WriteAheadLog;
+using smartbotic::database::WalEntry;
+constexpr int kN = 200;
+
+std::vector<uint8_t> readAll(const fs::path& p) {
+    std::ifstream in(p, std::ios::binary);
+    return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
+}
+void writeAll(const fs::path& p, const std::vector<uint8_t>& b) {
+    std::ofstream out(p, std::ios::binary | std::ios::trunc);
+    out.write(reinterpret_cast<const char*>(b.data()), static_cast<std::streamsize>(b.size()));
+}
+// Record start offsets (the header is 16 bytes, each record is len + body).
+std::vector<size_t> offsets(const std::vector<uint8_t>& b) {
+    std::vector<size_t> o;
+    size_t off = 16;
+    while (off + 4 <= b.size()) {
+        uint32_t len = 0;
+        std::memcpy(&len, &b[off], 4);
+        o.push_back(off);
+        off += 4 + len;
+    }
+    return o;
+}
+fs::path makeWal(const std::string& name, WriteAheadLog::Config& cfg) {
+    auto dir = makeSnapshotDir(name);
+    cfg.walDir = dir;
+    WriteAheadLog wal(cfg);
+    assert(wal.open());
+    for (int i = 0; i < kN; ++i) {
+        Document d;
+        d.id = "d" + std::to_string(i);
+        d.set_data(nlohmann::json{{"i", i}, {"pad", std::string(100 + (i * 7) % 90, 'q')}});
+        wal.append(WriteAheadLog::makeInsertEntry("t", d, "n"));
+    }
+    wal.close();
+    return dir / "wal-current.log";
+}
+// Replays the WAL; returns the sequences seen and the file's stats.
+std::vector<uint64_t> replayAll(WriteAheadLog::Config& cfg, WriteAheadLog::ReplayFileStats& st) {
+    WriteAheadLog wal(cfg);
+    std::vector<uint64_t> seqs;
+    wal.replay(0, [&](const WalEntry& e) { seqs.push_back(e.sequence); });
+    st = wal.lastReplayStats().at(0);
+    return seqs;
+}
+bool missingOnly(const std::vector<uint64_t>& seqs, const std::set<uint64_t>& lost) {
+    std::vector<uint64_t> want;
+    for (uint64_t s = 1; s <= kN; ++s) if (!lost.count(s)) want.push_back(s);
+    if (seqs != want) {
+        std::cerr << "got " << seqs.size() << " entries, want " << want.size() << "\n";
+        return false;
+    }
+    return true;
+}
+}  // namespace walresync
+
+void test_wal_reader_resyncs_past_damage() {
+    using namespace walresync;
+    // A: one byte deleted inside record 50 (the production shape: the record is
+    // a byte shorter than its length prefix, so everything after it misframes).
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-delete", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        b.erase(b.begin() + static_cast<long>(o[49] + 30));
+        writeAll(p, b);
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(missingOnly(seqs, {50}));
+        assert(st.unreadable == 1 && st.resynced == 1);
+    }
+    // B: one byte flipped inside record 120's data (length intact, checksum fails).
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-flip", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        b[o[119] + 40] ^= 0x5a;
+        writeAll(p, b);
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(missingOnly(seqs, {120}));
+        assert(st.checksumFailures == 1);
+    }
+    // C: record 10's length prefix replaced by garbage.
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-length", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        b[o[9]] = 0xf0; b[o[9] + 1] = 0xff; b[o[9] + 2] = 0xff; b[o[9] + 3] = 0x7f;
+        writeAll(p, b);
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(missingOnly(seqs, {10}));
+    }
+    // D: 1,000 bytes zeroed from the middle of record 80: exactly the records
+    // the region touches are lost.
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-zero", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        const size_t from = o[79] + 20, to = from + 1000;
+        std::set<uint64_t> lost;
+        for (size_t k = 0; k < o.size(); ++k) {
+            const size_t end = k + 1 < o.size() ? o[k + 1] : b.size();
+            if (o[k] < to && end > from) lost.insert(k + 1);
+        }
+        std::fill(b.begin() + static_cast<long>(from), b.begin() + static_cast<long>(to), 0);
+        writeAll(p, b);
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(lost.size() >= 3);
+        assert(missingOnly(seqs, lost));
+    }
+    // E: a torn tail (a crash mid-write): open() cuts it, the sequence continues
+    // from the last valid record, and an append after it is readable.
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-torn", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        b.resize(o.back() + 25);   // record 200 half-written
+        writeAll(p, b);
+        {
+            WriteAheadLog wal(cfg);
+            assert(wal.open());
+            assert(wal.lastOpenTruncatedBytes() == 25);
+            assert(wal.currentSequence() == kN - 1);
+            Document d;
+            d.id = "after";
+            d.set_data(nlohmann::json{{"x", 1}});
+            assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN);
+            wal.close();
+        }
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(seqs.size() == static_cast<size_t>(kN) && seqs.back() == kN);
+        assert(st.unreadable == 0 && st.bytesRead == st.fileBytes);
+    }
+    // F: damage in the current file before a reopen: the highest sequence is
+    // still found, so a new append does not reuse one already on disk.
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-reopen", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        b.erase(b.begin() + static_cast<long>(o[29] + 30));
+        writeAll(p, b);
+        WriteAheadLog wal(cfg);
+        assert(wal.open());
+        assert(wal.currentSequence() == kN);
+        Document d;
+        d.id = "next";
+        d.set_data(nlohmann::json{{"x", 1}});
+        assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN + 1);
+        wal.close();
+    }
+    std::cout << "PASS: WAL reader resynchronises past damaged records\n";
+}
+
 // ──────────────────────────────────────────────────────────
 // Test 6: loadWithFallback throws when all snapshots corrupt
 // ──────────────────────────────────────────────────────────
@@ -933,6 +1104,7 @@ int main() {
     test_orphaned_tmp_cleaned_by_listSnapshots();
     test_snapshot_survives_concurrent_listing();
     test_wal_append_races_sync();
+    test_wal_reader_resyncs_past_damage();
     test_loadWithFallback_throws_when_all_corrupt();
     test_v4_format_roundtrip_at_scale();
     test_wal_sequence_floor_anchors_after_truncate();

部分文件因文件數量過多而無法顯示