Преглед изворни кода

fix: 2.17.1 - safe encryption-verify, bounded migration memory, reserved project:_name

From the first live 2.17.0 upgrade, found through the consumers' measurements:
- encryption-verify read history under the global append lock, stalling every
  history-recording write server-wide while a large file was read; it now
  uses HistoryStore::forEach, a read-only scan without the lock.
- HistoryStore::rewrite is streamed (one record in memory), so the boot
  migration's peak no longer scales with the largest history file.
- Compaction installs the compacted env with one atomic rename; the old
  two-rename swap could leave no data.mdb if killed in between.
- GetCollectionInfo reports the ENFORCED encryption rule (merged with the
  bare alias); the CLI info also prints versioning on/off.
- project:_name collections are refused (reserved_collection_name): writes
  to them answered ok and could never be read back (since 2.3.0). Drop is
  still allowed.
- createCollection(existing, lower maxVersions) prunes history on disk.
Tests: test_history_audit_scan, test_collection_admin (port 9033),
test_encryption_at_rest +3; test_server_info's old phase no longer assumes
the previous release lacks the newest capability. ABI: unchanged, soname 2.
fszontagh пре 1 месец
родитељ
комит
8d6f6f3e1d

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.17.0
+2.17.1

+ 13 - 1
cli/main.cpp

