Sfoglia il codice sorgente

release: 2.21.7 - WAL sequence gaps reported; upload metadata validated; update() dropping fields logged; consistency.memory_newer (bug fix, server only)

- replay reports sequence numbers a WAL file's range has no record for (the
  2.21.5 race dropped whole records that no reader could see)
- UploadFile refuses an invalid project name (invalid_project) and a MIME
  type without a slash (invalid_mime_type)
- an update that removes stored top-level fields is logged, rate limited
- storage.consistency.memory_newer: report (default) | write for rows the
  version audit finds newer in memory than on disk

Tests: test_snapshot_durability (gap case), test_file_store (+2),
test_stale_memory (dropped-field line, memory_newer=write boot).
fszontagh 6 giorni fa
parent
commit
7ed9425a53

+ 27 - 0
CHANGELOG.md

@@ -12,6 +12,33 @@ consumer-facing usage is in `docs/integration-guide.md`.
 
 ## Unreleased
 
+## 2.21.7 - 2026-11-20 (bug fix, server only)
+
+### Fixed
+- **[server]** WAL replay reports sequence numbers missing from a file (`N
+  sequence number(s) in this file's range have no record, at M place(s)`,
+  WARN). A file can be perfectly framed and still lack records: the 2.21.5
+  race dropped 63 whole records from a production file, and every reader
+  reported a complete read.
+- **[server]** Upload metadata that cannot be right is refused with
+  `INVALID_ARGUMENT`: a project that is not a valid project name (reason
+  `invalid_project`), or a MIME type without a `/` (reason
+  `invalid_mime_type`). Before, it was stored as given; two records held a
+  file path as their project and could never be addressed.
+- **[server]** An `update` that removes fields the stored document had is
+  logged (`update of <collection>/<id> removed N field(s) ...`, WARN, at most
+  once a minute per collection, system collections excepted). An update
+  replaces the whole document, so a call meant as a `patch` silently wiped
+  fields.
+
+### Added
+- **[server]** `storage.consistency.memory_newer`: `report` (default) |
+  `write`. For rows the boot version audit finds NEWER in memory than on disk,
+  `write` copies memory's version to disk at boot. The default leaves them,
+  and reads show the older disk copy until the next write to the row. Opt-in
+  per instance, because it makes a write nobody has reviewed the one every
+  read returns.
+
 ## 2.21.6 - 2026-11-20 (bug fix, server only)
 
 ### Fixed

File diff suppressed because it is too large
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.21.6
+2.21.7

+ 2 - 1
docs/ROADMAP.md

@@ -434,7 +434,8 @@ service. Report, then an operator decision per row.
 without the write lock, and the race damaged one record in a production WAL
 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.
+tail is cut before appending. 2.21.7 reports sequence gaps per file (records
+dropped whole, which no reader could see). 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

+ 27 - 0
docs/integration-guide.md

