Просмотр исходного кода

fix(unreleased 2.17.2): per-file history locks, prune outside the global lock, targeted reseal

- HistoryStore: one mutex per collection file instead of one global mutex, so
  a prune or rewrite of one collection no longer stalls history-recording
  writes in every other collection.
- prune(): streamed in two passes (count per doc, copy the newest N); a
  no-op leaves the file untouched. createCollection/alterCollection run it
  after releasing MemoryStore's global and collection locks.
- An online encryption upgrade requests a reseal only when it rewrote
  plaintext, naming its project; the reseal compacts only the named projects
  (all for the first run, a failure path, or a pre-2.17.2 marker).
Tests: test_history_audit_scan (per-file lock, prune keeps newest N),
test_encryption_at_rest (+ no reseal over already-encrypted values, reseal
compacts 1 of 2 projects). Each reverted alone fails its check.
Not released (owner's call). ROADMAP: encrypted collections refuse inserts
carrying _vector (since 2.17.0) - needs a decision.
fszontagh 1 месяц назад
Родитель
Сommit
efb78e5042

+ 1 - 1
VERSION

@@ -1 +1 @@
-2.17.1
+2.17.2

+ 12 - 13
docs/ROADMAP.md

@@ -372,19 +372,18 @@ joins; see 5c), which does not fit in 10 s. Run the container with
   encrypted). See CLAUDE.md v2.17.0. What a database cannot fix: copies made
   before the upgrade (backups, `pre-upgrade-*`, nightly backup archives)
   still hold the plaintext.
-- **Prune under the global lock (2.17.1):** `createCollection(existing, lower
-  maxVersions)` prunes history while holding MemoryStore's global collection
-  lock and the history append lock, so every collection waits for it. Move the
-  file rewrite outside the global lock (the prune needs only the append lock,
-  and a streamed rewrite like `HistoryStore::rewrite`'s rather than per-doc
-  buckets of the whole file).
-- **Reseal compaction cost:** a boot after an online encryption upgrade
-  compacts EVERY project, including ones the upgrade never touched (a 262 MB
-  test env took 2.5 minutes and reclaimed nothing). Compact only the projects
-  whose collections were rewritten, or skip an env whose free pages are few.
-  And request the reseal at all only when the online upgrade REWROTE something:
-  switching on a flag whose values were already encrypted (through a bare
-  alias) wrote no plaintext anywhere, yet still cost a full compaction restart.
+- ~~**Prune under the global lock**~~ and ~~**reseal compaction cost**~~ - FIXED
+  on main for 2.17.2 (not released): history locks are per collection file and
+  the prune streams in two passes outside MemoryStore's locks; a reseal is
+  requested only when an online upgrade rewrote plaintext, and compacts only
+  that project.
+- **⚠ Encrypted collection with vectors (found 2026-10-12, since 2.17.0):** an
+  insert carrying `_vector` into an `encrypted=true` collection is REFUSED
+  ("Invalid JSON ... type must be number, but is string"): the handler
+  encrypts the body, `_vector` included, before the store extracts the vector.
+  Vectors stored before the flag was switched on stay searchable. Needs a
+  decision: exempt `_vector` from encryption, or refuse `encrypted` together
+  with `vector_dimension`.
 - Collection schemas cannot be declared in a migration file yet (the
   existing-row check lives in the SetCollectionSchema handler).
 - ~~**Bogus index declarations on a production instance (found 2026-10-09, predates 2.14.0):**~~ removed

+ 11 - 7
docs/integration-guide.md

@@ -1033,9 +1033,12 @@ backups or copies taken before the upgrade.
 and `sensitive_fields` given that way are added. Its rows and history are
 encrypted immediately. The old plaintext copies are removed at the next
 restart: `encryption-verify` reports `sealed: NO` until then. **That next
-restart compacts every project again** (the same cost as the migration's seal:
-about the time to copy the largest `data.mdb`), so plan it as a window, not as
-an ordinary 15-second restart. Later restarts are ordinary.
+restart compacts again** (about the time to copy the `data.mdb` involved), so
+plan it as a window, not as an ordinary 15-second restart. In 2.17.1 it
+compacts EVERY project, and is requested whenever the flag changes; since
+2.17.2 (on main, not yet released) it is requested only when plaintext was
+actually rewritten, and compacts only that collection's project. Later
+restarts are ordinary.
 
 **This includes the defensive idiom.** A client that calls
 `createCollection(name, ..., encrypted=true)` on every startup changes nothing