@@ -78,7 +78,9 @@ void printUsage() {
               << "  " << C_CYAN << "unlock" << C_RESET << "                               Unlock database (accept writes)\n"
               << "  " << C_CYAN << "unlock" << C_RESET << "                               Unlock database (accept writes)\n"
               << "  " << C_CYAN << "status" << C_RESET << "                               Show read-only + recovery status\n"
               << "  " << C_CYAN << "status" << C_RESET << "                               Show read-only + recovery status\n"
               << "  " << C_CYAN << "server-info" << C_RESET << "                          Server version, commit and feature names (2.15.0+)\n"
               << "  " << C_CYAN << "server-info" << C_RESET << "                          Server version, commit and feature names (2.15.0+)\n"
-              << "  " << C_CYAN << "encryption-verify" << C_RESET << " [collection]         Audit encryption at rest (exit 1 on any finding)\n"
+              << "  " << C_CYAN << "encryption-verify" << C_RESET << " [collection]         Audit encryption at rest (exit 1 on any finding).\n"
+              << "                                       Against a 2.17.0 SERVER it stalls history-recording writes\n"
+              << "                                       server-wide while it reads history; 2.17.1+ does not.\n"
               << C_BOLD << "  Collection schema (v2.16.0+)" << C_RESET << "\n"
               << C_BOLD << "  Collection schema (v2.16.0+)" << C_RESET << "\n"
               << "  " << C_CYAN << "schema" << C_RESET << " <collection>                  Show the schema, mode and counters\n"
               << "  " << C_CYAN << "schema" << C_RESET << " <collection>                  Show the schema, mode and counters\n"
               << "  " << C_CYAN << "schema-set" << C_RESET << " <collection> <json|@file> [--audit]\n"
               << "  " << C_CYAN << "schema-set" << C_RESET << " <collection> <json|@file> [--audit]\n"
@@ -646,6 +648,16 @@ bool execCommand(smartbotic::database::Client& client,
             // printed, since the default is ON and an operator should not
             // printed, since the default is ON and an operator should not
             // have to know that to learn a delete may be refused. A failed
             // have to know that to learn a delete may be refused. A failed
             // read says so rather than printing the default.
             // read says so rather than printing the default.
+            // v2.17.1 - versioning on/off: a collection whose history stopped
+            // was otherwise visible only as a config field nobody reads.
+            try {
+                const auto cfg = client.getCollectionConfig(params[0]);
+                std::cout << "  versioning: "
+                          << (!cfg.versioningEnabled ? "unknown" : *cfg.versioningEnabled ? "on" : "OFF (no history is recorded)")
+                          << "\n";
+            } catch (const std::exception&) {
+                std::cout << "  versioning: unknown (could not be read)\n";
+            }
             const auto enforced = client.tryGetRelationsEnforced(params[0]);
             const auto enforced = client.tryGetRelationsEnforced(params[0]);
             std::cout << "  relations_enforced: "
             std::cout << "  relations_enforced: "
                       << (!enforced ? "unknown (could not be read)" : *enforced ? "on" : "off")
                       << (!enforced ? "unknown (could not be read)" : *enforced ? "on" : "off")

+ 6 - 3
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 # Smartbotic Database - Status and Roadmap
 
 
-**Released version: 2.17.0** (see `VERSION`). Last reviewed: 2026-10-09.
+**Released version: 2.17.1** (see `VERSION`). Last reviewed: 2026-10-12.
 
 
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > 2.11.5 was prepared but never released on its own: its work (event actors,
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
 > `removeAs()`) ships inside 2.12.0. There is no 2.11.5 package.
@@ -56,7 +56,7 @@ Consequences of that substitution, which trip up readers:
 
 
 ## Shipped
 ## Shipped
 
 
-Every item below is in the installed product as of 2.17.0. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.17.1. `CLAUDE.md` has the
 detail and the failure modes.
 detail and the failure modes.
 
 
 - JSON document store: collections, version history, field-level encryption, TTL
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -64,7 +64,10 @@ detail and the failure modes.
 - Multi-project namespaces (`<project>:<collection>`)
 - Multi-project namespaces (`<project>:<collection>`)
 - Encryption at rest that does what it says: encrypted collections,
 - Encryption at rest that does what it says: encrypted collections,
   `sensitive_fields`, sensitive names at any depth, a one-time migration with
   `sensitive_fields`, sensitive names at any depth, a one-time migration with
-  a seal, `encryption-verify`, comparisons on ciphertext refused (2.17.0)
+  a seal, `encryption-verify`, comparisons on ciphertext refused (2.17.0);
+  verify without the global history lock, a streamed history rewrite, an
+  atomic compaction swap, `info` showing the enforced rule and versioning,
+  `project:_name` refused, history pruned when `maxVersions` is lowered (2.17.1)
 - Optional per-collection JSON Schema (enforce/audit, existing rows checked
 - Optional per-collection JSON Schema (enforce/audit, existing rows checked
   first, suggested from data) (2.16.0)
   first, suggested from data) (2.16.0)
 - Independent client and server releases: `GetServerInfo` capability
 - Independent client and server releases: `GetServerInfo` capability

+ 36 - 3
docs/integration-guide.md

@@ -794,6 +794,16 @@ accepts none of them from a caller. The originals stay in `row.document` in your
 archive; copy them into a field of your own before importing if you need them as
 archive; copy them into a field of your own before importing if you need them as
 data.
 data.
 
 
+### Reserved collection names: `project:_name` (2.17.1+)
+
+A collection name starting with `_` is internal. Written WITH a project
+(`app:_cache`) such a name is **refused** for reads and writes with INVALID_ARGUMENT, reason
+`reserved_collection_name`. Before 2.17.1 a write to one answered ok and could
+never be read back: it was kept in memory and the WAL but not in the on-disk
+store every read uses. `dropCollection` still accepts such a name, so leftovers
+can be removed. A bare `_name` is not qualified by the client and lives in the
+global namespace (the system collections); that is unchanged.
+
 ### Reserved names in a write body (2.13.0+)
 ### Reserved names in a write body (2.13.0+)
 
 
 `_id`, `_version`, `_created_at`, `_updated_at`, `_created_by` and `_updated_by`
 `_id`, `_version`, `_created_at`, `_updated_at`, `_created_by` and `_updated_by`
@@ -1017,8 +1027,12 @@ restart: `encryption-verify` reports `sealed: NO` until then.
 **Check the flag rather than assume it.** A bootstrap that calls
 **Check the flag rather than assume it.** A bootstrap that calls
 `createCollection(..., encrypted=true)` only when the collection does not exist
 `createCollection(..., encrypted=true)` only when the collection does not exist
 yet never sets it when an earlier write already created the collection
 yet never sets it when an earlier write already created the collection
-implicitly. `smartbotic-db-cli info <collection>` shows `encrypted: yes|no`.
-Calling `createCollection(..., encrypted=true)` unconditionally fixes it.
+implicitly. Calling `createCollection(..., encrypted=true)` unconditionally fixes
+it. To check, use `encryption-verify` (an encrypted collection is marked
+`[encrypted]`). Since 2.17.1 `smartbotic-db-cli info <collection>` also reports
+the ENFORCED rule; in 2.17.0 it showed only the collection's own options, which
+can disagree with the bytes in either direction (options declared on a bare
+alias name are enforced but were not shown).
 
 
 **Encrypted fields cannot be compared, so comparisons are REFUSED** with
 **Encrypted fields cannot be compared, so comparisons are REFUSED** with
 INVALID_ARGUMENT, reason `encrypted_field`, the fields named:
 INVALID_ARGUMENT, reason `encrypted_field`, the fields named:
@@ -1058,6 +1072,17 @@ and counts:
 - ciphertext the key cannot open;
 - ciphertext the key cannot open;
 and whether the migration's seal is complete. It exits 1 on any finding.
 and whether the migration's seal is complete. It exits 1 on any finding.
 
 
+What CLEAN means: everything the rules above REQUIRE to be encrypted is
+encrypted, once, and decrypts. It does not mean "nothing sensitive is in the
+clear": a secret stored under a non-sensitive name in a collection that is not
+encrypted is invisible to it by design.
+
+**⚠ Against a 2.17.0 server, do not run it on a live database:** it read
+history under the global history lock, so every history-recording write, in
+every collection, waited while a large history file was read (minutes for a
+230 MB file; seen as Deadline Exceeded on unrelated collections). 2.17.1 reads
+history without that lock.
+
 **To turn encryption off** set `storage.encryption.enabled: false`. Existing
 **To turn encryption off** set `storage.encryption.enabled: false`. Existing
 ciphertext then reads back as the literal `$ENC$` string, so do it before
 ciphertext then reads back as the literal `$ENC$` string, so do it before
 storing such fields, not after.
 storing such fields, not after.
@@ -1245,6 +1270,13 @@ Semantics:
   it survives restarts through the normal WAL + snapshot path.
   it survives restarts through the normal WAL + snapshot path.
 - Takes effect on the next write.
 - Takes effect on the next write.
 
 
+**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, so a large file takes seconds; do it at a
+quiet moment. 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+)
 #### Relation enforcement on/off (2.11.0+)
 
 
 Whether declared relations are enforced is a per-collection setting. It
 Whether declared relations are enforced is a per-collection setting. It
@@ -1646,7 +1678,8 @@ db.listCollections();                      // -> { "users", ... }
 > **After upgrading:** leftover empty phantom collections are harmless litter,
 > **After upgrading:** leftover empty phantom collections are harmless litter,
 > but options that were swallowed do **not** retroactively apply.
 > but options that were swallowed do **not** retroactively apply.
 > `createCollection` on a now-correctly-resolved existing collection returns
 > `createCollection` on a now-correctly-resolved existing collection returns
-> `false` and only updates `maxVersions`. Since `vectorDimension` is **immutable
+> `false` and only updates `maxVersions` (and, since 2.17.1, prunes history to a
+> lower cap). Since `vectorDimension` is **immutable
 > after creation**, a collection that needs vector search must be recreated:
 > after creation**, a collection that needs vector search must be recreated:
 > create a new collection with the right `vectorDimension`, copy the documents
 > create a new collection with the right `vectorDimension`, copy the documents
 > across, then drop the old one.
 > across, then drop the old one.

+ 54 - 5
service/src/database_grpc_impl.cpp

@@ -205,10 +205,36 @@ static std::optional<uint64_t> expiryOverrideFrom(const Req& request) {
            static_cast<uint64_t>(request.ttl_seconds()) * 1000ULL;
            static_cast<uint64_t>(request.ttl_seconds()) * 1000ULL;
 }
 }
 
 
