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

feat: 2.12.0 - refusal detail, conditional patch, atomic increment, composite and null-safe unique constraints, batch delete, event actors

What smartbotic-vectorapi asked for (D1-D7), plus the event-actor work prepared
as 2.11.5 and never released on its own. There is no 2.11.5 package.

Event actors (prepared as 2.11.5): actor on DeleteRequest/BatchDeleteRequest
and on every DatabaseEvent; Client::removeAs() and subscribeEvents(). A trigger
that writes in response to events can now recognise its own writes, deletes
included. Patch, cascades and TTL expiry pass the actor explicitly, because
deriving it from the stored updatedBy misattributes.

D1 refusal detail: any refused write may carry trailing metadata
sbdb-error-detail-bin - reason, fields, values, conflicting_id, relation,
current_version. Trailing metadata because it accompanies an error status AND an
in-band reply. The reason also separates read-only mode from relation refusals,
which share FAILED_PRECONDITION. Client::FailureDetail with overloads beside
every Failure& one, and Client::errorDetail() for the throwing calls; the thrown
objects are internal subclasses of the public types, so no public class
changes size.

In-band refusals of Update/PatchDocument now carry error_code (still in-band,
so older clients see what they always did). updateIfVersion no longer reports a
missing document as a version conflict.

D2 patchIfVersion: expected_version on PatchDocumentRequest, checked under the
collection lock; a stale version is ABORTED with the current version.

D5 increment(): increments_json on PatchDocumentRequest, applied with the merge
on a copy BEFORE anything is mutated, so a refused increment writes nothing.

D3 null is not a value for uniqueness (SQL); still indexed for EQ null.

D4 composite unique constraints: one sub-db per constraint keyed by a
length-prefixed tuple, enforced in the document's own write transaction,
declared in CollectionCfg, re-armed at boot. MemoryStore's undo gate counts
them, the write-path gates see composite-only collections, and the builder
scans and populates in one write transaction after arming. Refused over
existing duplicates, with examples. CLI unique-create / unique-drop.

D6 removeManyAs(): BatchDelete exposed, with deleted_ids in request order.

D7 was already solved: get() and find() return _version. Documented.

Tests: test_event_actor (56) and test_db_changes_for_vectorapi (87 + 7 after a
restart, including 8 concurrent claims of one version and 8x50 concurrent
increments). Each part reverted on its own fails them: null rule 2, undo gate
2, boot re-arm 1, version check 4, detail trailer 29, in-band codes 6; actor
send 6, Delete/cascade plumbing 6, explicit patch actor 1, wire copy 13.

Also: the roadmap no longer lists unique constraints as unshipped (stale since
2.11.0).
fszontagh 1 месяц назад
Родитель
Сommit
269020b951

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.11.4
+2.12.0

+ 42 - 1
cli/main.cpp

@@ -86,6 +86,10 @@ void printUsage() {
               << C_RESET << "\n"
               << "  " << C_CYAN << "index-drop" << C_RESET << " <collection> <field>"
               << "          remove an index\n"
+              << "  " << C_CYAN << "unique-create" << C_RESET << " <collection> <field> <field> [...]"
+              << "   Composite unique constraint\n"
+              << "  " << C_CYAN << "unique-drop" << C_RESET << " <collection> <field> <field> [...]"
+              << "     Drop a composite unique constraint\n"
               << "  " << C_CYAN << "index-values" << C_RESET << " <coll> <field> [n] [asc|desc]"
               << "  distinct values + counts\n"
               << C_BOLD << "  Relations / referential integrity (v2.11.0+)" << C_RESET << "\n"
@@ -647,10 +651,22 @@ bool execCommand(smartbotic::database::Client& client,
             if (params.empty()) { printError("usage: indexes <collection>"); return false; }
             std::vector<bool> uniqueFlags;
             auto list = client.listIndexes(params[0], uniqueFlags);
-            if (list.empty()) {
+            // v2.12.0 - composite unique constraints are listed separately: they
+            // are constraints over several fields, not indexes on one.
+            const auto composites = client.listCompositeUniqueIndexes(params[0]);
+            if (list.empty() && composites.empty()) {
                 std::cout << "no indexes on " << params[0] << "\n";
                 return true;
             }
+            if (!composites.empty()) {
+                std::cout << C_BOLD << "composite unique constraints" << C_RESET << "\n";
+                for (const auto& cf : composites) {
+                    std::cout << "  (";
+                    for (size_t i = 0; i < cf.size(); ++i) std::cout << (i ? ", " : "") << cf[i];
+                    std::cout << ")\n";
+                }
+                if (list.empty()) return true;
+            }
             std::cout << C_BOLD << "field                          distinct      entries  unique"
                       << C_RESET << "\n";
             for (size_t idx = 0; idx < list.size(); ++idx) {
@@ -730,6 +746,31 @@ bool execCommand(smartbotic::database::Client& client,
             return true;
         }
 
+        // v2.12.0 - composite unique constraints.
+        if (cmd == "unique-create" || cmd == "unique-drop") {
+            if (params.size() < 3) {
+                printError("usage: " + cmd + " <collection> <field> <field> [field...]");
+                return false;
+            }
+            const std::vector<std::string> fields(params.begin() + 1, params.end());
+            if (cmd == "unique-drop") {
+                if (!client.dropCompositeUniqueIndex(params[0], fields)) {
+                    printError("could not drop the constraint (see the service log)");
+                    return false;
+                }
+                std::cout << C_GREEN << "ok" << C_RESET << " dropped\n";
+                return true;
+            }
+            auto r = client.createCompositeUniqueIndex(params[0], fields);
+            if (!r.success) {
+                printError(r.error);
+                return false;
+            }
+            std::cout << C_GREEN << "ok" << C_RESET << " " << (r.alreadyExisted ? "already declared" : "declared")
+                      << ", " << r.rowsIndexed << " row(s) constrained\n";
+            return true;
+        }
+
         if (cmd == "index-drop") {
             if (params.size() < 2) {
                 printError("usage: index-drop <collection> <field>");

+ 232 - 0
client/include/smartbotic/database/client.hpp

@@ -124,6 +124,57 @@ public:
         std::string message;
     };
 
+    /**
+     * v2.12.0 - why a call failed, in full. Supersedes Failure for new code;
+     * Failure stays because its size is fixed by the ABI of existing callers.
+     *
+     * Filled by the overloads that take a FailureDetail&, and available for
+     * the throwing calls through Client::errorDetail(e). Everything beyond
+     * code and message is empty from a server older than 2.12.0.
+     *
+     * `reason` is what to branch on - the status code alone is ambiguous
+     * (FailedPrecondition means a missing parent, a restricted delete AND
+     * read-only mode):
+     *
+     *   "unique_violation"   fields = the constrained field(s) (several for a
+     *                        composite constraint), values = field -> the
+     *                        colliding value, conflictingId = who holds it
+     *   "missing_parent"     fields = the reference field, values = field ->
+     *                        the id that does not exist, relation = its name
+     *   "delete_restricted"  a relation with on_delete="restrict" refused it
+     *   "version_conflict"   currentVersion = the document's version now
+     *   "not_found"          no such document
+     *   "invalid_increment"  fields = the path that could not be incremented
+     *   "read_only"          the database is in read-only mode
+     *   "memory_pressure"    refused under memory pressure; retry later
+     *   "view_write"         the name is a view, which is read-only
+     *   ""                   no further detail (transport errors, denials...)
+     *
+     * Reset at the start of every call that fills it.
+     */
+    struct FailureDetail {
+        ErrorCode code = ErrorCode::Ok;
+        std::string message;
+        std::string reason;
+        std::vector<std::string> fields;
+        nlohmann::json values;              // object, or null when none
+        std::string conflictingId;
+        std::string relation;
+        std::optional<uint64_t> currentVersion;
+    };
+
+    /**
+     * v2.12.0 - the detail behind an exception this client threw, or nullptr
+     * for one it did not (or one caught BY VALUE, which slices it off).
+     *
+     *   try { db.insert("calls", doc); }
+     *   catch (const Client::AlreadyExists& e) {
+     *       if (auto* d = Client::errorDetail(e); d && d->fields == std::vector<std::string>{"vapi_call_id"})
+     *           ...;   // that slot is taken: read d->conflictingId
+     *   }
+     */
+    static const FailureDetail* errorDetail(const Error& e) noexcept;
+
     struct Config {
         std::string address = "localhost:9004";
         uint32_t timeoutMs = 5000;
@@ -274,6 +325,9 @@ public:
      */
     bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
                 Failure& failureOut, const std::string& actor = "");
+    /** v2.12.0 - as above, with the full FailureDetail. */
+    bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
+                FailureDetail& failureOut, const std::string& actor = "");
 
     /**
      * Update with optimistic locking.
@@ -291,6 +345,11 @@ public:
     bool updateIfVersion(const std::string& collection, const std::string& id,
                         const nlohmann::json& data, uint64_t expectedVersion,
                         Failure& failureOut, const std::string& actor = "");
+    /** v2.12.0 - a stale version is ErrorCode::Aborted, reason "version_conflict",
+     *  with currentVersion; a missing document ErrorCode::NotFound. */
+    bool updateIfVersion(const std::string& collection, const std::string& id,
+                        const nlohmann::json& data, uint64_t expectedVersion,
+                        FailureDetail& failureOut, const std::string& actor = "");
 
     /**
      * Atomically merge fields into an existing document (server-side).
@@ -333,6 +392,60 @@ public:
                           const nlohmann::json& patch, uint32_t ttlSeconds,
                           Failure& failureOut, const std::string& actor = "");
 
+    /** v2.12.0 - patch() / patchWithTtl() with the full FailureDetail. */
+    uint64_t patch(const std::string& collection, const std::string& id,
+                   const nlohmann::json& fields, FailureDetail& failureOut,
+                   const std::string& actor = "");
+    uint64_t patchWithTtl(const std::string& collection, const std::string& id,
+                          const nlohmann::json& patch, uint32_t ttlSeconds,
+                          FailureDetail& failureOut, const std::string& actor = "");
+
+    /**
+     * v2.12.0 - a conditional PARTIAL update: merge `fields` only if the
+     * document is still at `expectedVersion` (read it from the `_version` that
+     * get() and find() already return). The check and the write happen under
+     * one lock on the server, so it is a compare-and-set - e.g. claiming a task
+     * exactly once - that touches nothing but `fields`.
+     *
+     * updateIfVersion() is the whole-document form; using it to change one
+     * field means writing back everything that was read, silently reverting
+     * any field a concurrent writer changed in between.
+     *
+     * @return the new version, or 0. A stale version fails with
+     *   ErrorCode::Aborted, reason "version_conflict" and currentVersion set;
+     *   a missing document with ErrorCode::NotFound.
+     */
+    uint64_t patchIfVersion(const std::string& collection, const std::string& id,
+                            const nlohmann::json& fields, uint64_t expectedVersion,
+                            FailureDetail& failureOut, const std::string& actor = "");
+
+    /**
+     * v2.12.0 - ATOMIC INCREMENT. Adds each number in `deltas` (an object of
+     * field -> number; dotted paths address nested fields) to the document's
+     * field, in one locked read-modify-write on the server, so concurrent
+     * increments never lose an update.
+     *
+     *   auto v = db.increment("stats", "2026-10-07", {{"calls", 1}, {"minutes", 3.5}}, why);
+     *   // v = {"calls": 18, "minutes": 61.5}
+     *
+     * An absent or null field counts as 0. Integer + integer stays an integer
+     * (overflow is refused); anything else becomes a double. A field holding a
+     * non-number is refused with ErrorCode::InvalidArgument, reason
+     * "invalid_increment" and the field in `fields` - and then nothing at all
+     * is written.
+     *
+     * The document must exist (ErrorCode::NotFound otherwise). For a counter
+     * that may not exist yet: increment; on NotFound insert it with the
+     * starting value under a fixed id; on AlreadyExists (someone else just
+     * created it) increment again.
+     *
+     * @return the incremented fields' new values, or nullopt on failure.
+     */
+    std::optional<nlohmann::json> increment(const std::string& collection, const std::string& id,
+                                            const nlohmann::json& deltas,
+                                            FailureDetail& failureOut,
+                                            const std::string& actor = "");
+
     /**
      * Upsert a document.
      * @param actor User ID performing the operation (for audit trail)
@@ -373,6 +486,56 @@ public:
      */
     bool remove(const std::string& collection, const std::string& id, Failure& failureOut);
 
+    /**
+     * Delete a document AS `actor` (v2.12.0) - the delete counterpart of the
+     * `actor` every other write takes. The actor is reported on the DELETE
+     * event (see subscribeEvents()), and on the event of every document a
+     * relation cascade deletes or nulls because of this delete.
+     *
+     * Returns as remove() does. The Failure& form also reports why, with the
+     * same contract as remove(collection, id, Failure&).
+     *
+     * A separate NAME rather than one more remove() overload, on purpose:
+     * `remove(collection, id, someString)` already means "report the error
+     * into someString" (the errorOut overload), and C++ prefers that binding
+     * for a non-const std::string. An actor overload would have compiled and
+     * silently cleared the caller's actor instead of sending it.
+     */
+    bool removeAs(const std::string& collection, const std::string& id,
+                  const std::string& actor);
+    bool removeAs(const std::string& collection, const std::string& id,
+                  const std::string& actor, Failure& failureOut);
+    /** v2.12.0 - with the full FailureDetail (a restricted delete has reason
+     *  "delete_restricted"). */
+    bool removeAs(const std::string& collection, const std::string& id,
+                  const std::string& actor, FailureDetail& failureOut);
+
+    /** Result of removeManyAs(). A new struct - same ABI reasoning as Event. */
+    struct BatchRemoveResult {
+        uint64_t deletedCount = 0;
+        /// The ids that existed and were deleted, in request order. An id
+        /// missing from here did not exist.
+        std::vector<std::string> deletedIds;
+    };
+
+    /**
+     * v2.12.0 - delete many documents in ONE round trip, AS `actor` (empty for
+     * none), via the BatchDelete RPC.
+     *
+     * Relations are enforced exactly as for removeAs(), and all-or-nothing on
+     * restrict: if ANY id is protected, nothing is deleted (reason
+     * "delete_restricted"). A cascade fault part-way fails the call with ids
+     * before it possibly already gone - re-read to learn which.
+     *
+     * A server older than 2.12.0 reports the count but not deletedIds.
+     *
+     * @return the outcome, or nullopt on failure (see failureOut).
+     */
+    std::optional<BatchRemoveResult> removeManyAs(const std::string& collection,
+                                                  const std::vector<std::string>& ids,
+                                                  const std::string& actor,
+                                                  FailureDetail& failureOut);
+
     /**
      * Check if a document exists.
      */
@@ -861,6 +1024,34 @@ public:
     [[nodiscard]] CreateIndexResult createUniqueIndex(const std::string& collection,
                                                        const std::string& field);
 
+    /**
+     * v2.12.0 - a COMPOSITE unique constraint: no two documents may hold the
+     * same COMBINATION of `fields` (two or more), e.g. {"chat_id",
+     * "file_unique_id"}. A document in which any of them is absent, null, an
+     * object or an array is not constrained (the SQL rule for a NULL in a
+     * unique key).
+     *
+     * Declaring it over existing duplicates is refused, with examples in
+     * duplicateExamples, as for createUniqueIndex(). It backs no query. A
+     * write that violates it fails with ErrorCode::AlreadyExists, reason
+     * "unique_violation", `fields` = this list and `values` = the combination.
+     *
+     * A separate NAME rather than a createUniqueIndex() overload: a braced
+     * list like {"a", "b"} would also match createUniqueIndex's std::string
+     * parameter (as an iterator pair), so the overload would be ambiguous at
+     * best and undefined behaviour at worst.
+     */
+    [[nodiscard]] CreateIndexResult createCompositeUniqueIndex(const std::string& collection,
+                                                               const std::vector<std::string>& fields);
+
+    /** v2.12.0 - drop a composite constraint, named by its exact field list. */
+    bool dropCompositeUniqueIndex(const std::string& collection,
+                                  const std::vector<std::string>& fields);
+
+    /** v2.12.0 - the composite constraints declared on `collection`. */
+    [[nodiscard]] std::vector<std::vector<std::string>>
+    listCompositeUniqueIndexes(const std::string& collection);
+
     /** One declared index, as reported by listIndexes(). */
     struct IndexDefinition {
         std::string field;
@@ -1195,6 +1386,47 @@ public:
      */
     std::shared_ptr<void> subscribe(const std::vector<std::string>& collections, EventCallback callback);
 
+    /**
+     * One change, as subscribeEvents() delivers it (v2.12.0).
+     *
+     * A brand-new struct rather than more parameters on EventCallback: that
+     * type is part of subscribe()'s exported signature and cannot change
+     * without breaking every consumer already linked against it.
+     */
+    struct Event {
+        /// As the server reports it - project-qualified (`<project>:<name>`),
+        /// the same string subscribe() passes.
+        std::string collection;
+        std::string id;
+        /// "insert", "update", "delete", "expire" or "invalidate".
+        std::string eventType;
+        /// The document's fields after the change. Absent for a delete or an
+        /// expiry.
+        std::optional<nlohmann::json> data;
+        /// Who caused the change: the `actor` the write or delete carried.
+        /// Empty when it carried none, and for an expiry. For a document a
+        /// relation cascade deleted or nulled, the actor of the delete that
+        /// triggered it. Empty from a server older than 2.12.0.
+        ///
+        /// This is what a consumer that writes in response to events needs to
+        /// recognise its own writes - including its own deletes - and stop a
+        /// trigger from feeding itself.
+        std::string actor;
+        /// Milliseconds since the epoch, stamped by the server.
+        uint64_t timestamp = 0;
+        /// The server node that made the change.
+        std::string nodeId;
+    };
+
+    using EventHandler = std::function<void(const Event&)>;
+
+    /**
+     * subscribe(), delivering an Event that also says WHO caused the change
+     * (v2.12.0). Same collections semantics and the same handle.
+     */
+    std::shared_ptr<void> subscribeEvents(const std::vector<std::string>& collections,
+                                          EventHandler handler);
+
     // ===== Statistics =====
 
     struct StatsInfo {

+ 378 - 47
client/src/client.cpp

@@ -54,31 +54,116 @@ Client::ErrorCode toErrorCode(grpc::StatusCode code) {
     return static_cast<Client::ErrorCode>(static_cast<int>(code));
 }
 
+// v2.12.0 — the refusal detail the server attaches as trailing metadata (see
+// `service DatabaseService` in database.proto). Empty when absent.
+constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin";
+
+std::string trailerDetail(const grpc::ClientContext& context) {
+    const auto& md = context.GetServerTrailingMetadata();
+    auto it = md.find(kErrorDetailKey);
+    if (it == md.end()) return {};
+    return std::string(it->second.data(), it->second.size());
+}
+
+// Build a FailureDetail from a code, a message and the trailer JSON. A detail
+// that does not parse is ignored rather than allowed to turn a refusal into a
+// crash: the code and message still stand.
+Client::FailureDetail makeDetail(Client::ErrorCode code, const std::string& message,
+                                 const std::string& detailJson) {
+    Client::FailureDetail d;
+    d.code = code;
+    d.message = message;
+    if (detailJson.empty()) return d;
+    try {
+        const auto j = nlohmann::json::parse(detailJson);
+        if (!j.is_object()) return d;
+        d.reason = j.value("reason", std::string{});
+        if (auto it = j.find("fields"); it != j.end() && it->is_array()) {
+            for (const auto& f : *it) if (f.is_string()) d.fields.push_back(f.get<std::string>());
+        }
+        if (auto it = j.find("values"); it != j.end()) d.values = *it;
+        d.conflictingId = j.value("conflicting_id", std::string{});
+        d.relation = j.value("relation", std::string{});
+        if (auto it = j.find("current_version"); it != j.end() && it->is_number_unsigned()) {
+            d.currentVersion = it->get<uint64_t>();
+        }
+    } catch (const std::exception&) {
+        // keep code + message
+    }
+    return d;
+}
+
+// The exceptions this client throws carry a FailureDetail by deriving from the
+// public type AND this internal carrier; Client::errorDetail() cross-casts to
+// it. Internal types, so no public class changes size, and a consumer that
+// catches the public base sees exactly what it always did.
+struct DetailCarrier {
+    explicit DetailCarrier(Client::FailureDetail d) : detail(std::move(d)) {}
+    virtual ~DetailCarrier() = default;
+    Client::FailureDetail detail;
+};
+struct DetailedError : Client::Error, DetailCarrier {
+    DetailedError(Client::ErrorCode c, const std::string& m, Client::FailureDetail d)
+        : Client::Error(c, m), DetailCarrier(std::move(d)) {}
+};
+struct DetailedAlreadyExists : Client::AlreadyExists, DetailCarrier {
+    DetailedAlreadyExists(const std::string& m, Client::FailureDetail d)
+        : Client::AlreadyExists(m), DetailCarrier(std::move(d)) {}
+};
+struct DetailedFailedPrecondition : Client::FailedPrecondition, DetailCarrier {
+    DetailedFailedPrecondition(const std::string& m, Client::FailureDetail d)
+        : Client::FailedPrecondition(m), DetailCarrier(std::move(d)) {}
+};
+struct DetailedPermissionDenied : Client::PermissionDenied, DetailCarrier {
+    DetailedPermissionDenied(const std::string& m, Client::FailureDetail d)
+        : Client::PermissionDenied(m), DetailCarrier(std::move(d)) {}
+};
+
 // Throw the Client::Error subtype matching a failed status. `message` becomes
 // what(): every site passes what it threw before 2.11.4, so the text an
-// existing consumer logs or matches on is unchanged.
-[[noreturn]] void throwStatus(const grpc::Status& status, const std::string& message) {
+// existing consumer logs or matches on is unchanged. v2.12.0: the thrown
+// object also carries the detail - see Client::errorDetail().
+[[noreturn]] void throwStatus(const grpc::Status& status, const std::string& message,
+                              const std::string& detailJson = {}) {
+    auto d = makeDetail(toErrorCode(status.error_code()), status.error_message(), detailJson);
     switch (status.error_code()) {
-        case grpc::StatusCode::ALREADY_EXISTS:      throw Client::AlreadyExists(message);
-        case grpc::StatusCode::FAILED_PRECONDITION: throw Client::FailedPrecondition(message);
-        case grpc::StatusCode::PERMISSION_DENIED:   throw Client::PermissionDenied(message);
-        default: throw Client::Error(toErrorCode(status.error_code()), message);
+        case grpc::StatusCode::ALREADY_EXISTS:      throw DetailedAlreadyExists(message, std::move(d));
+        case grpc::StatusCode::FAILED_PRECONDITION: throw DetailedFailedPrecondition(message, std::move(d));
+        case grpc::StatusCode::PERMISSION_DENIED:   throw DetailedPermissionDenied(message, std::move(d));
+        default: throw DetailedError(toErrorCode(status.error_code()), message, std::move(d));
+    }
+}
+
+// Where a non-throwing call reports its failure: the 2.11.4 Failure, the
+// 2.12.0 FailureDetail, or neither (the original overloads). One sink so every
+// method records a failure once and both overload families stay identical.
+struct FailureSink {
+    FailureSink() = default;
+    FailureSink(Client::Failure* f) : failure(f) {}               // NOLINT: implicit on purpose
+    FailureSink(Client::FailureDetail* d) : detail(d) {}          // NOLINT
+    Client::Failure* failure = nullptr;
+    Client::FailureDetail* detail = nullptr;
+
+    void reset() const {
+        if (failure) *failure = Client::Failure{};
+        if (detail) *detail = Client::FailureDetail{};
+    }
+    void record(Client::ErrorCode code, const std::string& message,
+                const std::string& detailJson = {}) const {
+        if (failure) { failure->code = code; failure->message = message; }
+        if (detail) *detail = makeDetail(code, message, detailJson);
+    }
+    void record(const grpc::Status& status, const std::string& detailJson = {}) const {
+        record(toErrorCode(status.error_code()), status.error_message(), detailJson);
+    }
+    // An in-band refusal (status OK, success=false): the code is in the
+    // response from a 2.12.0+ server, Unknown from an older one.
+    void recordInBand(int32_t errorCode, const std::string& message,
+                      const std::string& detailJson) const {
+        record(errorCode != 0 ? static_cast<Client::ErrorCode>(errorCode) : Client::ErrorCode::Unknown,
+               message, detailJson);
     }
-}
-
-// Record a failure for the calls that report through their return value.
-// `out` is null for the original overloads, which keep their old behaviour.
-void recordFailure(Client::Failure* out, const grpc::Status& status) {
-    if (out == nullptr) return;
-    out->code = toErrorCode(status.error_code());
-    out->message = status.error_message();
-}
-
-void recordFailure(Client::Failure* out, Client::ErrorCode code, const std::string& message) {
-    if (out == nullptr) return;
-    out->code = code;
-    out->message = message;
-}
+};
 
 // v1.7.0 T11 — transient transport errors that are safe to retry for idempotent
 // writes (insert with explicit ID, updateIfVersion, upsert, remove, patch).
@@ -116,6 +201,11 @@ std::string readCaCertFile(const std::string& path) {
 }
 } // anonymous namespace
 
+const Client::FailureDetail* Client::errorDetail(const Error& e) noexcept {
+    const auto* carrier = dynamic_cast<const DetailCarrier*>(&e);
+    return carrier != nullptr ? &carrier->detail : nullptr;
+}
+
 // ===== PIMPL Implementation =====
 
 class Client::Impl {
@@ -305,11 +395,13 @@ public:
 
         smartbotic::databasepb::InsertResponse response;
         grpc::Status status;
+        std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
             setDeadline(context);
             response.Clear();
             status = stub_->Insert(&context, request, &response);
+            detailJson = trailerDetail(context);   // v2.12.0
             if (status.ok() || !retryableStatus(status)) {
                 break;
             }
@@ -325,7 +417,7 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::insert failed after retries: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), detailJson);
         }
 
         return response.id();
@@ -370,7 +462,7 @@ public:
     }
 
     bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
-                const std::string& actor, Client::Failure* failureOut = nullptr) {
+                const std::string& actor, FailureSink failureOut = {}) {
         // Strip metadata fields from data — callers pass the JSON from get() which
         // includes _version, _id, etc.  We use _version for optimistic locking.
         auto cleanData = data;
@@ -392,8 +484,9 @@ public:
                 // The one failure here the client can name itself, without
                 // reading a server message: get() just said there is no
                 // such document.
-                recordFailure(failureOut, Client::ErrorCode::NotFound,
-                              "document not found: " + collection + "/" + id);
+                failureOut.record(Client::ErrorCode::NotFound,
+                                  "document not found: " + collection + "/" + id,
+                                  R"({"reason":"not_found"})");
                 return false;  // document doesn't exist
             }
             uint64_t version = (*current)["_version"].get<uint64_t>();
@@ -420,8 +513,8 @@ public:
     bool updateIfVersion(const std::string& collection, const std::string& id,
                         const nlohmann::json& data, uint64_t expectedVersion,
                         const std::string& actor,
-                        Client::Failure* failureOut = nullptr) {
-        if (failureOut != nullptr) *failureOut = Client::Failure{};
+                        FailureSink failureOut = {}) {
+        failureOut.reset();
         smartbotic::databasepb::UpdateRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
@@ -433,11 +526,13 @@ public:
 
         smartbotic::databasepb::UpdateResponse response;
         grpc::Status status;
+        std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
             setDeadline(context);
             response.Clear();
             status = stub_->Update(&context, request, &response);
+            detailJson = trailerDetail(context);   // v2.12.0
             if (status.ok() || !retryableStatus(status)) {
                 break;
             }
@@ -453,14 +548,14 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message());
-            recordFailure(failureOut, status);
+            failureOut.record(status, detailJson);
             return false;
         }
 
         if (!response.success()) {
-            // Refused in-band: status OK, no code on the wire. See
-            // Client::ErrorCode::Unknown.
-            recordFailure(failureOut, Client::ErrorCode::Unknown, response.error());
+            // Refused in-band: status OK. Since 2.12.0 the response carries the
+            // code the refusal would have as a status; before, Unknown.
+            failureOut.recordInBand(response.error_code(), response.error(), detailJson);
         }
         return response.success();
     }