@@ -1296,10 +1299,11 @@ Semantics:
 **Trimming history that already exists (2.17.1+).** `createCollection(name, ...,
 maxVersions=N)` on an EXISTING collection with a cap lower than before (or any
 cap over unlimited) rewrites its history file keeping the newest N versions per
-document. ⚠ It runs inside the call while holding the store's global collection
-lock and the global history lock, so EVERY collection's operations wait until
-it finishes (seconds or more for a large file): run it at a quiet moment, one
-collection at a time, never in a loop under live traffic. Before 2.17.1 the call changed the setting and trimmed nothing,
+document. It runs inside the call. Since 2.17.2 (on main, not yet released)
+it holds only that collection's history lock: only writes that record history
+in THAT collection wait. In 2.17.1 it held the store's global lock, so every
+collection's operations waited: on 2.17.1 run it at a quiet moment, one
+collection at a time. Before 2.17.1 the call changed the setting and trimmed nothing,
 and no supported call could cut back history kept with `maxVersions = 0`.
 
 #### Relation enforcement on/off (2.11.0+)

+ 9 - 1
service/src/database_grpc_impl.cpp

@@ -2442,7 +2442,15 @@ grpc::Status DatabaseGrpcImpl::CreateCollection(
         const auto full = store_.collectionOptions(request->name()).value_or(opts);
         persistence_.logCreateCollection(request->name(), full);
         const auto s = service_.encryptCollectionAtRest(request->name());
-        service_.requestResealAtNextBoot();
+        // v2.17.2 - a reseal (and its compaction restart) only when plaintext
+        // was actually replaced, and only for this collection's project.
+        // Switching on a flag whose values were already ciphertext (through a
+        // bare alias) wrote no plaintext anywhere, yet 2.17.1 still cost every
+        // project a compaction at the next restart.
+        if (s.rewritten + s.lmdbOnly + s.versions > 0) {
+            service_.requestResealAtNextBoot(
+                smartbotic::database::resolveCollection(request->name()).project);
+        }
         spdlog::warn("v2.17 encryption: {} upgraded (encrypted={}, {} sensitive field(s)); {} row(s) "
                      "and {} history version(s) encrypted now; old plaintext copies are removed at "
                      "the next restart", request->name(), full.encrypted, full.sensitiveFields.size(),

+ 28 - 6
service/src/database_service.cpp

@@ -597,8 +597,9 @@ DatabaseService::AtRestStats DatabaseService::encryptCollectionAtRest(const std:
     return st;
 }
 
-void DatabaseService::requestResealAtNextBoot() {
-    std::ofstream(config_.dataDirectory / "encryption-reseal.pending") << "1\n";
+void DatabaseService::requestResealAtNextBoot(const std::string& project) {
+    std::ofstream(config_.dataDirectory / "encryption-reseal.pending", std::ios::app)
+        << (project.empty() ? "*" : project) << "\n";
 }
 
 void DatabaseService::migrateEncryptionAtRest() {
@@ -661,7 +662,27 @@ void DatabaseService::migrateEncryptionAtRest() {
         requestResealAtNextBoot();
         return;
     }
+    // v2.17.2 - which envs to compact. The first run compacts every project.
+    // A reseal compacts only the projects named in the pending file; "*" (a
+    // failure path) or a pre-2.17.2 file (its content was "1") means all.
+    // 2.17.1 compacted every project on any reseal: a 262 MB env the upgrade
+    // never touched cost 2.5 minutes of a restart and reclaimed nothing.
+    bool compactAll = firstRun;
+    std::set<std::string> toCompact;
+    if (!firstRun) {
+        std::ifstream in(reseal);
+        std::string line;
+        while (std::getline(in, line)) {
+            if (line.empty()) continue;
+            if (line == "*" || line == "1") compactAll = true;
+            else toCompact.insert(line);
+        }
+        if (toCompact.empty()) compactAll = true;
+    }
+    size_t compacted = 0;
     for (const auto& p : projects_->listOpen()) {
+        if (!compactAll && !toCompact.count(p)) continue;
+        ++compacted;
         uint64_t before = 0, after = 0;
         std::string cerr;
         if (projects_->compact(p, before, after, cerr)) {
@@ -669,7 +690,7 @@ void DatabaseService::migrateEncryptionAtRest() {
         } else {
             spdlog::error("v2.17 at-rest: project '{}' compaction failed: {} - freed pages may "
                           "still hold old plaintext; the next boot retries", p, cerr);
-            requestResealAtNextBoot();
+            requestResealAtNextBoot(p);
             applyIndexDeclarations();
             applyRelationDeclarations(/*afterMigrations=*/true);
             return;
@@ -681,9 +702,10 @@ void DatabaseService::migrateEncryptionAtRest() {
 
     std::ofstream(marker) << "encrypted at rest by 2.17.0\n";
     fs::remove(reseal, ec);
-    spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, every "
-                 "project compacted. Copies made BEFORE this boot (backups, pre-upgrade copies, "
-                 "replicas, disk blocks) are outside the database's reach.", snaps, wals);
+    spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, {} "
+                 "project(s) compacted{}. Copies made BEFORE this boot (backups, pre-upgrade copies, "
+                 "replicas, disk blocks) are outside the database's reach.", snaps, wals, compacted,
+                 compactAll ? " (all)" : "");
 }
 
 void DatabaseService::applySchemaDeclarations() {

+ 4 - 1
service/src/database_service.hpp

@@ -403,7 +403,10 @@ public:
 
     // v2.17.0 - old plaintext copies (WAL, older snapshots, LMDB free pages)
     // can only be removed at boot; ask the next boot to do it.
-    void requestResealAtNextBoot();
+    // v2.17.2: `project` names the one project whose env must be compacted;
+    // empty means every project (the failure paths). Requests accumulate, one
+    // line per request, until a boot performs the seal.
+    void requestResealAtNextBoot(const std::string& project = "");
     // v2.17.0 - the one-time migration ran and no reseal is pending.
     bool atRestSealed() const {
         std::error_code ec;

+ 13 - 4
service/src/memory_store.cpp

@@ -164,13 +164,19 @@ bool MemoryStore::createCollection(const std::string& name, const CollectionOpti
             // did. Before, the setting was accepted and nothing was trimmed,
             // so a collection that had kept unlimited history could not be
             // cut back by any supported call.
+            it->second->updatedAt = currentTimeMs();
+            spdlog::info("Updated maxVersions for collection '{}' to {}", name, options.maxVersions);
             if (historyStore_ && (oldMax == 0 || options.maxVersions < oldMax)) {
-                historyStore_->prune(name, options.maxVersions);
+                // v2.17.2 - prune AFTER releasing the global lock: the rewrite
+                // takes seconds on a large file and needs only that file's
+                // history mutex. 2.17.1 ran it here, under globalMutex_
+                // exclusively, so every collection's operations waited.
+                const uint32_t newMax = options.maxVersions;
+                lock.unlock();
+                historyStore_->prune(name, newMax);
                 spdlog::info("Pruned on-disk version history for collection '{}' (maxVersions: {} -> {})",
-                             name, oldMax, options.maxVersions);
+                             name, oldMax, newMax);
             }
-            it->second->updatedAt = currentTimeMs();
-            spdlog::info("Updated maxVersions for collection '{}' to {}", name, options.maxVersions);
         }
         return false;  // Already exists
     }
@@ -285,6 +291,9 @@ bool MemoryStore::alterCollection(const std::string& name, const CollectionOptio
     // expect their setting to take effect immediately.
     if (historyStore_ && newMaxVersions > 0 &&
         (oldMaxVersions == 0 || newMaxVersions < oldMaxVersions)) {
+        // v2.17.2 - outside the collection and global locks (see createCollection).
+        collLock.unlock();
+        globalLock.unlock();
         historyStore_->prune(name, newMaxVersions);
         spdlog::info("Pruned on-disk version history for collection '{}' (maxVersions: {} -> {})",
                      name, oldMaxVersions, newMaxVersions);

+ 42 - 28
service/src/persistence/history_store.cpp

@@ -156,7 +156,7 @@ void HistoryStore::append(const std::string& collection,
                           const DocumentVersion& version) {
     auto bytes = serializeRecord(docId, version);
 
-    std::lock_guard<std::mutex> lock(appendMutex_);
+    std::lock_guard<std::mutex> lock(fileMutex(collection));
     std::ofstream f(filePath(collection), std::ios::binary | std::ios::app);
     if (!f) {
         spdlog::error("HistoryStore: failed to open {} for append",
@@ -229,7 +229,7 @@ uint64_t HistoryStore::countVersions(
 }
 
 void HistoryStore::dropCollection(const std::string& collection) {
-    std::lock_guard<std::mutex> lock(appendMutex_);
+    std::lock_guard<std::mutex> lock(fileMutex(collection));
     std::error_code ec;
     std::filesystem::remove(filePath(collection), ec);
 }
@@ -240,39 +240,46 @@ void HistoryStore::prune(const std::string& collection, uint32_t maxVersions) {
     auto path = filePath(collection);
     if (!std::filesystem::exists(path)) return;
 
-    // Read the whole file into a per-doc bucket (newest-last order, as the
-    // file is append-only). Keep the last `maxVersions` per doc, then
-    // rewrite. The append lock is held for the duration so no concurrent
-    // writer interleaves.
-    std::lock_guard<std::mutex> lock(appendMutex_);
+    // v2.17.2 - two streamed passes under this file's mutex only: count the
+    // versions per doc, then copy each doc's newest `maxVersions` (the file is
+    // append-only, so a doc's records are oldest first). Memory is one counter
+    // per doc instead of every kept version of every doc.
+    std::lock_guard<std::mutex> lock(fileMutex(collection));
 
-    std::ifstream in(path, std::ios::binary);
-    if (!in) return;
-
-    std::unordered_map<std::string, std::deque<DocumentVersion>> buckets;
-    scanFile(in, [&](const std::string& recDocId, DocumentVersion&& v) {
-        auto& q = buckets[recDocId];
-        q.push_back(std::move(v));
-        if (q.size() > maxVersions) q.pop_front();
-    });
-    in.close();
+    std::unordered_map<std::string, uint64_t> total;
+    {
+        std::ifstream in(path, std::ios::binary);
+        if (!in) return;
+        scanFile(in, [&](const std::string& recDocId, DocumentVersion&&) { ++total[recDocId]; });
+    }
+    bool anyOver = false;
+    for (const auto& [id, n] : total) anyOver = anyOver || n > maxVersions;
+    if (!anyOver) return;   // nothing to drop: leave the file as it is
 
-    // Write atomically: tmp + rename.
     auto tmp = path;
     tmp += ".tmp";
     {
+        std::ifstream in(path, std::ios::binary);
         std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
-        if (!out) {
-            spdlog::warn("HistoryStore::prune: failed to open {} for rewrite",
-                         tmp.string());
+        if (!in || !out) {
+            spdlog::warn("HistoryStore::prune: failed to open {} for rewrite", tmp.string());
             return;
         }
-        for (auto& [docId, versions] : buckets) {
-            for (auto& v : versions) {
-                auto bytes = serializeRecord(docId, v);
-                out.write(reinterpret_cast<const char*>(bytes.data()),
-                          static_cast<std::streamsize>(bytes.size()));
-            }
+        std::unordered_map<std::string, uint64_t> seen;
+        scanFile(in, [&](const std::string& recDocId, DocumentVersion&& v) {
+            const uint64_t n = total[recDocId];
+            const uint64_t k = ++seen[recDocId];
+            if (n > maxVersions && k <= n - maxVersions) return;   // older than the newest N
+            auto bytes = serializeRecord(recDocId, v);
+            out.write(reinterpret_cast<const char*>(bytes.data()),
+                      static_cast<std::streamsize>(bytes.size()));
+        });
+        out.flush();
+        if (!out) {
+            spdlog::warn("HistoryStore::prune: write failed for {}", tmp.string());
+            std::error_code ec;
+            std::filesystem::remove(tmp, ec);
+            return;
         }
     }
 
@@ -289,7 +296,7 @@ uint64_t HistoryStore::rewrite(const std::string& collection,
                                const std::function<bool(DocumentVersion&)>& transform) {
     auto path = filePath(collection);
     if (!std::filesystem::exists(path)) return 0;
-    std::lock_guard<std::mutex> lock(appendMutex_);
+    std::lock_guard<std::mutex> lock(fileMutex(collection));
 
     std::ifstream in(path, std::ios::binary);
     if (!in) return 0;
@@ -341,6 +348,13 @@ uint64_t HistoryStore::forEach(
     return scanFile(f, [&](const std::string& docId, DocumentVersion&& v) { visit(docId, v); });
 }
 
+std::mutex& HistoryStore::fileMutex(const std::string& collection) const {
+    std::lock_guard<std::mutex> g(fileMutexesGuard_);
+    auto& slot = fileMutexes_[collection];
+    if (!slot) slot = std::make_unique<std::mutex>();
+    return *slot;
+}
+
 uint64_t HistoryStore::totalSizeBytes() const {
     uint64_t total = 0;
     std::error_code ec;

+ 15 - 6
service/src/persistence/history_store.hpp

@@ -7,6 +7,7 @@
 #include <filesystem>
 #include <fstream>
 #include <functional>
+#include <memory>
 #include <mutex>
 #include <optional>
 #include <string>
@@ -40,10 +41,11 @@ namespace smartbotic::database {
  * doc_id; called periodically by a background thread on collections
  * that have a `max_versions` cap.
  *
- * Concurrency: a single `appendMutex_` serializes appends. Reads open a
- * fresh ifstream, so concurrent readers don't block each other. The
- * worst case under high write rate is a single producer writing
- * sequentially, which is what the file system handles best anyway.
+ * Concurrency: one mutex PER FILE (per collection) serializes appends,
+ * prune, rewrite and drop on that file. Before 2.17.2 a single global mutex
+ * did, so pruning or rewriting one collection's large file stalled every
+ * history-recording write in every collection. Reads open a fresh ifstream
+ * and take no lock.
  */
 class HistoryStore {
 public:
@@ -99,7 +101,9 @@ public:
      * Rewrite the history file for `collection` keeping at most
      * `maxVersions` entries per doc_id (newest). Called periodically
      * by a background thread; safe to call concurrently with writes
-     * (under the appendMutex_).
+     * (under that collection's file mutex). v2.17.2: streamed in two passes
+     * (count per doc, then copy the newest N), so memory holds a per-doc
+     * counter, not the file.
      */
     void prune(const std::string& collection, uint32_t maxVersions);
 
@@ -130,7 +134,12 @@ public:
 
 private:
     std::filesystem::path historyDir_;
-    mutable std::mutex appendMutex_;
+    // v2.17.2 - per-file mutexes. fileMutexesGuard_ protects only the map;
+    // entries are never erased (a dropped collection's mutex is reused if
+    // the name returns), so a reference stays valid for the store's life.
+    mutable std::mutex fileMutexesGuard_;
+    mutable std::unordered_map<std::string, std::unique_ptr<std::mutex>> fileMutexes_;
+    [[nodiscard]] std::mutex& fileMutex(const std::string& collection) const;
 
     [[nodiscard]] std::filesystem::path filePath(const std::string& collection) const;
 

+ 9 - 0
tests/load_test/test_encryption_at_rest.cpp

@@ -85,6 +85,9 @@ static int seed() {
     // `aliased` is declared encrypted by the migration file under its BARE
     // name; the client's rows land in default:aliased.
     c.insert("aliased", {{"v", "CANARY-ALIASED-4417"}}, "a1");
+    // A second project, untouched by the online upgrade below: a reseal must
+    // not compact it (v2.17.2).
+    c.insert("bystander:things", {{"name", "untouched"}}, "t1");
     return 0;
 }
 
@@ -242,6 +245,12 @@ static int upgraded() {
 static int upgrade2() {
     Client c(cfg());
     c.connect();
+    // v2.17.2 - switching on a flag whose values are already ciphertext (here
+    // through the bare alias) rewrites nothing, so it must not request a
+    // reseal and its compaction restart.
+    (void)c.createCollection("aliased", 0, true, 0, 0);
+    ck(c.verifyEncryption("aliased").atRestSealed,
+       "a flag switched on over values already encrypted requests no reseal");
     ck(!c.verifyEncryption("late").collections.empty(), "late is audited");
     ck(!c.createCollection("late", 0, true, 0, 0), "createCollection on existing late returns false");
     auto r = c.verifyEncryption("late");

+ 16 - 0
tests/load_test/test_encryption_at_rest.sh

@@ -117,6 +117,14 @@ grep -E "v2.17 at-rest" "$DIR/server.log" | sed 's/^/    /'
 run upgraded
 stop
 for c in "${ALL[@]}"; do must_not_find "$c"; done
+# The first seal compacts every project - both of them, so the reseal check
+# below (only the touched one) is not vacuous.
+if grep -E "at-rest: sealed" "$DIR/server.log" | tail -1 | grep -q "2 project(s) compacted (all)"; then
+    echo "ok   the first seal compacted both projects"
+else
+    echo "FAIL first seal: $(grep -E 'at-rest: sealed' "$DIR/server.log" | tail -1)"
+    FAILS=$((FAILS+1))
+fi
 # `late` is neither encrypted nor sensitive yet: still plaintext, by design.
 must_find CANARY-LATE-VALUE-6604
 
@@ -129,6 +137,14 @@ echo "=== restart: the reseal ==="
 start "$NEW"
 run resealed
 stop
+# v2.17.2 - the reseal compacts only the project the online upgrade touched
+# (default), not the bystander project.
+if grep -E "at-rest: sealed" "$DIR/server.log" | tail -1 | grep -q "1 project(s) compacted\. "; then
+    echo "ok   the reseal compacted only the touched project"
+else
+    echo "FAIL the reseal did not compact exactly one project: $(grep -E 'at-rest: sealed' "$DIR/server.log" | tail -1)"
+    FAILS=$((FAILS+1))
+fi
 for c in "${ALL[@]}" CANARY-LATE-VALUE-6604; do must_not_find "$c"; done
 
 echo "=== restart again: nothing re-runs, nothing changes ==="

+ 58 - 15
tests/test_history_audit_scan.cpp

@@ -8,9 +8,14 @@
 //
 // The test is deterministic: from INSIDE the scan callback it starts an
 // append on another thread and waits up to 2 s for it. Under forEach the
-// append completes at once; under rewrite() it cannot complete until the scan
-// ends, so the wait times out (asserted for rewrite() too, so a forEach that
-// quietly took the lock would fail, and the harness is shown to detect it).
+// append completes at once; under rewrite() an append to the SAME collection
+// cannot complete until the scan ends, so the wait times out (asserted, so a
+// forEach that quietly took the lock would fail, and the harness is shown to
+// detect it).
+//
+// v2.17.2 - history locks are per file: a rewrite or prune of one collection
+// must not block an append to ANOTHER (2.17.1 had one global lock, so pruning
+// a large file stalled every collection's history-recording writes).
 
 #include "persistence/history_store.hpp"
 
@@ -21,6 +26,8 @@
 #include <iostream>
 #include <string>
 #include <thread>
+#include <unordered_map>
+#include <vector>
 
 using namespace smartbotic::database;
 
@@ -43,11 +50,12 @@ int main() {
     std::filesystem::remove_all(dir);
     HistoryStore hs(HistoryStore::Config{dir});
     for (uint64_t i = 1; i <= 200; ++i) hs.append("audited", "d" + std::to_string(i % 7), version(i));
+    // The lock tests append into "busy" while scanning it, so they get their own file.
+    for (uint64_t i = 1; i <= 200; ++i) hs.append("busy", "b" + std::to_string(i % 7), version(i));
 
-    // An append to ANOTHER collection, started from inside the scan: it takes
-    // the same global lock, which is exactly what stalled a live server.
-    const auto appendDuringScan = [&](bool& sawCompletion, uint64_t n) {
-        auto fut = std::async(std::launch::async, [&] { hs.append("other", "o", version(n)); });
+    // An append started from inside the scan, to `target`.
+    const auto appendDuringScan = [&](bool& sawCompletion, uint64_t n, const std::string& target) {
+        auto fut = std::async(std::launch::async, [&hs, n, target] { hs.append(target, "o", version(n)); });
         sawCompletion = fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready;
         return fut;   // joined by the caller after the scan, so rewrite() can finish
     };
@@ -55,24 +63,59 @@ int main() {
     {
         bool first = true, completed = false;
         std::future<void> pending;
-        const uint64_t visited = hs.forEach("audited", [&](const std::string&, const DocumentVersion&) {
-            if (first) { first = false; pending = appendDuringScan(completed, 1); }
+        const uint64_t visited = hs.forEach("busy", [&](const std::string&, const DocumentVersion&) {
+            if (first) { first = false; pending = appendDuringScan(completed, 1, "busy"); }
         });
         if (pending.valid()) pending.wait();
-        check(visited == 200, "forEach visits every stored version (" + std::to_string(visited) + ")");
-        check(completed, "an append completes while forEach is reading (no append lock held)");
+        // 200, or 201 if the scan also reached the record appended meanwhile.
+        check(visited == 200 || visited == 201, "forEach visits every stored version (" + std::to_string(visited) + ")");
+        check(hs.forEach("audited", [](const std::string&, const DocumentVersion&) {}) == 200,
+              "forEach on a quiet file visits exactly its 200 versions");
+        check(completed, "an append to the SAME collection completes while forEach is reading (no lock held)");
     }
     {
         bool first = true, completed = true;
         std::future<void> pending;
-        hs.rewrite("audited", [&](DocumentVersion&) {
-            if (first) { first = false; pending = appendDuringScan(completed, 2); }
+        hs.rewrite("busy", [&](DocumentVersion&) {
+            if (first) { first = false; pending = appendDuringScan(completed, 2, "busy"); }
             return false;
         });
         if (pending.valid()) pending.wait();
-        check(!completed, "control: under rewrite() the same append waits (the harness detects the lock)");
+        check(!completed, "control: under rewrite() an append to the same collection waits (the harness detects the lock)");
+    }
+    {
+        bool first = true, completed = false;
+        std::future<void> pending;
+        hs.rewrite("busy", [&](DocumentVersion&) {
+            if (first) { first = false; pending = appendDuringScan(completed, 3, "other"); }
+            return false;
+        });
+        if (pending.valid()) pending.wait();
+        check(completed, "v2.17.2: a rewrite of one collection does NOT block an append to another");
+    }
+    {
+        // prune: keeps the newest N per doc, in file order.
+        for (uint64_t i = 1; i <= 50; ++i) hs.append("pruned", "p" + std::to_string(i % 5), version(i));
+        // (Its lock is the same per-file mutex the rewrite case above proves.)
+        hs.prune("pruned", 3);
+        std::unordered_map<std::string, std::vector<uint64_t>> kept;
+        uint64_t total = 0;
+        hs.forEach("pruned", [&](const std::string& id, const DocumentVersion& v) {
+            kept[id].push_back(v.version);
+            ++total;
+        });
+        bool newest = total == 15;
+        for (const auto& [id, vs] : kept) {
+            newest = newest && vs.size() == 3 && vs[0] < vs[1] && vs[1] < vs[2] && vs[2] > 40;
+        }
+        check(newest, "prune keeps exactly the newest 3 versions per doc, oldest first (" + std::to_string(total) + " kept)");
+        hs.prune("pruned", 3);
+        uint64_t again = 0;
+        hs.forEach("pruned", [&](const std::string&, const DocumentVersion&) { ++again; });
+        check(again == 15, "pruning again to the same cap changes nothing");
     }
-    check(hs.countVersions("other", "o") == 2, "both appends landed");
+    check(hs.countVersions("other", "o") == 1 && hs.countVersions("busy", "o") == 2,
+          "every append landed (1 in the other collection, 2 in the scanned one)");
 
     // v2.17.1 - rewrite() streams record by record. A pass that changes nothing
     // leaves the file byte-identical and no tmp behind; a pass that changes