@@ -544,6 +544,12 @@ db.patch("users", "user-123",                   db.patch("users", "user-123",
 
 **`update()`** — full document replacement with automatic retry. Uses optimistic locking internally (reads current version, writes with version check, retries on conflict). Use when you need to replace the entire document:
 
+Every field the stored document has and the new body lacks is REMOVED. Since
+2.21.7 the server logs it (`update of <collection>/<id> removed N field(s) the
+stored document had: ...`, WARN, at most once a minute per collection). If you
+see that line and did not mean to remove the fields, the call should have been
+a `patch()`.
+
 ```cpp
 auto doc = db.get("users", "user-123");
 (*doc)["name"] = "Alice Smith";
@@ -1993,6 +1999,12 @@ db.getFileInfo(up.id);                 // resolves
 db.listFiles("document");              // only acme's files
 ```
 
+Since 2.21.7 an upload is refused with `INVALID_ARGUMENT` when its project is
+not a valid project name (reason `invalid_project`) or its MIME type has no
+`/` (reason `invalid_mime_type`). Before, such metadata was stored as given:
+two records on one instance held a file path as their project, so no client
+could ever address them.
+
 An id belonging to another project is reported as **`NOT_FOUND`**, not as
 "forbidden" — `getFileInfo` returns `nullopt`, `downloadFile` throws,
 `deleteFile` returns `false`, and `listFiles` omits it. The indistinguishability
@@ -2646,6 +2658,7 @@ it applies these settings:
 |---|---|---|---|
 | `disk_only` | `adopt` / `report` / `remove` | `adopt` | `adopt` loads the rows into memory (reads already see them, so nothing visible changes; they are in the next snapshot again). `remove` deletes them from disk. |
 | `memory_only` | `report` / `write` / `remove` | `report` | `write` copies the rows to disk (they become readable). `remove` deletes them from memory, through the ordinary delete path (WAL, history, a `DELETE` event with actor `system:consistency-repair`). |
+| `memory_newer` (2.21.7+) | `report` / `write` | `report` | For the boot **version audit**: a row present on both sides whose memory copy is NEWER than its disk copy (a write whose disk copy failed long ago). `report` leaves it; reads show the older disk copy until the next write to the row. `write` copies memory's version to disk at boot, so reads return it. It makes a write nobody has reviewed authoritative, so it is opt-in per instance; the log line names the collection and the count either way. |
 
 `report` changes nothing; the log line says which setting would do what. An
 unknown value is treated as `report`.
@@ -2715,6 +2728,20 @@ 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.
 
+**Missing records show up (2.21.7+).** A WAL file can be perfectly readable
+and still lack records: the 2.21.5 write race dropped 63 whole records from
+one production file, and every reader reported a complete read. Replay now
+reports the sequence numbers in a file's range that have no record:
+
+```
+[warning] WAL file wal-...: 63 sequence number(s) in this file's range have no record,
+at 46 place(s): writes may have been lost from the WAL before it was durable ...
+```
+
+The LMDB copy is not affected (it got those writes when they happened), and
+the version audit repairs memory. Report the line anyway: it points at the
+WAL writer.
+
 **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

+ 17 - 0
service/src/database_grpc_impl.cpp

@@ -2847,6 +2847,23 @@ grpc::Status DatabaseGrpcImpl::UploadFile(
         }
     }
 
+    // v2.21.7 - refuse metadata that cannot be right. Two records on one
+    // instance held a file path in `project` and a filename in `mime_type`:
+    // every field shifted by one in some consumer's own wrapper. They were
+    // stored as given, in a project nobody can address.
+    if (!metadata.project().empty() &&
+        !smartbotic::database::isValidProjectName(metadata.project())) {
+        attachErrorDetail(context, {{"reason", "invalid_project"}, {"fields", nlohmann::json::array({"project"})}});
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+            "UploadFile: '" + metadata.project() + "' is not a project name "
+            "(^[a-zA-Z_][a-zA-Z0-9_-]{0,62}$)");
+    }
+    if (!metadata.mime_type().empty() && metadata.mime_type().find('/') == std::string::npos) {
+        attachErrorDetail(context, {{"reason", "invalid_mime_type"}, {"fields", nlohmann::json::array({"mime_type"})}});
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+            "UploadFile: '" + metadata.mime_type() + "' is not a MIME type (type/subtype)");
+    }
+
     try {
         FileManager::FileInfo info;
         info.name = metadata.name();

+ 30 - 8
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, memNewerTotal = 0;
+    uint64_t checked = 0, reloaded = 0, failed = 0, memNewerTotal = 0, memNewerWritten = 0;
     constexpr size_t kBatch = 256;
 
     for (const auto& name : store_->listCollections()) {
@@ -1175,12 +1175,27 @@ uint64_t DatabaseService::repairStaleResidentRows() {
         }
         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.
+            // 2.21.0 recorded them): memory holds the later write. By default
+            // 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.
+            // v2.21.7 - `memory_newer: write` copies memory's version to LMDB
+            // now. Opt-in: it makes a write nobody has looked at the one
+            // every read returns.
             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 (config_.consistencyMemoryNewer == "write") {
+                std::vector<std::pair<std::string, std::string>> rows;
+                for (const auto& id : memNewer) rows.emplace_back(name, id);
+                const auto r = store_->syncDocStoreFromMemory(rows);
+                memNewerWritten += r.written;
+                failed += r.failed.size();
+                spdlog::warn("version audit: {}: {} resident row(s) are NEWER than LMDB's copy, "
+                             "{} written to LMDB (memory_newer=write; e.g. {})",
+                             name, memNewer.size(), r.written, memDetail);
+            } else {
+                spdlog::warn("version audit: {}: {} resident row(s) are NEWER than LMDB's copy, "
+                             "left in memory (memory_newer=report; e.g. {})",
+                             name, memNewer.size(), memDetail);
+            }
         }
         if (stale.empty()) continue;
 
@@ -1208,8 +1223,9 @@ uint64_t DatabaseService::repairStaleResidentRows() {
                         std::chrono::steady_clock::now() - started).count();
     if (reloaded > 0 || failed > 0 || memNewerTotal > 0) {
         spdlog::warn("version audit: {} resident row(s) checked, {} reloaded from LMDB, "
-                     "{} newer in memory (left), {} failed ({} ms)",
-                     checked, reloaded, memNewerTotal, failed, ms);
+                     "{} newer in memory ({} written to LMDB, {} left), {} failed ({} ms)",
+                     checked, reloaded, memNewerTotal, memNewerWritten,
+                     memNewerTotal - memNewerWritten, failed, ms);
     } else {
         spdlog::info("version audit: {} resident row(s) agree with LMDB ({} ms)", checked, ms);
     }