@@ -468,26 +563,36 @@ public:
     uint64_t patch(const std::string& collection, const std::string& id,
                    const nlohmann::json& fields, const std::string& actor,
                    std::optional<uint32_t> ttlSeconds = std::nullopt,
-                   Client::Failure* failureOut = nullptr) {
-        if (failureOut != nullptr) *failureOut = Client::Failure{};
+                   FailureSink failureOut = {},
+                   std::optional<uint64_t> expectedVersion = std::nullopt,   // v2.12.0
+                   const nlohmann::json* increments = nullptr,               // v2.12.0
+                   nlohmann::json* incrementedOut = nullptr) {               // v2.12.0
+        failureOut.reset();
         smartbotic::databasepb::PatchDocumentRequest request;
         request.set_collection(qualify(collection));
         // v2.8.0 — presence distinguishes "leave the expiry alone" (absent) from
         // "clear it" (0) from "set it" (N).
         if (ttlSeconds.has_value()) request.set_ttl_seconds(*ttlSeconds);
         request.set_id(id);
-        request.set_patch_json(fields.dump());
+        // v2.12.0 - an increment-only call sends no merge patch.
+        if (!(increments != nullptr && fields.is_object() && fields.empty())) {
+            request.set_patch_json(fields.dump());
+        }
+        if (expectedVersion.has_value()) request.set_expected_version(*expectedVersion);
+        if (increments != nullptr) request.set_increments_json(increments->dump());
         if (!actor.empty()) {
             request.set_actor(actor);
         }
 
         smartbotic::databasepb::PatchDocumentResponse response;
         grpc::Status status;
+        std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
             setDeadline(context);
             response.Clear();
             status = stub_->PatchDocument(&context, request, &response);
+            detailJson = trailerDetail(context);   // v2.12.0
             if (status.ok() || !retryableStatus(status)) {
                 break;
             }
@@ -503,16 +608,21 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::patch failed after retries: {}", status.error_message());
-            recordFailure(failureOut, status);
+            failureOut.record(status, detailJson);
             return 0;
         }
 
         if (!response.success()) {
             spdlog::error("Client::patch failed: {}", response.error());
-            recordFailure(failureOut, Client::ErrorCode::Unknown, response.error());
+            failureOut.recordInBand(response.error_code(), response.error(), detailJson);
             return 0;
         }
 
+        if (incrementedOut != nullptr) {
+            *incrementedOut = response.incremented_json().empty()
+                ? nlohmann::json::object()
+                : nlohmann::json::parse(response.incremented_json());
+        }
         return response.new_version();
     }
 
@@ -534,11 +644,13 @@ public:
 
         smartbotic::databasepb::UpsertResponse response;
         grpc::Status status;
+        std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
             setDeadline(context);
             response.Clear();
             status = stub_->Upsert(&context, request, &response);
+            detailJson = trailerDetail(context);   // v2.12.0
             if (status.ok() || !retryableStatus(status)) {
                 break;
             }
@@ -554,7 +666,7 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::upsert failed after retries: {}", status.error_message());
-            throwStatus(status, status.error_message());
+            throwStatus(status, status.error_message(), detailJson);
         }
 
         return {response.id(), response.inserted()};
@@ -567,19 +679,25 @@ public:
     // FAILED_PRECONDITION, not deleted=false, and that message is the only
     // way an operator learns WHAT blocked the delete.
     bool removeImpl(const std::string& collection, const std::string& id,
-                    std::string* errorOut, Client::Failure* failureOut = nullptr) {
-        if (failureOut != nullptr) *failureOut = Client::Failure{};
+                    std::string* errorOut, FailureSink failureOut = {},
+                    const std::string& actor = {}) {
+        failureOut.reset();
         smartbotic::databasepb::DeleteRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
+        if (!actor.empty()) {
+            request.set_actor(actor);
+        }
 
         smartbotic::databasepb::DeleteResponse response;
         grpc::Status status;
+        std::string detailJson;   // v2.12.0 - the refusal detail, if any
         for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
             grpc::ClientContext context;
             setDeadline(context);
             response.Clear();
             status = stub_->Delete(&context, request, &response);
+            detailJson = trailerDetail(context);   // v2.12.0
             if (status.ok() || !retryableStatus(status)) {
                 break;
             }
@@ -596,7 +714,7 @@ public:
         if (!status.ok()) {
             spdlog::error("Client::remove failed after retries: {}", status.error_message());
             if (errorOut != nullptr) *errorOut = status.error_message();
-            recordFailure(failureOut, status);
+            failureOut.record(status, detailJson);
             return false;
         }
 
@@ -616,6 +734,52 @@ public:
         return removeImpl(collection, id, nullptr, &failureOut);
     }
 
+    bool removeAs(const std::string& collection, const std::string& id,
+                  const std::string& actor, FailureSink failureOut) {
+        return removeImpl(collection, id, nullptr, failureOut, actor);
+    }
+
+    // v2.12.0 - BatchDelete, which the client never exposed.
+    std::optional<Client::BatchRemoveResult> removeManyAs(const std::string& collection,
+                                                          const std::vector<std::string>& ids,
+                                                          const std::string& actor,
+                                                          FailureSink failureOut) {
+        failureOut.reset();
+        smartbotic::databasepb::BatchDeleteRequest request;
+        request.set_collection(qualify(collection));
+        for (const auto& id : ids) request.add_ids(id);
+        if (!actor.empty()) request.set_actor(actor);
+
+        smartbotic::databasepb::BatchDeleteResponse response;
+        grpc::Status status;
+        std::string detailJson;
+        // Retried like the other deletes: deleting an id twice is harmless, and
+        // a retry after a lost reply reports the ids the first attempt removed
+        // as not found - which is why deletedIds is "what THIS call removed".
+        for (uint32_t attempt = 0; attempt <= config_.writeRetries; ++attempt) {
+            grpc::ClientContext context;
+            setDeadline(context);
+            response.Clear();
+            status = stub_->BatchDelete(&context, request, &response);
+            detailJson = trailerDetail(context);
+            if (status.ok() || !retryableStatus(status)) break;
+            if (attempt < config_.writeRetries) {
+                std::this_thread::sleep_for(std::chrono::milliseconds(computeBackoffMs(
+                    config_.writeRetryBackoffMs, attempt,
+                    config_.writeRetryMaxBackoffMs, config_.writeRetryJitter)));
+            }
+        }
+        if (!status.ok()) {
+            spdlog::error("Client::removeManyAs failed: {}", status.error_message());
+            failureOut.record(status, detailJson);
+            return std::nullopt;
+        }
+        Client::BatchRemoveResult out;
+        out.deletedCount = response.deleted_count();
+        out.deletedIds.assign(response.deleted_ids().begin(), response.deleted_ids().end());
+        return out;
+    }
+
     bool exists(const std::string& collection, const std::string& id) {
         smartbotic::databasepb::ExistsRequest request;
         request.set_collection(qualify(collection));
@@ -1449,6 +1613,11 @@ public:
             uniqueFlags->reserve(response.indexes_size());
         }
         for (const auto& i : response.indexes()) {
+            // v2.12.0 - a composite unique constraint is not an index on a
+            // field; its `field` is only a display form ("a+b"). Reported by
+            // listCompositeUniqueIndexes() instead, so nothing here can be
+            // mistaken for a real field.
+            if (i.fields_size() > 0) continue;
             Client::IndexDefinition d;
             d.field = i.field();
             d.distinctValues = i.distinct_values();
@@ -1459,6 +1628,73 @@ public:
         return out;
     }
 
+    // v2.12.0 - composite unique constraints.
+    Client::CreateIndexResult createCompositeUniqueIndex(const std::string& collection,
+                                                         const std::vector<std::string>& fields) {
+        smartbotic::databasepb::CreateIndexRequest request;
+        request.set_collection(qualify(collection));
+        for (const auto& f : fields) request.add_fields(f);
+        request.set_unique(true);
+        smartbotic::databasepb::CreateIndexResponse response;
+        grpc::ClientContext context;
+        setDeadline(context);
+
+        Client::CreateIndexResult out;
+        auto status = stub_->CreateIndex(&context, request, &response);
+        if (!status.ok()) {
+            out.error = status.error_message();
+            spdlog::error("Client::createCompositeUniqueIndex failed: {}", out.error);
+            return out;
+        }
+        out.success = response.success();
+        out.error = response.error();
+        out.rowsIndexed = response.rows_indexed();
+        out.alreadyExisted = response.already_existed();
+        out.duplicateExamples.assign(response.duplicate_examples().begin(),
+                                     response.duplicate_examples().end());
+        if (!out.success) {
+            spdlog::error("Client::createCompositeUniqueIndex rejected: {}", out.error);
+        }
+        return out;
+    }
+
+    bool dropCompositeUniqueIndex(const std::string& collection,
+                                  const std::vector<std::string>& fields) {
+        smartbotic::databasepb::DropIndexRequest request;
+        request.set_collection(qualify(collection));
+        for (const auto& f : fields) request.add_fields(f);
+        smartbotic::databasepb::DropIndexResponse response;
+        grpc::ClientContext context;
+        setDeadline(context);
+        auto status = stub_->DropIndex(&context, request, &response);
+        if (!status.ok()) {
+            spdlog::error("Client::dropCompositeUniqueIndex failed: {}", status.error_message());
+            return false;
+        }
+        if (!response.success()) {
+            spdlog::error("Client::dropCompositeUniqueIndex rejected: {}", response.error());
+        }
+        return response.success();
+    }
+
+    std::vector<std::vector<std::string>> listCompositeUniqueIndexes(const std::string& collection) {
+        smartbotic::databasepb::ListIndexesRequest request;
+        request.set_collection(qualify(collection));
+        smartbotic::databasepb::ListIndexesResponse response;
+        grpc::ClientContext context;
+        setDeadline(context);
+        std::vector<std::vector<std::string>> out;
+        auto status = stub_->ListIndexes(&context, request, &response);
+        if (!status.ok()) {
+            spdlog::error("Client::listCompositeUniqueIndexes failed: {}", status.error_message());
+            return out;
+        }
+        for (const auto& i : response.indexes()) {
+            if (i.fields_size() > 0) out.emplace_back(i.fields().begin(), i.fields().end());
+        }
+        return out;
+    }
+
     std::vector<Client::IndexValue> indexValues(const std::string& collection,
                                                 const std::string& field,
                                                 uint32_t limit, bool ascending) {
@@ -1804,8 +2040,17 @@ public:
         std::atomic<bool> active_;
     };
 