+// v2.17.1 - "project:_name" is reserved. A leading '_' marks a system
+// collection, but the checks disagreed on WHERE to look: the LMDB mirror tests
+// the collection part (and skips it), the read paths test the whole qualified
+// name (and go to LMDB). So a write to "app:_x" answered ok, lived only in
+// memory and the WAL, and no read could ever find it - silently, since 2.3.0.
+// Refused for reads and writes alike, before any handler work. Bare "_name"
+// (the global system collections) is unchanged.
+static grpc::Status refuseReservedName(const grpc::ServerContext* context, const std::string& qualified) {
+    const auto colon = qualified.find(':');
+    if (colon == std::string::npos || colon + 1 >= qualified.size() || qualified[colon + 1] != '_') {
+        return grpc::Status::OK;
+    }
+    attachErrorDetail(const_cast<grpc::ServerContext*>(context),
+                      {{"reason", "reserved_collection_name"},
+                       {"fields", nlohmann::json::array({qualified})}});
+    return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
+                        "collection name '" + qualified +
+                        "' is reserved: a name starting with '_' inside a project is an "
+                        "internal name. Choose a name that does not start with '_'.");
+}
+
 grpc::Status DatabaseGrpcImpl::gate(const grpc::ServerContext* context,
 grpc::Status DatabaseGrpcImpl::gate(const grpc::ServerContext* context,
                                      const std::string& qualified,
                                      const std::string& qualified,
                                      smartbotic::database::Access access,
                                      smartbotic::database::Access access,
-                                     smartbotic::database::Decision& out) const {
+                                     smartbotic::database::Decision& out,
+                                     bool allowReservedName) const {
+    // v2.17.1 - "project:_name" is reserved (see refuseReservedName).
+    if (!allowReservedName) {
+        if (auto st = refuseReservedName(context, qualified); !st.ok()) return st;
+    }
     // Fast path: no project has security enabled, which is the default and the
     // Fast path: no project has security enabled, which is the default and the
     // whole pre-2.8.0 world. One relaxed atomic load.
     // whole pre-2.8.0 world. One relaxed atomic load.
     if (!policy_manager_.anyProjectSecured()) {
     if (!policy_manager_.anyProjectSecured()) {
@@ -1567,6 +1593,10 @@ grpc::Status DatabaseGrpcImpl::Find(
     const pb::FindRequest* request,
     const pb::FindRequest* request,
     pb::FindResponse* response
     pb::FindResponse* response
 ) {
 ) {
+    // v2.17.1 - before the existence check, so a reserved name is refused
+    // whether or not an older server left such a collection behind.
+    if (auto st = refuseReservedName(context, request->collection()); !st.ok()) return st;
+
     // Resolve view to real collection (if applicable)
     // Resolve view to real collection (if applicable)
     std::string targetCollection = request->collection();
     std::string targetCollection = request->collection();
     std::optional<ViewInfo> view;
     std::optional<ViewInfo> view;
@@ -2455,8 +2485,11 @@ grpc::Status DatabaseGrpcImpl::DropCollection(
     pb::DropCollectionResponse* response
     pb::DropCollectionResponse* response
 ) {
 ) {
     // v2.8.0 — access gate. Destructive; must never be reachable without a write grant.
     // v2.8.0 — access gate. Destructive; must never be reachable without a write grant.
+    // v2.17.1: a reserved "project:_name" may still be DROPPED, so the empty
+    // collections the pre-2.17.1 bug left behind can be removed.
     smartbotic::database::Decision dec;
     smartbotic::database::Decision dec;
-    if (auto st = gate(context, request->name(), smartbotic::database::Access::Write, dec); !st.ok()) {
+    if (auto st = gate(context, request->name(), smartbotic::database::Access::Write, dec,
+                       /*allowReservedName=*/true); !st.ok()) {
         return st;
         return st;
     }
     }
 
 
@@ -2611,6 +2644,21 @@ grpc::Status DatabaseGrpcImpl::GetCollectionInfo(
     }
     }
 
 
     *response->mutable_info() = toProtoCollInfo(*info);
     *response->mutable_info() = toProtoCollInfo(*info);
+    // v2.17.1 - report the encryption that is ENFORCED: the collection's own
+    // options merged with its bare/qualified alias (encryptionOptionsFor), the
+    // rule every write and the at-rest migration apply. Reporting only the
+    // collection's own flag said "encrypted: no" for collections whose values
+    // were encrypted through the alias (found on a live server: options set on
+    // a bare name by a pre-2.4.5 client).
+    {
+        bool enc = false;
+        std::vector<std::string> fields;
+        store_.encryptionOptionsFor(request->name(), enc, fields);
+        auto* opts = response->mutable_info()->mutable_options();
+        opts->set_encrypted(enc);
+        opts->clear_sensitive_fields();
+        for (const auto& f : fields) opts->add_sensitive_fields(f);
+    }
     response->set_found(true);
     response->set_found(true);
 
 
     return grpc::Status::OK;
     return grpc::Status::OK;
@@ -3330,10 +3378,11 @@ grpc::Status DatabaseGrpcImpl::VerifyEncryption(
             }
             }
             uint64_t versions = 0;
             uint64_t versions = 0;
             if (auto* hs = service_.historyStore()) {
             if (auto* hs = service_.historyStore()) {
-                hs->rewrite(coll, [&](DocumentVersion& v) {
-                    ++versions;
+                // Read-only, no append lock: rewrite() would stall every
+                // history-recording write server-wide while a large file is
+                // read (minutes on a 230 MB file, found on a live server).
+                versions = hs->forEach(coll, [&](const std::string&, const DocumentVersion& v) {
                     encryption_.auditTree(v.data(), rule, hist);
                     encryption_.auditTree(v.data(), rule, hist);
-                    return false;   // audit only: nothing is written
                 });
                 });
             }
             }
             a->set_rows(n);
             a->set_rows(n);

+ 5 - 1
service/src/database_grpc_impl.hpp

@@ -577,10 +577,14 @@ private:
     //
     //
     // Deliberately ONE function rather than inline checks: with ~16 call sites,
     // Deliberately ONE function rather than inline checks: with ~16 call sites,
     // a per-handler check is a place to forget, and forgetting fails open.
     // a per-handler check is a place to forget, and forgetting fails open.
+    // v2.17.1: also refuses a project-qualified name whose collection part
+    // starts with '_' (reserved_collection_name) unless `allowReservedName`
+    // (DropCollection only, so such a collection can be removed).
     grpc::Status gate(const grpc::ServerContext* context,
     grpc::Status gate(const grpc::ServerContext* context,
                       const std::string& qualified,
                       const std::string& qualified,
                       smartbotic::database::Access access,
                       smartbotic::database::Access access,
-                      smartbotic::database::Decision& out) const;
+                      smartbotic::database::Decision& out,
+                      bool allowReservedName = false) const;
 
 
     // Same for the file RPCs, which key on file type rather than collection.
     // Same for the file RPCs, which key on file type rather than collection.
     grpc::Status gateFile(const grpc::ServerContext* context,
     grpc::Status gateFile(const grpc::ServerContext* context,

+ 11 - 0
service/src/memory_store.cpp

@@ -157,7 +157,18 @@ bool MemoryStore::createCollection(const std::string& name, const CollectionOpti
 
 
         // Update maxVersions on existing collection if specified
         // Update maxVersions on existing collection if specified
         if (options.maxVersions > 0 && it->second->options.maxVersions != options.maxVersions) {
         if (options.maxVersions > 0 && it->second->options.maxVersions != options.maxVersions) {
+            const uint32_t oldMax = it->second->options.maxVersions;
             it->second->options.maxVersions = options.maxVersions;
             it->second->options.maxVersions = options.maxVersions;
+            // v2.17.1 - a LOWER cap (or a first cap over "unlimited") now
+            // prunes the history already on disk, as alterCollection always
+            // 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.
+            if (historyStore_ && (oldMax == 0 || options.maxVersions < oldMax)) {
+                historyStore_->prune(name, options.maxVersions);
+                spdlog::info("Pruned on-disk version history for collection '{}' (maxVersions: {} -> {})",
+                             name, oldMax, options.maxVersions);
+            }
             it->second->updatedAt = currentTimeMs();
             it->second->updatedAt = currentTimeMs();
             spdlog::info("Updated maxVersions for collection '{}' to {}", name, options.maxVersions);
             spdlog::info("Updated maxVersions for collection '{}' to {}", name, options.maxVersions);
         }
         }

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

@@ -293,31 +293,38 @@ uint64_t HistoryStore::rewrite(const std::string& collection,
 
 
     std::ifstream in(path, std::ios::binary);
     std::ifstream in(path, std::ios::binary);
     if (!in) return 0;
     if (!in) return 0;
-    std::vector<std::pair<std::string, DocumentVersion>> records;
-    uint64_t changed = 0;
-    scanFile(in, [&](const std::string& recDocId, DocumentVersion&& v) {
-        if (transform(v)) ++changed;
-        records.emplace_back(recDocId, std::move(v));
-    });
-    in.close();
-    if (changed == 0) return 0;
-
+    // v2.17.1 - STREAMED: each record is transformed and written to the tmp
+    // file as it is read, so memory holds one record, not the whole file. The
+    // 2.17.0 version collected every record first, which made the boot
+    // migration's peak memory a multiple of the largest history file - an OOM
+    // risk on a small host with a 100+ MB history file.
     auto tmp = path;
     auto tmp = path;
     tmp += ".tmp";
     tmp += ".tmp";
+    uint64_t changed = 0;
     {
     {
         std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
         std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
         if (!out) {
         if (!out) {
             throw std::runtime_error("HistoryStore::rewrite: cannot open " + tmp.string());
             throw std::runtime_error("HistoryStore::rewrite: cannot open " + tmp.string());
         }
         }
-        for (const auto& [docId, v] : records) {
-            auto bytes = serializeRecord(docId, v);
+        scanFile(in, [&](const std::string& recDocId, DocumentVersion&& v) {
+            if (transform(v)) ++changed;
+            auto bytes = serializeRecord(recDocId, v);
             out.write(reinterpret_cast<const char*>(bytes.data()),
             out.write(reinterpret_cast<const char*>(bytes.data()),
                       static_cast<std::streamsize>(bytes.size()));
                       static_cast<std::streamsize>(bytes.size()));
-        }
+        });
         out.flush();
         out.flush();
-        if (!out) throw std::runtime_error("HistoryStore::rewrite: write failed for " + tmp.string());
+        if (!out) {
+            std::error_code ec;
+            std::filesystem::remove(tmp, ec);
+            throw std::runtime_error("HistoryStore::rewrite: write failed for " + tmp.string());
+        }
     }
     }
+    in.close();
     std::error_code ec;
     std::error_code ec;
+    if (changed == 0) {
+        std::filesystem::remove(tmp, ec);   // nothing to change: the original stays as it was
+        return 0;
+    }
     std::filesystem::rename(tmp, path, ec);
     std::filesystem::rename(tmp, path, ec);
     if (ec) {
     if (ec) {
         std::filesystem::remove(tmp, ec);
         std::filesystem::remove(tmp, ec);
@@ -326,6 +333,14 @@ uint64_t HistoryStore::rewrite(const std::string& collection,
     return changed;
     return changed;
 }
 }
 
 
+uint64_t HistoryStore::forEach(
+    const std::string& collection,
+    const std::function<void(const std::string&, const DocumentVersion&)>& visit) const {
+    std::ifstream f(filePath(collection), std::ios::binary);
+    if (!f) return 0;
+    return scanFile(f, [&](const std::string& docId, DocumentVersion&& v) { visit(docId, v); });
+}
+
 uint64_t HistoryStore::totalSizeBytes() const {
 uint64_t HistoryStore::totalSizeBytes() const {
     uint64_t total = 0;
     uint64_t total = 0;
     std::error_code ec;
     std::error_code ec;

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

@@ -112,6 +112,17 @@ public:
     uint64_t rewrite(const std::string& collection,
     uint64_t rewrite(const std::string& collection,
                      const std::function<bool(DocumentVersion&)>& transform);
                      const std::function<bool(DocumentVersion&)>& transform);
 
 
+    /**
+     * v2.17.1 - visit every stored version of `collection`, read-only, WITHOUT
+     * the append lock (like getVersions). For audits on a live server:
+     * rewrite() holds the global append lock for the whole file, which stalls
+     * every history-recording write in every collection while a large file is
+     * read. A record being appended concurrently is either complete (CRC
+     * passes) or ends the scan. Returns the number of versions visited.
+     */
+    uint64_t forEach(const std::string& collection,
+                     const std::function<void(const std::string&, const DocumentVersion&)>& visit) const;
+
     /**
     /**
      * Total disk bytes used by all history files.
      * Total disk bytes used by all history files.
      */
      */

+ 6 - 11
service/src/storage/project_store.cpp

@@ -214,25 +214,20 @@ bool ProjectStoreRegistry::compact(std::string_view name, uint64_t& bytesBefore,
         return false;   // nothing changed
         return false;   // nothing changed
     }
     }
     // Close the env (destroys the DocumentStore first), then swap the files.
     // Close the env (destroys the DocumentStore first), then swap the files.
+    // v2.17.1 - ONE rename, replacing data.mdb atomically (same directory
+    // tree, same filesystem). 2.17.0 moved the original aside first, so a
+    // process killed between its two renames left NO data.mdb, and the next
+    // boot would have opened an empty env. Now a crash leaves either the
+    // original or the compacted copy, never neither.
     it->second.reset();
     it->second.reset();
-    const fs::path old = dir / "data.mdb.pre-compact";
-    fs::rename(dir / "data.mdb", old, ec);
-    if (ec) {
-        error = "rename data.mdb: " + ec.message();
-        it->second = open_one(std::string(name));   // the original is untouched
-        fs::remove_all(tmp, ec);
-        return false;
-    }
     fs::rename(tmp / "data.mdb", dir / "data.mdb", ec);
     fs::rename(tmp / "data.mdb", dir / "data.mdb", ec);
     if (ec) {
     if (ec) {
         error = "install compacted copy: " + ec.message();
         error = "install compacted copy: " + ec.message();
+        it->second = open_one(std::string(name));   // the original is untouched
         std::error_code ec2;
         std::error_code ec2;
-        fs::rename(old, dir / "data.mdb", ec2);   // put the original back
-        it->second = open_one(std::string(name));
         fs::remove_all(tmp, ec2);
         fs::remove_all(tmp, ec2);
         return false;
         return false;
     }
     }
-    fs::remove(old, ec);
     fs::remove_all(tmp, ec);
     fs::remove_all(tmp, ec);
     it->second = open_one(std::string(name));
     it->second = open_one(std::string(name));
     bytesAfter = fs::file_size(dir / "data.mdb", ec);
     bytesAfter = fs::file_size(dir / "data.mdb", ec);

+ 26 - 0
tests/CMakeLists.txt

@@ -911,3 +911,29 @@ else()
     target_include_directories(test_json_schema PRIVATE ${NLOHMANN_JSON_INCLUDE_DIRS})
     target_include_directories(test_json_schema PRIVATE ${NLOHMANN_JSON_INCLUDE_DIRS})
 endif()
 endif()
 add_test(NAME test_json_schema COMMAND test_json_schema)
 add_test(NAME test_json_schema COMMAND test_json_schema)
+
+# v2.17.1 - the read-only history scan holds no append lock (encryption-verify
+# on a live server stalled every history-recording write with rewrite()).
+add_executable(test_history_audit_scan
+    test_history_audit_scan.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/persistence/history_store.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/persistence/wal.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/json_parse.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src/doc_binary.cpp
+)
+target_include_directories(test_history_audit_scan PRIVATE
+    ${CMAKE_CURRENT_SOURCE_DIR}/../service/src ${yyjson_INCLUDE_DIRS})
+if(TARGET nlohmann_json::nlohmann_json)
+    target_link_libraries(test_history_audit_scan PRIVATE nlohmann_json::nlohmann_json)
+else()
+    target_include_directories(test_history_audit_scan PRIVATE ${NLOHMANN_JSON_INCLUDE_DIRS})
+endif()
+if(TARGET spdlog::spdlog)
+    target_link_libraries(test_history_audit_scan PRIVATE spdlog::spdlog)
+else()
+    target_link_libraries(test_history_audit_scan PRIVATE ${SPDLOG_LIBRARIES})
+    target_include_directories(test_history_audit_scan PRIVATE ${SPDLOG_INCLUDE_DIRS})
+endif()
+target_link_libraries(test_history_audit_scan PRIVATE Threads::Threads ${yyjson_LIBRARIES})
+target_compile_options(test_history_audit_scan PRIVATE -UNDEBUG)
+add_test(NAME test_history_audit_scan COMMAND test_history_audit_scan)

+ 90 - 0
tests/load_test/test_collection_admin.cpp

@@ -0,0 +1,90 @@
+// v2.17.1 - a project-qualified collection whose name starts with '_' is
+// reserved and refused, for writes and reads alike, with reason
+// reserved_collection_name. Before 2.17.1 the LMDB mirror skipped it (it tests
+// the collection part) while reads went to LMDB (they test the whole qualified
+// name), so a write answered ok and nothing could ever read it back.
+
+#include <smartbotic/database/client.hpp>
+
+#include <functional>
+#include <iostream>
+#include <string>
+
+using namespace smartbotic::database;
+static int pass = 0, fail = 0;
+static void ck(bool c, const std::string& m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+static bool refusedReserved(const std::function<void()>& f) {
+    try {
+        f();
+        std::cerr << "  (no exception)\n";
+    } catch (const Client::Error& e) {
+        const auto* d = Client::errorDetail(e);
+        if (d && d->reason == "reserved_collection_name" && e.code() == Client::ErrorCode::InvalidArgument) return true;
+        std::cerr << "  (" << e.what() << " reason '" << (d ? d->reason : "-") << "')\n";
+    }
+    return false;
+}
+
+int main() {
+    Client::Config cfg;
+    cfg.address = "127.0.0.1:9033";
+    cfg.project = "app";
+    cfg.writeRetries = 0;
+    Client c(cfg);
+    c.connect();
+
+    ck(refusedReserved([&] { c.insert("app:_hidden", {{"name", "plain"}}, "d1"); }),
+       "insert into app:_hidden is refused with reserved_collection_name");
+    ck(refusedReserved([&] { c.upsert("app:_hidden", {{"name", "plain"}}, "d2"); }),
+       "upsert into app:_hidden is refused");
+    ck(refusedReserved([&] { (void)c.find("app:_hidden", Client::QueryOptions{}); }),
+       "find on app:_hidden is refused, not an empty answer");
+    ck(refusedReserved([&] { (void)c.count("app:_hidden"); }), "count on app:_hidden is refused");
+    {
+        Client::FailureDetail fd;
+        ck(!c.patch("app:_hidden", "d1", {{"x", 1}}, fd) && fd.reason == "reserved_collection_name",
+           "patch on app:_hidden reports reserved_collection_name (" + fd.reason + ")");
+    }
+    ck(!c.createCollection("app:_hidden"), "createCollection(app:_hidden) is refused");
+
+    // Ordinary names in the project, and bare "_" names (the global namespace),
+    // are unaffected.
+    c.insert("visible", {{"name", "plain"}}, "v1");
+    ck(c.count("visible") == 1, "an ordinary project collection stores and reads back");
+    c.insert("_global_scratch", {{"name", "plain"}}, "g1");
+    ck(c.get("_global_scratch", "g1").has_value(), "a bare '_' name (global) still stores and reads back");
+    ck(c.dropCollection("_global_scratch"), "the global one drops");
+
+    // A reserved collection left behind by an older server can still be
+    // dropped: the drop is let through the gate, so it never answers
+    // reserved_collection_name (nothing exists here, so the drop says false).
+    {
+        bool threw = false;
+        try { (void)c.dropCollection("app:_hidden"); } catch (...) { threw = true; }
+        ck(!threw, "dropCollection on a reserved name is not refused");
+    }
+
+    // createCollection on an existing collection with a LOWER maxVersions
+    // prunes the history already on disk (before 2.17.1: setting accepted,
+    // nothing trimmed, history unbounded forever).
+    {
+        c.insert("hist", {{"n", 0}}, "h1");
+        for (int i = 1; i <= 12; ++i) c.update("hist", "h1", {{"n", i}});
+        const auto before = c.getVersionHistory("hist", "h1", 0).versions.size();
+        ck(before >= 12, "12 updates recorded history (" + std::to_string(before) + ")");
+        (void)c.createCollection("hist", 0, false, 3, 0);   // existing: returns false, applies the cap
+        const auto h = c.getVersionHistory("hist", "h1", 0);
+        ck(h.versions.size() <= 3, "lowering maxVersions to 3 pruned history (" + std::to_string(h.versions.size()) + " left)");
+        bool newestKept = false;
+        for (const auto& v : h.versions) if (v.data.value("n", -1) == 11) newestKept = true;
+        ck(newestKept, "the NEWEST versions are the ones kept");
+        auto cur = c.get("hist", "h1");
+        ck(cur && cur->value("n", -1) == 12, "the live document is untouched");
+    }
+
+    std::cout << "collection admin: " << pass << " passed, " << fail << " failed\n";
+    return fail == 0 ? 0 : 1;
+}

+ 43 - 0
tests/load_test/test_collection_admin.sh

@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# v2.17.1 e2e - collection administration fixes: "project:_name" collections are
+# refused (reserved_collection_name; before, a write answered ok and could never
+# be read back), and createCollection(existing, lower maxVersions) prunes the
+# history already written (before, it was accepted and nothing was trimmed).
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-collection-admin
+PORT=9033
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+cat > "$DIR/config.json" <<CFG
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+CFG
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/t" test_collection_admin.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+"$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" > "$DIR/server.log" 2>&1 &
+SERVER_PID=$!
+trap 'kill $SERVER_PID 2>/dev/null || true; wait $SERVER_PID 2>/dev/null || true' EXIT
+for _ in $(seq 1 120); do grep -q "Notified systemd: READY" "$DIR/server.log" && break; sleep 0.5; done
+
+LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" 2>&1 | grep -v '\[error\]\|\[info\]'
+rc=${PIPESTATUS[0]}
+[[ $rc -eq 0 ]] && echo "OK - collection admin e2e passed" || { echo "FAILED"; tail -20 "$DIR/server.log"; }
+exit $rc

+ 12 - 0
tests/load_test/test_encryption_at_rest.cpp

@@ -82,6 +82,9 @@ static int seed() {
     // sf is created by the migration file (sensitive_fields ["pin"]) and
     // sf is created by the migration file (sensitive_fields ["pin"]) and
     // seeded by its insert op; one more row through the client.
     // seeded by its insert op; one more row through the client.
     c.insert("sf", kSf, "s2");
     c.insert("sf", kSf, "s2");
+    // `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");
     return 0;
     return 0;
 }
 }
 
 
@@ -142,6 +145,15 @@ static int upgraded() {
     ck(c.serverSupports(Client::Capability::kEncryptionAtRest), "server reports encryption_at_rest");
     ck(c.serverSupports(Client::Capability::kEncryptionAtRest), "server reports encryption_at_rest");
     commonChecks(c, "upgraded");
     commonChecks(c, "upgraded");
     verifyClean(c, "upgraded", true);
     verifyClean(c, "upgraded", true);
+    // v2.17.1 - info reports the ENFORCED rule (merged with the bare alias),
+    // not only the qualified collection's own flag, which says no.
+    {
+        auto info = c.getCollectionInfo("aliased");
+        ck(info && info->encrypted, "info: a collection encrypted through its bare alias reports encrypted");
+        auto plainInfo = c.getCollectionInfo("plain");
+        ck(plainInfo && !plainInfo->encrypted, "info: a pattern-only collection still reports encrypted=false");
+        exact(c, "aliased", "a1", {{"v", "CANARY-ALIASED-4417"}}, "aliased row");
+    }
 
 
     // The refusals: comparisons over ciphertext are refused, not silently empty.
     // The refusals: comparisons over ciphertext are refused, not silently empty.
     ck(refusedEncrypted([&] {
     ck(refusedEncrypted([&] {

+ 3 - 2
tests/load_test/test_encryption_at_rest.sh

@@ -47,7 +47,8 @@ cat > "$DIR/migrations/001_sf.json" <<'MIG'
   "name": "sf",
   "name": "sf",
   "operations": [
   "operations": [
     { "type": "create_collection", "collection": "sf", "options": { "sensitive_fields": ["pin"] } },
     { "type": "create_collection", "collection": "sf", "options": { "sensitive_fields": ["pin"] } },
-    { "type": "insert", "collection": "sf", "id": "s1", "data": { "pin": "CANARY-SF-MIGRATION-3398", "label": "seeded" } }
+    { "type": "insert", "collection": "sf", "id": "s1", "data": { "pin": "CANARY-SF-MIGRATION-3398", "label": "seeded" } },
+    { "type": "create_collection", "collection": "aliased", "options": { "encrypted": true } }
   ]
   ]
 }
 }
 MIG
 MIG
@@ -100,7 +101,7 @@ must_not_find() {
 
 
 LEGACY=(CANARY-TOP-PW-3391 CANARY-HIST-PW-4471 CANARY-PATCH-PW-6025 CANARY-ARRAY-0457
 LEGACY=(CANARY-TOP-PW-3391 CANARY-HIST-PW-4471 CANARY-PATCH-PW-6025 CANARY-ARRAY-0457
         CANARY-APIKEY-7720 CANARY-VAULT-KEY-5512 CANARY-VAULT-NESTED-9930 CANARY-VAULT-LIST-2210
         CANARY-APIKEY-7720 CANARY-VAULT-KEY-5512 CANARY-VAULT-NESTED-9930 CANARY-VAULT-LIST-2210
-        CANARY-SF-MIGRATION-3398 CANARY-SF-PIN-8841)
+        CANARY-SF-MIGRATION-3398 CANARY-SF-PIN-8841 CANARY-ALIASED-4417)
 ALL=("${LEGACY[@]}" CANARY-NESTED-PW-1182 CANARY-NEW-PW-1906 CANARY-NEW-TOKEN-7783 CANARY-NEW-VAULT-3360)
 ALL=("${LEGACY[@]}" CANARY-NESTED-PW-1182 CANARY-NEW-PW-1906 CANARY-NEW-TOKEN-7783 CANARY-NEW-VAULT-3360)
 
 
 echo "=== seed with the RELEASED 2.16.0 server ==="
 echo "=== seed with the RELEASED 2.16.0 server ==="

+ 11 - 3
tests/load_test/test_server_info.cpp

@@ -97,8 +97,16 @@ static int old() {
         ck(!c.serverSupports(Cap::kServerInfo), "old (pre-2.15.0): serverSupports is false");
         ck(!c.serverSupports(Cap::kServerInfo), "old (pre-2.15.0): serverSupports is false");
     } else {
     } else {
         ck(si->version != clientLibraryVersion(), "old (2.15.0+): reports its own version " + si->version);
         ck(si->version != clientLibraryVersion(), "old (2.15.0+): reports its own version " + si->version);
-        // The newest capability this client knows; bump it with each release.
-        ck(!c.serverSupports(Cap::kEncryptionAtRest), "old (2.15.0+): lacks encryption_at_rest");
+        // An older server knows no capability this client does not: its list
+        // is a subset of ours. (A patch release adds no capability, so "lacks
+        // the newest one" would be false for the previous patch release.)
+        bool subset = true;
+        for (const auto& name : si->capabilities) {
+            bool known = false;
+            for (const char* k : kAllCaps) known = known || name == k;
+            if (!known) { subset = false; std::cerr << "  unknown capability " << name << "\n"; }
+        }
+        ck(subset, "old (2.15.0+): every capability it reports is one this client knows");
     }
     }
     basics(c, "old");
     basics(c, "old");
     // A pre-2.14.0 server would answer a filtered search UNFILTERED; a 2.14.0
     // A pre-2.14.0 server would answer a filtered search UNFILTERED; a 2.14.0
@@ -130,7 +138,7 @@ static int old() {
         }
         }
         ck(getRefused, "old: getCollectionSchema refused with server_unsupported");
         ck(getRefused, "old: getCollectionSchema refused with server_unsupported");
     }
     }
-    {
+    if (!c.serverSupports(Cap::kEncryptionAtRest)) {
         bool refused = false;
         bool refused = false;
         try {
         try {
             (void)c.verifyEncryption();
             (void)c.verifyEncryption();

+ 119 - 0
tests/test_history_audit_scan.cpp

@@ -0,0 +1,119 @@
+// v2.17.1 - HistoryStore::forEach is a read-only scan that does NOT hold the
+// append lock, so a history-recording write can proceed while an audit
+// (encryption-verify) reads a large history file.
+//
+// 2.17.0's verifier read history through rewrite(), which holds the GLOBAL
+// append lock for a whole file: on a live server with a 230 MB history file,
+// every write that records a version, in every collection, waited minutes.
+//
+// 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).
+
+#include "persistence/history_store.hpp"
+
+#include <chrono>
+#include <cstdio>
+#include <filesystem>
+#include <future>
+#include <iostream>
+#include <string>
+#include <thread>
+
+using namespace smartbotic::database;
+
+static int failures = 0;
+static void check(bool ok, const std::string& what) {
+    std::cout << (ok ? "ok   " : "FAIL ") << what << "\n";
+    if (!ok) ++failures;
+}
+
+static DocumentVersion version(uint64_t n) {
+    DocumentVersion v;
+    v.version = n;
+    v.set_data({{"n", n}, {"pad", std::string(256, 'x')}});
+    v.timestamp = n;
+    return v;
+}
+
+int main() {
+    const auto dir = std::filesystem::temp_directory_path() / "sbdb-history-audit-scan";
+    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));
+
+    // 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)); });
+        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
+    };
+
+    {
+        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); }
+        });
+        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)");
+    }
+    {
+        bool first = true, completed = true;
+        std::future<void> pending;
+        hs.rewrite("audited", [&](DocumentVersion&) {
+            if (first) { first = false; pending = appendDuringScan(completed, 2); }
+            return false;
+        });
+        if (pending.valid()) pending.wait();
+        check(!completed, "control: under rewrite() the same append waits (the harness detects the lock)");
+    }
+    check(hs.countVersions("other", "o") == 2, "both appends landed");
+
+    // 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
+    // some records keeps every record, in order, with the changes applied.
+    {
+        const auto file = dir / "history" / "audited.hlog";
+        const auto sizeBefore = std::filesystem::file_size(file);
+        const auto timeBefore = std::filesystem::last_write_time(file);
+        check(hs.rewrite("audited", [](DocumentVersion&) { return false; }) == 0,
+              "a no-change rewrite reports 0");
+        check(std::filesystem::file_size(file) == sizeBefore &&
+                  std::filesystem::last_write_time(file) == timeBefore,
+              "a no-change rewrite leaves the file untouched");
+        check(!std::filesystem::exists(dir / "history" / "audited.hlog.tmp"), "no tmp file is left behind");
+
+        const auto changed = hs.rewrite("audited", [](DocumentVersion& v) {
+            if (v.version % 2 != 0) return false;
+            auto d = v.data();
+            d["even"] = true;
+            v.set_data(d);
+            return true;
+        });
+        check(changed == 100, "rewrite reports the 100 changed versions (" + std::to_string(changed) + ")");
+        uint64_t seen = 0, marked = 0, lastVersion = 0;
+        bool ordered = true;
+        hs.forEach("audited", [&](const std::string&, const DocumentVersion& v) {
+            ++seen;
+            if (v.version <= lastVersion) ordered = false;
+            lastVersion = v.version;
+            if (v.data().value("even", false)) {
+                ++marked;
+                if (v.version % 2 != 0) ordered = false;
+            }
+        });
+        check(seen == 200 && marked == 100 && ordered,
+              "every record survives the streamed rewrite, in order, changes applied");
+    }
+    check(hs.forEach("missing", [](const std::string&, const DocumentVersion&) {}) == 0,
+          "a collection without history visits nothing");
+
+    std::filesystem::remove_all(dir);
+    std::cout << (failures == 0 ? "PASS" : "FAILED") << "\n";
+    return failures == 0 ? 0 : 1;
+}

Неке датотеке нису приказане због велике количине промена