@@ -1709,6 +1725,12 @@ DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json)
             const auto& c = db["consistency"];
             config.consistencyDiskOnly = c.value("disk_only", config.consistencyDiskOnly);
             config.consistencyMemoryOnly = c.value("memory_only", config.consistencyMemoryOnly);
+            config.consistencyMemoryNewer = c.value("memory_newer", config.consistencyMemoryNewer);
+        }
+        if (config.consistencyMemoryNewer != "report" && config.consistencyMemoryNewer != "write") {
+            spdlog::error("storage.consistency.memory_newer '{}' is not report|write; using report",
+                          config.consistencyMemoryNewer);
+            config.consistencyMemoryNewer = "report";
         }
         if (config.consistencyDiskOnly != "adopt" && config.consistencyDiskOnly != "report" &&
             config.consistencyDiskOnly != "remove") {

+ 6 - 0
service/src/database_service.hpp

@@ -127,6 +127,12 @@ public:
         // memory_only: report | write | remove. An unknown value means report.
         std::string consistencyDiskOnly = "adopt";
         std::string consistencyMemoryOnly = "report";
+        // v2.21.7 - what the boot version audit does with a row memory holds
+        // in a NEWER version than LMDB (a write whose LMDB copy failed before
+        // 2.21.0 recorded such failures): report (leave it; reads show LMDB's
+        // older copy until the next write) | write (copy memory's version to
+        // LMDB at boot).
+        std::string consistencyMemoryNewer = "report";
 
         // Bootstrap/service registration
         std::string webapiUrl;

+ 52 - 0
service/src/memory_store.cpp

@@ -15,6 +15,7 @@
 #endif
 
 #include <spdlog/spdlog.h>
+#include <yyjson.h>
 
 #include <algorithm>
 #include <cmath>
@@ -33,6 +34,55 @@
 namespace smartbotic::database {
 
 namespace {
+// v2.21.7 - an update replaces the whole document, so a body that lacks a
+// field the stored document has removes it. A consumer one argument away from
+// calling update() instead of patch() would have wiped four fields on every
+// duplicate it saw, silently. The fields an update drops are logged (WARN, at
+// most once a minute per collection, the rest counted). Top-level keys only,
+// read from the yyjson bodies without building a JSON tree.
+void warnDroppedFields(const std::string& collection, const std::string& id,
+                       const Document& before, const Document& after) {
+    // System collections are written whole by the server itself.
+    const auto pc = parseProjectCollection(collection);
+    if (pc.collection.empty() || pc.collection.front() == '_') return;
+    yyjson_mut_doc* b = before.data_binary.raw();
+    if (!b) return;
+    yyjson_mut_val* broot = yyjson_mut_doc_get_root(b);
+    if (!yyjson_mut_is_obj(broot)) return;
+    yyjson_mut_doc* a = after.data_binary.raw();
+    yyjson_mut_val* aroot = a ? yyjson_mut_doc_get_root(a) : nullptr;
+    const bool aobj = yyjson_mut_is_obj(aroot);
+    std::string dropped;
+    size_t n = 0;
+    yyjson_mut_obj_iter it;
+    yyjson_mut_obj_iter_init(broot, &it);
+    while (yyjson_mut_val* k = yyjson_mut_obj_iter_next(&it)) {
+        const char* name = yyjson_mut_get_str(k);
+        const size_t len = yyjson_mut_get_len(k);
+        if (aobj && yyjson_mut_obj_getn(aroot, name, len)) continue;
+        if (n++ < 10) dropped += (dropped.empty() ? "" : ", ") + std::string(name, len);
+    }
+    if (n == 0) return;
+    static std::mutex m;
+    static std::unordered_map<std::string, std::pair<uint64_t, uint64_t>> last;  // ms, suppressed
+    const uint64_t now = static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(
+        std::chrono::steady_clock::now().time_since_epoch()).count());
+    uint64_t suppressed = 0;
+    {
+        std::lock_guard<std::mutex> g(m);
+        auto& e = last[collection];
+        if (e.first != 0 && now - e.first < 60'000) { ++e.second; return; }
+        suppressed = e.second;
+        e = {now, 0};
+    }
+    spdlog::warn("update of {}/{} removed {} field(s) the stored document had: {}{} (an update "
+                 "replaces the whole document; patch changes only the fields it names){}",
+                 collection, id, n, dropped, n > 10 ? ", ..." : "",
+                 suppressed ? fmt::format(". {} more such update(s) on this collection in the "
+                                          "last minute were not logged", suppressed)
+                            : std::string());
+}
+
 // `_collection_meta`, `_views`, ... (global) - never mirrored to LMDB.
 bool isSystemCollectionName(const std::string& name) {
     const auto pc = parseProjectCollection(name);
@@ -678,6 +728,7 @@ bool MemoryStore::update(const std::string& collection, const std::string& id, c
 
     // Extract vector before storing document (strips _vector from JSON data)
     auto vec = extractVector(*coll, updated);
+    warnDroppedFields(collection, id, it->second, updated);   // v2.21.7
     const auto vc = replaceVectorChange(*coll, vec, updated);   // v2.13.0
 
     updated.id = id;
@@ -1394,6 +1445,7 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
     // collection (the v2.0 mirror made the divergence observable
     // across handlers).
     auto vec = extractVector(*coll, updated);
+    warnDroppedFields(collection, id, it->second, updated);   // v2.21.7
     const auto vc = replaceVectorChange(*coll, vec, updated);   // v2.13.0
 
     // Add to new expiration index

+ 8 - 0
service/src/persistence/persistence_manager.cpp

@@ -311,6 +311,14 @@ RecoveryOutcome PersistenceManager::recover(MemoryStore& store) {
                 !f.headerReadable ? " (HEADER UNREADABLE, file skipped)"
                 : endedEarly      ? " (a torn tail after the last valid record)" : "");
             if (suspect) spdlog::warn("{}", line); else spdlog::info("{}", line);
+            if (f.missingSequences > 0) {
+                spdlog::warn("WAL file {}: {} sequence number(s) in this file's range have no "
+                             "record, at {} place(s): writes may have been lost from the WAL "
+                             "before it was durable (the LMDB mirror is not affected; it got "
+                             "them at write time, and a damaged record skipped above counts "
+                             "here too). Report it: it points at the WAL writer.",
+                             f.path.filename().string(), f.missingSequences, f.gapRuns);
+            }
         }
 
         std::vector<std::pair<std::string, std::string>> toRemirror;

+ 10 - 1
service/src/persistence/wal.cpp

@@ -820,7 +820,16 @@ void WriteAheadLog::scanFile(const std::filesystem::path& path,
         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;
+            else if (e->sequence > stats.lastSequence + 1) {
+                // v2.21.7 - a number append() assigned with no record behind
+                // it. A well-framed file can be missing records (the 2.21.5
+                // race dropped 63 whole records from a production file and
+                // every reader reported a complete read); this is the only
+                // place that shows it.
+                stats.missingSequences += e->sequence - stats.lastSequence - 1;
+                ++stats.gapRuns;
+            }
+            if (e->sequence > stats.lastSequence) stats.lastSequence = e->sequence;
             if (e->sequence > floor) floor = e->sequence;
             onEntry(*e);
             off += 4 + static_cast<uint64_t>(len);

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

@@ -136,6 +136,8 @@ public:
         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 missingSequences = 0;   // v2.21.7: numbers between records with no record
+        uint64_t gapRuns = 0;            // how many places they are missing at
         uint64_t skippedBytes = 0;   // bytes in those regions
         uint64_t firstSequence = 0;  // of readable entries, 0 = none
         uint64_t lastSequence = 0;

+ 20 - 0
tests/load_test/test_file_store.cpp

@@ -88,6 +88,26 @@ static void beforeRestart() {
         ck(!ok.id.empty(), "an allowed MIME type is accepted");
     }
 
+    // ---- v2.21.7 metadata that cannot be right is refused, nothing stored
+    //      (two production records held a path in `project` and a filename
+    //      in `mime_type`: a consumer's arguments shifted by one)
+    {
+        Client::FailureDetail d;
+        try { c.uploadFile(bytes(100, 4), meta("shifted.bin", "output_1.png")); }
+        catch (const Client::Error& e) { if (const auto* p = Client::errorDetail(e)) d = *p; else d.code = e.code(); }
+        ck(d.code == Code::InvalidArgument && d.reason == "invalid_mime_type",
+           "a MIME type without a slash: InvalidArgument, invalid_mime_type, got '" + d.reason + "'");
+        ck(c.listFiles("", "", 100, 0, "", "shifted.bin").files.empty(), "invalid MIME type: nothing stored");
+
+        Client bad({.address = ADDR, .project = "355b1e9c/output_1.png"});
+        bad.connect();
+        Client::FailureDetail d2;
+        try { bad.uploadFile(bytes(100, 5), meta("p.bin")); }
+        catch (const Client::Error& e) { if (const auto* p = Client::errorDetail(e)) d2 = *p; else d2.code = e.code(); }
+        ck(d2.code == Code::InvalidArgument && d2.reason == "invalid_project",
+           "a path as the project: InvalidArgument, invalid_project, got '" + d2.reason + "'");
+    }
+
     // ---- dropProject deletes the project's files, not shared content
     Client admin({.address = ADDR, .project = "default"});
     admin.connect();

+ 17 - 1
tests/load_test/test_stale_memory.cpp

@@ -12,7 +12,10 @@
 // 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
+// v2.21.7 - `memory_newer: write` copies such a row to LMDB at boot (m1, left
+// alone through boot 3 under the default `report`).
+//
+// Phases: seed | newer | check | written
 
 #include <smartbotic/database/client.hpp>
 
@@ -37,6 +40,8 @@ int main(int argc, char** argv) {
         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");
+        c.insert("rows", {{"mstate", "first"}}, "m1");
+        ck(c.patch("rows", "m1", {{"mstate", "newer"}}), "seed: m1 at version 2");
         for (int i = 0; i < 20; ++i) {
             c.insert("rows", {{"state", "old"}, {"n", 1}}, "r" + std::to_string(i));
         }
@@ -75,6 +80,17 @@ int main(int argc, char** argv) {
         nlohmann::json body = {{"state", "replaced"}};
         ck(r1 && c.updateIfVersion("rows", "r1", body, (*r1)["_version"].get<uint64_t>()),
            "check: updateIfVersion at the version a read returned succeeds");
+        // v2.21.7 - an update that drops a stored field is logged (the
+        // script greps for the line). u0 holds `state`; this body does not.
+        ck(c.update("untouched", "u0", {{"other", 1}}), "check: updated u0 without `state`");
+        // m1 is left under `report`: reads still show LMDB's older copy.
+        auto m1 = c.get("rows", "m1");
+        ck(m1 && (*m1).value("state", "") == "older-copy" && !(*m1).contains("mstate"),
+           "check: m1 still reads LMDB's older copy under memory_newer=report");
+    } else if (phase == "written") {
+        auto m1 = c.get("rows", "m1");
+        ck(m1 && (*m1).value("mstate", "") == "newer" && (*m1)["_version"] == 2,
+           "written: m1 reads memory's newer version from LMDB after memory_newer=write");
     } else {
         return 2;
     }

+ 17 - 3
tests/load_test/test_stale_memory.sh

@@ -52,6 +52,8 @@ SERVER_PID=""
 ENV="$DIR/data/projects/default/env"
 "$DIR/rowtool" "$ENV" rows del m0
 "$DIR/rowtool" "$ENV" rows copy o0 m0
+"$DIR/rowtool" "$ENV" rows del m1
+"$DIR/rowtool" "$ENV" rows copy o0 m1
 start 2
 client newer || fails=$((fails+1))
 kill -9 "$SERVER_PID"; wait "$SERVER_PID" 2>/dev/null || true
@@ -62,14 +64,26 @@ 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: m0 and m1 reported as newer in memory and left" \
+   "grep -q 'version audit: default:rows: 2 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, 1 newer in memory (left), 0 failed' '$DIR/server3.log'"
+   "grep -q 'version audit: .* checked, 10 reloaded from LMDB, 2 newer in memory (0 written to LMDB, 2 left), 0 failed' '$DIR/server3.log'"
 client check || fails=$((fails+1))
+ck "boot 3: the update that dropped a field was logged" \
+   "grep -q 'update of default:untouched/u0 removed 1 field(s) the stored document had: state' '$DIR/server3.log'"
 grep -h "version audit" "$DIR/server3.log" || true
 kill "$SERVER_PID"; wait "$SERVER_PID" || true
 SERVER_PID=""
 
+# Boot 4 with memory_newer=write: m1 (still newer in memory) goes to LMDB.
+sed -i 's|"replication": { "enabled": false },|"replication": { "enabled": false },\n    "consistency": { "memory_newer": "write" },|' "$DIR/config.json"
+start 4
+ck "boot 4: m1 written to LMDB" \
+   "grep -q 'version audit: default:rows: 1 resident row(s) are NEWER than LMDB.s copy, 1 written to LMDB' '$DIR/server4.log'"
+client written || fails=$((fails+1))
+grep -h "version audit" "$DIR/server4.log" || true
+kill "$SERVER_PID"; wait "$SERVER_PID" || true
+SERVER_PID=""
+
 [[ $fails -eq 0 ]] && echo "OK - stale memory reloaded from LMDB" || echo "FAILED ($fails)"
 exit $(( fails > 0 ))

+ 18 - 0
tests/test_snapshot_durability.cpp

@@ -504,6 +504,24 @@ void test_wal_reader_resyncs_past_damage() {
         assert(wal.append(WriteAheadLog::makeInsertEntry("t", d, "n")) == kN + 1);
         wal.close();
     }
+    // G (v2.21.7): whole records removed cleanly (what the 2.21.5 race did to
+    // 63 records of a production file): the file is perfectly framed, nothing
+    // is unreadable, and only the sequence gap shows it.
+    {
+        WriteAheadLog::Config cfg;
+        auto p = makeWal("resync-gap", cfg);
+        auto b = readAll(p);
+        auto o = offsets(b);
+        // records 101 and 102 (one run of two), then record 150 (a run of one)
+        b.erase(b.begin() + static_cast<long>(o[149]), b.begin() + static_cast<long>(o[150]));
+        b.erase(b.begin() + static_cast<long>(o[100]), b.begin() + static_cast<long>(o[102]));
+        writeAll(p, b);
+        WriteAheadLog::ReplayFileStats st;
+        auto seqs = replayAll(cfg, st);
+        assert(missingOnly(seqs, {101, 102, 150}));
+        assert(st.unreadable == 0 && st.bytesRead == st.fileBytes);
+        assert(st.missingSequences == 3 && st.gapRuns == 2);
+    }
     std::cout << "PASS: WAL reader resynchronises past damaged records\n";
 }
 

Some files were not shown because too many files changed in this diff