+    // v2.12.0 - the original callback shape, delivered from the one reader
+    // loop below so both subscription forms decode events identically.
     std::shared_ptr<void> subscribe(const std::vector<std::string>& collections,
                                     Client::EventCallback callback) {
+        return subscribeEvents(collections, [callback = std::move(callback)](const Client::Event& e) {
+            callback(e.collection, e.id, e.eventType, e.data);
+        });
+    }
+
+    std::shared_ptr<void> subscribeEvents(const std::vector<std::string>& collections,
+                                          Client::EventHandler handler) {
         auto context = std::make_shared<grpc::ClientContext>();
         // Subscribe is a long-running stream — no deadline — but the auth
         // metadata still has to land on the initial request headers.
@@ -1835,7 +2080,7 @@ public:
         auto reader = stub_->Subscribe(context.get(), request);
 
         // Create reader thread
-        auto readerThread = std::thread([reader = reader.get(), callback = std::move(callback)]() {
+        auto readerThread = std::thread([reader = reader.get(), handler = std::move(handler)]() {
             smartbotic::databasepb::DatabaseEvent event;
             while (reader->Read(&event)) {
                 std::optional<nlohmann::json> data;
@@ -1854,12 +2099,15 @@ public:
                     default: eventType = "unknown"; break;
                 }
 
-                callback(
-                    event.collection(),
-                    event.document_id(),
-                    eventType,
-                    data
-                );
+                Client::Event out;
+                out.collection = event.collection();
+                out.id = event.document_id();
+                out.eventType = std::move(eventType);
+                out.data = std::move(data);
+                out.actor = event.actor();
+                out.timestamp = event.timestamp();
+                out.nodeId = event.node_id();
+                handler(out);
             }
         });
 
@@ -2440,6 +2688,48 @@ bool Client::update(const std::string& collection, const std::string& id, const
     return impl_->update(collection, id, data, actor, &failureOut);
 }
 
+bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data,
+                    FailureDetail& failureOut, const std::string& actor) {
+    failureOut = FailureDetail{};
+    return impl_->update(collection, id, data, actor, &failureOut);
+}
+
+bool Client::updateIfVersion(const std::string& collection, const std::string& id,
+                             const nlohmann::json& data, uint64_t expectedVersion,
+                             FailureDetail& failureOut, const std::string& actor) {
+    return impl_->updateIfVersion(collection, id, data, expectedVersion, actor, &failureOut);
+}
+
+uint64_t Client::patch(const std::string& collection, const std::string& id,
+                       const nlohmann::json& fields, FailureDetail& failureOut,
+                       const std::string& actor) {
+    return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut);
+}
+
+uint64_t Client::patchWithTtl(const std::string& collection, const std::string& id,
+                              const nlohmann::json& fields, uint32_t ttlSeconds,
+                              FailureDetail& failureOut, const std::string& actor) {
+    return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut);
+}
+
+uint64_t Client::patchIfVersion(const std::string& collection, const std::string& id,
+                                const nlohmann::json& fields, uint64_t expectedVersion,
+                                FailureDetail& failureOut, const std::string& actor) {
+    return impl_->patch(collection, id, fields, actor, std::nullopt, &failureOut,
+                        expectedVersion);
+}
+
+std::optional<nlohmann::json> Client::increment(const std::string& collection, const std::string& id,
+                                                const nlohmann::json& deltas,
+                                                FailureDetail& failureOut,
+                                                const std::string& actor) {
+    nlohmann::json incremented;
+    const uint64_t v = impl_->patch(collection, id, nlohmann::json::object(), actor, std::nullopt,
+                                    &failureOut, std::nullopt, &deltas, &incremented);
+    if (v == 0) return std::nullopt;
+    return incremented;
+}
+
 bool Client::updateIfVersion(const std::string& collection, const std::string& id,
                              const nlohmann::json& data, uint64_t expectedVersion,
                              Failure& failureOut, const std::string& actor) {
@@ -2487,6 +2777,27 @@ bool Client::remove(const std::string& collection, const std::string& id, Failur
     return impl_->remove(collection, id, failureOut);
 }
 
+bool Client::removeAs(const std::string& collection, const std::string& id,
+                      const std::string& actor) {
+    return impl_->removeAs(collection, id, actor, FailureSink{});
+}
+
+bool Client::removeAs(const std::string& collection, const std::string& id,
+                      const std::string& actor, Failure& failureOut) {
+    return impl_->removeAs(collection, id, actor, &failureOut);
+}
+
+bool Client::removeAs(const std::string& collection, const std::string& id,
+                      const std::string& actor, FailureDetail& failureOut) {
+    return impl_->removeAs(collection, id, actor, &failureOut);
+}
+
+std::optional<Client::BatchRemoveResult>
+Client::removeManyAs(const std::string& collection, const std::vector<std::string>& ids,
+                     const std::string& actor, FailureDetail& failureOut) {
+    return impl_->removeManyAs(collection, ids, actor, &failureOut);
+}
+
 bool Client::exists(const std::string& collection, const std::string& id) {
     return impl_->exists(collection, id);
 }
@@ -2640,6 +2951,21 @@ Client::CreateIndexResult Client::createUniqueIndex(const std::string& collectio
     return impl_->createUniqueIndex(collection, field);
 }
 
+Client::CreateIndexResult Client::createCompositeUniqueIndex(const std::string& collection,
+                                                             const std::vector<std::string>& fields) {
+    return impl_->createCompositeUniqueIndex(collection, fields);
+}
+
+bool Client::dropCompositeUniqueIndex(const std::string& collection,
+                                      const std::vector<std::string>& fields) {
+    return impl_->dropCompositeUniqueIndex(collection, fields);
+}
+
+std::vector<std::vector<std::string>>
+Client::listCompositeUniqueIndexes(const std::string& collection) {
+    return impl_->listCompositeUniqueIndexes(collection);
+}
+
 std::vector<Client::IndexDefinition> Client::listIndexes(const std::string& collection) {
     return impl_->listIndexes(collection, nullptr);
 }
@@ -2719,6 +3045,11 @@ std::shared_ptr<void> Client::subscribe(const std::vector<std::string>& collecti
     return impl_->subscribe(collections, std::move(callback));
 }
 
+std::shared_ptr<void> Client::subscribeEvents(const std::vector<std::string>& collections,
+                                              EventHandler handler) {
+    return impl_->subscribeEvents(collections, std::move(handler));
+}
+
 bool Client::healthCheck() {
     return impl_->healthCheck();
 }

+ 66 - 15
docs/ROADMAP.md

@@ -1,6 +1,9 @@
 # Smartbotic Database - Status and Roadmap
 
-**Current version: 2.11.4** (see `VERSION`). Last reviewed: 2026-10-05.
+**Released version: 2.12.0** (see `VERSION`). Last reviewed: 2026-10-07.
+
+> 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.
 
 This is the single authoritative statement of what exists and what does not.
 If any other document in this repository disagrees with this one, this one is
@@ -53,7 +56,7 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.11.4. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.12.0. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -69,7 +72,16 @@ detail and the failure modes.
 - Referential integrity: relations with restrict / cascade / set_null / no_action,
   a DUPSORT reverse index, `DescribeDelete`, `relations check`, per-collection
   enforcement switches, and TTL expiry running the same policy as a manual delete
-- Unique constraints, enforced inside the document's own transaction
+- Unique constraints, enforced inside the document's own transaction; null is
+  not a value for uniqueness (2.12.0); composite constraints over several fields
+  (2.12.0). CLI: `index-create --unique`, `unique-create`, `unique-drop`
+- Machine-readable refusal detail on every refused write - reason, field(s),
+  value(s), conflicting id, current version (2.12.0); `Client::FailureDetail`,
+  `Client::errorDetail()`
+- Conditional partial update (`patchIfVersion`) and atomic increment
+  (`increment`) (2.12.0)
+- Event provenance: the actor on every `DatabaseEvent`, `removeAs()`,
+  `subscribeEvents()` (2.12.0); client batch delete `removeManyAs()` (2.12.0)
 - Paging fast path (no filter, no sort) and the two-pass filtered/sorted scan
 - Secondary indexes on declared fields: equality, IN, CONTAINS, EXISTS,
   ranges, intersection, result ordering, filtered totals, and distinct
@@ -90,10 +102,6 @@ Served from an index: equality, `IN`, `CONTAINS`, `EXISTS=true`, numeric and
 string ranges, two-list intersection, result ORDERING, filtered TOTALS, and
 distinct values / min / max. Remaining:
 
-- **Unique constraints.** Built and deliberately not shipped - see the v2.10.0
-  entry in `CLAUDE.md`. The check is correct; it cannot be enforced while
-  `applyDualWriteMirror` swallows every exception and MemoryStore mutates before
-  the mirror runs. Needs the write path restructured, which wants its own change.
 - **`NE` and `REGEX`** would need a full walk either way. A prefix-anchored
   `REGEX` (`^abc`) could become a range over the string tag - the one real
   opportunity here.
@@ -190,18 +198,61 @@ reason each was left:
   becomes readable. Deliberate (a row predicate selects rows, and the row's
   identity is its current document) but worth restating before security is armed.
 
+### 5a-2. Follow-up for smartbotic-vectorapi after 2.12.0
+
+vectorapi's requests (`/tmp/db-changes-for-vectorapi.md`, D1-D7) are all in
+2.12.0; the answers were appended to that file. What remains is theirs: move
+the loop guard to `Client::Event::actor`, delete with `removeAs()` /
+`removeManyAs()`, claim with `patchIfVersion()` using the `_version` that
+`find()` already returns (no history call), count with `increment()`, and map
+`FailureDetail::reason` to HTTP. Their package floor becomes
+`libsmartbotic-db-client (>= 2.12.0)`, and the database must be deployed first.
+
+### 5a-3. Pending: upgrade the zeus `smartbotic-db` container
+
+The container on zeus is **not a test**: it is the live database of the
+smartbotic-automation stack (`smartbotic-webserver` and `smartbotic-runner`
+connect via `host.docker.internal:9004`, project `smartbotic-automation`; data
+since April). It runs 2.11.3. A nightly cron (`/etc/cron.d/smartbotic-db-backup`,
+03:30 local) stops it, archives data + key to `/data/backups/smartbotic-db/`
+(keeps 14) and starts it again; the automation stack rides through that.
+
+A **2.11.4** runtime image is built and tested but NOT swapped in - since
+superseded: build **2.12.0** the same way instead, because vectorapi 0.5.0
+needs it on any database it talks to
+(`smartbotic-database:2.11.4`, made with the Ubuntu 26.04 recipe in
+`/data/smartbotic-db/build/`: `src-2.11.4/`, `hostbin-2.11.4/`,
+`Dockerfile.2.11.4`). It booted cleanly on a copy of the 2026-10-06 backup
+(`TrivialSuccess`, 10111 docs). The owner has not yet decided whether to swap,
+and 2.12.0 is the version to build now (see above). The swap
+procedure used for every earlier upgrade: snapshot the data directory to
+`/data/smartbotic-db/backups/pre-<ver>-<ts>`, rename the running container to
+`smartbotic-db-<old>-rollback`, start the new image with the same name, ports,
+mounts, `--restart unless-stopped` and `--stop-timeout 120`, then check recovery
+and that both automation containers reconnected.
+
 ### 5b-2. Open after the v2.11.4 consumer feedback round
 
 Two reports from smartbotic-vectorapi produced v2.11.4. Left open, with reasons:
 
-- **In-band refusals carry no status code.** `Update` and `PatchDocument` answer
-  some failures with gRPC status OK plus `success=false` and a message: document
-  not found, version conflict, read-only mode, memory-pressure emergency, a write
-  to a view. The 2.11.4 client reports those as `ErrorCode::Unknown` with the
-  message, so a consumer wanting 404 on a patch of a missing document still has
-  to read text. Closing it is a wire change - either real status codes (which
-  changes what pre-2.11.4 clients see for those cases) or an additive
-  `error_code` field on the two responses. The second is the safe one.
+- ~~In-band refusals carry no status code.~~ **Closed in 2.12.0** with the
+  additive `error_code` on `UpdateResponse`/`PatchDocumentResponse`.
+- **Read-only mode and a relation refusal still share `FAILED_PRECONDITION`**,
+  but since 2.12.0 `FailureDetail::reason` (`read_only` / `missing_parent` /
+  `delete_restricted`) tells them apart. Changing the code itself would change
+  what older clients see; the reason is the supported way to branch.
+- **The stored `updated_by` of an actor-less patch is still the previous
+  writer** (`patchDocument` keeps it; insert and update overwrite it). Since
+  2.12.0 the EVENT reports the patch's own, empty, actor, so a loop guard is
+  correct; version history still shows the previous writer for that version.
+  Changing it changes what the audit trail has always said.
+- ~~The client has no batch delete.~~ **Closed in 2.12.0**: `removeManyAs()`.
+- **`increment()` does not create a missing document.** Deliberate (an upsert
+  needs a full initial body); the documented pattern is increment, insert on
+  `NotFound`, increment again on `AlreadyExists`.
+- **A composite constraint applies only when every component is a scalar.** An
+  absent, null, object or array component leaves the row unconstrained - the SQL
+  rule for NULL, extended to values that have no single key.
 - **Most management calls still return a bare `false`.** `createRelation`,
   `configureCollection`, `createIndex`, `createCollection` and the like log the
   reason and return `false`. The `Failure&` overloads cover the five document

+ 180 - 7
docs/integration-guide.md

@@ -275,13 +275,53 @@ if (!db.remove("workflows", "wf-1", why)) {
 
 `Failure` is reset at the start of every call, so it is safe to reuse.
 
-**One limit to know.** `Update` and `PatchDocument` refuse some writes in-band:
-the gRPC status is OK and the reply carries only a message. Those arrive as
-`ErrorCode::Unknown` with the server's text - "Document not found", "Version
-conflict", read-only mode, memory-pressure emergency, a write to a view. The
-unique-constraint and relation refusals above are real status codes and are
-not affected. `update()` does report a missing document as `NotFound`, because
-it reads the document first and knows.
+#### The full reason: `FailureDetail` (2.12.0+)
+
+A status code alone is ambiguous - `FailedPrecondition` means a missing parent,
+a restricted delete **and** read-only mode - and it does not say *which* unique
+constraint refused a write. `Client::FailureDetail` does. Every call that takes
+a `Failure&` also has an overload taking a `FailureDetail&`, and for the calls
+that throw, `Client::errorDetail(e)` returns the same struct (or `nullptr` for
+an exception this client did not throw):
+
+```cpp
+Client::FailureDetail why;
+if (db.patch("calls", id, {{"vapi_call_id", callId}}, why) == 0) {
+    if (why.reason == "unique_violation" && why.fields == std::vector<std::string>{"vapi_call_id"}) {
+        auto existing = db.get("calls", why.conflictingId);   // that call is already recorded
+    }
+}
+
+try {
+    db.insert("files", {{"chat_id", 1}, {"file_id", "a"}});
+} catch (const Client::AlreadyExists& e) {
+    if (const auto* d = Client::errorDetail(e)) {
+        // d->fields == {"chat_id", "file_id"}, d->values == {"chat_id":1,"file_id":"a"}
+    }
+}
+```
+
+| `reason` | Code | Also set |
+|---|---|---|
+| `unique_violation` | `AlreadyExists` | `fields` (several for a composite), `values` (field -> value), `conflictingId` |
+| `missing_parent` | `FailedPrecondition` | `fields` (the reference field), `values` (the missing id), `relation` |
+| `delete_restricted` | `FailedPrecondition` | |
+| `read_only` | `FailedPrecondition` | |
+| `version_conflict` | `Aborted` | `currentVersion` |
+| `not_found` | `NotFound` | |
+| `invalid_increment` | `InvalidArgument` | `fields` (the path) |
+| `memory_pressure` | `ResourceExhausted` | |
+| `view_write` | `InvalidArgument` | |
+| `""` | anything | nothing further (transport errors, denials, ...) |
+
+**`Update` and `PatchDocument` refusals now carry their code.** Before 2.12.0
+those two RPCs answered "not found", "version conflict", read-only, memory
+pressure and view writes in-band - status OK plus a message - and the client
+reported `ErrorCode::Unknown`. They still answer in-band, so an older client
+sees exactly what it always did, but the reply now says what the status would
+have been: a missing document is `NotFound`, a stale version `Aborted` (with
+`currentVersion`), and so on. Against a server older than 2.12.0 they are still
+`Unknown`, and `FailureDetail` holds only `code` and `message`.
 
 ### Concurrency: update() vs patch()
 
@@ -319,6 +359,91 @@ if (!db.updateIfVersion("users", "user-123", *doc, version)) {
 }
 ```
 
+**`patchIfVersion()`** (2.12.0+) — a conditional **partial** update: merge some
+fields only if the document is still at the version you read. This is the
+right tool for "claim this task exactly once". `updateIfVersion()` replaces the
+whole document, so using it to flip one field means writing back everything you
+read - silently reverting any field someone else changed in between.
+
+```cpp
+auto rows = db.find("tasks", {.filters = {Client::Filter::eq("state", "open")}, .limit = 1});
+const uint64_t v = rows.at(0)["_version"];          // find() and get() return _version
+Client::FailureDetail why;
+if (db.patchIfVersion("tasks", rows[0]["_id"], {{"state", "claimed"}, {"owner", me}}, v, why) == 0) {
+    if (why.code == Client::ErrorCode::Aborted) { /* someone else claimed it first */ }
+}
+```
+
+The check and the write happen under one lock on the server: of any number of
+concurrent claims at one version, exactly one succeeds.
+
+**`increment()`** (2.12.0+) — atomic counters. Adds numbers to fields in one
+locked read-modify-write, so concurrent increments never lose an update and no
+version loop is needed:
+
+```cpp
+Client::FailureDetail why;
+auto now = db.increment("stats", "2026-10-07", {{"calls", 1}, {"minutes", 3.5}, {"by.voice", 1}}, why);
+// now = {"calls": 18, "minutes": 61.5, "by.voice": 4}
+```
+
+- An absent or null field counts as 0; a dotted path creates nested objects.
+- Integer + integer stays an integer (overflow is refused); anything else is a
+  double.
+- A field holding a non-number, a non-numeric delta, or document metadata is
+  refused (`InvalidArgument`, reason `invalid_increment`, the path in `fields`),
+  and then **nothing** is written - not even the other increments in the call.
+- The document must exist (`NotFound` otherwise). For a counter that may not
+  exist yet: `increment`; on `NotFound` insert it under a fixed id with the
+  starting value; on `AlreadyExists` (someone else just created it) increment
+  again.
+
+### Indexes and unique constraints
+
+```cpp
+db.createIndex("executions", "workflowId");              // speeds up queries on the field
+auto r = db.createUniqueIndex("calls", "vapi_call_id");  // also refuses duplicates
+auto c = db.createCompositeUniqueIndex("files", {"chat_id", "file_unique_id"});  // 2.12.0+
+```
+
+A unique constraint refuses a write that would give two documents the same
+value, with `ErrorCode::AlreadyExists` and reason `unique_violation` (see
+[`FailureDetail`](#the-full-reason-failuredetail-2120)). Declaring one over data
+that already holds duplicates is **refused**, with examples in
+`r.duplicateExamples`, rather than accepted and left false.
+
+**Null is not a value (2.12.0+).** Any number of documents may hold `null` for a
+unique field, or omit it - the SQL rule. A record that gets its external id
+later can be created with the field null. Before 2.12.0 two nulls collided while
+two absent fields did not. Null is still indexed: `Filter::eq(field, nullptr)`
+finds those rows. Note that `patch()` with a `null` value *removes* the field
+(merge-patch semantics); either way it is unconstrained.
+
+**Composite constraints (2.12.0+)** make a *combination* unique - a received
+attachment per chat, a booking per `(day, slot)` - so the invariant lives in the
+schema, not in every writer. A document in which any of the fields is absent,
+null, an object or an array is not constrained. A composite backs no query; it
+only refuses duplicates. List them with `listCompositeUniqueIndexes()` (they do
+not appear in `listIndexes()`, which lists indexes on single fields) and drop
+one with `dropCompositeUniqueIndex(collection, sameFieldList)`. From the CLI:
+`unique-create <coll> <field> <field>...`, `unique-drop ...`, and `indexes
+<coll>` shows them.
+
+Constraints and indexes are declarations stored with the collection's config:
+they survive restarts and are re-armed at boot.
+
+### Batch delete (2.12.0+)
+
+```cpp
+Client::FailureDetail why;
+auto r = db.removeManyAs("jobs", staleIds, "cleanup-job", why);   // one round trip
+// r->deletedCount, r->deletedIds (in request order; an absent id did not exist)
+```
+
+Relations are enforced exactly as for `removeAs()`, and all-or-nothing on
+`restrict`: if any id is protected, nothing is deleted (reason
+`delete_restricted`). Every delete carries the actor onto its event.
+
 ### Views
 
 Views are named, read-only projections over collections. They filter which fields are returned and optionally enforce baked-in filters and default sort order. Views are ideal for:
@@ -1230,6 +1355,54 @@ auto subscription = db.subscribe({"users", "sessions"}, [](
 subscription.reset();
 ```
 
+#### Who caused a change, and avoiding trigger loops (2.12.0+)
+
+`subscribeEvents()` delivers a `Client::Event`, which adds the **actor** - the
+`actor` the write or delete carried - plus the server timestamp and node id:
+
+```cpp
+auto sub = db.subscribeEvents({"orders"}, [](const Client::Event& e) {
+    // e.collection, e.id, e.eventType, e.data, e.actor, e.timestamp, e.nodeId
+});
+```
+
+| Event | `actor` is |
+|---|---|
+| insert, update, upsert, patch | the `actor` argument of that call; empty if none was given |
+| delete | the actor passed to `removeAs()`; empty for `remove()` |
+| a document a relation cascade deleted or nulled | the actor of the delete that caused the cascade |
+| expire (TTL) | always empty: nobody asked for it |
+
+A consumer that **writes in response to events** - a trigger, a function, a
+sync job - must be able to recognise its own writes, or something that writes to
+a collection it watches feeds itself forever. Tag every write it makes with an
+actor it can recognise, deletes included, and check `e.actor` before reacting:
+
+```cpp
+const std::string me = "sync-job";
+db.patch("orders", id, {{"synced", true}}, me);
+db.removeAs("orders", staleId, me);         // remove() has no actor parameter
+
+auto sub = db.subscribeEvents({"orders"}, [&](const Client::Event& e) {
+    if (e.actor == me) return;                 // our own change: do not react
+    // ...
+});
+```
+
+Read the actor from the event, not from version history afterwards. History
+races any later write, a delete leaves the document's *previous* state there
+(its `updated_by` is whoever last wrote it, not who deleted it), and a patch
+without an actor keeps the previous writer in `updated_by` while its event
+correctly reports no actor.
+
+`removeAs()` is a separate name rather than a `remove()` overload on purpose:
+`remove(collection, id, someString)` already means "write the error into
+`someString`", and C++ would pick that for a `std::string` variable - an actor
+overload would have compiled and silently sent nothing.
+
+The original `subscribe()` is unchanged and still works; it simply does not
+expose the actor.
+
 ### Set Operations
 
 Redis-compatible set operations on top of documents.

+ 105 - 0
proto/database.proto

@@ -20,6 +20,27 @@ package smartbotic.databasepb;
 
 // ===== Main Database Service =====
 
+// v2.12.0 - REFUSAL DETAIL. Any refused write may carry trailing metadata
+// `sbdb-error-detail-bin`: UTF-8 JSON (gRPC base64s a -bin value on the wire)
+// that says WHY in a form a program can branch on, whether the refusal came as
+// an error status or in-band (status OK, success=false). Keys, all optional:
+//
+//   reason           "unique_violation" | "missing_parent" | "delete_restricted"
+//                    | "read_only" | "memory_pressure" | "view_write"
+//                    | "not_found" | "version_conflict" | "invalid_increment"
+//   code             the gRPC status code number - present for in-band
+//                    refusals, whose status is OK
+//   fields           the field(s) concerned: the constrained field(s) of a
+//                    unique violation, the reference field of a missing
+//                    parent, the field an increment could not be applied to
+//   values           object, field -> the value that collided / was refused
+//   conflicting_id   unique violation: the document already holding the value
+//   relation         missing parent: the relation that refused the write
+//   current_version  version conflict: the document's current version
+//
+// Absent on a server older than 2.12.0. The reason exists because a status
+// code alone is ambiguous: FAILED_PRECONDITION means a missing parent, a
+// restricted delete AND read-only mode.
 service DatabaseService {
     // Document operations
     rpc Insert(InsertRequest) returns (InsertResponse);
@@ -217,6 +238,13 @@ message UpdateResponse {
     uint64 new_version = 1;
     bool success = 2;
     string error = 3;
+    // v2.12.0 - when success=false, the gRPC status code this refusal WOULD
+    // carry: NOT_FOUND, ABORTED (version conflict), FAILED_PRECONDITION
+    // (read-only), RESOURCE_EXHAUSTED (memory pressure), INVALID_ARGUMENT
+    // (write to a view). These refusals stay in-band (status OK) so clients
+    // older than 2.12.0 see exactly what they always saw; 0 from an older
+    // server. The trailing `sbdb-error-detail-bin` adds the reason.
+    int32 error_code = 4;
 }
 
 message UpsertRequest {
@@ -236,6 +264,12 @@ message UpsertResponse {
 message DeleteRequest {
     string collection = 1;
     string id = 2;
+    // v2.12.0 - who is deleting, as `actor` is on every other write. Reported
+    // on the resulting DatabaseEvent (and on the events of any documents a
+    // relation cascade deletes or nulls because of it). Not stored: the
+    // document is gone, and its last version in history keeps the updated_by
+    // of whoever last WROTE it, which is not who deleted it.
+    string actor = 3;
 }
 
 message DeleteResponse {
@@ -251,12 +285,40 @@ message PatchDocumentRequest {
     // v2.8.0 — same three-way semantics as UpdateRequest.ttl_seconds: absent
     // leaves the expiry alone, 0 clears it, N sets N seconds from now.
     optional uint32 ttl_seconds = 5;
+
+    // v2.12.0 - apply only if the document is still at this version: a
+    // conditional PARTIAL update. updateIfVersion replaces the whole body, so a
+    // caller that only wants to change one field ("claim this task") would
+    // have to write back everything it read, reverting any field a concurrent
+    // writer changed meanwhile. A mismatch is refused with status ABORTED,
+    // reason "version_conflict" and the current version in the detail.
+    // Absent = unconditional, as before.
+    optional uint64 expected_version = 6;
+
+    // v2.12.0 - ATOMIC INCREMENT. A JSON object of field -> number to add, in
+    // the same locked read-modify-write as the merge, so concurrent increments
+    // never lose an update. Dotted paths descend objects (creating them).
+    //   - an absent or null field counts as 0;
+    //   - integer + integer stays an integer (overflow is refused), anything
+    //     else is a double;
+    //   - a non-numeric stored value, a non-numeric delta, or a field that
+    //     patch_json also sets is refused with INVALID_ARGUMENT, reason
+    //     "invalid_increment", and the field in the detail.
+    // Nothing is written when any increment is refused. patch_json may be
+    // empty when only incrementing. The new values come back in
+    // PatchDocumentResponse.incremented_json.
+    bytes increments_json = 7;
 }
 
 message PatchDocumentResponse {
     uint64 new_version = 1;
     bool success = 2;
     string error = 3;
+    // v2.12.0 - as UpdateResponse.error_code.
+    int32 error_code = 4;
+    // v2.12.0 - JSON object, field -> value AFTER the increments, for every
+    // field in increments_json. Empty when there were none.
+    bytes incremented_json = 5;
 }
 
 message ExistsRequest {
@@ -363,10 +425,16 @@ message BatchGetResponse {
 message BatchDeleteRequest {
     string collection = 1;
     repeated string ids = 2;
+    string actor = 3;                 // v2.12.0 - as DeleteRequest.actor, for every id
 }
 
 message BatchDeleteResponse {
     uint64 deleted_count = 1;
+    // v2.12.0 - the ids actually deleted, in request order. An id that is
+    // absent here did not exist. If the call fails partway (a relation
+    // refuses one id), the status is an error and no response is delivered:
+    // ids before it may already be gone - re-read to learn which.
+    repeated string deleted_ids = 2;
 }
 
 // ===== Query Operations =====
@@ -726,6 +794,23 @@ message DatabaseEvent {
     uint64 timestamp = 4;
     string node_id = 5;
     bytes data = 6;                   // JSON document (if include_data)
+
+    // v2.12.0 - who caused this change: the `actor` the write or delete
+    // request carried. Empty when the request carried none, and for changes
+    // the database makes itself (TTL expiry). Sent whether or not
+    // include_data is set.
+    //
+    // For a document a relation cascade deleted or nulled, it is the actor of
+    // the delete that triggered the cascade - the cascade is that caller's
+    // doing, not whoever last wrote the child.
+    //
+    // This is what makes a write-triggered-write loop guard possible: a
+    // subscriber that reacts to events by writing can tag its own writes and
+    // recognise them here. Before this an event said nothing about its
+    // origin; insert/update provenance had to be read back from version
+    // history after the fact (racing any later write), and a delete's was not
+    // recorded anywhere.
+    string actor = 7;
 }
 
 enum EventType {
@@ -1125,7 +1210,21 @@ message CreateIndexRequest {
     // collection that already contains duplicate values is REFUSED (see
     // CreateIndexResponse.duplicate_examples) rather than accepted and left
     // silently unenforced against the data that already violates it.
+    //
+    // v2.12.0 - NULL IS NOT A VALUE for uniqueness: any number of documents
+    // may hold null (or omit the field), as in SQL. Before 2.12.0 two nulls
+    // collided while two absent fields did not.
     bool unique = 3;
+
+    // v2.12.0 - a COMPOSITE unique constraint over the TUPLE of these fields
+    // (two or more; `field` must then be empty and `unique` true). Two
+    // documents may not hold the same combination. A document in which any
+    // of the fields is absent, null, an object or an array is not constrained
+    // - the SQL rule for a NULL in a unique key. Composite constraints back no
+    // query (the planner never uses them) and are listed by ListIndexes with
+    // `fields` set. Declaring one over existing duplicates is refused with
+    // examples, as for a single field.
+    repeated string fields = 4;
 }
 
 message CreateIndexResponse {
@@ -1147,6 +1246,9 @@ message CreateIndexResponse {
 message DropIndexRequest {
     string collection = 1;
     string field = 2;
+    // v2.12.0 - drop the composite unique constraint over exactly these
+    // fields, in the order they were declared. `field` must then be empty.
+    repeated string fields = 3;
 }
 
 message DropIndexResponse {
@@ -1167,6 +1269,9 @@ message IndexInfo {
     uint64 entries = 3;
     // v2.11.0 T11 — true when this index also carries a UNIQUE constraint.
     bool unique = 4;
+    // v2.12.0 - set for a COMPOSITE unique constraint: its fields, in order.
+    // `field` then holds a display form ("a+b") and `unique` is true.
+    repeated string fields = 5;
 }
 
 message ListIndexesResponse {

+ 4 - 1
service/src/config/collection_config_manager.cpp

@@ -16,7 +16,8 @@ nlohmann::json toJson(const CollectionCfg& cfg) {
         {"versioning_enabled", cfg.versioningEnabled},
         {"indexed_fields", cfg.indexedFields},
         {"relations_enforced", cfg.relationsEnforced},
-        {"unique_fields", cfg.uniqueFields}
+        {"unique_fields", cfg.uniqueFields},
+        {"composite_uniques", cfg.compositeUniques}
     };
 }
 
@@ -34,6 +35,8 @@ CollectionCfg fromJson(const nlohmann::json& j) {
     // fields (nothing enforces those yet).
     c.relationsEnforced = j.value("relations_enforced", true);
     c.uniqueFields = j.value("unique_fields", std::vector<std::string>{});
+    // v2.12.0 — absent on every older record: no composite constraints.
+    c.compositeUniques = j.value("composite_uniques", std::vector<std::vector<std::string>>{});
     return c;
 }
 

+ 9 - 5
service/src/config/collection_config_manager.hpp

@@ -77,12 +77,16 @@ struct CollectionCfg {
     // going stale.
     bool relationsEnforced = true;
 
-    // v2.11.0 T8 — persisted only. Nothing enforces uniqueness yet (Task 11
-    // activates it). A constraint that is advertised but unenforced would be
-    // worse than an absent one, so this deliberately has no RPC surface and
-    // no proto field yet - it exists here purely so the storage shape is
-    // settled before enforcement lands.
+    // v2.11.0 T8 — single-field UNIQUE constraints. Enforced since v2.11.0
+    // (T11), armed at boot by DatabaseService::applyIndexDeclarations().
     std::vector<std::string> uniqueFields;
+
+    // v2.12.0 — COMPOSITE unique constraints, each a list of two or more
+    // fields. Persisted here for the same reason as uniqueFields: this record
+    // lives in `_collection_meta`, so it is WAL'd and snapshotted for free.
+    // Armed at boot by applyIndexDeclarations(); a declared constraint whose
+    // sub-db is absent is rebuilt there.
+    std::vector<std::vector<std::string>> compositeUniques;
 };
 
 /**

+ 352 - 84
service/src/database_grpc_impl.cpp

@@ -10,6 +10,7 @@
 #include "json_parse.hpp"
 #include "persistence/wal.hpp"
 #include "views/projection.hpp"
+#include "storage/secondary_index.hpp"
 
 #include <spdlog/spdlog.h>
 #include <nlohmann/json.hpp>
@@ -20,6 +21,7 @@
 #include <memory>
 #include <mutex>
 #include <queue>
+#include <unordered_set>
 #include <utility>
 #include <vector>
 
@@ -29,9 +31,60 @@ namespace smartbotic::database {
 namespace pb = smartbotic::databasepb;
 
 namespace {
+// v2.12.0 — refusal detail. See the comment above `service DatabaseService` in
+// database.proto for the key and its JSON shape. Attached to the call's
+// trailing metadata, so it accompanies an error status AND an in-band refusal
+// (status OK, success=false) alike.
+constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin";
+
+void attachErrorDetail(grpc::ServerContext* context, const nlohmann::json& detail) {
+    if (context != nullptr) {
+        context->AddTrailingMetadata(kErrorDetailKey, detail.dump());
+    }
+}
+
+grpc::Status uniqueViolationStatus(grpc::ServerContext* context,
+                                   const smartbotic::db::storage::UniqueViolation& e) {
+    attachErrorDetail(context, {{"reason", "unique_violation"},
+                                {"fields", e.fields},
+                                {"values", e.values},
+                                {"conflicting_id", e.existing_id}});
+    return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+}
+
+grpc::Status missingParentStatus(grpc::ServerContext* context,
+                                 const smartbotic::db::storage::MissingParentReference& e) {
+    attachErrorDetail(context, {{"reason", "missing_parent"},
+                                {"fields", nlohmann::json::array({e.childField})},
+                                {"values", {{e.childField, e.parentId}}},
+                                {"relation", e.relation}});
+    return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+}
+
+// An in-band refusal: status OK, success=false, as these RPCs have always
+// answered - so a pre-2.12 client sees exactly what it always saw - plus the
+// code it would carry as a status, and the detail.
+template <typename Response>
+grpc::Status refuseInBand(grpc::ServerContext* context, Response* response,
+                          grpc::StatusCode code, const std::string& reason,
+                          const std::string& message,
+                          nlohmann::json extra = nlohmann::json::object()) {
+    response->set_success(false);
+    response->set_error(message);
+    response->set_error_code(static_cast<int32_t>(code));
+    extra["reason"] = reason;
+    extra["code"] = static_cast<int>(code);
+    attachErrorDetail(context, extra);
+    return grpc::Status::OK;
+}
+
 // Returns a Status that should be returned when the DB is read-only.
 // Used by write handlers whose responses don't have set_success/set_error fields.
-grpc::Status readOnlyStatus(const std::string& rpcName, const DatabaseService& svc) {
+grpc::Status readOnlyStatus(grpc::ServerContext* context, const std::string& rpcName,
+                            const DatabaseService& svc) {
+    // v2.12.0 — reason "read_only": FAILED_PRECONDITION alone is ambiguous with
+    // a relation refusal, which uses the same code.
+    attachErrorDetail(context, {{"reason", "read_only"}});
     return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
         rpcName + " rejected: database is in read-only mode. " + svc.readOnlyReason());
 }
@@ -39,7 +92,9 @@ grpc::Status readOnlyStatus(const std::string& rpcName, const DatabaseService& s
 // Returns a Status for rejecting writes when memory pressure is EMERGENCY.
 // Shares the RESOURCE_EXHAUSTED code with gRPC concurrency cap so clients
 // can reuse the same retry path.
-grpc::Status memoryEmergencyStatus(const std::string& rpcName, const MemoryStore& store) {
+grpc::Status memoryEmergencyStatus(grpc::ServerContext* context, const std::string& rpcName,
+                                   const MemoryStore& store) {
+    attachErrorDetail(context, {{"reason", "memory_pressure"}});
     return grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
         rpcName + " rejected: memory pressure emergency (" +
         std::to_string(store.pressurePercent()) + "% of max, threshold " +
@@ -354,10 +409,10 @@ grpc::Status DatabaseGrpcImpl::Insert(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("Insert", service_);
+        return readOnlyStatus(context, "Insert", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("Insert", store_);
+        return memoryEmergencyStatus(context, "Insert", store_);
     }
     if (view_manager_.isView(request->collection())) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -418,13 +473,13 @@ grpc::Status DatabaseGrpcImpl::Insert(
         // v2.11.0 T11 — a duplicate is the caller's mistake, not a server
         // fault. MemoryStore has already undone its own mutation by the
         // time this propagates here (see mirrorDocOrUndo).
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
         // v2.11.0 T13 — a validate_on_write rejection: the referenced
         // parent does not exist. Not a server fault either, and not
         // ALREADY_EXISTS - FAILED_PRECONDITION is the right status for "the
         // system is not in a state this write requires".
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -544,21 +599,20 @@ grpc::Status DatabaseGrpcImpl::Update(
         return st;
     }
 
+    // v2.12.0 — still in-band (status OK) so older clients see what they always
+    // saw, now with error_code and a reason in the refusal detail.
     if (service_.isReadOnly()) {
-        response->set_success(false);
-        response->set_error("database is in read-only mode: " + service_.readOnlyReason());
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
+                            "database is in read-only mode: " + service_.readOnlyReason());
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        response->set_success(false);
-        response->set_error("memory pressure emergency (" +
-            std::to_string(store_.pressurePercent()) + "%); retry after backoff");
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::RESOURCE_EXHAUSTED, "memory_pressure",
+                            "memory pressure emergency (" +
+                            std::to_string(store_.pressurePercent()) + "%); retry after backoff");
     }
     if (view_manager_.isView(request->collection())) {
-        response->set_success(false);
-        response->set_error("cannot write to view '" + request->collection() + "': views are read-only");
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::INVALID_ARGUMENT, "view_write",
+                            "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
         nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
@@ -583,16 +637,24 @@ grpc::Status DatabaseGrpcImpl::Update(
                 expiryOverrideFrom(*request)
             );
             if (!success) {
-                response->set_success(false);
-                response->set_error("Version conflict");
-                return grpc::Status::OK;
+                // v2.12.0 — updateIfVersion answers false for a missing
+                // document AND a stale version, and both used to be reported
+                // as "Version conflict". The message stays (older clients may
+                // match it); the code and detail now tell them apart.
+                auto current = store_.get(request->collection(), request->id());
+                if (!current) {
+                    return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
+                                        "not_found", "Version conflict");
+                }
+                return refuseInBand(context, response, grpc::StatusCode::ABORTED,
+                                    "version_conflict", "Version conflict",
+                                    {{"current_version", current->version}});
             }
         } else {
             success = store_.update(request->collection(), request->id(), doc);
             if (!success) {
-                response->set_success(false);
-                response->set_error("Document not found");
-                return grpc::Status::OK;
+                return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
+                                    "not_found", "Document not found");
             }
         }
 
@@ -620,10 +682,10 @@ grpc::Status DatabaseGrpcImpl::Update(
                            "Invalid JSON: " + std::string(e.what()));
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
         // v2.11.0 T13 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -640,37 +702,72 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
         return st;
     }
 
+    // v2.12.0 — still in-band (status OK) so older clients see what they always
+    // saw, now with error_code and a reason in the refusal detail.
     if (service_.isReadOnly()) {
-        response->set_success(false);
-        response->set_error("database is in read-only mode: " + service_.readOnlyReason());
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
+                            "database is in read-only mode: " + service_.readOnlyReason());
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        response->set_success(false);
-        response->set_error("memory pressure emergency (" +
-            std::to_string(store_.pressurePercent()) + "%); retry after backoff");
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::RESOURCE_EXHAUSTED, "memory_pressure",
+                            "memory pressure emergency (" +
+                            std::to_string(store_.pressurePercent()) + "%); retry after backoff");
     }
     if (view_manager_.isView(request->collection())) {
-        response->set_success(false);
-        response->set_error("cannot write to view '" + request->collection() + "': views are read-only");
-        return grpc::Status::OK;
+        return refuseInBand(context, response, grpc::StatusCode::INVALID_ARGUMENT, "view_write",
+                            "cannot write to view '" + request->collection() + "': views are read-only");
     }
     try {
-        nlohmann::json patch = smartbotic::db::parse_to_nlohmann(request->patch_json());
+        // v2.12.0 — an increment-only request may send no merge patch at all.
+        nlohmann::json patch = request->patch_json().empty()
+            ? nlohmann::json::object()
+            : smartbotic::db::parse_to_nlohmann(request->patch_json());
+
+        std::optional<nlohmann::json> increments;
+        if (!request->increments_json().empty()) {
+            increments = smartbotic::db::parse_to_nlohmann(request->increments_json());
+        }
+        std::optional<uint64_t> expectedVersion;
+        if (request->has_expected_version()) {
+            expectedVersion = request->expected_version();
+        }
 
+        nlohmann::json incremented = nlohmann::json::object();
+        MemoryStore::PatchRefusal refusal;
         uint64_t newVersion = store_.patchDocument(
             request->collection(),
             request->id(),
             patch,
             request->actor(),
-            expiryOverrideFrom(*request)
+            expiryOverrideFrom(*request),
+            expectedVersion,
+            increments ? &*increments : nullptr,
+            &incremented,
+            &refusal
         );
 
         if (newVersion == 0) {
-            response->set_success(false);
-            response->set_error("Document not found");
-            return grpc::Status::OK;
+            using Kind = MemoryStore::PatchRefusal::Kind;
+            if (refusal.kind == Kind::VersionConflict) {
+                // A real status: only a caller that SENT expected_version can
+                // get here, so no pre-2.12 client ever sees it.
+                attachErrorDetail(context, {{"reason", "version_conflict"},
+                                            {"current_version", refusal.currentVersion}});
+                return grpc::Status(grpc::StatusCode::ABORTED,
+                    "version conflict: document is at version " +
+                    std::to_string(refusal.currentVersion) + ", expected " +
+                    std::to_string(*expectedVersion));
+            }
+            if (refusal.kind == Kind::InvalidIncrement) {
+                attachErrorDetail(context, {{"reason", "invalid_increment"},
+                                            {"fields", nlohmann::json::array({refusal.field})}});
+                return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, refusal.message);
+            }
+            return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
+                                "not_found", "Document not found");
+        }
+        if (increments) {
+            response->set_incremented_json(incremented.dump());
         }
 
         // Persist vector changes (store_.patchDocument handles WAL for the document itself
@@ -692,10 +789,10 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
                            "Invalid JSON: " + std::string(e.what()));
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
         // v2.11.0 T13 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -713,10 +810,10 @@ grpc::Status DatabaseGrpcImpl::Upsert(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("Upsert", service_);
+        return readOnlyStatus(context, "Upsert", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("Upsert", store_);
+        return memoryEmergencyStatus(context, "Upsert", store_);
     }
     if (view_manager_.isView(request->collection())) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -794,10 +891,10 @@ grpc::Status DatabaseGrpcImpl::Upsert(
                            "Invalid JSON: " + std::string(e.what()));
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
         // v2.11.0 T11 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
         // v2.11.0 T13 — see the Insert handler's note.
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -827,10 +924,10 @@ grpc::Status DatabaseGrpcImpl::Delete(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("Delete", service_);
+        return readOnlyStatus(context, "Delete", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("Delete", store_);
+        return memoryEmergencyStatus(context, "Delete", store_);
     }
     if (view_manager_.isView(request->collection())) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -846,13 +943,19 @@ grpc::Status DatabaseGrpcImpl::Delete(
     // checkRelationDeleteAllowed()/performRelationCascade() so that
     // BatchDelete enforces identically instead of bypassing all of it.
     if (auto st = checkRelationDeleteAllowed(request->collection(), request->id()); !st.ok()) {
+        if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
+            attachErrorDetail(context, {{"reason", "delete_restricted"}});
+        }
         return st;
     }
     {
         bool handled = false;
         bool parentExisted = false;
         if (auto st = performRelationCascade(request->collection(), request->id(),
-                                            handled, parentExisted); !st.ok()) {
+                                            request->actor(), handled, parentExisted); !st.ok()) {
+            if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
+                attachErrorDetail(context, {{"reason", "delete_restricted"}});
+            }
             return st;
         }
         if (handled) {
@@ -871,7 +974,7 @@ grpc::Status DatabaseGrpcImpl::Delete(
         hadVector = vectors->count(request->id()) > 0;
     }
 
-    bool deleted = store_.remove(request->collection(), request->id());
+    bool deleted = store_.remove(request->collection(), request->id(), request->actor());
 
     if (deleted && hadVector) {
         persistence_.logVecDelete(request->collection(), request->id());
@@ -1093,9 +1196,9 @@ grpc::Status DatabaseGrpcImpl::RestoreVersion(
         response->set_success(true);
         return grpc::Status::OK;
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -1141,9 +1244,9 @@ grpc::Status DatabaseGrpcImpl::RestoreToDate(
         response->set_success(true);
         return grpc::Status::OK;
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -1163,10 +1266,10 @@ grpc::Status DatabaseGrpcImpl::BatchInsert(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("BatchInsert", service_);
+        return readOnlyStatus(context, "BatchInsert", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("BatchInsert", store_);
+        return memoryEmergencyStatus(context, "BatchInsert", store_);
     }
     if (view_manager_.isView(request->collection())) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -1244,10 +1347,10 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("BatchDelete", service_);
+        return readOnlyStatus(context, "BatchDelete", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("BatchDelete", store_);
+        return memoryEmergencyStatus(context, "BatchDelete", store_);
     }
     if (view_manager_.isView(request->collection())) {
         return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
@@ -1287,6 +1390,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
             }
         }
         if (blockedCount > 0) {
+            attachErrorDetail(context, {{"reason", "delete_restricted"}});
             return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
                 "batch delete refused: " + std::to_string(blockedCount) + " of " +
                 std::to_string(ids.size()) + " document(s) are protected by a relation, "
@@ -1299,6 +1403,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
     uint64_t deleted = 0;
     std::vector<std::string> plain;      // ids with no destructive relation
     plain.reserve(ids.size());
+    std::unordered_set<std::string> gone;   // v2.12.0 — for deleted_ids
     for (const auto& id : ids) {
         bool handled = false;
         bool parentExisted = false;
@@ -1308,20 +1413,31 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
         // cascade fault the WAL may already hold durable entries (see
         // performRelationCascade's INTERNAL branch), and pressing on would make
         // the reported count meaningless.
-        if (auto st = performRelationCascade(request->collection(), id,
+        if (auto st = performRelationCascade(request->collection(), id, request->actor(),
                                             handled, parentExisted); !st.ok()) {
+            if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
+                attachErrorDetail(context, {{"reason", "delete_restricted"}});
+            }
             return st;
         }
         if (handled) {
-            if (parentExisted) ++deleted;
+            if (parentExisted) { ++deleted; gone.insert(id); }
         } else {
             plain.push_back(id);
         }
     }
-    if (!plain.empty()) {
-        deleted += store_.bulkDelete(request->collection(), plain);
+    // v2.12.0 — one remove() per id rather than bulkDelete(), which is the same
+    // loop but reports only a count: the caller now learns WHICH ids existed.
+    for (const auto& id : plain) {
+        if (store_.remove(request->collection(), id, request->actor())) {
+            ++deleted;
+            gone.insert(id);
+        }
     }
     response->set_deleted_count(deleted);
+    for (const auto& id : ids) {
+        if (gone.erase(id) > 0) response->add_deleted_ids(id);   // request order, once each
+    }
     return grpc::Status::OK;
 }
 
@@ -1715,10 +1831,10 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("SetAdd", service_);
+        return readOnlyStatus(context, "SetAdd", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("SetAdd", store_);
+        return memoryEmergencyStatus(context, "SetAdd", store_);
     }
     // v2.11.0 T11 — setAdd can raise UniqueViolation if a unique field is
     // declared over this collection; without this, an uncaught exception
@@ -1728,9 +1844,9 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
         response->set_added(added);
         return grpc::Status::OK;
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -1748,10 +1864,10 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("SetRemove", service_);
+        return readOnlyStatus(context, "SetRemove", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("SetRemove", store_);
+        return memoryEmergencyStatus(context, "SetRemove", store_);
     }
     // v2.11.0 T11 — setRemove bumps _version/_updated_at, which are
     // index-declarable metadata fields, so it can raise UniqueViolation the
@@ -1761,9 +1877,9 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
         response->set_removed(removed);
         return grpc::Status::OK;
     } catch (const smartbotic::db::storage::UniqueViolation& e) {
-        return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
+        return uniqueViolationStatus(context, e);
     } catch (const smartbotic::db::storage::MissingParentReference& e) {
-        return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
+        return missingParentStatus(context, e);
     } catch (const std::exception& e) {
         return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
     }
@@ -1817,10 +1933,10 @@ grpc::Status DatabaseGrpcImpl::CreateCollection(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("CreateCollection", service_);
+        return readOnlyStatus(context, "CreateCollection", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("CreateCollection", store_);
+        return memoryEmergencyStatus(context, "CreateCollection", store_);
     }
     CollectionOptions opts;
     // Proto3 defaults bools to false, but we want autoCreateId to default to true
@@ -1857,10 +1973,10 @@ grpc::Status DatabaseGrpcImpl::DropCollection(
     }
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("DropCollection", service_);
+        return readOnlyStatus(context, "DropCollection", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("DropCollection", store_);
+        return memoryEmergencyStatus(context, "DropCollection", store_);
     }
 
     // v2.11.0 final review (finding 1, from the "audit every other RPC that can
@@ -2045,7 +2161,7 @@ grpc::Status DatabaseGrpcImpl::CreateProject(
     if (auto st = requireAnyAdmin(context, "CreateProject"); !st.ok()) return st;
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("CreateProject", service_);
+        return readOnlyStatus(context, "CreateProject", service_);
     }
     std::string error;
     bool created = service_.createProject(request->name(), error);
@@ -2065,7 +2181,7 @@ grpc::Status DatabaseGrpcImpl::DropProject(
     if (auto st = requireAnyAdmin(context, "DropProject"); !st.ok()) return st;
 
     if (service_.isReadOnly()) {
-        return readOnlyStatus("DropProject", service_);
+        return readOnlyStatus(context, "DropProject", service_);
     }
     std::string error;
     bool dropped = service_.dropProject(request->name(), error);
@@ -2091,10 +2207,10 @@ grpc::Status DatabaseGrpcImpl::UploadFile(
             std::to_string(maxFileStreams_) + " reached)");
     }
     if (service_.isReadOnly()) {
-        return readOnlyStatus("UploadFile", service_);
+        return readOnlyStatus(context, "UploadFile", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("UploadFile", store_);
+        return memoryEmergencyStatus(context, "UploadFile", store_);
     }
     pb::FileChunk chunk;
     std::vector<uint8_t> fileData;
@@ -2232,10 +2348,10 @@ grpc::Status DatabaseGrpcImpl::DeleteFile(
     pb::DeleteFileResponse* response
 ) {
     if (service_.isReadOnly()) {
-        return readOnlyStatus("DeleteFile", service_);
+        return readOnlyStatus(context, "DeleteFile", service_);
     }
     if (store_.pressure() == MemoryPressure::Emergency) {
-        return memoryEmergencyStatus("DeleteFile", store_);
+        return memoryEmergencyStatus(context, "DeleteFile", store_);
     }
     // v2.8.0 — gate the delete on the record's file type. Resolve first so we
     // know the type; report a denial as "not deleted" rather than distinguishing
@@ -2300,7 +2416,7 @@ grpc::Status DatabaseGrpcImpl::SetFileTtl(
     pb::SetFileTtlResponse* response
 ) {
     if (service_.isReadOnly()) {
-        return readOnlyStatus("SetFileTtl", service_);
+        return readOnlyStatus(context, "SetFileTtl", service_);
     }
 
     // Changing retention is a WRITE, gated on the record's own file type - which
@@ -2489,6 +2605,10 @@ grpc::Status DatabaseGrpcImpl::Subscribe(
         protoEvent.set_document_id(event.documentId);
         protoEvent.set_timestamp(event.timestamp);
         protoEvent.set_node_id(event.nodeId);
+        // v2.12.0 - sent whether or not the subscriber asked for data: it is
+        // provenance, not document content, and a loop guard needs it on
+        // every event.
+        protoEvent.set_actor(event.actor);
 
         if (includeData && event.data) {
             // Masked columns must not ride out through the event stream - that
@@ -3062,6 +3182,7 @@ grpc::Status DatabaseGrpcImpl::checkRelationDeleteAllowed(const std::string& col
 
 grpc::Status DatabaseGrpcImpl::performRelationCascade(const std::string& collection,
                                                       const std::string& id,
+                                                      const std::string& actor,
                                                       bool& handled,
                                                       bool& parentExisted) {
     handled = false;
@@ -3099,10 +3220,15 @@ grpc::Status DatabaseGrpcImpl::performRelationCascade(const std::string& collect
         // MemoryStore apply. See relation_cascade.hpp's file header for why
         // executeCascade() cannot go back through the ordinary
         // persistCallback_ path itself.
-        auto notify = [this](const std::string& coll, const std::string& docId,
-                             const std::optional<smartbotic::database::Document>& doc,
-                             smartbotic::database::EventType eventType) {
-            service_.notifyReplicationAndEvents(coll, docId, doc, eventType);
+        //
+        // v2.12.0 - every event here carries the DELETING caller's actor,
+        // explicitly. The parent is gone so there is nothing to derive it
+        // from, and a child this cascade nulled still has its previous
+        // writer in updatedBy - deriving would blame them for our delete.
+        auto notify = [this, actor](const std::string& coll, const std::string& docId,
+                                    const std::optional<smartbotic::database::Document>& doc,
+                                    smartbotic::database::EventType eventType) {
+            service_.notifyReplicationAndEvents(coll, docId, doc, eventType, actor);
         };
         try {
             parentExisted = smartbotic::database::executeCascade(
@@ -3746,6 +3872,98 @@ grpc::Status DatabaseReplicationGrpcImpl::GetNodeState(
 // error.
 // -------------------------------------------------------------------------
 
+// v2.12.0 — CreateIndex with `fields` set: a COMPOSITE unique constraint. See
+// CreateIndexRequest.fields in database.proto for the contract.
+grpc::Status DatabaseGrpcImpl::createCompositeUnique(
+    grpc::ServerContext* /*context*/,
+    const pb::CreateIndexRequest* request,
+    pb::CreateIndexResponse* response,
+    const smartbotic::database::Decision& dec) {
+    auto refuse = [&](const std::string& msg) {
+        response->set_success(false);
+        response->set_error(msg);
+        return grpc::Status::OK;
+    };
+    const std::vector<std::string> fields(request->fields().begin(), request->fields().end());
+    if (!request->field().empty()) return refuse("set either field or fields, not both");
+    if (fields.size() < 2) {
+        return refuse("a composite unique constraint needs two or more fields; "
+                      "for one field use `field` with unique=true");
+    }
+    if (!request->unique()) {
+        return refuse("a composite index is only a unique constraint - it backs no "
+                      "query - so unique must be true");
+    }
+    for (size_t i = 0; i < fields.size(); ++i) {
+        if (fields[i].empty()) return refuse("field names must not be empty");
+        for (size_t j = i + 1; j < fields.size(); ++j) {
+            if (fields[i] == fields[j]) return refuse("field '" + fields[i] + "' is listed twice");
+        }
+        if (!dec.mask.empty() &&
+            std::find(dec.mask.begin(), dec.mask.end(), fields[i]) != dec.mask.end()) {
+            return refuse("cannot constrain a masked field");
+        }
+    }
+    // Same gate and reason as a single-field unique constraint (see CreateIndex).
+    if (!service_.mirrorHealthy() || service_.mirrorDriftSinceReady() != 0) {
+        return refuse("cannot declare a unique constraint while the LMDB mirror is "
+                      "unhealthy or has drifted since startup: the duplicate check "
+                      "only consults LMDB, and MemoryStore may be ahead of it right now");
+    }
+    try {
+        const auto rc = smartbotic::database::resolveCollection(request->collection());
+        auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
+            service_.docStore(rc.project));
+        if (lmdb == nullptr) return refuse("unique constraints require the LMDB substrate");
+
+        CollectionCfg cfg = config_manager_.configFor(request->collection());
+        const bool existed = std::find(cfg.compositeUniques.begin(), cfg.compositeUniques.end(),
+                                       fields) != cfg.compositeUniques.end();
+        // ARM FIRST, then build in one write transaction (see
+        // build_composite_unique): writes from here on maintain the constraint,
+        // and the build sees every row committed before it, so nothing slips
+        // between the two.
+        auto armed = cfg.compositeUniques;
+        if (!existed) armed.push_back(fields);
+        lmdb->set_composite_uniques(rc.collection, armed);
+
+        uint64_t rows = 0;
+        auto dupes = lmdb->build_composite_unique(rc.collection, fields, rows);
+        if (!dupes.empty()) {
+            // Disarm: the constraint is refused, so it must not enforce anything.
+            lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
+            std::string msg = "cannot declare " + request->collection() + "#(" +
+                smartbotic::db::storage::composite_display_name(fields) + ") unique: " +
+                std::to_string(dupes.size()) + " duplicate value combination(s) found, e.g. ";
+            for (size_t i = 0; i < dupes.size(); ++i) {
+                if (i) msg += ", ";
+                msg += dupes[i].sample_id + " (x" + std::to_string(dupes[i].count) + ")";
+                response->add_duplicate_examples(dupes[i].sample_id);
+            }
+            return refuse(msg);
+        }
+        if (!existed) {
+            cfg.compositeUniques.push_back(fields);
+            std::string err;
+            if (!config_manager_.setConfig(request->collection(), cfg, err)) {
+                lmdb->set_composite_uniques(rc.collection, armed);   // keep enforcing what was built
+                return refuse("constraint built but could not be recorded: " + err);
+            }
+        }
+        response->set_success(true);
+        response->set_rows_indexed(rows);
+        response->set_already_existed(existed);
+        spdlog::info("v2.12 composite unique created coll={} fields=({}) rows={} (already_existed={})",
+                     request->collection(), smartbotic::db::storage::composite_display_name(fields),
+                     rows, existed);
+        return grpc::Status::OK;
+    } catch (const std::invalid_argument& e) {
+        return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
+    } catch (const std::exception& e) {
+        return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
+    }
+}
+
 grpc::Status DatabaseGrpcImpl::CreateIndex(
     grpc::ServerContext* context,
     const pb::CreateIndexRequest* request,
@@ -3763,6 +3981,9 @@ grpc::Status DatabaseGrpcImpl::CreateIndex(
         response->set_error("database is in read-only mode: " + service_.readOnlyReason());
         return grpc::Status::OK;
     }
+    if (request->fields_size() > 0) {
+        return createCompositeUnique(context, request, response, dec);
+    }
     if (request->field().empty()) {
         response->set_success(false);
         response->set_error("field is required");
@@ -3931,6 +4152,33 @@ grpc::Status DatabaseGrpcImpl::DropIndex(
             return grpc::Status::OK;
         }
 
+        // v2.12.0 — a composite unique constraint, named by its exact field list.
+        if (request->fields_size() > 0) {
+            if (!request->field().empty()) {
+                response->set_success(false);
+                response->set_error("set either field or fields, not both");
+                return grpc::Status::OK;
+            }
+            const std::vector<std::string> fields(request->fields().begin(),
+                                                  request->fields().end());
+            CollectionCfg cfg = config_manager_.configFor(request->collection());
+            auto cit = std::find(cfg.compositeUniques.begin(), cfg.compositeUniques.end(), fields);
+            if (cit != cfg.compositeUniques.end()) {
+                cfg.compositeUniques.erase(cit);
+                std::string err;
+                if (!config_manager_.setConfig(request->collection(), cfg, err)) {
+                    response->set_success(false);
+                    response->set_error(err);
+                    return grpc::Status::OK;
+                }
+            }
+            // Undeclare first, then drop - same order and reason as below.
+            lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
+            lmdb->drop_composite_unique(rc.collection, fields);
+            response->set_success(true);
+            return grpc::Status::OK;
+        }
+
         // Undeclare FIRST. While the declaration stands, writes maintain the
         // index; dropping the sub-db first would leave a window where writes
         // recreate entries in a half-dropped index.
@@ -4011,6 +4259,26 @@ grpc::Status DatabaseGrpcImpl::ListIndexes(
                 }
             }
         }
+        // v2.12.0 — composite unique constraints. Hidden when ANY of their
+        // fields is masked, for the same reason a masked field's index is.
+        for (const auto& cf : cfg.compositeUniques) {
+            bool masked = false;
+            for (const auto& f : cf) {
+                masked = masked || (!dec.mask.empty() &&
+                    std::find(dec.mask.begin(), dec.mask.end(), f) != dec.mask.end());
+            }
+            if (masked) continue;
+            auto* info = response->add_indexes();
+            info->set_field(smartbotic::db::storage::composite_display_name(cf));
+            info->set_unique(true);
+            for (const auto& f : cf) info->add_fields(f);
+            if (lmdb != nullptr) {
+                const uint64_t n = lmdb->composite_unique_entries(rc.collection, cf);
+                // Every recorded tuple is distinct by construction.
+                info->set_distinct_values(n);
+                info->set_entries(n);
+            }
+        }
         response->set_success(true);
         return grpc::Status::OK;
     } catch (const std::invalid_argument& e) {

+ 10 - 0
service/src/database_grpc_impl.hpp

@@ -496,8 +496,18 @@ private:
     // performed atomically and `parentExisted` says whether there was a
     // parent to remove. Assumes checkRelationDeleteAllowed() has already
     // permitted the delete, exactly as Delete's original ordering did.
+    //
+    // v2.12.0 - `actor` is the deleting caller's; it is reported on the event
+    // of the parent AND of every child the cascade deletes or nulls.
+    // v2.12.0 — CreateIndex's composite-unique branch.
+    grpc::Status createCompositeUnique(grpc::ServerContext* context,
+                                       const pb::CreateIndexRequest* request,
+                                       pb::CreateIndexResponse* response,
+                                       const smartbotic::database::Decision& dec);
+
     grpc::Status performRelationCascade(const std::string& collection,
                                         const std::string& id,
+                                        const std::string& actor,
                                         bool& handled,
                                         bool& parentExisted);
 

+ 40 - 5
service/src/database_service.cpp

@@ -1,6 +1,7 @@
 #include "database_service.hpp"
 #include "json_parse.hpp"
 #include "project_addressing.hpp"
+#include "storage/secondary_index.hpp"
 #include "storage/document_store.hpp"
 #include "storage/document_store_lmdb.hpp"
 #include "storage/dual_write_mirror.hpp"
@@ -495,7 +496,7 @@ bool DatabaseService::runMigrations() {
 void DatabaseService::applyIndexDeclarations() {
     size_t applied = 0;
     for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
-        if (cfg.indexedFields.empty()) continue;
+        if (cfg.indexedFields.empty() && cfg.compositeUniques.empty()) continue;
         try {
             const auto rc = resolveCollection(qualified);
             auto* ds = docStore(rc.project);
@@ -511,6 +512,30 @@ void DatabaseService::applyIndexDeclarations() {
             // call would silently stop enforcing a constraint every write
             // handler still advertises as active.
             lmdb->set_unique_fields(rc.collection, cfg.uniqueFields);
+            // v2.12.0 — composite constraints, armed the same way and for the
+            // same reason: skipping this would stop enforcing a constraint the
+            // record still declares. Self-healed below if its sub-db is gone.
+            lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
+            for (const auto& cf : cfg.compositeUniques) {
+                if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
+                uint64_t rows = 0;
+                auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
+                if (dupes.empty()) {
+                    spdlog::warn("v2.12 composite unique: rebuilt {}#({}) over {} row(s) - "
+                                 "declared but its sub-db was absent",
+                                 qualified, smartbotic::db::storage::composite_display_name(cf), rows);
+                } else {
+                    // Cannot happen through the API (declaring over duplicates is
+                    // refused). If it does, say so loudly: the constraint stays
+                    // declared and armed, but rows already violating it exist.
+                    spdlog::error("v2.12 composite unique: {}#({}) is declared but {} "
+                                  "existing value combination(s) violate it (e.g. document "
+                                  "'{}'); its index could not be rebuilt. Writes that would "
+                                  "add another duplicate are still refused.",
+                                  qualified, smartbotic::db::storage::composite_display_name(cf),
+                                  dupes.size(), dupes.front().sample_id);
+                }
+            }
             ++applied;
             spdlog::info("v2.9 index: {} field(s) active on {} ({} unique)",
                          cfg.indexedFields.size(), qualified, cfg.uniqueFields.size());
@@ -570,9 +595,12 @@ MemoryStore::TtlExpiryAction DatabaseService::ttlExpiryRelationDecision(
         // TTL-driven cascade would be invisible to followers and subscribers,
         // and a follower that never saw the child deletions diverges
         // permanently (the v2.3.1 class of bug).
+        // v2.12.0 - an expiry has no caller, so every event this cascade
+        // produces carries an explicitly EMPTY actor. Letting it default
+        // would report a nulled child's previous writer as the cause.
         auto notify = [this](const std::string& coll, const std::string& docId,
                              const std::optional<Document>& doc, EventType eventType) {
-            notifyReplicationAndEvents(coll, docId, doc, eventType);
+            notifyReplicationAndEvents(coll, docId, doc, eventType, std::string{});
         };
 
         // firstAttempt -> the refusal (if any) is logged at WARN; a retry of an
@@ -1401,7 +1429,8 @@ void DatabaseService::setupComponents() {
 
     // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
     store_->setPersistCallback([this](const std::string& collection, const std::string& id,
-                                       const std::optional<Document>& doc, EventType eventType) {
+                                       const std::optional<Document>& doc, EventType eventType,
+                                       const std::optional<std::string>& actor) {
         // Log to WAL based on event type. v1.7.4: capture the assigned WAL
         // sequence and record it on the store so eviction stubs can carry
         // a real seq (instead of doc.version, which was useless as a
@@ -1432,7 +1461,7 @@ void DatabaseService::setupComponents() {
         // v2.11.0 T12 review (C2) — replication + events extracted into
         // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
         // drive them explicitly too. See that method's doc comment.
-        notifyReplicationAndEvents(collection, id, doc, eventType);
+        notifyReplicationAndEvents(collection, id, doc, eventType, actor);
     });
 
     // Set up document load callback for LRU eviction recovery.
@@ -1513,7 +1542,8 @@ void DatabaseService::setupComponents() {
 void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
                                                   const std::string& id,
                                                   const std::optional<Document>& doc,
-                                                  EventType eventType) {
+                                                  EventType eventType,
+                                                  const std::optional<std::string>& actor) {
     // Queue for replication broadcast
     if (replication_ && config_.replicationEnabled) {
         databasepb::ReplicationEntry entry;
@@ -1562,6 +1592,11 @@ void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
             std::chrono::system_clock::now().time_since_epoch()
         ).count();
         event.nodeId = config_.nodeId;
+        if (actor) {
+            event.actor = *actor;
+        } else if (doc) {
+            event.actor = doc->updatedBy;
+        }
         if (doc) {
             event.data = doc->data();
         }

+ 8 - 1
service/src/database_service.hpp

@@ -329,10 +329,17 @@ public:
     // caller's job, done separately, and calling this a second time for
     // the same mutation would double-queue replication and double-publish
     // the event, so callers must call it exactly once per mutation.
+    //
+    // v2.12.0 - `actor` fills DatabaseEvent::actor. std::nullopt takes it
+    // from doc->updatedBy, which every insert/update stamps from its request;
+    // a value is used as given. Cascade callers MUST pass one: a child the
+    // cascade nulled still carries its previous writer in updatedBy, and the
+    // event has to name the caller whose delete caused it.
     void notifyReplicationAndEvents(const std::string& collection,
                                     const std::string& id,
                                     const std::optional<Document>& doc,
-                                    EventType eventType);
+                                    EventType eventType,
+                                    const std::optional<std::string>& actor = std::nullopt);
 
     // v2.3 Stage F — project CRUD entry points (delegate to registry).
     // The registry is the source of truth for listing / creating / dropping.

+ 4 - 0
service/src/document.hpp

@@ -448,6 +448,7 @@ struct DatabaseEvent {
     uint64_t timestamp = 0;
     std::string nodeId;
     std::optional<nlohmann::json> data;  // Document data (if included)
+    std::string actor;                   // v2.12.0 - who caused it; see DatabaseEvent.actor in the proto
 
     [[nodiscard]] nlohmann::json toJson() const {
         nlohmann::json j;
@@ -456,6 +457,9 @@ struct DatabaseEvent {
         j["documentId"] = documentId;
         j["timestamp"] = timestamp;
         j["nodeId"] = nodeId;
+        if (!actor.empty()) {
+            j["actor"] = actor;
+        }
         if (data) {
             j["data"] = *data;
         }

+ 183 - 15
service/src/memory_store.cpp

@@ -845,7 +845,8 @@ std::string MemoryStore::upsert(const std::string& collection, Document doc) {
     return docId;
 }
 
-bool MemoryStore::remove(const std::string& collection, const std::string& id) {
+bool MemoryStore::remove(const std::string& collection, const std::string& id,
+                         const std::string& actor) {
     CollectionData* coll = getOrCreateCollection(collection);
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
@@ -888,7 +889,7 @@ bool MemoryStore::remove(const std::string& collection, const std::string& id) {
     estimatedMemoryBytes_.fetch_sub(docSize, std::memory_order_relaxed);
 
     // Emit callbacks
-    emitPersist(collection, id, std::nullopt, EventType::DELETE);
+    emitPersist(collection, id, std::nullopt, EventType::DELETE, actor);
     emitEvent(EventType::DELETE, collection, id);
 
     return true;
@@ -1348,9 +1349,141 @@ bool MemoryStore::updateIfVersion(const std::string& collection, const std::stri
     return true;
 }
 
+namespace {
+
+// v2.12.0 — fields that live on the Document, not in its data. Incrementing
+// one would create a same-named user field instead, which is never meant.
+bool isMetadataPath(const std::string& first) {
+    return first == "_id" || first == "_version" || first == "_created_at" ||
+           first == "_updated_at" || first == "_created_by" || first == "_updated_by";
+}
+
+std::vector<std::string> splitPath(const std::string& path) {
+    std::vector<std::string> out;
+    std::string cur;
+    for (char c : path) {
+        if (c == '.') { out.push_back(cur); cur.clear(); } else { cur.push_back(c); }
+    }
+    out.push_back(cur);
+    return out;
+}
+
+// Does the merge patch itself set `segs` (or replace something above it with a
+// non-object)? Incrementing a field the same request also sets has no single
+// meaning, so it is refused rather than silently ordered.
+bool patchTouches(const nlohmann::json& patch, const std::vector<std::string>& segs) {
+    const nlohmann::json* node = &patch;
+    for (size_t i = 0; i < segs.size(); ++i) {
+        if (!node->is_object()) return false;
+        auto it = node->find(segs[i]);
+        if (it == node->end()) return false;
+        if (i + 1 == segs.size() || !it->is_object()) return true;
+        node = &*it;
+    }
+    return false;
+}
+
+// Apply `increments` to `data` in place. On refusal returns false with the
+// offending path and a message, having possibly half-modified `data` - the
+// caller works on a copy and discards it.
+bool applyIncrements(nlohmann::json& data, const nlohmann::json& patch,
+                     const nlohmann::json& increments, nlohmann::json& newValues,
+                     std::string& errField, std::string& errMsg) {
+    if (!increments.is_object()) {
+        errMsg = "increments must be a JSON object of field -> number";
+        return false;
+    }
+    if (!data.is_object()) data = nlohmann::json::object();
+    for (const auto& [path, delta] : increments.items()) {
+        errField = path;
+        const auto segs = splitPath(path);
+        bool emptySeg = false;
+        for (const auto& s : segs) emptySeg = emptySeg || s.empty();
+        if (path.empty() || emptySeg) {
+            errMsg = "increment path '" + path + "' is empty or has an empty segment";
+            return false;
+        }
+        if (isMetadataPath(segs.front())) {
+            errMsg = "cannot increment '" + path + "': it is document metadata";
+            return false;
+        }
+        if (!delta.is_number()) {
+            errMsg = "increment for '" + path + "' is not a number";
+            return false;
+        }
+        if (patchTouches(patch, segs)) {
+            errMsg = "'" + path + "' is both set by the patch and incremented";
+            return false;
+        }
+        nlohmann::json* node = &data;
+        for (size_t i = 0; i + 1 < segs.size(); ++i) {
+            nlohmann::json& next = (*node)[segs[i]];
+            if (next.is_null()) next = nlohmann::json::object();
+            if (!next.is_object()) {
+                errMsg = "cannot increment '" + path + "': '" + segs[i] +
+                         "' holds a " + std::string(next.type_name()) + ", not an object";
+                return false;
+            }
+            node = &next;
+        }
+        nlohmann::json& target = (*node)[segs.back()];
+        if (!target.is_null() && !target.is_number()) {
+            errMsg = "cannot increment '" + path + "': it holds a " +
+                     std::string(target.type_name()) + ", not a number";
+            return false;
+        }
+        const bool curInt = target.is_null() || target.is_number_integer();
+        const bool deltaInt = delta.is_number_integer();
+        if (curInt && deltaInt) {
+            // number_integer covers number_unsigned too; anything above
+            // INT64_MAX cannot be represented and is refused as overflow.
+            auto asI64 = [](const nlohmann::json& j, int64_t& out) {
+                if (j.is_null()) { out = 0; return true; }
+                if (j.is_number_unsigned()) {
+                    const auto u = j.get<uint64_t>();
+                    if (u > static_cast<uint64_t>(INT64_MAX)) return false;
+                    out = static_cast<int64_t>(u);
+                    return true;
+                }
+                out = j.get<int64_t>();
+                return true;
+            };
+            int64_t a = 0, b = 0, sum = 0;
+            if (!asI64(target, a) || !asI64(delta, b) || __builtin_add_overflow(a, b, &sum)) {
+                errMsg = "incrementing '" + path + "' overflows a 64-bit integer";
+                return false;
+            }
+            target = sum;
+        } else {
+            const double sum = (target.is_null() ? 0.0 : target.get<double>()) + delta.get<double>();
+            if (!std::isfinite(sum)) {
+                errMsg = "incrementing '" + path + "' does not give a finite number";
+                return false;
+            }
+            target = sum;
+        }
+        newValues[path] = target;
+    }
+    errField.clear();
+    return true;
+}
+
+}  // namespace
+
 uint64_t MemoryStore::patchDocument(const std::string& collection, const std::string& id,
                                      const nlohmann::json& patch, const std::string& actor,
                                      std::optional<uint64_t> expiryOverride) {
+    return patchDocument(collection, id, patch, actor, expiryOverride,
+                         std::nullopt, nullptr, nullptr, nullptr);
+}
+
+uint64_t MemoryStore::patchDocument(const std::string& collection, const std::string& id,
+                                     const nlohmann::json& patch, const std::string& actor,
+                                     std::optional<uint64_t> expiryOverride,
+                                     std::optional<uint64_t> expectedVersion,
+                                     const nlohmann::json* increments,
+                                     nlohmann::json* incrementedOut,
+                                     PatchRefusal* refusal) {
     CollectionData* coll = getOrCreateCollection(collection);
 
     // v1.7.0 T6 quiesce: mark before taking the write lock.
@@ -1360,9 +1493,39 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
 
     auto it = coll->documents.find(id);
     if (it == coll->documents.end()) {
+        if (refusal) refusal->kind = PatchRefusal::Kind::NotFound;
         return 0;
     }
 
+    // v2.12.0 — the version condition, under the same lock the write takes,
+    // so nothing can change the document between the check and the write.
+    if (expectedVersion.has_value() && it->second.version != *expectedVersion) {
+        if (refusal) {
+            refusal->kind = PatchRefusal::Kind::VersionConflict;
+            refusal->currentVersion = it->second.version;
+        }
+        return 0;
+    }
+
+    // v2.12.0 — compute the merged body (and apply any increments to it)
+    // BEFORE touching the stored document, its expiry index or its history:
+    // a refused increment must leave no trace.
+    nlohmann::json merged = it->second.data();
+    merged.merge_patch(patch);
+    if (increments != nullptr) {
+        nlohmann::json newValues = nlohmann::json::object();
+        std::string errField, errMsg;
+        if (!applyIncrements(merged, patch, *increments, newValues, errField, errMsg)) {
+            if (refusal) {
+                refusal->kind = PatchRefusal::Kind::InvalidIncrement;
+                refusal->field = errField;
+                refusal->message = errMsg;
+            }
+            return 0;
+        }
+        if (incrementedOut) *incrementedOut = std::move(newValues);
+    }
+
     // Track memory change (old size)
     uint64_t oldSize = estimateDocumentSize(it->second);
 
@@ -1387,13 +1550,9 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
     // Save current state to history
     saveToHistory(*coll, it->second);
 
-    // Merge patch into existing data (RFC 7396 merge patch). Materialise
-    // once, merge, then re-encode. Avoids per-field re-encode.
-    {
-        auto merged = it->second.data();
-        merged.merge_patch(patch);
-        it->second.set_data(merged);
-    }
+    // Merge patch into existing data (RFC 7396 merge patch). Computed above,
+    // before anything was mutated (v2.12.0), together with any increments.
+    it->second.set_data(merged);
 
     // Handle vector field if present in patch
     auto vec = extractVector(*coll, it->second);
@@ -1485,7 +1644,12 @@ uint64_t MemoryStore::patchDocument(const std::string& collection, const std::st
     }
 
     // Emit callbacks (WAL persistence + event notification)
-    emitPersist(collection, id, updatedDoc, EventType::UPDATE);
+    // v2.12.0 - the actor is passed EXPLICITLY, not left to be read from the
+    // document: a patch with no actor keeps the previous updatedBy (above),
+    // so deriving it would report whoever wrote last as the author of this
+    // patch. For a subscriber's loop guard that misattribution makes an
+    // ordinary client patch look like a function's write.
+    emitPersist(collection, id, updatedDoc, EventType::UPDATE, actor);
     emitEvent(EventType::UPDATE, collection, id, std::optional<nlohmann::json>(updatedDoc.data()));
 
     return newVersion;
@@ -1961,10 +2125,11 @@ std::vector<std::string> MemoryStore::bulkInsert(const std::string& collection,
     return ids;
 }
 
-uint64_t MemoryStore::bulkDelete(const std::string& collection, const std::vector<std::string>& ids) {
+uint64_t MemoryStore::bulkDelete(const std::string& collection, const std::vector<std::string>& ids,
+                                 const std::string& actor) {
     uint64_t deleted = 0;
     for (const auto& id : ids) {
-        if (remove(collection, id)) {
+        if (remove(collection, id, actor)) {
             deleted++;
         }
     }
@@ -2516,7 +2681,9 @@ uint64_t MemoryStore::expireDocuments() {
         }
         estimatedMemoryBytes_.fetch_sub(docSize, std::memory_order_relaxed);
 
-        emitPersist(cand.collection, cand.id, std::nullopt, EventType::EXPIRE);
+        // No caller: the database expired it. Explicitly empty, so nothing
+        // tries to recover an actor from a document that no longer exists.
+        emitPersist(cand.collection, cand.id, std::nullopt, EventType::EXPIRE, std::string{});
         emitEvent(EventType::EXPIRE, cand.collection, cand.id);
     }
 
@@ -3261,10 +3428,11 @@ void MemoryStore::emitEvictionBurst(uint64_t docs, uint64_t bytesFreed) {
 }
 
 void MemoryStore::emitPersist(const std::string& collection, const std::string& id,
-                              const std::optional<Document>& doc, EventType eventType) {
+                              const std::optional<Document>& doc, EventType eventType,
+                              const std::optional<std::string>& actor) {
     std::lock_guard<std::mutex> lock(callbackMutex_);
     if (persistCallback_) {
-        persistCallback_(collection, id, doc, eventType);
+        persistCallback_(collection, id, doc, eventType, actor);
     }
 }
 

+ 45 - 4
service/src/memory_store.hpp

@@ -54,10 +54,17 @@ using EventCallback = std::function<void(const DatabaseEvent&)>;
 /**
  * Callback for WAL/persistence operations.
  */
+//
+// v2.12.0 - `actor` says who caused the change, for the DatabaseEvent a
+// subscriber sees. std::nullopt means "take it from the document" (an insert
+// or update stamps doc.updatedBy with the request's actor on every write);
+// a value - even empty - is used as given. A delete has no document left to
+// read, and a TTL expiry has no caller, so those always pass a value.
 using PersistCallback = std::function<void(const std::string& collection,
                                            const std::string& id,
                                            const std::optional<Document>& doc,
-                                           EventType eventType)>;
+                                           EventType eventType,
+                                           const std::optional<std::string>& actor)>;
 
 /**
  * In-memory storage engine with collection-based document storage.
@@ -385,9 +392,12 @@ public:
 
     /**
      * Delete a document.
+     * @param actor who is deleting (v2.12.0); reported on the DELETE event.
+     *   Empty is a real value - "no actor given" - not "derive it".
      * @return true if deleted, false if not found
      */
-    bool remove(const std::string& collection, const std::string& id);
+    bool remove(const std::string& collection, const std::string& id,
+                const std::string& actor = {});
 
     /**
      * v2.11.0 T12 — memory-only counterpart to loadDocument()/
@@ -600,6 +610,35 @@ public:
                            const nlohmann::json& patch, const std::string& actor = "",
                            std::optional<uint64_t> expiryOverride = std::nullopt);
 
+    // v2.12.0 — why patchDocument() below returned 0.
+    struct PatchRefusal {
+        enum class Kind { None, NotFound, VersionConflict, InvalidIncrement };
+        Kind kind = Kind::None;
+        uint64_t currentVersion = 0;   // VersionConflict: the stored version
+        std::string field;             // InvalidIncrement: the offending path
+        std::string message;
+    };
+
+    /**
+     * v2.12.0 — patch with a version condition and atomic increments. Both are
+     * decided under the collection lock BEFORE anything is mutated, so a
+     * refusal leaves the document, its history and its expiry untouched.
+     *
+     * @param expectedVersion apply only if the stored version equals it
+     * @param increments      object of dotted path -> number to add, applied
+     *                        after the merge (see PatchDocumentRequest in
+     *                        database.proto for the rules)
+     * @param incrementedOut  receives path -> value after the increment
+     * @return new version, or 0 with `refusal` saying why
+     */
+    uint64_t patchDocument(const std::string& collection, const std::string& id,
+                           const nlohmann::json& patch, const std::string& actor,
+                           std::optional<uint64_t> expiryOverride,
+                           std::optional<uint64_t> expectedVersion,
+                           const nlohmann::json* increments,
+                           nlohmann::json* incrementedOut,
+                           PatchRefusal* refusal);
+
     /**
      * Directly update a document's createdAt / updatedAt metadata fields
      * without triggering re-stamping or version-bumping. Metadata-only mutation,
@@ -662,7 +701,8 @@ public:
      * Delete multiple documents by ID.
      * @return Number of documents deleted
      */
-    uint64_t bulkDelete(const std::string& collection, const std::vector<std::string>& ids);
+    uint64_t bulkDelete(const std::string& collection, const std::vector<std::string>& ids,
+                        const std::string& actor = {});
 
     // ===== Vector Similarity Search =====
 
@@ -1168,7 +1208,8 @@ private:
 
     // Emit a persist callback
     void emitPersist(const std::string& collection, const std::string& id,
-                     const std::optional<Document>& doc, EventType eventType);
+                     const std::optional<Document>& doc, EventType eventType,
+                     const std::optional<std::string>& actor = std::nullopt);
 
     // v2.0 Stage 4 — mirror a write into the LMDB DocumentStore. Called
     // from within the per-collection write lock, BEFORE lock release, so

+ 243 - 8
service/src/storage/document_store_lmdb.cpp

@@ -571,7 +571,10 @@ void LmdbDocumentStore::put(WriteTxn& wtxn,
     // throws after this point rolls the index back with the document. An
     // asynchronously-maintained index would let a query read entries for a row
     // that was never stored, and return silently wrong rows rather than an error.
-    const bool needs_index = !indexed_fields(collection).empty();
+    // v2.12.0 - a collection with only a composite unique constraint has no
+    // indexed field but still needs maintainIndexes().
+    const bool needs_index = !indexed_fields(collection).empty() ||
+                             !composite_uniques(collection).empty();
     const bool needs_relations = !relations(collection).empty();
     if (needs_index || needs_relations) {
         MDB_val old{0, nullptr};
@@ -625,7 +628,8 @@ void LmdbDocumentStore::maintainIndexes(
     std::vector<std::pair<std::string, unsigned int>>& to_cache) {
 
     const auto fields = indexed_fields(collection);
-    if (fields.empty()) return;   // unindexed collections pay nothing
+    const auto composites = composite_uniques(collection);
+    if (fields.empty() && composites.empty()) return;   // unindexed collections pay nothing
     const auto uniques = unique_fields(collection);
 
     // Old keys come from the STORED bytes, parsed with yyjson and resolved one
@@ -637,6 +641,8 @@ void LmdbDocumentStore::maintainIndexes(
     // difference - remove the keys the row no longer owns, add the ones it gained,
     // leave the rest untouched.
     std::unordered_map<std::string, std::vector<std::string>> old_keys;
+    // v2.12.0 - the tuple key each composite constraint held for the OLD row.
+    std::vector<std::optional<std::string>> old_tuples(composites.size());
     if (!old_payload.empty()) {
         yyjson_doc* d = yyjson_read(old_payload.data(), old_payload.size(), 0);
         if (d) {
@@ -645,6 +651,11 @@ void LmdbDocumentStore::maintainIndexes(
                 auto v = resolve_from_yyjson(root, f);
                 if (v) old_keys[f] = encode_index_keys(*v);
             }
+            for (size_t i = 0; i < composites.size(); ++i) {
+                std::vector<std::optional<nlohmann::json>> vals;
+                for (const auto& f : composites[i]) vals.push_back(resolve_from_yyjson(root, f));
+                old_tuples[i] = encode_composite_unique_key(vals);
+            }
             yyjson_doc_free(d);
         }
     }
@@ -652,6 +663,7 @@ void LmdbDocumentStore::maintainIndexes(
     for (const auto& f : fields) {
         std::vector<std::string> new_k;
         bool new_is_array = false;
+        nlohmann::json new_value;   // v2.12.0 - reported if the unique check refuses it
         if (new_doc != nullptr) {
             // resolveFilterValue is the SAME resolver the scan uses, so an
             // indexed lookup and a scan cannot disagree about which field a
@@ -659,6 +671,7 @@ void LmdbDocumentStore::maintainIndexes(
             if (auto v = filter_eval::resolveFilterValue(*new_doc, f)) {
                 new_k = encode_index_keys(*v);
                 new_is_array = v->is_array();
+                new_value = *v;
             }
         }
         std::vector<std::string> old_k;
@@ -700,6 +713,9 @@ void LmdbDocumentStore::maintainIndexes(
         // rejection must leave neither the row nor an index entry behind.
         if (std::find(uniques.begin(), uniques.end(), f) != uniques.end()) {
             for (const auto& key : to_add) {
+                // v2.12.0 - null is not a value for uniqueness (SQL): any number
+                // of rows may hold it. It is still indexed, for EQ null.
+                if (is_null_index_key(key)) continue;
                 MDB_cursor* cur = nullptr;
                 mdb_check(mdb_cursor_open(wtxn.raw(), dbi, &cur),
                           "cursor_open (unique check)");
@@ -713,7 +729,7 @@ void LmdbDocumentStore::maintainIndexes(
                     // rewritten with the value it already had.
                     if (holder != id) {
                         throw UniqueViolation(std::string(collection), f,
-                                              std::string(holder));
+                                              std::string(holder), new_value);
                     }
                     crc = mdb_cursor_get(cur, &ck, &cv, MDB_NEXT_DUP);
                 }
@@ -732,6 +748,58 @@ void LmdbDocumentStore::maintainIndexes(
             if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw_mdb(rc, "index put");
         }
     }
+
+    // v2.12.0 - COMPOSITE unique constraints. Same transaction, same rule as a
+    // single unique field: the check runs before anything for this constraint
+    // is written, and a refusal throws, which aborts the whole transaction -
+    // document, postings and every other constraint's entries with it.
+    for (size_t i = 0; i < composites.size(); ++i) {
+        const auto& cfields = composites[i];
+        std::optional<std::string> new_tuple;
+        std::vector<std::optional<nlohmann::json>> new_vals;
+        if (new_doc != nullptr) {
+            for (const auto& f : cfields) {
+                new_vals.push_back(filter_eval::resolveFilterValue(*new_doc, f));
+            }
+            new_tuple = encode_composite_unique_key(new_vals);
+        }
+        const auto& old_tuple = old_tuples[i];
+        if (old_tuple == new_tuple) continue;   // unchanged, or not constrained either way
+
+        const std::string sub = composite_unique_subdb_name(collection, cfields);
+        const unsigned int dbi = open_for_write(wtxn, sub, 0);
+        to_cache.emplace_back(sub, dbi);
+
+        if (new_tuple) {
+            MDB_val k = to_val(*new_tuple);
+            MDB_val held{0, nullptr};
+            const int grc = mdb_get(wtxn.raw(), dbi, &k, &held);
+            if (grc == MDB_SUCCESS && to_sv(held) != id) {
+                nlohmann::json values = nlohmann::json::object();
+                for (size_t c = 0; c < cfields.size(); ++c) {
+                    values[cfields[c]] = new_vals[c] ? *new_vals[c] : nlohmann::json();
+                }
+                throw UniqueViolation(std::string(collection), cfields,
+                                      std::string(to_sv(held)), std::move(values));
+            }
+            if (grc != MDB_SUCCESS && grc != MDB_NOTFOUND) throw_mdb(grc, "get (composite unique)");
+        }
+        if (old_tuple) {
+            // Only remove the entry if it is still THIS row's - never someone
+            // else's under the same tuple.
+            MDB_val k = to_val(*old_tuple);
+            MDB_val held{0, nullptr};
+            if (mdb_get(wtxn.raw(), dbi, &k, &held) == MDB_SUCCESS && to_sv(held) == id) {
+                const int drc = mdb_del(wtxn.raw(), dbi, &k, nullptr);
+                if (drc != MDB_SUCCESS && drc != MDB_NOTFOUND) throw_mdb(drc, "del (composite unique)");
+            }
+        }
+        if (new_tuple) {
+            MDB_val k = to_val(*new_tuple);
+            MDB_val v = to_val(id);
+            mdb_check(mdb_put(wtxn.raw(), dbi, &k, &v, 0), "put (composite unique)");
+        }
+    }
 }
 
 // -------------------------------------------------------------------------
@@ -772,7 +840,10 @@ bool LmdbDocumentStore::can_reject_writes(std::string_view collection) {
     const std::string key(collection);
     {
         std::lock_guard<std::mutex> lock(index_mutex_);
-        if (unique_fields_.contains(key)) return true;
+        // v2.12.0 - a composite constraint rejects writes too. Missing it here
+        // would skip MemoryStore's undo snapshot, so a refused write would stay
+        // applied in memory while LMDB rolled it back.
+        if (unique_fields_.contains(key) || composite_uniques_.contains(key)) return true;
     }
     {
         std::lock_guard<std::mutex> lock(relations_mutex_);
@@ -1630,7 +1701,10 @@ bool LmdbDocumentStore::del(WriteTxn& wtxn,
 
     // Remove index entries before the row goes, while its stored bytes are
     // still readable - they are the only record of which index keys it owns.
-    const bool needs_index = !indexed_fields(collection).empty();
+    // v2.12.0 - a collection with only a composite unique constraint has no
+    // indexed field but still needs maintainIndexes().
+    const bool needs_index = !indexed_fields(collection).empty() ||
+                             !composite_uniques(collection).empty();
     const bool needs_relations = !relations(collection).empty();
     if (needs_index || needs_relations) {
         MDB_val old{0, nullptr};
@@ -1720,8 +1794,36 @@ void LmdbDocumentStore::set_unique_fields(std::string_view collection,
     // counter can never disagree with it. Recomputed rather than incremented:
     // this setter is idempotent-by-replacement, so a blind ++ would double
     // count a re-declaration.
-    rejecting_unique_collections_.store(unique_fields_.size(),
-                                       std::memory_order_relaxed);
+    recount_rejecting_uniques_locked();
+}
+
+void LmdbDocumentStore::recount_rejecting_uniques_locked() {
+    // Collections with ANY rejecting unique constraint - single or composite -
+    // counted once each.
+    size_t n = unique_fields_.size();
+    for (const auto& [coll, cs] : composite_uniques_) {
+        if (!unique_fields_.contains(coll)) ++n;
+    }
+    rejecting_unique_collections_.store(n, std::memory_order_relaxed);
+}
+
+void LmdbDocumentStore::set_composite_uniques(
+    std::string_view collection, std::vector<std::vector<std::string>> constraints) {
+    std::lock_guard<std::mutex> lock(index_mutex_);
+    if (constraints.empty()) {
+        composite_uniques_.erase(std::string(collection));
+    } else {
+        composite_uniques_[std::string(collection)] = std::move(constraints);
+    }
+    recount_rejecting_uniques_locked();
+}
+
+std::vector<std::vector<std::string>>
+LmdbDocumentStore::composite_uniques(std::string_view collection) {
+    std::lock_guard<std::mutex> lock(index_mutex_);
+    auto it = composite_uniques_.find(std::string(collection));
+    if (it == composite_uniques_.end()) return {};
+    return it->second;
 }
 
 std::vector<std::string>
@@ -1749,7 +1851,9 @@ LmdbDocumentStore::find_duplicate_values(std::string_view collection,
     MDB_val v{0, nullptr};
     int rc = mdb_cursor_get(cur, &k, &v, MDB_FIRST);
     while (rc == MDB_SUCCESS && out.size() < limit) {
-        if (!is_index_meta_key(to_sv(k))) {
+        // v2.12.0 - null is not a value for uniqueness, so rows sharing null
+        // never block declaring the constraint.
+        if (!is_index_meta_key(to_sv(k)) && !is_null_index_key(to_sv(k))) {
             size_t n = 0;
             mdb_check(mdb_cursor_count(cur, &n), "cursor_count (dupes)");
             if (n > 1) {
@@ -1765,6 +1869,137 @@ LmdbDocumentStore::find_duplicate_values(std::string_view collection,
     return out;
 }
 
+std::vector<LmdbDocumentStore::DuplicateValue>
+LmdbDocumentStore::build_composite_unique(std::string_view collection,
+                                          const std::vector<std::string>& fields,
+                                          uint64_t& rowsOut,
+                                          size_t limit) {
+    rowsOut = 0;
+    bool collectionExists = false;
+    {
+        ReadTxn rtxn(env_);
+        collectionExists = try_open_for_read(rtxn, collection).has_value();
+    }
+
+    const std::string sub = composite_unique_subdb_name(collection, fields);
+    // tuple -> {first holder, how many hold it}; only populated for duplicates.
+    std::unordered_map<std::string, std::pair<std::string, uint64_t>> dupes;
+    std::vector<std::string> dupe_order;
+    std::vector<std::pair<std::string, unsigned int>> to_cache;
+
+    // ONE write transaction for the scan AND the build. LMDB admits one writer
+    // at a time, so no document can change between reading the rows and
+    // recording their tuples - a separate read pass would let a write landing
+    // in between be wiped by the rebuild. The caller arms the constraint
+    // BEFORE calling this, so writes after this transaction maintain it.
+    WriteTxn wtxn(env_);
+    const unsigned int dbi = open_for_write(wtxn, sub, 0);
+    to_cache.emplace_back(sub, dbi);
+    // From scratch: a rebuild must not keep entries for rows that changed.
+    // mdb_drop(dbi, 0) empties it - sentinel included - so put that back.
+    mdb_check(mdb_drop(wtxn.raw(), dbi, 0), "mdb_drop (composite rebuild)");
+    write_subdb_identity(wtxn, dbi, sub);
+
+    if (collectionExists) {
+        const unsigned int cdbi = open_for_write(wtxn, collection, 0);
+        to_cache.emplace_back(std::string(collection), cdbi);
+        MDB_cursor* cur = nullptr;
+        mdb_check(mdb_cursor_open(wtxn.raw(), cdbi, &cur), "cursor_open (composite build)");
+        struct G { MDB_cursor* c; ~G() { if (c) mdb_cursor_close(c); } } g{cur};
+        MDB_val ck{0, nullptr};
+        MDB_val cv{0, nullptr};
+        int crc = mdb_cursor_get(cur, &ck, &cv, MDB_FIRST);
+        while (crc == MDB_SUCCESS) {
+            const std::string_view id = to_sv(ck);
+            if (!is_identity_key(id)) {
+                const std::string_view payload = to_sv(cv);
+                yyjson_doc* d = yyjson_read(payload.data(), payload.size(), 0);
+                if (d) {
+                    std::vector<std::optional<nlohmann::json>> vals;
+                    yyjson_val* root = yyjson_doc_get_root(d);
+                    for (const auto& f : fields) vals.push_back(resolve_from_yyjson(root, f));
+                    yyjson_doc_free(d);
+                    if (const auto tuple = encode_composite_unique_key(vals)) {
+                        MDB_val kk = to_val(*tuple);
+                        MDB_val vv = to_val(id);
+                        const int rc = mdb_put(wtxn.raw(), dbi, &kk, &vv, MDB_NOOVERWRITE);
+                        if (rc == MDB_KEYEXIST) {
+                            // MDB_NOOVERWRITE hands back the holder in vv.
+                            auto it = dupes.find(*tuple);
+                            if (it == dupes.end()) {
+                                dupes.emplace(*tuple, std::make_pair(std::string(to_sv(vv)), uint64_t{2}));
+                                dupe_order.push_back(*tuple);
+                            } else {
+                                ++it->second.second;
+                            }
+                        } else if (rc != MDB_SUCCESS) {
+                            throw_mdb(rc, "composite build put");
+                        } else {
+                            ++rowsOut;
+                        }
+                    }
+                }
+            }
+            crc = mdb_cursor_get(cur, &ck, &cv, MDB_NEXT);
+        }
+        if (crc != MDB_SUCCESS && crc != MDB_NOTFOUND) throw_mdb(crc, "cursor (composite build)");
+    }
+
+    std::vector<DuplicateValue> out;
+    if (!dupes.empty()) {
+        // Refused: commit nothing. The WriteTxn aborts on destruction and,
+        // because nothing was cached, no closed handle is left behind (v2.8.0).
+        for (const auto& t : dupe_order) {
+            if (out.size() >= limit) break;
+            DuplicateValue d;
+            d.sample_id = dupes[t].first;
+            d.count = dupes[t].second;
+            out.push_back(std::move(d));
+        }
+        return out;
+    }
+    wtxn.commit();
+    for (const auto& [name, h] : to_cache) cacheCommittedDbi(name, h);
+    return out;
+}
+
+uint64_t LmdbDocumentStore::composite_unique_entries(std::string_view collection,
+                                                     const std::vector<std::string>& fields) {
+    ReadTxn rtxn(env_);
+    auto dbi_opt = try_open_for_read(rtxn, composite_unique_subdb_name(collection, fields));
+    if (!dbi_opt) return 0;
+    MDB_stat st{};
+    mdb_check(mdb_stat(rtxn.raw(), *dbi_opt, &st), "mdb_stat (composite unique)");
+    MDB_val k{kSubdbIdentityKey.size(), const_cast<char*>(kSubdbIdentityKey.data())};
+    MDB_val v{0, nullptr};
+    const bool hasSentinel = mdb_get(rtxn.raw(), *dbi_opt, &k, &v) == MDB_SUCCESS;
+    return st.ms_entries - (hasSentinel && st.ms_entries > 0 ? 1 : 0);
+}
+
+bool LmdbDocumentStore::has_composite_unique_subdb(std::string_view collection,
+                                                    const std::vector<std::string>& fields) {
+    ReadTxn rtxn(env_);
+    return try_open_for_read(rtxn, composite_unique_subdb_name(collection, fields)).has_value();
+}
+
+bool LmdbDocumentStore::drop_composite_unique(std::string_view collection,
+                                              const std::vector<std::string>& fields) {
+    const std::string sub = composite_unique_subdb_name(collection, fields);
+    {
+        ReadTxn rtxn(env_);
+        if (!try_open_for_read(rtxn, sub)) return false;
+    }
+    WriteTxn wtxn(env_);
+    const unsigned int dbi = open_for_write(wtxn, sub, 0);
+    mdb_check(mdb_drop(wtxn.raw(), dbi, 1), "mdb_drop (composite unique)");
+    wtxn.commit();
+    {
+        std::lock_guard<std::mutex> lock(cache_mutex_);
+        dbi_cache_.erase(sub);
+    }
+    return true;
+}
+
 void LmdbDocumentStore::markIndexMultiValued(WriteTxn& wtxn, unsigned int dbi) {
     MDB_val k{kIndexMultiValuedKey.size(),
               const_cast<char*>(kIndexMultiValuedKey.data())};

+ 61 - 4
service/src/storage/document_store_lmdb.hpp

@@ -32,18 +32,45 @@ class LmdbEnv;
 // v2.10.0 — thrown when a write would put two rows under one value of a UNIQUE
 // index. A distinct type so the gRPC layer can answer ALREADY_EXISTS instead of
 // INTERNAL: a duplicate is the caller's business, not a server fault.
+//
+// v2.12.0 - carries what a caller needs to act on it without parsing what():
+// the constrained field(s) - several for a composite constraint - the colliding
+// value(s) as an object field -> value, and the document already holding them.
+// The gRPC layer forwards these as the refusal detail.
 class UniqueViolation : public std::runtime_error {
 public:
-    UniqueViolation(std::string collection, std::string field, std::string existing_id)
+    UniqueViolation(std::string collection, std::string field, std::string existing_id,
+                    nlohmann::json value = nullptr)
         : std::runtime_error("unique constraint violated on " + collection + "#" +
                              field + ": value already held by document '" +
                              existing_id + "'"),
           collection(std::move(collection)),
-          field(std::move(field)),
-          existing_id(std::move(existing_id)) {}
+          fields{field},
+          existing_id(std::move(existing_id)),
+          values(nlohmann::json::object({{field, std::move(value)}})) {}
+
+    // Composite form.
+    UniqueViolation(std::string collection, std::vector<std::string> fields_,
+                    std::string existing_id, nlohmann::json values_)
+        : std::runtime_error("unique constraint violated on " + collection + "#(" +
+                             joined(fields_) + "): values already held by document '" +
+                             existing_id + "'"),
+          collection(std::move(collection)),
+          fields(std::move(fields_)),
+          existing_id(std::move(existing_id)),
+          values(std::move(values_)) {}
+
     std::string collection;
-    std::string field;
+    std::vector<std::string> fields;
     std::string existing_id;
+    nlohmann::json values;   // object: field -> the colliding value
+
+private:
+    static std::string joined(const std::vector<std::string>& f) {
+        std::string out;
+        for (size_t i = 0; i < f.size(); ++i) { if (i) out += ", "; out += f[i]; }
+        return out;
+    }
 };
 
 // v2.11.0 T13 — thrown when a write to a child collection introduces a
@@ -180,6 +207,31 @@ public:
                                                        const std::string& field,
                                                        size_t limit = 5);
 
+    // v2.12.0 - COMPOSITE unique constraints (see composite_unique_subdb_name).
+    // Declared per collection as a list of field lists, re-armed at boot from
+    // CollectionCfg::compositeUniques exactly as unique fields are. Enforced and
+    // maintained in maintainIndexes(), in the document's own write transaction.
+    void set_composite_uniques(std::string_view collection,
+                               std::vector<std::vector<std::string>> constraints);
+    std::vector<std::vector<std::string>> composite_uniques(std::string_view collection);
+
+    // Build (or rebuild from scratch) the sub-db backing one composite
+    // constraint, in ONE write transaction. If existing rows already violate
+    // it, nothing is committed and the duplicates are returned (up to `limit`
+    // examples) - declaring it must then be refused. `rowsOut` counts the rows
+    // the constraint applies to.
+    std::vector<DuplicateValue> build_composite_unique(std::string_view collection,
+                                                       const std::vector<std::string>& fields,
+                                                       uint64_t& rowsOut,
+                                                       size_t limit = 5);
+    bool drop_composite_unique(std::string_view collection,
+                               const std::vector<std::string>& fields);
+    bool has_composite_unique_subdb(std::string_view collection,
+                                    const std::vector<std::string>& fields);
+    // Rows the constraint currently records (excludes the identity sentinel).
+    uint64_t composite_unique_entries(std::string_view collection,
+                                      const std::vector<std::string>& fields);
+
     // Doc ids whose `field` equals `value`, straight from the index. nullopt
     // means "no index for this field" - the caller must fall back to a scan
     // rather than treat it as "no matches", which would be silently wrong.
@@ -488,6 +540,11 @@ private:
     std::mutex index_mutex_;
     std::unordered_map<std::string, std::vector<std::string>> indexed_fields_;
     std::unordered_map<std::string, std::vector<std::string>> unique_fields_;
+    // v2.12.0 - collection -> composite unique constraints (field lists).
+    std::unordered_map<std::string, std::vector<std::vector<std::string>>> composite_uniques_;
+    // Recomputes rejecting_unique_collections_ over BOTH unique maps; caller
+    // holds index_mutex_.
+    void recount_rejecting_uniques_locked();
 
     // v2.11.0 T3 — collection (as CHILD) -> declared relation refs. Its own
     // mutex for the same reason indexed_fields_ has one: the write path

+ 48 - 0
service/src/storage/secondary_index.cpp

@@ -200,4 +200,52 @@ std::vector<std::string> encode_index_keys(const nlohmann::json& value) {
     return out;
 }
 
+
+// ---- v2.12.0 ---------------------------------------------------------------
+
+bool is_null_index_key(std::string_view key) {
+    return key.size() == 1 && static_cast<unsigned char>(key[0]) == kTagNull;
+}
+
+std::string composite_display_name(const std::vector<std::string>& fields) {
+    std::string out;
+    for (size_t i = 0; i < fields.size(); ++i) {
+        if (i) out.push_back('+');
+        out.append(fields[i]);
+    }
+    return out;
+}
+
+std::string composite_unique_subdb_name(std::string_view collection,
+                                        const std::vector<std::string>& fields) {
+    std::string out(kCompositeUniqueSubdbPrefix);
+    out.append(collection);
+    out.push_back(kSep);
+    for (size_t i = 0; i < fields.size(); ++i) {
+        if (i) out.push_back('+');
+        for (char c : fields[i]) {
+            if (c == '+' || c == '\\') out.push_back('\\');
+            out.push_back(c);
+        }
+    }
+    return out;
+}
+
+std::optional<std::string>
+encode_composite_unique_key(const std::vector<std::optional<nlohmann::json>>& values) {
+    std::string out;
+    for (const auto& v : values) {
+        if (!v || v->is_null() || v->is_object() || v->is_array()) return std::nullopt;
+        auto k = encode_index_key(*v);
+        if (!k) return std::nullopt;
+        const auto n = static_cast<uint32_t>(k->size());
+        out.push_back(static_cast<char>((n >> 24) & 0xFF));
+        out.push_back(static_cast<char>((n >> 16) & 0xFF));
+        out.push_back(static_cast<char>((n >> 8) & 0xFF));
+        out.push_back(static_cast<char>(n & 0xFF));
+        out.append(*k);
+    }
+    return out;
+}
+
 }  // namespace smartbotic::db::storage

+ 28 - 0
service/src/storage/secondary_index.hpp

@@ -122,6 +122,34 @@ bool is_index_meta_key(std::string_view key);
 // stay inside one type.
 unsigned char index_key_tag(std::string_view key);
 
+// v2.12.0 - true for the encoded form of JSON null. A UNIQUE constraint does not
+// count null as a value (SQL semantics): null stays indexed - EQ null is still
+// served from the index - but two nulls never collide, and a null never counts
+// as a duplicate when uniqueness is declared over existing data.
+bool is_null_index_key(std::string_view key);
+
+// v2.12.0 - COMPOSITE unique constraints. Each lives in its own plain (not
+// DUPSORT) sub-db: key = the encoded value TUPLE, data = the one id holding it.
+// The planner never consults these; they exist only to refuse duplicates.
+//
+// Name: "_uniq1_<collection>#<fields>", fields joined by '+' with '+' and '\\'
+// escaped, so distinct field lists can never share a sub-db. The trailing 1 is
+// a key-format version, the `_idx_` -> `_idx2_` lesson paid forward.
+inline constexpr std::string_view kCompositeUniqueSubdbPrefix = "_uniq1_";
+std::string composite_unique_subdb_name(std::string_view collection,
+                                        const std::vector<std::string>& fields);
+
+// The display form ListIndexes reports for a composite: fields joined by '+'.
+std::string composite_display_name(const std::vector<std::string>& fields);
+
+// The tuple key for one document, or nullopt when the constraint does not apply
+// to it: any component absent, null, an object or an array (the SQL rule for a
+// NULL in a unique key, extended to values that have no single key). Each
+// component is encode_index_key()'s form with a 4-byte big-endian length in
+// front, so no two different tuples can encode alike - ("ab","c") vs ("a","bc").
+std::optional<std::string>
+encode_composite_unique_key(const std::vector<std::optional<nlohmann::json>>& values);
+
 // Every index key a single field value contributes.
 //
 // A scalar contributes one key. An ARRAY contributes one key PER ELEMENT, which

+ 404 - 0
tests/load_test/test_db_changes_for_vectorapi.cpp

@@ -0,0 +1,404 @@
+// v2.12.0 client/server boundary test: the database changes smartbotic-vectorapi
+// asked for (/tmp/db-changes-for-vectorapi.md, D1-D7), over real gRPC.
+//
+// Run twice by the .sh: "before-restart" does almost everything, then the
+// server restarts and "after-restart" checks that what was DECLARED (composite
+// constraints, the single-field unique index) is still enforced - a
+// declaration that silently stops being enforced after a restart is the
+// failure this codebase has hit before (v2.9.0's applyIndexDeclarations).
+//
+// Each item is driven through every call that can reach it, and the traps a
+// plausible wrong implementation would fall into are asserted explicitly:
+//   - a refused composite write must leave MemoryStore untouched too, not just
+//     LMDB (MemoryStore's undo snapshot is keyed off "can this collection
+//     reject a write", which had to learn about composite constraints);
+//   - a refused increment must write NOTHING, not the increments before it;
+//   - two concurrent patchIfVersion claims of one version: exactly one wins;
+//   - concurrent increments lose nothing.
+
+#include <smartbotic/database/client.hpp>
+#include <atomic>
+#include <iostream>
+#include <string>
+#include <thread>
+#include <vector>
+
+using namespace smartbotic::database;
+using Code = Client::ErrorCode;
+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 const char* ADDR = "127.0.0.1:9018";
+
+// Run f, expecting it to throw a Client::Error; returns the detail (or a
+// default-constructed one with code Ok when nothing was thrown).
+template <typename F>
+static Client::FailureDetail thrownDetail(F f, bool* threw = nullptr) {
+    try {
+        f();
+    } catch (const Client::Error& e) {
+        if (threw) *threw = true;
+        if (const auto* d = Client::errorDetail(e)) return *d;
+        Client::FailureDetail d;
+        d.code = e.code();
+        d.message = e.what();
+        return d;
+    }
+    if (threw) *threw = false;
+    return {};
+}
+
+static uint64_t versionOf(Client& c, const std::string& coll, const std::string& id) {
+    auto d = c.get(coll, id);
+    return d ? (*d)["_version"].get<uint64_t>() : 0;
+}
+
+static void beforeRestart() {
+    Client c({.address = ADDR, .project = "acme"});
+    c.connect();
+
+    // ================= D1: a unique violation says which constraint ==========
+    c.insert("users", nlohmann::json{{"email", "a@x"}, {"handle", "a"}}, "u1");
+    c.insert("users", nlohmann::json{{"email", "b@x"}, {"handle", "b"}}, "u2");
+    ck(c.createUniqueIndex("users", "email").success, "D1: unique(email) declared");
+    ck(c.createUniqueIndex("users", "handle").success, "D1: unique(handle) declared - two unique fields on one collection");
+    {
+        bool threw = false;
+        auto d = thrownDetail([&] { c.insert("users", nlohmann::json{{"email", "z@x"}, {"handle", "a"}}, "u3"); }, &threw);
+        ck(threw && d.code == Code::AlreadyExists, "D1 insert: AlreadyExists");
+        ck(d.reason == "unique_violation", "D1 insert: reason unique_violation, got '" + d.reason + "'");
+        ck(d.fields == std::vector<std::string>{"handle"}, "D1 insert: names the field that collided (handle, not email)");
+        ck(d.values.is_object() && d.values.value("handle", "") == "a", "D1 insert: carries the colliding value");
+        ck(d.conflictingId == "u1", "D1 insert: names the document already holding it, got '" + d.conflictingId + "'");
+    }
+    {
+        // the original exception type is still what a 2.11.4 consumer catches
+        bool caught = false;
+        try { c.insert("users", nlohmann::json{{"email", "a@x"}}, "u4"); }
+        catch (const Client::AlreadyExists& e) { caught = Client::errorDetail(e) != nullptr; }
+        ck(caught, "D1: still a Client::AlreadyExists, and errorDetail() finds its detail");
+    }
+    {
+        Client::FailureDetail d;
+        ck(c.patch("users", "u2", nlohmann::json{{"email", "a@x"}}, d) == 0, "D1 patch: refused");
+        ck(d.code == Code::AlreadyExists && d.reason == "unique_violation", "D1 patch: AlreadyExists, unique_violation");
+        ck(d.fields == std::vector<std::string>{"email"} && d.conflictingId == "u1", "D1 patch: field and conflicting id");
+    }
+    {
+        Client::FailureDetail d;
+        ck(!c.update("users", "u2", nlohmann::json{{"email", "b@x"}, {"handle", "a"}}, d), "D1 update: refused");
+        ck(d.reason == "unique_violation" && d.fields == std::vector<std::string>{"handle"}, "D1 update: detail");
+    }
+    {
+        // 2.11.4's Failure overloads keep working, code only
+        Client::Failure f;
+        ck(c.patch("users", "u2", nlohmann::json{{"email", "a@x"}}, f) == 0 && f.code == Code::AlreadyExists,
+           "D1: the 2.11.4 Failure overload still reports the code");
+    }
+
+    // ================= missing parent / restricted delete / read-only =========
+    c.upsert("workflows", nlohmann::json{{"name", "wf"}}, "wf-1");
+    ck(c.createRelation("ex_wf", "executions", "workflowId", "workflows", "restrict", true),
+       "relation declared (restrict, validate_on_write)");
+    c.upsert("executions", nlohmann::json{{"workflowId", "wf-1"}}, "ex-1");
+    {
+        auto d = thrownDetail([&] { c.insert("executions", nlohmann::json{{"workflowId", "nope"}}, "ex-2"); });
+        ck(d.code == Code::FailedPrecondition && d.reason == "missing_parent", "missing parent: reason missing_parent");
+        // Bare name, like listRelations() reports it.
+        ck(d.fields == std::vector<std::string>{"workflowId"} && d.relation == "ex_wf",
+           "missing parent: field and relation, got relation '" + d.relation + "'");
+        ck(d.values.is_object() && d.values.value("workflowId", "") == "nope", "missing parent: the missing id");
+    }
+    {
+        Client::FailureDetail d;
+        ck(!c.removeAs("workflows", "wf-1", "me", d), "restrict: delete refused");
+        ck(d.code == Code::FailedPrecondition && d.reason == "delete_restricted",
+           "restrict: reason delete_restricted, got '" + d.reason + "'");
+    }
+    {
+        // read-only shares FAILED_PRECONDITION with the two above; the reason is
+        // what tells them apart.
+        ck(c.lock(), "read-only: locked");
+        auto d = thrownDetail([&] { c.insert("items", nlohmann::json{{"n", 1}}, "ro-1"); });
+        ck(d.code == Code::FailedPrecondition && d.reason == "read_only", "read-only insert: reason read_only");
+        Client::FailureDetail p;
+        ck(c.patch("users", "u1", nlohmann::json{{"n", 1}}, p) == 0, "read-only patch: refused");
+        ck(p.code == Code::FailedPrecondition && p.reason == "read_only",
+           "read-only patch (in-band): now carries its code and reason");
+        Client::FailureDetail u;
+        ck(!c.update("users", "u1", nlohmann::json{{"email", "a@x"}}, u) && u.reason == "read_only",
+           "read-only update (in-band): reason read_only");
+        ck(c.unlock(), "read-only: unlocked");
+    }
+
+    // ================= in-band refusals now have codes ========================
+    {
+        Client::FailureDetail d;
+        ck(!c.update("users", "nobody", nlohmann::json{{"x", 1}}, d) && d.code == Code::NotFound,
+           "update of a missing document: NotFound");
+        Client::FailureDetail p;
+        ck(c.patch("users", "nobody", nlohmann::json{{"x", 1}}, p) == 0 && p.code == Code::NotFound &&
+           p.reason == "not_found", "patch of a missing document: NotFound, not_found (was Unknown)");
+        const uint64_t v = versionOf(c, "users", "u2");
+        Client::FailureDetail s;
+        ck(!c.updateIfVersion("users", "u2", nlohmann::json{{"email", "b@x"}, {"handle", "b"}}, v + 5, s),
+           "updateIfVersion stale: refused");
+        ck(s.code == Code::Aborted && s.reason == "version_conflict" && s.currentVersion == v,
+           "updateIfVersion stale: Aborted, version_conflict, currentVersion");
+        Client::FailureDetail m;
+        ck(!c.updateIfVersion("users", "nobody", nlohmann::json{{"x", 1}}, 1, m) && m.code == Code::NotFound,
+           "updateIfVersion of a missing document: NotFound (was reported as a version conflict)");
+    }
+
+    // ================= D7: find() already returns _version =====================
+    {
+        auto rows = c.find("users", Client::QueryOptions{.filters = {Client::Filter::eq("_id", "u2")}});
+        ck(rows.size() == 1 && rows[0].contains("_version") && rows[0]["_version"].get<uint64_t>() > 0,
+           "D7: find() rows carry _version - no history call needed for a compare-and-set");
+    }
+
+    // ================= D2: patchIfVersion =====================================
+    c.insert("tasks", nlohmann::json{{"state", "open"}, {"note", "keep me"}}, "t1");
+    {
+        const uint64_t v = versionOf(c, "tasks", "t1");
+        // a concurrent writer changes ANOTHER field after we read v ...
+        c.patch("tasks", "t1", nlohmann::json{{"note", "changed by someone else"}});
+        // ... so our claim at v must be refused, and must not revert their field.
+        Client::FailureDetail d;
+        ck(c.patchIfVersion("tasks", "t1", nlohmann::json{{"state", "claimed"}}, v, d) == 0, "D2: stale claim refused");
+        ck(d.code == Code::Aborted && d.reason == "version_conflict" && d.currentVersion == v + 1,
+           "D2: Aborted, version_conflict, currentVersion = v+1");
+        auto t = c.get("tasks", "t1");
+        ck(t && (*t)["state"] == "open" && (*t)["note"] == "changed by someone else",
+           "D2: a refused claim changes nothing");
+
+        const uint64_t v2 = versionOf(c, "tasks", "t1");
+        Client::FailureDetail ok;
+        ck(c.patchIfVersion("tasks", "t1", nlohmann::json{{"state", "claimed"}}, v2, ok) == v2 + 1,
+           "D2: a current claim succeeds and returns the new version");
+        t = c.get("tasks", "t1");
+        ck(t && (*t)["state"] == "claimed" && (*t)["note"] == "changed by someone else",
+           "D2: the claim merged ONE field and kept the other writer's change");
+
+        Client::FailureDetail nf;
+        ck(c.patchIfVersion("tasks", "ghost", nlohmann::json{{"state", "x"}}, 1, nf) == 0 && nf.code == Code::NotFound,
+           "D2: missing document is NotFound");
+    }
+    {
+        // exactly-once claim under contention
+        c.insert("tasks", nlohmann::json{{"state", "open"}}, "t2");
+        const uint64_t v = versionOf(c, "tasks", "t2");
+        std::atomic<int> winners{0}, conflicts{0};
+        std::vector<std::thread> ts;
+        for (int i = 0; i < 8; ++i) {
+            ts.emplace_back([&, i] {
+                Client w({.address = ADDR, .project = "acme"});
+                w.connect();
+                Client::FailureDetail d;
+                if (w.patchIfVersion("tasks", "t2", nlohmann::json{{"owner", i}}, v, d) != 0) ++winners;
+                else if (d.code == Code::Aborted) ++conflicts;
+            });
+        }
+        for (auto& t : ts) t.join();
+        ck(winners == 1 && conflicts == 7,
+           "D2: 8 concurrent claims of one version - exactly one wins (" + std::to_string(winners.load()) + " won)");
+    }
+
+    // ================= D5: increment ==========================================
+    c.insert("stats", nlohmann::json{{"label", "day"}, {"calls", 5}, {"name", "x"}}, "s1");
+    {
+        Client::FailureDetail d;
+        auto r = c.increment("stats", "s1", nlohmann::json{{"calls", 2}, {"minutes", 1.5}, {"by.voice", 1}}, d);
+        ck(r.has_value(), "D5: increment succeeds");
+        ck(r && (*r)["calls"] == 7 && (*r)["calls"].is_number_integer(), "D5: int + int stays an integer");
+        ck(r && (*r)["minutes"] == 1.5, "D5: an absent field counts as 0");
+        ck(r && (*r)["by.voice"] == 1, "D5: a dotted path is reported by its path");
+        auto s = c.get("stats", "s1");
+        ck(s && (*s)["by"]["voice"] == 1, "D5: a dotted path creates the nested object");
+        ck(s && (*s)["label"] == "day", "D5: other fields untouched");
+
+        auto r2 = c.increment("stats", "s1", nlohmann::json{{"calls", 0.5}}, d);
+        ck(r2 && (*r2)["calls"] == 7.5, "D5: int + double becomes a double");
+    }
+    {
+        const uint64_t before = versionOf(c, "stats", "s1");
+        Client::FailureDetail d;
+        auto r = c.increment("stats", "s1", nlohmann::json{{"calls", 1}, {"name", 1}}, d);
+        ck(!r && d.code == Code::InvalidArgument && d.reason == "invalid_increment",
+           "D5: a non-numeric field is refused, InvalidArgument, invalid_increment");
+        ck(d.fields == std::vector<std::string>{"name"}, "D5: the refusal names the field");
+        auto s = c.get("stats", "s1");
+        ck(versionOf(c, "stats", "s1") == before && s && (*s)["calls"] == 7.5,
+           "D5: a refused increment writes NOTHING - not even the valid one before it");
+
+        Client::FailureDetail d2;
+        ck(!c.increment("stats", "s1", nlohmann::json{{"calls", "1"}}, d2) && d2.reason == "invalid_increment",
+           "D5: a non-numeric delta is refused");
+        c.patch("stats", "s1", nlohmann::json{{"big", 9223372036854775807LL}});
+        Client::FailureDetail d3;
+        ck(!c.increment("stats", "s1", nlohmann::json{{"big", 1}}, d3) && d3.reason == "invalid_increment",
+           "D5: integer overflow is refused");
+        Client::FailureDetail d4;
+        ck(!c.increment("stats", "s1", nlohmann::json{{"_version", 1}}, d4) && d4.reason == "invalid_increment",
+           "D5: metadata cannot be incremented");
+        Client::FailureDetail d5;
+        ck(!c.increment("stats", "nope", nlohmann::json{{"calls", 1}}, d5) && d5.code == Code::NotFound,
+           "D5: a missing document is NotFound");
+    }
+    {
+        c.insert("stats", nlohmann::json{{"hits", 0}}, "s2");
+        std::vector<std::thread> ts;
+        for (int i = 0; i < 8; ++i) {
+            ts.emplace_back([&] {
+                Client w({.address = ADDR, .project = "acme"});
+                w.connect();
+                for (int k = 0; k < 50; ++k) {
+                    Client::FailureDetail d;
+                    w.increment("stats", "s2", nlohmann::json{{"hits", 1}}, d);
+                }
+            });
+        }
+        for (auto& t : ts) t.join();
+        auto s = c.get("stats", "s2");
+        ck(s && (*s)["hits"] == 400, "D5: 8 x 50 concurrent increments lose nothing (got " +
+                                       (s ? (*s)["hits"].dump() : std::string("none")) + ")");
+    }
+
+    // ================= D3: null is not a value for uniqueness =================
+    {
+        c.insert("calls", nlohmann::json{{"vapi_call_id", nullptr}}, "c-null-1");
+        c.insert("calls", nlohmann::json{{"vapi_call_id", nullptr}}, "c-null-2");
+        c.insert("calls", nlohmann::json{{"other", 1}}, "c-absent-1");
+        c.insert("calls", nlohmann::json{{"other", 2}}, "c-absent-2");
+        auto r = c.createUniqueIndex("calls", "vapi_call_id");
+        ck(r.success, "D3: unique declared over two existing nulls (refused before 2.12): " + r.error);
+        bool threw = false;
+        thrownDetail([&] { c.insert("calls", nlohmann::json{{"vapi_call_id", nullptr}}, "c-null-3"); }, &threw);
+        ck(!threw, "D3: a third null is accepted");
+        c.insert("calls", nlohmann::json{{"vapi_call_id", "call-1"}}, "c-1");
+        auto d = thrownDetail([&] { c.insert("calls", nlohmann::json{{"vapi_call_id", "call-1"}}, "c-2"); });
+        ck(d.reason == "unique_violation", "D3: a real duplicate is still refused");
+        // update(), not patch(): a merge patch with null REMOVES the field (RFC
+        // 7396), which would test "absent", not "null".
+        Client::FailureDetail p;
+        ck(c.update("calls", "c-1", nlohmann::json{{"vapi_call_id", nullptr}}, p),
+           "D3: setting the field back to an explicit null is accepted");
+        auto nulls = c.find("calls", Client::QueryOptions{.filters = {Client::Filter::eq("vapi_call_id", nullptr)}});
+        ck(nulls.size() == 4, "D3: EQ null still finds every null row (" + std::to_string(nulls.size()) + ")");
+    }
+
+    // ================= D4: composite unique ===================================
+    {
+        c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}}, "f1");
+        c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", "b"}}, "f2");
+        c.insert("files", nlohmann::json{{"chat_id", 2}, {"file_id", "a"}}, "f3");
+        auto r = c.createCompositeUniqueIndex("files", {"chat_id", "file_id"});
+        ck(r.success && r.rowsIndexed == 3, "D4: composite declared over 3 rows: " + r.error);
+        auto again = c.createCompositeUniqueIndex("files", {"chat_id", "file_id"});
+        ck(again.success && again.alreadyExisted, "D4: declaring it again is idempotent");
+
+        auto d = thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}}, "f4"); });
+        ck(d.code == Code::AlreadyExists && d.reason == "unique_violation", "D4: duplicate pair refused");
+        ck(d.fields == std::vector<std::string>{"chat_id", "file_id"}, "D4: detail names BOTH fields");
+        ck(d.values.is_object() && d.values.value("chat_id", 0) == 1 && d.values.value("file_id", "") == "a",
+           "D4: detail carries the combination");
+        ck(d.conflictingId == "f1", "D4: detail names the holder");
+
+        // MemoryStore must not keep the refused row: re-using the id works.
+        bool threw = true;
+        thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 3}, {"file_id", "a"}}, "f4"); }, &threw);
+        ck(!threw, "D4: a refused insert left nothing behind - its id is free (MemoryStore undo ran)");
+
+        Client::FailureDetail u;
+        ck(!c.update("files", "f2", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}}, u) &&
+           u.reason == "unique_violation", "D4: updating INTO a taken pair is refused");
+        Client::FailureDetail p;
+        ck(c.patch("files", "f2", nlohmann::json{{"note", "x"}}, p) != 0, "D4: a later unrelated patch succeeds");
+        auto f2 = c.get("files", "f2");
+        ck(f2 && (*f2)["file_id"] == "b", "D4: ...and the refused update is not resurrected by it");
+
+        Client::FailureDetail own;
+        ck(c.update("files", "f1", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}, {"seen", true}}, own),
+           "D4: rewriting a row with its OWN pair is fine");
+        thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", nullptr}}, "fn1"); }, &threw);
+        bool threw2 = true;
+        thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", nullptr}}, "fn2"); }, &threw2);
+        ck(!threw && !threw2, "D4: a null component means not constrained");
+        thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}}, "fn3"); }, &threw);
+        ck(!threw, "D4: an absent component means not constrained");
+
+        ck(c.remove("files", "f3"), "D4: delete the holder of (2, a)");
+        thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 2}, {"file_id", "a"}}, "f5"); }, &threw);
+        ck(!threw, "D4: a deleted row frees its pair");
+
+        // ("ab","c") and ("a","bc") must be different tuples
+        c.insert("pairs", nlohmann::json{{"x", "ab"}, {"y", "c"}}, "p1");
+        ck(c.createCompositeUniqueIndex("pairs", {"x", "y"}).success, "D4: second composite declared");
+        thrownDetail([&] { c.insert("pairs", nlohmann::json{{"x", "a"}, {"y", "bc"}}, "p2"); }, &threw);
+        ck(!threw, "D4: (ab, c) and (a, bc) are different combinations");
+
+        // declaring over existing duplicates is refused, with examples
+        c.insert("dupes", nlohmann::json{{"a", 1}, {"b", 1}}, "d1");
+        c.insert("dupes", nlohmann::json{{"a", 1}, {"b", 1}}, "d2");
+        auto bad = c.createCompositeUniqueIndex("dupes", {"a", "b"});
+        ck(!bad.success && !bad.duplicateExamples.empty(), "D4: declaring over duplicates is refused with examples");
+        thrownDetail([&] { c.insert("dupes", nlohmann::json{{"a", 1}, {"b", 1}}, "d3"); }, &threw);
+        ck(!threw, "D4: ...and the refused constraint enforces nothing");
+
+        ck(!c.createCompositeUniqueIndex("files", {"chat_id"}).success, "D4: one field is refused (use createUniqueIndex)");
+        ck(!c.createCompositeUniqueIndex("files", {"chat_id", "chat_id"}).success, "D4: a repeated field is refused");
+
+        auto list = c.listCompositeUniqueIndexes("files");
+        ck(list.size() == 1 && list[0] == std::vector<std::string>{"chat_id", "file_id"}, "D4: listed by listCompositeUniqueIndexes");
+        bool leaked = false;
+        for (const auto& i : c.listIndexes("files")) leaked = leaked || i.field.find('+') != std::string::npos;
+        ck(!leaked, "D4: listIndexes() does not report it as a field");
+    }
+
+    // ================= D6: removeManyAs =======================================
+    {
+        c.insert("bulk", nlohmann::json{{"n", 1}}, "b1");
+        c.insert("bulk", nlohmann::json{{"n", 2}}, "b2");
+        c.insert("bulk", nlohmann::json{{"n", 3}}, "b3");
+        Client::FailureDetail d;
+        auto r = c.removeManyAs("bulk", {"b3", "missing", "b1"}, "fn:acme/cleanup:1", d);
+        ck(r.has_value() && r->deletedCount == 2, "D6: two of three existed and were deleted");
+        ck(r && r->deletedIds == std::vector<std::string>{"b3", "b1"}, "D6: deletedIds in request order, missing id absent");
+        ck(!c.exists("bulk", "b1") && !c.exists("bulk", "b3") && c.exists("bulk", "b2"), "D6: exactly those are gone");
+
+        Client::FailureDetail rd;
+        auto blocked = c.removeManyAs("workflows", {"wf-1"}, "me", rd);
+        ck(!blocked && rd.reason == "delete_restricted", "D6: a restricted id refuses the batch");
+        ck(c.exists("workflows", "wf-1"), "D6: ...and nothing was deleted");
+    }
+}
+
+static void afterRestart() {
+    Client c({.address = ADDR, .project = "acme"});
+    c.connect();
+    auto d = thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}}, "r1"); });
+    ck(d.reason == "unique_violation" && d.fields == std::vector<std::string>{"chat_id", "file_id"},
+       "after restart: the composite constraint is still enforced");
+    bool threw = true;
+    thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 9}, {"file_id", "z"}}, "r2"); }, &threw);
+    ck(!threw, "after restart: a new pair is accepted");
+    auto u = thrownDetail([&] { c.insert("users", nlohmann::json{{"email", "a@x"}}, "r3"); });
+    ck(u.reason == "unique_violation", "after restart: the single-field unique is still enforced");
+    bool nullThrew = true;
+    thrownDetail([&] { c.insert("calls", nlohmann::json{{"vapi_call_id", nullptr}}, "r4"); }, &nullThrew);
+    ck(!nullThrew, "after restart: null still does not collide");
+
+    ck(c.dropCompositeUniqueIndex("files", {"chat_id", "file_id"}), "drop the composite constraint");
+    thrownDetail([&] { c.insert("files", nlohmann::json{{"chat_id", 1}, {"file_id", "a"}}, "r5"); }, &threw);
+    ck(!threw, "dropped: no longer enforced");
+    ck(c.listCompositeUniqueIndexes("files").empty(), "dropped: no longer listed");
+}
+
+int main(int argc, char** argv) {
+    const std::string phase = argc > 1 ? argv[1] : "before-restart";
+    if (phase == "before-restart") beforeRestart();
+    else afterRestart();
+    std::cout << "\n[" << phase << "] passed=" << pass << " failed=" << fail << "\n";
+    return fail == 0 ? 0 : 1;
+}

+ 75 - 0
tests/load_test/test_db_changes_for_vectorapi.sh

@@ -0,0 +1,75 @@
+#!/usr/bin/env bash
+# v2.12.0 client/server boundary e2e - the database changes smartbotic-vectorapi
+# asked for (D1-D7), over real gRPC, across a real restart. See
+# test_db_changes_for_vectorapi.cpp for what each assertion covers.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-db-changes-for-vectorapi
+PORT=9018
+
+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_db_changes_for_vectorapi.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+SERVER_PID=""
+boot() {
+    "$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" \
+        > "$DIR/server-$1.log" 2>&1 &
+    SERVER_PID=$!
+    for _ in $(seq 1 60); do
+        grep -q "Notified systemd: READY" "$DIR/server-$1.log" && return 0
+        sleep 0.5
+    done
+    echo "server failed to become ready; log:"
+    tail -30 "$DIR/server-$1.log"
+    exit 1
+}
+stop() { kill "$SERVER_PID" 2>/dev/null || true; wait "$SERVER_PID" 2>/dev/null || true; }
+trap stop EXIT
+
+run() {   # run <phase>
+    set +e
+    LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/t" "$1"
+    local rc=$?
+    set -e
+    if [[ $rc -ne 0 ]]; then
+        echo ""
+        echo "FAILED in phase $1 - server log tail:"
+        tail -30 "$DIR"/server-*.log | tail -30
+        exit $rc
+    fi
+}
+
+echo "=== phase 1 ==="
+boot 1
+run before-restart
+stop
+
+echo "=== restart: declarations must survive ==="
+boot 2
+run after-restart
+
+echo ""
+echo "OK - db changes for vectorapi e2e passed"

+ 219 - 0
tests/load_test/test_event_actor.cpp

@@ -0,0 +1,219 @@
+// v2.12.0 client/server boundary test: an event says WHO caused it.
+//
+// A consumer that reacts to events by writing (vectorapi's database-triggered
+// functions) has to recognise its own writes, or a function that writes to the
+// collection it watches feeds itself. It tags its writes with an `actor`. That
+// worked, slowly and racily, for inserts and updates - the event said nothing
+// about origin, so provenance was read back from version history afterwards -
+// and not at all for deletes: remove() could not send an actor, and the
+// history entry a delete leaves is the document's PRE-delete state, whose
+// updated_by names its last writer rather than its deleter.
+//
+// Now DeleteRequest carries an actor (Client::removeAs) and every
+// DatabaseEvent reports one (Client::subscribeEvents).
+//
+// The traps, each asserted explicitly because each is the plausible wrong
+// implementation:
+//   - a delete WITHOUT an actor, of a document last written by a function,
+//     must report NO actor - not the function (deriving from the stored
+//     document would do exactly that);
+//   - a child that a set_null cascade nulls still has its previous writer in
+//     updated_by, and its event must name the DELETING caller instead;
+//   - a cascade-deleted child likewise reports the deleting caller.
+
+#include <smartbotic/database/client.hpp>
+#include <chrono>
+#include <condition_variable>
+#include <functional>
+#include <iostream>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+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"; }
+}
+
+// Events arrive on the subscription's reader thread.
+struct Recorder {
+    std::mutex m;
+    std::condition_variable cv;
+    std::vector<Client::Event> events;
+
+    void add(const Client::Event& e) {
+        { std::lock_guard<std::mutex> lk(m); events.push_back(e); }
+        cv.notify_all();
+    }
+
+    // The first event matching (collection suffix, id, type) recorded at or
+    // after index `from`, waiting up to 5 s for it.
+    std::optional<Client::Event> waitFor(const std::string& coll, const std::string& id,
+                                         const std::string& type, size_t from = 0) {
+        std::unique_lock<std::mutex> lk(m);
+        std::optional<Client::Event> hit;
+        cv.wait_for(lk, std::chrono::seconds(5), [&] {
+            for (size_t i = from; i < events.size(); ++i) {
+                const auto& e = events[i];
+                const bool collMatches = e.collection == coll ||
+                    (e.collection.size() > coll.size() &&
+                     e.collection.compare(e.collection.size() - coll.size() - 1, std::string::npos,
+                                          ":" + coll) == 0);
+                if (collMatches && e.id == id && e.eventType == type) { hit = e; return true; }
+            }
+            return false;
+        });
+        return hit;
+    }
+
+    size_t size() { std::lock_guard<std::mutex> lk(m); return events.size(); }
+};
+
+static void expectActor(Recorder& rec, const std::string& coll, const std::string& id,
+                        const std::string& type, const std::string& actor,
+                        const std::string& what, size_t from = 0) {
+    auto e = rec.waitFor(coll, id, type, from);
+    ck(e.has_value(), what + ": a " + type + " event arrives for " + coll + "/" + id);
+    if (e) {
+        ck(e->actor == actor, what + ": actor is '" + actor + "', got '" + e->actor + "'");
+    }
+}
+
+int main() {
+    Client c({.address = "127.0.0.1:9016", .project = "acme"});
+    c.connect();
+
+    Recorder rec;
+    auto sub = c.subscribeEvents({}, [&](const Client::Event& e) { rec.add(e); });
+
+    // The original callback shape must keep working, fed by the same loop.
+    std::mutex om;
+    std::vector<std::tuple<std::string, std::string, std::string, bool>> oldEvents;
+    auto oldSub = c.subscribe({}, [&](const std::string& coll, const std::string& id,
+                                      const std::string& type, const std::optional<nlohmann::json>& data) {
+        std::lock_guard<std::mutex> lk(om);
+        oldEvents.emplace_back(coll, id, type, data.has_value());
+    });
+
+    std::this_thread::sleep_for(std::chrono::milliseconds(300));  // let both streams attach
+
+    // ---- Part 1: every write path reports the actor it carried.
+    const std::string fn1 = "fn:acme/f1:1";
+    c.insert("items", nlohmann::json{{"n", 1}}, "i1", 0, fn1);
+    expectActor(rec, "items", "i1", "insert", fn1, "insert");
+
+    c.update("items", "i1", nlohmann::json{{"n", 2}}, "alice");
+    expectActor(rec, "items", "i1", "update", "alice", "update");
+
+    size_t mark = rec.size();
+    c.patch("items", "i1", nlohmann::json{{"n", 3}}, "bob");
+    expectActor(rec, "items", "i1", "update", "bob", "patch", mark);
+
+    mark = rec.size();
+    c.upsert("items", nlohmann::json{{"n", 4}}, "i1", 0, "carol");
+    expectActor(rec, "items", "i1", "update", "carol", "upsert", mark);
+
+    // ---- Part 2: THE BUG. A delete can now carry an actor, and it is reported.
+    const std::string fn2 = "fn:acme/f2:2";
+    ck(c.removeAs("items", "i1", fn2), "removeAs deletes the document");
+    expectActor(rec, "items", "i1", "delete", fn2, "removeAs");
+    {
+        auto e = rec.waitFor("items", "i1", "delete");
+        ck(e && !e->data.has_value(), "a delete event carries no document body");
+        ck(e && e->timestamp > 0, "the event carries the server timestamp");
+        ck(e && !e->nodeId.empty(), "the event carries the server node id");
+    }
+
+    // A delete with NO actor of a document a function wrote last must NOT be
+    // attributed to that function.
+    c.insert("items", nlohmann::json{{"n", 5}}, "i2", 0, fn1);
+    expectActor(rec, "items", "i2", "insert", fn1, "insert before a plain delete");
+    ck(c.remove("items", "i2"), "plain remove deletes the document");
+    expectActor(rec, "items", "i2", "delete", "", "remove() without an actor");
+
+    // Same for a write with no actor after one that had one.
+    c.insert("items", nlohmann::json{{"n", 6}}, "i3", 0, fn1);
+    mark = rec.size();
+    c.patch("items", "i3", nlohmann::json{{"n", 7}});
+    expectActor(rec, "items", "i3", "update", "", "patch without an actor after a tagged write", mark);
+    mark = rec.size();
+    c.update("items", "i3", nlohmann::json{{"n", 71}});
+    expectActor(rec, "items", "i3", "update", "", "update without an actor after a tagged write", mark);
+    c.patch("items", "i3", nlohmann::json{{"n", 72}}, fn1);
+    mark = rec.size();
+    c.upsert("items", nlohmann::json{{"n", 73}}, "i3");
+    expectActor(rec, "items", "i3", "update", "", "upsert without an actor after a tagged write", mark);
+
+    // The Failure& form: success reports through the return value, and a
+    // missing document is not a failure - the remove(.., Failure&) contract.
+    {
+        c.insert("items", nlohmann::json{{"n", 8}}, "i4");
+        Client::Failure f;
+        ck(c.removeAs("items", "i4", "dave", f), "removeAs(.., Failure&) deletes");
+        ck(f.code == Client::ErrorCode::Ok, "removeAs(.., Failure&) success leaves Failure clean");
+        expectActor(rec, "items", "i4", "delete", "dave", "removeAs(.., Failure&)");
+
+        Client::Failure g;
+        ck(!c.removeAs("items", "never-existed", "dave", g), "removeAs of nothing reports false");
+        ck(g.code == Client::ErrorCode::Ok, "removeAs of nothing is not a failure");
+    }
+
+    // The errorOut overload is the reason removeAs is a separate NAME: an
+    // lvalue std::string third argument must still mean errorOut.
+    {
+        c.insert("items", nlohmann::json{{"n", 9}}, "i5");
+        std::string errorOut = "stale";
+        ck(c.remove("items", "i5", errorOut), "remove(.., errorOut) still deletes");
+        ck(errorOut.empty(), "remove(.., errorOut) still clears errorOut");
+        expectActor(rec, "items", "i5", "delete", "", "remove(.., errorOut) sends no actor");
+    }
+
+    // ---- Part 3: cascade. Every document the cascade touches is reported as
+    // the DELETING caller's doing, not its own last writer's.
+    ck(c.createRelation("ex_wf", "executions", "workflowId", "workflows", "cascade"),
+       "cascade relation declared");
+    c.upsert("workflows", nlohmann::json{{"name", "wf"}}, "wf-1", 0, "alice");
+    c.upsert("executions", nlohmann::json{{"workflowId", "wf-1"}}, "ex-1", 0, "writer-x");
+    expectActor(rec, "executions", "ex-1", "insert", "writer-x", "child insert");
+    ck(c.removeAs("workflows", "wf-1", "deleter"), "removeAs deletes a parent with a cascade");
+    expectActor(rec, "workflows", "wf-1", "delete", "deleter", "cascade parent");
+    expectActor(rec, "executions", "ex-1", "delete", "deleter", "cascade-deleted child");
+    ck(!c.exists("executions", "ex-1"), "the cascade did delete the child");
+
+    ck(c.createRelation("note_tag", "notes", "tagId", "tags", "set_null"),
+       "set_null relation declared");
+    c.upsert("tags", nlohmann::json{{"name", "t"}}, "t-1", 0, "alice");
+    c.upsert("notes", nlohmann::json{{"tagId", "t-1"}}, "n-1", 0, "writer-y");
+    expectActor(rec, "notes", "n-1", "insert", "writer-y", "set_null child insert");
+    mark = rec.size();
+    ck(c.removeAs("tags", "t-1", "deleter-2"), "removeAs deletes a parent with set_null");
+    expectActor(rec, "tags", "t-1", "delete", "deleter-2", "set_null parent");
+    expectActor(rec, "notes", "n-1", "update", "deleter-2",
+                "set_null child (its stored updatedBy is still writer-y)", mark);
+    {
+        auto n = c.get("notes", "n-1");
+        ck(n && (*n)["tagId"].is_null(), "the cascade did null the child's reference");
+    }
+
+    // ---- Part 4: the original subscribe() still sees everything, decoded
+    // the same way, with no body on a delete.
+    std::this_thread::sleep_for(std::chrono::milliseconds(300));
+    {
+        std::lock_guard<std::mutex> lk(om);
+        ck(oldEvents.size() == rec.size(),
+           "subscribe() and subscribeEvents() saw the same number of events (" +
+           std::to_string(oldEvents.size()) + " vs " + std::to_string(rec.size()) + ")");
+        bool sawDelete = false;
+        for (const auto& [coll, id, type, hasData] : oldEvents) {
+            if (id == "i1" && type == "delete") { sawDelete = true; ck(!hasData, "subscribe(): no body on a delete"); }
+        }
+        ck(sawDelete, "subscribe() still delivers the delete");
+    }
+
+    sub.reset();
+    oldSub.reset();
+    std::cout << "\npassed=" << pass << " failed=" << fail << "\n";
+    return fail == 0 ? 0 : 1;
+}

+ 76 - 0
tests/load_test/test_event_actor.sh

@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# v2.12.0 client/server boundary e2e - an event must say WHO caused it,
+# over real gRPC. See test_event_actor.cpp for
+# what each assertion covers.
+
+set -euo pipefail
+
+# v2.11.0 final review (finding 10) - SCRIPT-RELATIVE, resolved ONCE and
+# BEFORE any cd.
+#
+# Three of these scripts hardcoded `ROOT=/data/smartbotic-database`, so running
+# them from a git worktree built and tested the MAIN checkout instead of the
+# branch under test: a green result was evidence about main, not about the
+# change. The two that were already script-relative computed ROOT from a
+# RELATIVE "$0" AFTER cd-ing, so `bash tests/load_test/<script>.sh` from the
+# repo root failed outright - they only worked when invoked by absolute path.
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+cd "$SCRIPT_DIR"
+
+DIR=/tmp/sbdb-event-actor
+PORT=9016
+
+rm -rf "$DIR"
+mkdir -p "$DIR/data"
+
+cat > "$DIR/config.json" <<EOF
+{
+  "storage": {
+    "data_directory": "$DIR/data",
+    "bind_address": "127.0.0.1",
+    "rpc_port": $PORT,
+    "encryption": { "enabled": false },
+    "migrations": { "enabled": false },
+    "replication": { "enabled": false }
+  }
+}
+EOF
+
+echo "=== building test binary ==="
+g++ -std=c++20 -O1 -o "$DIR/test_event_actor" test_event_actor.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt -pthread
+
+echo "=== booting server on $PORT ==="
+"$ROOT/build/service/smartbotic-database" --config "$DIR/config.json" \
+    > "$DIR/server.log" 2>&1 &
+SERVER_PID=$!
+cleanup() { kill "$SERVER_PID" 2>/dev/null || true; wait "$SERVER_PID" 2>/dev/null || true; }
+trap cleanup EXIT
+
+for _ in $(seq 1 60); do
+    grep -q "Notified systemd: READY" "$DIR/server.log" && break
+    sleep 0.5
+done
+if ! grep -q "Notified systemd: READY" "$DIR/server.log"; then
+    echo "server failed to become ready; log:"
+    tail -30 "$DIR/server.log"
+    exit 1
+fi
+
+echo "=== running assertions ==="
+set +e
+LD_LIBRARY_PATH="$ROOT/build/client" "$DIR/test_event_actor"
+RC=$?
+set -e
+
+if [[ $RC -ne 0 ]]; then
+    echo ""
+    echo "FAILED - server log tail:"
+    tail -30 "$DIR/server.log"
+    exit $RC
+fi
+
+echo ""
+echo "OK - event actor e2e passed"

+ 2 - 1
tests/test_dual_write_mirror.cpp

@@ -307,7 +307,8 @@ void test_integration_via_memory_store_callback() {
     cfg.maxMemoryBytes = 64ULL * 1024 * 1024;
     MemoryStore mem(cfg);
     mem.setPersistCallback([&](const std::string& coll, const std::string& id,
-                                const std::optional<Document>& d, EventType ev) {
+                                const std::optional<Document>& d, EventType ev,
+                                const std::optional<std::string>&) {
         applyDualWriteMirror(&doc_store, healthy, drift, coll, id, d, ev);
     });
 

Некоторые файлы не были показаны из-за большого количества измененных файлов