Browse Source

release: 2.21.5 - WAL flush raced writes; the version audit reloads only LMDB-newer rows (bug fix, server only)

- WriteAheadLog::sync() flushed the stream without the write lock while
  append() wrote under it; one damaged record made replay skip the 160,261
  intact records behind it on a production instance
- the 2.21.4 boot audit replaced rows that were NEWER in memory (old mirror
  failures) with LMDB's older copy; now only LMDB-newer rows are reloaded,
  memory-newer rows are reported with both versions

Tests: test_snapshot_durability (append racing sync), test_stale_memory
(memory-newer row). Each fix reverted fails its test.
fszontagh 6 ngày trước cách đây
mục cha
commit
e4f0c5d892

+ 23 - 0
CHANGELOG.md

@@ -12,6 +12,29 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
 
+## 2.21.5 - 2026-11-20 (bug fix, server only)
+
+### Fixed
+- **[server]** ⚠ The WAL file could be corrupted by a race: `sync()` (the WAL
+  sync thread, every 100 ms, and the flush before a relation cascade) flushed
+  the file stream without the write lock, while writes to the same stream
+  held it. A record could lose or gain a byte. Replay then stopped at that
+  record and skipped every intact record behind it in the file. This is the
+  cause of the 2.21.4 production replay that applied 193,776 of 354,089
+  entries: one damaged record, 160,261 intact ones never applied. Now the
+  flush holds the lock. The fsync runs outside it, on a descriptor opened
+  under it.
+- **[server]** ⚠ The 2.21.4 boot version audit reloaded from LMDB every row
+  whose `_version` or `_updated_at` differed, on the premise that LMDB is
+  always the newer side. It is not: a store with old mirror failures (before
+  2.21.0 they were not recorded) has rows where memory holds a write LMDB
+  missed, and 2.21.4 replaced that newer copy with LMDB's older one. Found by
+  staging 2.21.4 on a real backup: 4 of 5 sampled rows were newer in memory.
+  The audit now reloads a row only when LMDB's copy is newer (later
+  `_updated_at`, then higher `_version`). Rows newer in memory are left alone
+  and reported (`... are NEWER than LMDB's copy, left in memory`). Both
+  versions are logged for the first five rows of each kind.
+
 ## 2.21.4 - 2026-11-20 (bug fix, server only)
 
 ### Fixed

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.21.4
+2.21.5

+ 9 - 12
docs/ROADMAP.md

@@ -430,18 +430,15 @@ service. Report, then an operator decision per row.
 
 ### 5g. ⚠ A WAL replay that applied fewer entries than it should (found 2026-11-20)
 
-A production boot (2.21.2, after a 15-day snapshot stall, see CLAUDE.md
-v2.21.4) replayed 193,776 of the 354,089 entries above its snapshot. The WAL
-files were contiguous by their headers and none had a torn tail; the count
-was close to the middle file alone. **Cause not established.** 2.21.4 makes the
-consequence safe (the boot version audit reloads stale rows from LMDB) and
-makes the next occurrence visible: each WAL file's replay line reports
-unreadable entries (checksum vs format, first byte offset), entries out of
-sequence order, and bytes read against the file size. **Next:** boot the
-preserved cold copy (the 11-05 snapshot plus its three WAL files, held by
-smartbotic-vectorapi) under 2.21.4 and read those lines. If entries fail their
-checksum or parse, find which write path produced them; if sequences go
-backwards, find what reset the counter.
+**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.
 
 **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

+ 24 - 12
docs/integration-guide.md

@@ -2715,23 +2715,35 @@ 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.
 
-**Memory behind disk after a replay (2.21.4+).** If a replay applies fewer
-entries than it should, memory keeps older versions of rows LMDB has newer
-copies of. Reads are still right, because they are served from LMDB. A
-`patch`/`increment` is not: it merges into memory's copy, so it writes the
-old fields back over the newer row. The boot step
+**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
+LMDB. A `patch`/`increment` is not: it merges into memory's copy, so it writes
+the old fields back over the newer row. The boot step
 `Boot: memory/disk version audit` compares every resident row's `_version`
-and `_updated_at` with LMDB's and reloads from LMDB the ones that differ:
+and `_updated_at` with LMDB's and reloads from LMDB the rows whose LMDB copy
+is newer:
 
 ```
-[warning] version audit: proj:coll: 12 resident row(s) were older than LMDB's copy,
-12 reloaded from LMDB (e.g. ...)
+[warning] version audit: proj:coll: 3 resident row(s) were older than LMDB's copy,
+3 reloaded from LMDB (e.g. id (memory v2 at ..., LMDB v3 at ...); ...)
 ```
 
-A healthy boot logs `version audit: N resident row(s) agree with LMDB`. The
-step reads each resident row once from LMDB, so it adds a little boot time.
-It is skipped (WARN) when the LMDB mirror is unhealthy or has drift, because
-then memory may be the newer side.
+A row can also be newer in MEMORY: an old LMDB copy that missed a write
+(before 2.21.0 a failed copy was not recorded). Such rows are left in memory
+and reported (`... are NEWER than LMDB's copy, left in memory`). Reads show
+LMDB's older copy until the next write to the row mirrors memory's version
+over it. **2.21.4 reloaded those too, replacing the newer copy; 2.21.5 does
+not.** A healthy boot logs `version audit: N resident row(s) agree with LMDB`.
+The step reads each resident row once from LMDB: about 1 s per 22,000 rows
+here, 29 s for 222,000 rows on a 1-vCPU host. It is skipped (WARN) when the
+LMDB mirror is unhealthy or has drift.
+
+**The WAL write race (fixed in 2.21.5).** Up to 2.21.4 the WAL's periodic
+flush could race a write and damage one record. Replay stops at a damaged
+record, so every record behind it in that file was not applied. A
+`WAL file ...: ... (ended early ...)` WARN at boot is the sign; the version
+audit then repairs memory from LMDB.
 
 ### Configuring for Your Project
 

+ 34 - 9
service/src/database_service.cpp

@@ -1120,7 +1120,7 @@ uint64_t DatabaseService::repairStaleResidentRows() {
     }
     namespace sd = smartbotic::database;
     const auto started = std::chrono::steady_clock::now();
-    uint64_t checked = 0, reloaded = 0, failed = 0;
+    uint64_t checked = 0, reloaded = 0, failed = 0, memNewerTotal = 0;
     constexpr size_t kBatch = 256;
 
     for (const auto& name : store_->listCollections()) {
@@ -1135,7 +1135,9 @@ uint64_t DatabaseService::repairStaleResidentRows() {
         if (!ds) continue;
 
         const auto ids = store_->getDocumentIds(name);
-        std::vector<std::string> stale;
+        std::vector<std::string> stale;      // LMDB newer: reloaded
+        std::vector<std::string> memNewer;   // memory newer: reported, left alone
+        std::string detail, memDetail;       // both sides of the first few, for the log
         for (size_t from = 0; from < ids.size(); from += kBatch) {
             const auto mem = store_->copyDocuments(name, ids, from, kBatch);
             for (size_t k = 0; k < mem.size(); ++k) {
@@ -1151,11 +1153,35 @@ uint64_t DatabaseService::repairStaleResidentRows() {
                     continue;
                 }
                 if (!disk) continue;   // memory only: the key audit reports it
-                if (disk->version != mem[k]->version || disk->updatedAt != mem[k]->updatedAt) {
-                    stale.push_back(ids[from + k]);
+                if (disk->version == mem[k]->version && disk->updatedAt == mem[k]->updatedAt) {
+                    continue;
+                }
+                // Which side is newer: the later _updated_at (ms and ns
+                // stamps coexist; 10^15 tells them apart), then the higher
+                // version. Only an LMDB-newer row is reloaded.
+                const auto ns = [](uint64_t t) { return t < 1'000'000'000'000'000ULL ? t * 1'000'000ULL : t; };
+                const uint64_t dt = ns(disk->updatedAt), mt = ns(mem[k]->updatedAt);
+                const bool diskNewer = dt != mt ? dt > mt : disk->version > mem[k]->version;
+                auto& list = diskNewer ? stale : memNewer;
+                auto& text = diskNewer ? detail : memDetail;
+                if (list.size() < 5) {
+                    text += fmt::format("{}{} (memory v{} at {}, LMDB v{} at {})",
+                                        list.empty() ? "" : "; ", ids[from + k],
+                                        mem[k]->version, mem[k]->updatedAt,
+                                        disk->version, disk->updatedAt);
                 }
+                list.push_back(ids[from + k]);
             }
         }
+        if (!memNewer.empty()) {
+            // An old LMDB copy that missed a write (a mirror failure before
+            // 2.21.0 recorded them): memory holds the later write. Left as it
+            // is; reads have been showing LMDB's older copy, and the next
+            // write to the row mirrors memory's version over it.
+            memNewerTotal += memNewer.size();
+            spdlog::warn("version audit: {}: {} resident row(s) are NEWER than LMDB's copy, "
+                         "left in memory (e.g. {})", name, memNewer.size(), memDetail);
+        }
         if (stale.empty()) continue;
 
         uint64_t done = 0;
@@ -1174,17 +1200,16 @@ uint64_t DatabaseService::repairStaleResidentRows() {
             }
         }
         reloaded += done;
-        std::string sample;
-        for (size_t i = 0; i < stale.size() && i < 10; ++i) sample += (i ? ", " : "") + stale[i];
         spdlog::warn("version audit: {}: {} resident row(s) were older than LMDB's copy, "
-                     "{} reloaded from LMDB (e.g. {})", name, stale.size(), done, sample);
+                     "{} reloaded from LMDB (e.g. {})", name, stale.size(), done, detail);
     }
 
     const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                         std::chrono::steady_clock::now() - started).count();
-    if (reloaded > 0 || failed > 0) {
+    if (reloaded > 0 || failed > 0 || memNewerTotal > 0) {
         spdlog::warn("version audit: {} resident row(s) checked, {} reloaded from LMDB, "
-                     "{} failed ({} ms)", checked, reloaded, failed, ms);
+                     "{} newer in memory (left), {} failed ({} ms)",
+                     checked, reloaded, memNewerTotal, failed, ms);
     } else {
         spdlog::info("version audit: {} resident row(s) agree with LMDB ({} ms)", checked, ms);
     }

+ 24 - 3
service/src/persistence/wal.cpp

@@ -438,7 +438,7 @@ uint64_t WriteAheadLog::append(WalEntry entry) {
 
     if (config_.syncOnWrite) {
         currentFile_.flush();
-        sync();
+        fsyncCurrentFile();   // writeMutex_ is held: sync() would deadlock
     }
 
     // Rotate if file is too large
@@ -450,8 +450,29 @@ uint64_t WriteAheadLog::append(WalEntry entry) {
 }
 
 void WriteAheadLog::sync() {
-    if (!currentFile_.is_open()) return;
-    currentFile_.flush();
+    // v2.21.5 - under writeMutex_. This flushed the stream with no lock while
+    // append() wrote to it under the lock (the sync thread calls this every
+    // interval, flushWal() before a cascade commit); a std::filebuf is not
+    // thread-safe, and the race dropped or duplicated bytes in the file. A
+    // production WAL file held one record a byte shorter than its length
+    // prefix, and replay abandoned the 160,261 intact records behind it.
+    // The fsync runs outside the lock (it waits on the disk); the fd is
+    // opened under it, so it is the file just flushed even if a rotation
+    // renames it meanwhile.
+    int fd = -1;
+    {
+        std::lock_guard<std::mutex> lock(writeMutex_);
+        if (!currentFile_.is_open()) return;
+        currentFile_.flush();
+        fd = ::open(currentFilePath().c_str(), O_WRONLY);
+    }
+    if (fd >= 0) {
+        ::fsync(fd);
+        ::close(fd);
+    }
+}
+
+void WriteAheadLog::fsyncCurrentFile() {
     // v2.11.0 T12 — real fsync, not just flush(). flush() only pushes the
     // C++ stream buffer into the OS page cache; on a crash before the OS
     // itself writes that page back to disk, a "flushed" WAL entry is

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

@@ -240,6 +240,9 @@ private:
     // Write header to file
     void writeHeader();
 
+    // fsync the current file by path (std::ofstream has no fd); no lock.
+    void fsyncCurrentFile();
+
     // Read entries from a file
     uint64_t replayFile(const std::filesystem::path& path, uint64_t fromSequence,
                         const std::function<void(const WalEntry&)>& callback,

+ 13 - 0
tests/load_test/test_stale_memory.cpp

@@ -8,6 +8,10 @@
 // WAL holding the newer writes is removed before a boot) and the boot's
 // version audit must reload those rows from LMDB.
 //
+// The reverse also exists (found staging 2.21.4 on a real backup): an old LMDB
+// copy that missed a write, memory holding the later one. The audit must leave
+// that row in memory, not replace it with LMDB's older copy.
+//
 // Phases: seed | newer | check
 
 #include <smartbotic/database/client.hpp>
@@ -30,6 +34,9 @@ int main(int argc, char** argv) {
     c.connect();
 
     if (phase == "seed") {
+        c.insert("rows", {{"state", "older-copy"}}, "o0");   // its body becomes m0's LMDB copy
+        c.insert("rows", {{"mstate", "first"}}, "m0");
+        ck(c.patch("rows", "m0", {{"mstate", "newer"}}), "seed: m0 at version 2");
         for (int i = 0; i < 20; ++i) {
             c.insert("rows", {{"state", "old"}, {"n", 1}}, "r" + std::to_string(i));
         }
@@ -54,6 +61,12 @@ int main(int argc, char** argv) {
                (*d)["n"] == 2 && (*d)["_version"] == 3,
                "check: " + id + " keeps the newer fields after a patch (version 3)");
         }
+        // m0: memory (version 2) is newer than LMDB's planted copy (version
+        // 1): left alone, so a patch builds on memory's version.
+        ck(c.patch("rows", "m0", {{"n", 2}}), "check: patched m0");
+        auto m0 = c.get("rows", "m0");
+        ck(m0 && (*m0).value("mstate", "") == "newer" && (*m0)["_version"] == 3,
+           "check: m0 kept memory's newer version (mstate newer, version 3)");
         // Rows memory had right are untouched.
         auto r15 = c.get("rows", "r15");
         ck(r15 && (*r15)["state"] == "old" && (*r15)["_version"] == 1, "check: r15 unchanged");

+ 10 - 1
tests/load_test/test_stale_memory.sh

@@ -26,6 +26,7 @@ cat > "$DIR/config.json" <<CFG
 }
 CFG
 
+g++ -std=c++20 -O1 -o "$DIR/rowtool" lmdb_row_tool.cpp -llmdb
 g++ -std=c++20 -O1 -o "$DIR/t" test_stale_memory.cpp \
     -I"$ROOT/client/include" -I"$ROOT/build/client" \
     -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
@@ -45,6 +46,12 @@ ck() { if eval "$2"; then echo "ok   $1"; else echo "FAIL $1"; fails=$((fails+1)
 start 1
 client seed || fails=$((fails+1))
 kill "$SERVER_PID"; wait "$SERVER_PID" || true    # graceful: the snapshot holds version 1
+SERVER_PID=""
+# m0's LMDB copy replaced by an OLDER body (o0's, version 1) with the server
+# stopped: an LMDB copy that missed a write, memory (the snapshot) newer.
+ENV="$DIR/data/projects/default/env"
+"$DIR/rowtool" "$ENV" rows del m0
+"$DIR/rowtool" "$ENV" rows copy o0 m0
 start 2
 client newer || fails=$((fails+1))
 kill -9 "$SERVER_PID"; wait "$SERVER_PID" 2>/dev/null || true
@@ -55,8 +62,10 @@ rm -f "$DIR"/data/wal/wal-*.log
 start 3
 ck "boot 3: the version audit reloaded the 10 rows" \
    "grep -q 'version audit: default:rows: 10 resident row(s) were older than LMDB' '$DIR/server3.log'"
+ck "boot 3: m0 reported as newer in memory and left" \
+   "grep -q 'version audit: default:rows: 1 resident row(s) are NEWER than LMDB' '$DIR/server3.log'"
 ck "boot 3: the summary counts them" \
-   "grep -q 'version audit: .* checked, 10 reloaded from LMDB, 0 failed' '$DIR/server3.log'"
+   "grep -q 'version audit: .* checked, 10 reloaded from LMDB, 1 newer in memory (left), 0 failed' '$DIR/server3.log'"
 client check || fails=$((fails+1))
 grep -h "version audit" "$DIR/server3.log" || true
 kill "$SERVER_PID"; wait "$SERVER_PID" || true

+ 51 - 0
tests/test_snapshot_durability.cpp

@@ -286,6 +286,56 @@ void test_snapshot_survives_concurrent_listing() {
     std::cout << "PASS: snapshots complete while another thread lists snapshots\n";
 }
 
+// v2.21.5 - WriteAheadLog::sync() flushed the std::ofstream WITHOUT the write
+// mutex while append() wrote to it under the mutex, from the WAL sync thread
+// every interval and from flushWal(). A std::filebuf is not thread-safe: a
+// production WAL file held one record a byte shorter than its length prefix,
+// and replay abandoned the 160,261 intact records behind it. Writers append
+// while another thread syncs in a loop; every entry must replay.
+void test_wal_append_races_sync() {
+    using smartbotic::database::WriteAheadLog;
+    auto dir = makeSnapshotDir("wal-sync-race");
+    WriteAheadLog::Config cfg;
+    cfg.walDir = dir;
+    constexpr int kWriters = 4, kPerWriter = 15000;
+    {
+        WriteAheadLog wal(cfg);
+        assert(wal.open());
+        std::atomic<bool> done{false};
+        std::thread syncer([&] { while (!done.load()) wal.sync(); });
+        std::vector<std::thread> writers;
+        for (int w = 0; w < kWriters; ++w) {
+            writers.emplace_back([&wal, w] {
+                for (int i = 0; i < kPerWriter; ++i) {
+                    Document d;
+                    d.id = "w" + std::to_string(w) + "-" + std::to_string(i);
+                    d.set_data(nlohmann::json{{"pad", std::string(100 + (i % 400), 'p')}});
+                    wal.append(WriteAheadLog::makeInsertEntry("t", d, "n"));
+                }
+            });
+        }
+        for (auto& t : writers) t.join();
+        done = true;
+        syncer.join();
+        wal.close();
+    }
+    WriteAheadLog wal(cfg);
+    const uint64_t n = wal.replay(0, [](const auto&) {});
+    uint64_t unreadable = 0, short_ = 0;
+    for (const auto& f : wal.lastReplayStats()) {
+        unreadable += f.unreadable;
+        if (f.bytesRead < f.fileBytes) ++short_;
+    }
+    if (n != static_cast<uint64_t>(kWriters * kPerWriter) || unreadable || short_) {
+        std::cerr << "replayed " << n << " of " << kWriters * kPerWriter << ", unreadable "
+                  << unreadable << ", files ended early " << short_ << "\n";
+    }
+    assert(n == static_cast<uint64_t>(kWriters * kPerWriter));
+    assert(unreadable == 0 && short_ == 0);
+    fs::remove_all(dir);
+    std::cout << "PASS: WAL entries survive appends racing sync()\n";
+}
+
 // ──────────────────────────────────────────────────────────
 // Test 6: loadWithFallback throws when all snapshots corrupt
 // ──────────────────────────────────────────────────────────
@@ -882,6 +932,7 @@ int main() {
     test_loadWithFallback_uses_older_when_newest_corrupt();
     test_orphaned_tmp_cleaned_by_listSnapshots();
     test_snapshot_survives_concurrent_listing();
+    test_wal_append_races_sync();
     test_loadWithFallback_throws_when_all_corrupt();
     test_v4_format_roundtrip_at_scale();
     test_wal_sequence_floor_anchors_after_truncate();

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác