Selaa lähdekoodia

fix(client): make relations_enforced readable where consumers look; carry gRPC status codes out of failed calls

Two reports from smartbotic-vectorapi, each checked against source first. One
was wrong about the database and right about its documentation; the other was
right about the symptom and wrong about where it lived.

relations_enforced "is write-only" - it was not. Client::getRelationsEnforced()
has shipped since v2.11.0. The reporter looked on CollectionInfo; the setting is
served by GetCollectionConfig. What made a careful reader miss it was ours: the
integration guide did not mention relations at all, the CLI could set the flag
and no command could show it, and nothing near CollectionInfo said where
changeable settings live. Now: a guide section, `configure-relations <c>` with
no value reads, `info` prints relations_enforced, and getCollectionInfo() and
the proto message point at the right RPC.

The requested third state ("never configured") is declined. The report's reason
was that unset and explicitly-disabled look alike, and they do not: one reads
true, the other false. Unset and explicitly-on behave identically, and every
config record written since 2.11.0 already carries the key.

One real weakness found on the way: getRelationsEnforced() answers true when the
read itself fails. Right for code relying on enforcement, wrong for a toggle.
Client::tryGetRelationsEnforced() returns optional<bool>; no value means it
could not be determined (any failed status, or a pre-2.11.0 server). It does not
throw on a denial: get()/find() throw because their empty result is a valid
answer a denial could be mistaken for, and no-value cannot be mistaken for on or
off.

Status codes: the server has returned ALREADY_EXISTS for a unique violation and
FAILED_PRECONDITION for a missing parent or a restricted delete since v2.11.0,
and the client dropped the code, so a duplicate key reached an HTTP caller as a
500. The report named insert, update and patch as throwing. Only insert, upsert,
find and the file calls throw; update, updateIfVersion, patch, patchWithTtl and
remove return false or 0, so a typed exception alone would have fixed POST and
left PUT and PATCH as broken. Both shapes are covered:

- throwing calls throw Client::Error carrying code(), with AlreadyExists,
  FailedPrecondition and PermissionDenied as subtypes. It derives from
  std::runtime_error with what() unchanged, so existing catch blocks behave as
  before.
- return-value calls gain overloads taking a Client::Failure& {code, message},
  the shape of the v2.11.0 remove(..., std::string& errorOut). They cannot start
  throwing without turning every `if (!db.update(...))` into an uncaught
  exception.

Everything is nested in Client, because a consumer with `using namespace
smartbotic::database` and its own ErrorCode would stop compiling. The exception
types are defined out of line so their typeinfo lives in the library.

Known limit, recorded in the roadmap: Update and PatchDocument refuse some
writes in-band (status OK, success=false, a message), which carry no code on the
wire and arrive as ErrorCode::Unknown with the text. Closing that is a wire
change.

ABI: methods and nested types only. All 30 public types are byte-identical to
the v2.11.3 header, soname stays 2, and a test binary built entirely against
2.11.3 plus the released 2.11.3 CLI both ran against the new library.

Tests: test_client_error_codes (33 checks, 17 fail with the propagation
reverted); test_relations_client_e2e 33 -> 46 plus 8 CLI checks (4 and 5 fail
with the read mapping reverted). ctest 23/23, all client/server suites green.
fszontagh 1 kuukausi sitten
vanhempi
sitoutus
293f4c4b92

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 0
CLAUDE.md


+ 1 - 1
VERSION

@@ -1 +1 @@
-2.11.3
+2.11.4

+ 28 - 3
cli/main.cpp

@@ -99,7 +99,7 @@ void printUsage() {
               << "  " << C_CYAN << "relation-check" << C_RESET << " <name>"
               << "                    Report dangling references (read-only)\n"
               << "  " << C_CYAN << "configure-relations" << C_RESET
-              << " <collection> <on|off>   Enable/disable enforcement for a collection\n"
+              << " <collection> [on|off]   Show, or enable/disable, enforcement for a collection\n"
               << "  " << C_CYAN << "describe-delete" << C_RESET << " <collection> <id>"
               << "        What would happen if this document were deleted\n"
               << "  " << C_CYAN << "security-set" << C_RESET << " <project> <on|off> [enforce|audit]\n"
@@ -518,6 +518,16 @@ bool execCommand(smartbotic::database::Client& client,
                       << "  max_versions: " << info->maxVersions << "\n";
             if (info->defaultTtlSeconds > 0)
                 std::cout << "  ttl: " << info->defaultTtlSeconds << "s\n";
+            // v2.11.4 - relations_enforced is not part of CollectionInfo (it
+            // is a changeable setting, served by GetCollectionConfig), and
+            // its absence here read as "the server cannot report it". Always
+            // printed, since the default is ON and an operator should not
+            // have to know that to learn a delete may be refused. A failed
+            // read says so rather than printing the default.
+            const auto enforced = client.tryGetRelationsEnforced(params[0]);
+            std::cout << "  relations_enforced: "
+                      << (!enforced ? "unknown (could not be read)" : *enforced ? "on" : "off")
+                      << "\n";
             return true;
         }
 
@@ -859,11 +869,26 @@ bool execCommand(smartbotic::database::Client& client,
 
         // v2.11.0 T8 — the only reachable path to relations_enforced besides
         // grpcurl. A partial update: touches only this one knob.
+        //
+        // v2.11.4 - with no value it READS the setting. Until then this
+        // command could change a flag no command could show, so the state
+        // after `configure-relations x off` was something you had to
+        // remember rather than something you could check.
         if (cmd == "configure-relations") {
-            if (params.size() < 2) {
-                printError("usage: configure-relations <collection> <on|off>");
+            if (params.empty()) {
+                printError("usage: configure-relations <collection> [on|off]");
                 return false;
             }
+            if (params.size() == 1) {
+                const auto current = client.tryGetRelationsEnforced(params[0]);
+                if (!current) {
+                    printError("could not read relations_enforced for " + params[0]);
+                    return false;
+                }
+                std::cout << params[0] << " relations_enforced="
+                          << (*current ? "on" : "off") << "\n";
+                return true;
+            }
             if (params[1] != "on" && params[1] != "off") {
                 printError("expected 'on' or 'off', got: " + params[1]);
                 return false;

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

@@ -6,6 +6,7 @@
 #include <map>
 #include <memory>
 #include <optional>
+#include <stdexcept>
 #include <string>
 #include <vector>
 
@@ -18,6 +19,111 @@ namespace smartbotic::database {
  */
 class Client {
 public:
+    // ===== Failure reporting (v2.11.4) =====
+    //
+    // The server classifies failures - a unique violation is ALREADY_EXISTS,
+    // a missing parent reference or a restricted delete FAILED_PRECONDITION -
+    // and until 2.11.4 the client dropped that classification on the way
+    // out: throwing calls threw std::runtime_error(message), and calls that
+    // report through their return value answered false or 0. A caller could
+    // not tell "you sent a duplicate" from "the server broke" without
+    // matching on message text.
+    //
+    // All of this is nested in Client so a consumer's own ErrorCode, Error
+    // or Failure cannot collide with it under `using namespace`.
+
+    /**
+     * The gRPC status code of a failed call, numerically identical to
+     * grpc::StatusCode. A library-local enum so this header still needs no
+     * gRPC include.
+     */
+    enum class ErrorCode : int {
+        Ok = 0,
+        Cancelled = 1,
+        /// Also used when the server refused IN-BAND (status OK, success
+        /// false, a message): those replies carry no code. The message says
+        /// why. Update and PatchDocument report "Document not found",
+        /// "Version conflict", read-only mode and memory-pressure this way.
+        Unknown = 2,
+        InvalidArgument = 3,
+        DeadlineExceeded = 4,
+        NotFound = 5,
+        /// A unique constraint is already held by another document.
+        AlreadyExists = 6,
+        PermissionDenied = 7,
+        ResourceExhausted = 8,
+        /// A relation refused the write or delete: a child references a
+        /// parent that does not exist (validate_on_write), or a delete is
+        /// blocked by on_delete="restrict".
+        FailedPrecondition = 9,
+        Aborted = 10,
+        OutOfRange = 11,
+        Unimplemented = 12,
+        Internal = 13,
+        Unavailable = 14,
+        DataLoss = 15,
+        Unauthenticated = 16,
+    };
+
+    /**
+     * Thrown by the calls that throw (insert, upsert, find, findWithMetrics,
+     * similaritySearch, the file calls, and get/exists/count on a denial).
+     *
+     * Derives from std::runtime_error with what() unchanged, so every
+     * existing `catch (const std::runtime_error&)` and
+     * `catch (const std::exception&)` behaves exactly as before. New code can
+     * catch Error and switch on code(), or catch a subtype below.
+     */
+    class Error : public std::runtime_error {
+    public:
+        Error(ErrorCode code, const std::string& message);
+        ~Error() override;
+        [[nodiscard]] ErrorCode code() const noexcept { return code_; }
+
+    private:
+        ErrorCode code_;
+    };
+
+    /** A unique constraint is already held by another document. */
+    class AlreadyExists : public Error {
+    public:
+        explicit AlreadyExists(const std::string& message);
+        ~AlreadyExists() override;
+    };
+
+    /** A relation refused the write (missing parent) or the delete (restrict). */
+    class FailedPrecondition : public Error {
+    public:
+        explicit FailedPrecondition(const std::string& message);
+        ~FailedPrecondition() override;
+    };
+
+    /** The access policy denied the call. */
+    class PermissionDenied : public Error {
+    public:
+        explicit PermissionDenied(const std::string& message);
+        ~PermissionDenied() override;
+    };
+
+    /**
+     * Why a call that reports failure through its RETURN VALUE failed.
+     *
+     * update(), updateIfVersion(), patch(), patchWithTtl() and remove()
+     * answer false or 0 rather than throwing, and they cannot start throwing
+     * without turning every existing `if (!db.update(...))` into an uncaught
+     * exception. Each has an overload taking a Failure& instead - the same
+     * shape as remove(collection, id, std::string& errorOut), carrying the
+     * code as well as the message.
+     *
+     * Reset at the start of every call, so `code == ErrorCode::Ok` after a
+     * call that returned false means nothing went wrong: the document was
+     * simply not there to delete.
+     */
+    struct Failure {
+        ErrorCode code = ErrorCode::Ok;
+        std::string message;
+    };
+
     struct Config {
         std::string address = "localhost:9004";
         uint32_t timeoutMs = 5000;
@@ -160,6 +266,15 @@ public:
     bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
                 const std::string& actor = "");
 
+    /**
+     * update(), reporting WHY on failure (v2.11.4). A missing document is
+     * ErrorCode::NotFound; a unique violation AlreadyExists; a missing parent
+     * reference FailedPrecondition. An OVERLOAD, so the symbol existing
+     * callers link against is untouched.
+     */
+    bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
+                Failure& failureOut, const std::string& actor = "");
+
     /**
      * Update with optimistic locking.
      * @param actor User ID performing the operation (for audit trail)
@@ -168,6 +283,15 @@ public:
                         const nlohmann::json& data, uint64_t expectedVersion,
                         const std::string& actor = "");
 
+    /**
+     * updateIfVersion(), reporting WHY on failure (v2.11.4). A version
+     * conflict is refused in-band by the server and arrives as
+     * ErrorCode::Unknown with the message "Version conflict".
+     */
+    bool updateIfVersion(const std::string& collection, const std::string& id,
+                        const nlohmann::json& data, uint64_t expectedVersion,
+                        Failure& failureOut, const std::string& actor = "");
+
     /**
      * Atomically merge fields into an existing document (server-side).
      * Only the specified fields are modified — other fields remain unchanged.
@@ -197,6 +321,18 @@ public:
     uint64_t patch(const std::string& collection, const std::string& id,
                    const nlohmann::json& fields, const std::string& actor = "");
 
+    /**
+     * patch() / patchWithTtl(), reporting WHY on failure (v2.11.4). Return 0
+     * on failure as the originals do, with the code and message in
+     * `failureOut`.
+     */
+    uint64_t patch(const std::string& collection, const std::string& id,
+                   const nlohmann::json& fields, Failure& failureOut,
+                   const std::string& actor = "");
+    uint64_t patchWithTtl(const std::string& collection, const std::string& id,
+                          const nlohmann::json& patch, uint32_t ttlSeconds,
+                          Failure& failureOut, const std::string& actor = "");
+
     /**
      * Upsert a document.
      * @param actor User ID performing the operation (for audit trail)
@@ -229,6 +365,14 @@ public:
      */
     bool remove(const std::string& collection, const std::string& id, std::string& errorOut);
 
+    /**
+     * remove(), reporting the code as well as the message (v2.11.4). A
+     * delete blocked by a relation is ErrorCode::FailedPrecondition. As with
+     * the std::string overload, a document that simply did not exist returns
+     * false with `failureOut.code == ErrorCode::Ok`.
+     */
+    bool remove(const std::string& collection, const std::string& id, Failure& failureOut);
+
     /**
      * Check if a document exists.
      */
@@ -491,6 +635,14 @@ public:
 
     /**
      * Get collection info including size and document count.
+     *
+     * This is what the collection IS (its creation-time options and its
+     * size). Settings that can be changed afterwards are not here and are
+     * read separately: getCollectionConfig() for timestamp precision and
+     * versioning, tryGetRelationsEnforced() / getRelationsEnforced() for
+     * relation enforcement, listIndexes() for indexes. They are served by a
+     * different RPC (GetCollectionConfig), so their absence from
+     * CollectionInfo does not mean they cannot be read.
      */
     [[nodiscard]] std::optional<CollectionInfo> getCollectionInfo(const std::string& name);
 
@@ -905,9 +1057,40 @@ public:
     /**
      * Read whether relations are currently enforced for `collection`.
      * Defaults to true when the collection has no explicit config.
+     *
+     * ⚠ Also answers true when the read itself FAILS (server unreachable,
+     * access denied): it fails toward the enforced default. That is the
+     * right answer for code deciding whether it may rely on enforcement and
+     * the wrong one for anything that SHOWS the setting to someone - a
+     * toggle rendered from a failed read would be inventing its position.
+     * Use tryGetRelationsEnforced() for display.
      */
     [[nodiscard]] bool getRelationsEnforced(const std::string& collection);
 
+    /**
+     * v2.11.4 - the same read for callers that display the value: it can
+     * decline to answer instead of defaulting.
+     *
+     * A value is what the server reported. `true` covers BOTH "explicitly
+     * enabled" and "never configured" - the two are indistinguishable on
+     * purpose, because they behave identically on every write and delete,
+     * and the server stores one bool, not a record of who chose it. What
+     * matters to an operator is enforced versus not, and that is exactly
+     * what the bool says: a collection reads `false` only if someone
+     * disabled it.
+     *
+     * No value means the setting could not be determined - never "unset".
+     * That covers every failure alike (server unreachable, deadline, access
+     * denied; the reason is logged) and a server older than 2.11.0, which
+     * has no relations to enforce. It does not throw: unlike an empty
+     * get()/find() result, no value cannot be mistaken for an answer.
+     *
+     * A METHOD, not a member on CollectionInfo, for the reason
+     * setRelationsEnforced() gives above: that public struct cannot change
+     * size under an unchanged soname.
+     */
+    [[nodiscard]] std::optional<bool> tryGetRelationsEnforced(const std::string& collection);
+
     /**
      * One relation's impact on deleting a specific document, as reported by
      * describeDelete(). A brand-new struct, not a member added to an

+ 186 - 24
client/src/client.cpp

@@ -18,7 +18,68 @@
 
 namespace smartbotic::database {
 
+// v2.11.4 - defined out of line on purpose. An exception type whose members
+// are all inline has its typeinfo emitted in every object that uses it; with
+// the destructors here it lives in this library, so a throw inside the .so
+// and a catch in the consumer agree on the type by construction.
+Client::Error::Error(ErrorCode code, const std::string& message)
+    : std::runtime_error(message), code_(code) {}
+Client::Error::~Error() = default;
+
+Client::AlreadyExists::AlreadyExists(const std::string& message)
+    : Error(ErrorCode::AlreadyExists, message) {}
+Client::AlreadyExists::~AlreadyExists() = default;
+
+Client::FailedPrecondition::FailedPrecondition(const std::string& message)
+    : Error(ErrorCode::FailedPrecondition, message) {}
+Client::FailedPrecondition::~FailedPrecondition() = default;
+
+Client::PermissionDenied::PermissionDenied(const std::string& message)
+    : Error(ErrorCode::PermissionDenied, message) {}
+Client::PermissionDenied::~PermissionDenied() = default;
+
 namespace {
+// v2.11.4 - Client::ErrorCode mirrors grpc::StatusCode number for number, so
+// the conversion is a cast. The asserts pin the values callers branch on; the
+// gRPC status codes are fixed by its wire protocol and have never been
+// renumbered.
+static_assert(static_cast<int>(Client::ErrorCode::NotFound) == grpc::StatusCode::NOT_FOUND);
+static_assert(static_cast<int>(Client::ErrorCode::AlreadyExists) == grpc::StatusCode::ALREADY_EXISTS);
+static_assert(static_cast<int>(Client::ErrorCode::PermissionDenied) == grpc::StatusCode::PERMISSION_DENIED);
+static_assert(static_cast<int>(Client::ErrorCode::FailedPrecondition) == grpc::StatusCode::FAILED_PRECONDITION);
+static_assert(static_cast<int>(Client::ErrorCode::Unavailable) == grpc::StatusCode::UNAVAILABLE);
+static_assert(static_cast<int>(Client::ErrorCode::Unauthenticated) == grpc::StatusCode::UNAUTHENTICATED);
+
+Client::ErrorCode toErrorCode(grpc::StatusCode code) {
+    return static_cast<Client::ErrorCode>(static_cast<int>(code));
+}
+
+// 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) {
+    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);
+    }
+}
+
+// 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).
 // All other codes (INVALID_ARGUMENT, FAILED_PRECONDITION, NOT_FOUND, ...) are
@@ -264,7 +325,7 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::insert failed after retries: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         return response.id();
@@ -288,7 +349,7 @@ public:
             // v2.4.2 change that stopped Find returning empty for a missing
             // collection.
             if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
-                throw std::runtime_error("access denied: get");
+                throw Client::PermissionDenied("access denied: get");
             }
             spdlog::error("Client::get failed: {}", status.error_message());
             return std::nullopt;
@@ -309,7 +370,7 @@ public:
     }
 
     bool update(const std::string& collection, const std::string& id, const nlohmann::json& data,
-                const std::string& actor) {
+                const std::string& actor, Client::Failure* failureOut = nullptr) {
         // 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;
@@ -328,12 +389,19 @@ public:
             // Get current version
             auto current = get(collection, id);
             if (!current) {
+                // 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);
                 return false;  // document doesn't exist
             }
             uint64_t version = (*current)["_version"].get<uint64_t>();
 
-            // Attempt version-checked update
-            if (updateIfVersion(collection, id, cleanData, version, actor)) {
+            // Attempt version-checked update. Each attempt overwrites
+            // failureOut, so what the caller reads is the LAST attempt's
+            // reason, and a success leaves it clean.
+            if (updateIfVersion(collection, id, cleanData, version, actor, failureOut)) {
                 return true;
             }
 
@@ -351,7 +419,9 @@ public:
 
     bool updateIfVersion(const std::string& collection, const std::string& id,
                         const nlohmann::json& data, uint64_t expectedVersion,
-                        const std::string& actor) {
+                        const std::string& actor,
+                        Client::Failure* failureOut = nullptr) {
+        if (failureOut != nullptr) *failureOut = Client::Failure{};
         smartbotic::databasepb::UpdateRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
@@ -383,15 +453,23 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::updateIfVersion failed after retries: {}", status.error_message());
+            recordFailure(failureOut, status);
             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());
+        }
         return response.success();
     }
 
     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) {
+                   std::optional<uint32_t> ttlSeconds = std::nullopt,
+                   Client::Failure* failureOut = nullptr) {
+        if (failureOut != nullptr) *failureOut = Client::Failure{};
         smartbotic::databasepb::PatchDocumentRequest request;
         request.set_collection(qualify(collection));
         // v2.8.0 — presence distinguishes "leave the expiry alone" (absent) from
@@ -425,11 +503,13 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::patch failed after retries: {}", status.error_message());
+            recordFailure(failureOut, status);
             return 0;
         }
 
         if (!response.success()) {
             spdlog::error("Client::patch failed: {}", response.error());
+            recordFailure(failureOut, Client::ErrorCode::Unknown, response.error());
             return 0;
         }
 
@@ -474,7 +554,7 @@ public:
         }
         if (!status.ok()) {
             spdlog::error("Client::upsert failed after retries: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         return {response.id(), response.inserted()};
@@ -487,7 +567,8 @@ 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) {
+                    std::string* errorOut, Client::Failure* failureOut = nullptr) {
+        if (failureOut != nullptr) *failureOut = Client::Failure{};
         smartbotic::databasepb::DeleteRequest request;
         request.set_collection(qualify(collection));
         request.set_id(id);
@@ -515,6 +596,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);
             return false;
         }
 
@@ -530,6 +612,10 @@ public:
         return removeImpl(collection, id, &errorOut);
     }
 
+    bool remove(const std::string& collection, const std::string& id, Client::Failure& failureOut) {
+        return removeImpl(collection, id, nullptr, &failureOut);
+    }
+
     bool exists(const std::string& collection, const std::string& id) {
         smartbotic::databasepb::ExistsRequest request;
         request.set_collection(qualify(collection));
@@ -548,7 +634,7 @@ public:
             // v2.4.2 change that stopped Find returning empty for a missing
             // collection.
             if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
-                throw std::runtime_error("access denied: exists");
+                throw Client::PermissionDenied("access denied: exists");
             }
             spdlog::error("Client::exists failed: {}", status.error_message());
             return false;
@@ -601,7 +687,7 @@ public:
             // caller bug, and returning {} here is indistinguishable from a
             // legitimately empty result. Other failures keep the old
             // log-and-return-empty behaviour.
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
         if (!status.ok()) {
             // v2.8.0 — a permission denial must NOT look like "no data".
@@ -611,7 +697,7 @@ public:
             // v2.4.2 change that stopped Find returning empty for a missing
             // collection.
             if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
-                throw std::runtime_error("access denied: find");
+                throw Client::PermissionDenied("access denied: find");
             }
             spdlog::error("Client::find failed: {}", status.error_message());
             return {};
@@ -671,7 +757,7 @@ public:
 
         auto status = stub_->Find(&context, request, &response);
         if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
-            throw std::runtime_error(status.error_message());  // see find()
+            throwStatus(status, status.error_message());  // see find()
         }
         if (!status.ok()) {
             // v2.8.0 — a permission denial must NOT look like "no data".
@@ -681,7 +767,7 @@ public:
             // v2.4.2 change that stopped Find returning empty for a missing
             // collection.
             if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
-                throw std::runtime_error("access denied: findWithMetrics");
+                throw Client::PermissionDenied("access denied: findWithMetrics");
             }
             spdlog::error("Client::findWithMetrics failed: {}", status.error_message());
             return {};
@@ -736,7 +822,7 @@ public:
             // v2.4.2 change that stopped Find returning empty for a missing
             // collection.
             if (status.error_code() == grpc::StatusCode::PERMISSION_DENIED) {
-                throw std::runtime_error("access denied: count");
+                throw Client::PermissionDenied("access denied: count");
             }
             spdlog::error("Client::count failed: {}", status.error_message());
             return 0;
@@ -842,7 +928,7 @@ public:
         auto status = stub_->SimilaritySearch(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::similaritySearch failed: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         std::vector<Client::SimilarityResult> results;
@@ -1007,8 +1093,7 @@ public:
         auto status = stub_->CreateProject(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::createProject failed: {}", status.error_message());
-            throw std::runtime_error("createProject transport failure: " +
-                                     status.error_message());
+            throwStatus(status, "createProject transport failure: " + status.error_message());
         }
         if (!response.error().empty()) {
             // Validation error (invalid name etc.) — surfaced via the
@@ -1030,8 +1115,7 @@ public:
         auto status = stub_->DropProject(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::dropProject failed: {}", status.error_message());
-            throw std::runtime_error("dropProject transport failure: " +
-                                     status.error_message());
+            throwStatus(status, "dropProject transport failure: " + status.error_message());
         }
         if (!response.error().empty()) {
             throw std::runtime_error("dropProject('" + name + "') refused: " +
@@ -1152,6 +1236,52 @@ public:
                    || response.config().relations_enforced();
     }
 
+    // v2.11.4 - decides what a relations_enforced read REPORTS, given what
+    // the RPC returned. Split out from the transport so the policy is one
+    // small function with no gRPC plumbing around it.
+    //
+    // Every way of not knowing collapses to nullopt, and nothing throws:
+    //
+    //   - A failed status, whatever the code. get()/find()/count() throw on
+    //     PERMISSION_DENIED (v2.8.0) because their empty result is a VALID
+    //     answer, so a denial returned as empty would be read as "no data".
+    //     That hazard does not exist here: nullopt is not a setting, it is
+    //     the absence of one, and a caller cannot mistake it for on or off.
+    //     One failure channel is also what the name promises.
+    //
+    //   - A successful reply WITHOUT the field. A 2.11.0+ server writes it
+    //     on every GetCollectionConfig reply - the handler sets it
+    //     unconditionally, including for a collection never configured or
+    //     not yet created, both of which report the default (true). So an
+    //     absent field can only be a server older than 2.11.0, which has no
+    //     relations. `true` there would claim enforcement that does not
+    //     exist, and `false` would offer a switch that server silently
+    //     ignores; the honest reading is that the setting is not there.
+    //     getRelationsEnforced() answers true for this case and is left
+    //     alone - it is the fail-toward-enforced read by contract.
+    static std::optional<bool> interpretRelationsEnforcedRead(
+        const grpc::Status& status,
+        const smartbotic::databasepb::GetCollectionConfigResponse& response
+    ) {
+        if (!status.ok()) return std::nullopt;
+        if (!response.config().has_relations_enforced()) return std::nullopt;
+        return response.config().relations_enforced();
+    }
+
+    std::optional<bool> tryGetRelationsEnforced(const std::string& collection) {
+        smartbotic::databasepb::GetCollectionConfigRequest request;
+        request.set_collection(qualify(collection));
+        smartbotic::databasepb::GetCollectionConfigResponse response;
+        grpc::ClientContext context;
+        setDeadline(context);
+
+        auto status = stub_->GetCollectionConfig(&context, request, &response);
+        if (!status.ok()) {
+            spdlog::error("Client::tryGetRelationsEnforced failed: {}", status.error_message());
+        }
+        return interpretRelationsEnforcedRead(status, response);
+    }
+
     Client::TimestampMigrationResult migrateCollectionTimestamps(
         const std::string& collection,
         const std::string& fromPrecision,
@@ -2077,7 +2207,7 @@ public:
         auto status = writer->Finish();
         if (!status.ok()) {
             spdlog::error("Client::uploadFile failed: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         return {response.id(), response.size(), response.checksum(), response.deduplicated()};
@@ -2108,7 +2238,7 @@ public:
         auto status = reader->Finish();
         if (!status.ok()) {
             spdlog::error("Client::downloadFile failed: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
         return fileData;
     }
@@ -2126,7 +2256,7 @@ public:
         if (!status.ok()) {
             if (status.error_code() == grpc::StatusCode::NOT_FOUND) return std::nullopt;
             spdlog::error("Client::getFileInfo failed: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         Client::FileRecord record;
@@ -2203,7 +2333,7 @@ public:
         auto status = stub_->ListFiles(&context, request, &response);
         if (!status.ok()) {
             spdlog::error("Client::listFiles failed: {}", status.error_message());
-            throw std::runtime_error(status.error_message());
+            throwStatus(status, status.error_message());
         }
 
         Client::FileListResult result;
@@ -2304,6 +2434,30 @@ bool Client::updateIfVersion(const std::string& collection, const std::string& i
     return impl_->updateIfVersion(collection, id, data, expectedVersion, actor);
 }
 
+bool Client::update(const std::string& collection, const std::string& id, const nlohmann::json& data,
+                    Failure& failureOut, const std::string& actor) {
+    failureOut = Failure{};
+    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,
+                             Failure& 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, Failure& 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,
+                              Failure& failureOut, const std::string& actor) {
+    return impl_->patch(collection, id, fields, actor, ttlSeconds, &failureOut);
+}
+
 uint64_t Client::patch(const std::string& collection, const std::string& id,
                        const nlohmann::json& fields, const std::string& actor) {
     return impl_->patch(collection, id, fields, actor);
@@ -2329,6 +2483,10 @@ bool Client::remove(const std::string& collection, const std::string& id, std::s
     return impl_->remove(collection, id, errorOut);
 }
 
+bool Client::remove(const std::string& collection, const std::string& id, Failure& failureOut) {
+    return impl_->remove(collection, id, failureOut);
+}
+
 bool Client::exists(const std::string& collection, const std::string& id) {
     return impl_->exists(collection, id);
 }
@@ -2544,6 +2702,10 @@ bool Client::getRelationsEnforced(const std::string& collection) {
     return impl_->getRelationsEnforced(collection);
 }
 
+std::optional<bool> Client::tryGetRelationsEnforced(const std::string& collection) {
+    return impl_->tryGetRelationsEnforced(collection);
+}
+
 Client::DescribeDeleteResult Client::describeDelete(const std::string& collection,
                                                      const std::string& id) {
     return impl_->describeDelete(collection, id);

+ 32 - 2
docs/ROADMAP.md

@@ -1,6 +1,6 @@
 # Smartbotic Database - Status and Roadmap
 
-**Current version: 2.11.3** (see `VERSION`). Last reviewed: 2026-08-10.
+**Current version: 2.11.4** (see `VERSION`). Last reviewed: 2026-10-05.
 
 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 +53,7 @@ Consequences of that substitution, which trip up readers:
 
 ## Shipped
 
-Every item below is in the installed product as of 2.11.3. `CLAUDE.md` has the
+Every item below is in the installed product as of 2.11.4. `CLAUDE.md` has the
 detail and the failure modes.
 
 - JSON document store: collections, version history, field-level encryption, TTL
@@ -190,6 +190,36 @@ 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.
 
+### 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.
+- **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
+  writes only. `createRelation` is the one a consumer is most likely to want
+  next, since its refusals (cross-project, missing collection) are caller faults.
+- **`relations_enforced` has no "never configured" state, by decision.** The
+  report asked for one. It was declined: unset and explicitly-on behave
+  identically, the server stores one bool, and every config record written since
+  2.11.0 already carries the key, so the distinction could not be recovered for
+  existing data even if it were added.
+- **`getRelationsEnforced()` still answers `true` against a pre-2.11.0 server,**
+  which enforces nothing. Left alone because it is the fail-toward-enforced read
+  by contract; `tryGetRelationsEnforced()` reports no value there.
+- **The build image has no `grpcurl`,** so `tests/load_test/test_relations.sh`
+  stops at its third phase when run inside `smartbotic-db-build-base:debian13`.
+  It passes with a `grpcurl` binary mounted in. Add it to
+  `packaging/Dockerfile.base` on the next base rebuild.
+
 ### 5c. Shutdown latency after v2.11.2
 
 The Subscribe unwind is instant (0 ms measured). What remains in a stop, neither

+ 127 - 0
docs/integration-guide.md

@@ -209,6 +209,80 @@ db.remove("users", "user-123");
 bool found = db.exists("users", "user-123");
 ```
 
+### Error handling: caller fault or server fault (2.11.4+)
+
+The server classifies every failure with a gRPC status code. From 2.11.4 the
+client carries that code out to you, so a duplicate key and a broken server no
+longer look the same. Nothing here needs matching on message text.
+
+| Condition | Code |
+|---|---|
+| A unique constraint is already held by another document | `AlreadyExists` |
+| A child references a parent that does not exist (`validate_on_write`) | `FailedPrecondition` |
+| A delete is blocked by a relation with `on_delete="restrict"` | `FailedPrecondition` |
+| The access policy denied the call | `PermissionDenied` |
+| Unknown collection or view on `find` | `NotFound` |
+| Server unreachable, or the deadline passed | `Unavailable`, `DeadlineExceeded` |
+
+The client has two kinds of call, and each reports the code its own way.
+
+**Calls that throw** - `insert`, `upsert`, `find`, `findWithMetrics`,
+`similaritySearch`, the file calls, and `get`/`exists`/`count` on a denial -
+throw `Client::Error`, which carries `code()`. `Client::AlreadyExists`,
+`Client::FailedPrecondition` and `Client::PermissionDenied` are subtypes for
+when you only care about one:
+
+```cpp
+using smartbotic::database::Client;
+
+try {
+    db.insert("users", {{"email", "a@example.com"}});
+} catch (const Client::AlreadyExists& e) {
+    return conflict(e.what());              // 409: the caller sent a duplicate
+} catch (const Client::FailedPrecondition& e) {
+    return unprocessable(e.what());         // 422: a referenced parent is missing
+} catch (const Client::Error& e) {
+    switch (e.code()) {
+        case Client::ErrorCode::Unavailable:
+        case Client::ErrorCode::DeadlineExceeded:
+            return unavailable(e.what());   // 503: worth retrying
+        default:
+            return internal(e.what());      // 500
+    }
+}
+```
+
+`Client::Error` derives from `std::runtime_error` and `what()` is the same text
+as before, so existing `catch (const std::runtime_error&)` and
+`catch (const std::exception&)` blocks keep working untouched.
+
+**Calls that report through their return value** - `update`, `updateIfVersion`,
+`patch`, `patchWithTtl` and `remove` return `false` or `0` and do not throw.
+Each has an overload taking a `Client::Failure&`:
+
+```cpp
+Client::Failure why;
+if (db.patch("users", "user-123", {{"email", "a@example.com"}}, why) == 0) {
+    if (why.code == Client::ErrorCode::AlreadyExists) return conflict(why.message);
+    return internal(why.message);
+}
+
+if (!db.remove("workflows", "wf-1", why)) {
+    if (why.code == Client::ErrorCode::Ok) return notFound();     // nothing to delete
+    if (why.code == Client::ErrorCode::FailedPrecondition) return conflict(why.message);
+}
+```
+
+`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.
+
 ### Concurrency: update() vs patch()
 
 When multiple clients modify the same document concurrently, choose the right method:
@@ -573,6 +647,10 @@ bool explicit_set = db.hasCollectionConfig("logs");        // true
 bool default_only = db.hasCollectionConfig("llm_tokens");  // false (still ns default)
 ```
 
+`getCollectionConfig()` covers timestamp precision and versioning. Relation
+enforcement comes from the same RPC but is read with its own accessor - see
+[Relation enforcement on/off](#relation-enforcement-onoff-2110) below.
+
 #### Version history on/off (2.4.5+)
 
 Version history can be switched per collection, **on a collection that already
@@ -602,6 +680,55 @@ Semantics:
   it survives restarts through the normal WAL + snapshot path.
 - Takes effect on the next write.
 
+#### Relation enforcement on/off (2.11.0+)
+
+Whether declared relations are enforced is a per-collection setting. It
+**defaults to on**: declaring a relation names its child and parent, so the
+declaration is the opt-in. Switching it off is the escape hatch for a bulk
+import, and it is not retroactive - references left dangling while it was off
+are found only by `relation-check`.
+
+It is both writable and readable, but **not through `getCollectionInfo()`**.
+`CollectionInfo` describes what a collection is (creation-time options, size);
+settings that can change afterwards are served by the `GetCollectionConfig`
+RPC, and this one has its own accessors because adding a member to a public
+client struct changes its size under an unchanged soname, which crashes
+consumers already installed against the old layout.
+
+```cpp
+db.setRelationsEnforced("executions", false);   // partial update: touches only this
+
+// For code that decides whether it may rely on enforcement.
+// Fails toward `true` if the read itself fails.
+bool relied_on = db.getRelationsEnforced("executions");
+
+// For anything that SHOWS the setting (2.11.4+). No value means the setting
+// could not be determined, so a UI can render "unknown" instead of a guess.
+std::optional<bool> shown = db.tryGetRelationsEnforced("executions");
+```
+
+| Reading | Meaning |
+|---|---|
+| `true` | Enforced. Either never configured (the default) or explicitly enabled. |
+| `false` | Someone disabled it. Deletes and writes on this collection skip relation checks. |
+| no value | Could not be determined: the server was unreachable, the read was denied, or the server predates 2.11.0 and has no relations. Never means "unset". Does not throw. |
+
+"Never configured" and "explicitly enabled" are deliberately one reading: they
+behave identically on every write and delete, and the server stores the
+setting, not a record of who chose it. The distinction an operator needs is
+enforced versus not, and `false` appears only when someone turned it off.
+
+From the CLI:
+
+```bash
+smartbotic-db-cli configure-relations executions        # show the current state
+smartbotic-db-cli configure-relations executions off    # change it
+smartbotic-db-cli info executions                       # also prints relations_enforced
+```
+
+Over raw gRPC, `GetCollectionConfigResponse.config.relations_enforced` is
+populated on every reply from a 2.11.0+ server.
+
 #### Partial updates (2.4.5+)
 
 `configureCollection()` is a **partial update**. Fields you leave unset are

+ 6 - 0
proto/database.proto

@@ -547,6 +547,12 @@ message GetCollectionInfoResponse {
     bool found = 2;
 }
 
+// What a collection IS: its creation-time options and its size.
+//
+// Settings changeable after creation are NOT here - timestamp_precision,
+// versioning_enabled and relations_enforced are read with GetCollectionConfig
+// (see CollectionConfig), which always populates all three on a reply. Their
+// absence from this message does not mean they cannot be read.
 message CollectionInfo {
     string name = 1;
     uint64 document_count = 2;

+ 195 - 0
tests/load_test/test_client_error_codes.cpp

@@ -0,0 +1,195 @@
+// v2.11.4 client/server boundary test: a failed call reports WHICH failure.
+//
+// The server has classified these correctly since v2.11.0 - a unique
+// violation is ALREADY_EXISTS, a missing parent reference or a restricted
+// delete is FAILED_PRECONDITION - and the client then threw
+// std::runtime_error(status.error_message()) or returned false, dropping the
+// code in both cases. A consumer two layers up could only answer HTTP 500 for
+// a duplicate key, or match on the message text.
+//
+// Two shapes are covered because the client has two:
+//   - calls that THROW (insert, upsert, find) now throw a Client::Error
+//     carrying the code, with Client::AlreadyExists / FailedPrecondition as
+//     catchable subtypes;
+//   - calls that report failure through their RETURN VALUE (update, patch,
+//     remove) have an overload taking a Failure&, since making them throw
+//     would turn every existing `if (!db.update(...))` into an uncaught
+//     exception.
+//
+// Each condition is driven through more than one call, so a fix applied to
+// insert() alone - the only call the original report named correctly - fails
+// here.
+
+#include <smartbotic/database/client.hpp>
+#include <iostream>
+#include <string>
+
+using namespace smartbotic::database;
+static int pass = 0, fail = 0;
+static void ck(bool c, const char* m) {
+    if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
+}
+
+int main() {
+    Client c({.address = "127.0.0.1:9014", .project = "acme"});
+    c.connect();
+
+    // ---- Part 1: unique violation -> AlreadyExists, on every write path.
+    c.insert("users", nlohmann::json{{"email", "a@x"}, {"n", 1}}, "u1");
+    c.insert("users", nlohmann::json{{"email", "b@x"}, {"n", 2}}, "u2");
+    auto uniq = c.createUniqueIndex("users", "email");
+    ck(uniq.success, "unique index declared");
+
+    {
+        bool typed = false, coded = false, messaged = false;
+        try {
+            c.insert("users", nlohmann::json{{"email", "a@x"}}, "u3");
+        } catch (const Client::AlreadyExists& e) {
+            typed = true;
+            coded = e.code() == Client::ErrorCode::AlreadyExists;
+            messaged = std::string(e.what()).find("unique constraint") != std::string::npos;
+        } catch (const std::exception&) {}
+        ck(typed, "insert: a unique violation throws AlreadyExists");
+        ck(coded, "insert: the exception carries ErrorCode::AlreadyExists");
+        ck(messaged, "insert: what() is still the server's message");
+    }
+    {
+        // The base type is enough for a caller that maps codes generically.
+        Client::ErrorCode seen = Client::ErrorCode::Ok;
+        try {
+            c.upsert("users", nlohmann::json{{"email", "a@x"}}, "u3");
+        } catch (const Client::Error& e) {
+            seen = e.code();
+        } catch (const std::exception&) {}
+        ck(seen == Client::ErrorCode::AlreadyExists, "upsert: a unique violation is catchable as Client::Error with the code");
+    }
+    {
+        // Back-compat: every existing consumer catches this, and must still.
+        bool caught = false;
+        try {
+            c.insert("users", nlohmann::json{{"email", "a@x"}}, "u3");
+        } catch (const std::runtime_error&) {
+            caught = true;
+        }
+        ck(caught, "insert: the typed exception is still a std::runtime_error");
+    }
+    ck(!c.exists("users", "u3"), "none of the refused writes stored the document");
+
+    {
+        Client::Failure f;
+        ck(c.patch("users", "u2", nlohmann::json{{"email", "a@x"}}, f) == 0,
+           "patch: a unique violation is refused");
+        ck(f.code == Client::ErrorCode::AlreadyExists, "patch: Failure carries Client::ErrorCode::AlreadyExists");
+        ck(!f.message.empty(), "patch: Failure carries the server's message");
+    }
+    {
+        Client::Failure f;
+        ck(c.patchWithTtl("users", "u2", nlohmann::json{{"email", "a@x"}}, 60, f) == 0,
+           "patchWithTtl: a unique violation is refused");
+        ck(f.code == Client::ErrorCode::AlreadyExists, "patchWithTtl: Failure carries Client::ErrorCode::AlreadyExists");
+    }
+    {
+        Client::Failure f;
+        ck(!c.update("users", "u2", nlohmann::json{{"email", "a@x"}}, f),
+           "update: a unique violation is refused");
+        ck(f.code == Client::ErrorCode::AlreadyExists, "update: Failure carries Client::ErrorCode::AlreadyExists");
+    }
+    {
+        auto cur = c.get("users", "u2");
+        Client::Failure f;
+        ck(cur && !c.updateIfVersion("users", "u2", nlohmann::json{{"email", "a@x"}},
+                                     (*cur)["_version"].get<uint64_t>(), f),
+           "updateIfVersion: a unique violation is refused");
+        ck(f.code == Client::ErrorCode::AlreadyExists, "updateIfVersion: Failure carries Client::ErrorCode::AlreadyExists");
+    }
+
+    // A SUCCESSFUL call must leave a clean Failure, including one that was
+    // dirty going in - a caller reusing the object must not read a stale code.
+    {
+        Client::Failure f;
+        f.code = Client::ErrorCode::Internal;
+        f.message = "stale";
+        ck(c.patch("users", "u2", nlohmann::json{{"n", 3}}, f) != 0, "patch: an ordinary patch succeeds");
+        ck(f.code == Client::ErrorCode::Ok && f.message.empty(), "patch: success clears a reused Failure");
+    }
+
+    // ---- Part 2: missing parent reference -> FailedPrecondition.
+    c.upsert("workflows", nlohmann::json{{"name", "wf-1"}}, "wf-1");
+    c.upsert("executions", nlohmann::json{{"workflowId", "wf-1"}}, "ex-1");
+    ck(c.createRelation("exec_wf", "executions", "workflowId", "workflows", "restrict", true),
+       "relation declared with validate_on_write");
+
+    {
+        bool typed = false;
+        try {
+            c.insert("executions", nlohmann::json{{"workflowId", "no-such-wf"}}, "ex-2");
+        } catch (const Client::FailedPrecondition& e) {
+            typed = e.code() == Client::ErrorCode::FailedPrecondition;
+        } catch (const std::exception&) {}
+        ck(typed, "insert: a missing parent throws FailedPrecondition with its code");
+    }
+    {
+        Client::Failure f;
+        ck(c.patch("executions", "ex-1", nlohmann::json{{"workflowId", "no-such-wf"}}, f) == 0,
+           "patch: a missing parent is refused");
+        ck(f.code == Client::ErrorCode::FailedPrecondition, "patch: Failure carries Client::ErrorCode::FailedPrecondition");
+    }
+
+    // ---- Part 3: a restricted delete, and a delete of nothing.
+    {
+        Client::Failure f;
+        ck(!c.remove("workflows", "wf-1", f), "remove: a referenced parent is refused");
+        ck(f.code == Client::ErrorCode::FailedPrecondition, "remove: Failure carries Client::ErrorCode::FailedPrecondition");
+        ck(!f.message.empty(), "remove: Failure carries the server's message");
+    }
+    {
+        // Not an error: the document was never there. Same contract as the
+        // string-errorOut overload, which leaves errorOut empty here.
+        Client::Failure f;
+        ck(!c.remove("workflows", "never-existed", f), "remove: nothing to delete reports false");
+        ck(f.code == Client::ErrorCode::Ok, "remove: nothing to delete is not a failure");
+    }
+
+    // ---- Part 4: failures the CLIENT can name without reading a message.
+    {
+        Client::Failure f;
+        ck(!c.update("users", "never-existed", nlohmann::json{{"n", 1}}, f),
+           "update: a missing document is refused");
+        ck(f.code == Client::ErrorCode::NotFound, "update: a missing document is Client::ErrorCode::NotFound");
+    }
+    {
+        // find() on a name that is neither a collection nor a view has been a
+        // NOT_FOUND throw since v2.4.2; the code now survives the throw.
+        Client::ErrorCode seen = Client::ErrorCode::Ok;
+        try {
+            (void)c.find("no_such_collection_anywhere", Client::QueryOptions{});
+        } catch (const Client::Error& e) {
+            seen = e.code();
+        } catch (const std::exception&) {}
+        ck(seen == Client::ErrorCode::NotFound, "find: a missing collection throws Client::Error with NotFound");
+    }
+
+    // ---- Part 5: a server that is not there is NOT a caller fault. This is
+    // the distinction the whole change exists for: the same catch block has
+    // to be able to answer 409 above and 503 here.
+    {
+        Client dead({.address = "127.0.0.1:1", .timeoutMs = 500, .writeRetries = 0, .project = "acme"});
+        dead.connect();
+        Client::ErrorCode seen = Client::ErrorCode::Ok;
+        try {
+            dead.insert("users", nlohmann::json{{"email", "z@x"}});
+        } catch (const Client::Error& e) {
+            seen = e.code();
+        } catch (const std::exception&) {}
+        ck(seen == Client::ErrorCode::Unavailable || seen == Client::ErrorCode::DeadlineExceeded,
+           "insert: an unreachable server reports Unavailable/DeadlineExceeded, not a caller fault");
+
+        Client::Failure f;
+        ck(dead.patch("users", "u1", nlohmann::json{{"n", 9}}, f) == 0, "patch: an unreachable server is refused");
+        ck(f.code == Client::ErrorCode::Unavailable || f.code == Client::ErrorCode::DeadlineExceeded,
+           "patch: an unreachable server reports Unavailable/DeadlineExceeded");
+    }
+
+    std::cout << "\npassed=" << pass << " failed=" << fail << "\n";
+    return fail == 0 ? 0 : 1;
+}

+ 76 - 0
tests/load_test/test_client_error_codes.sh

@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# v2.11.4 client/server boundary e2e - a failed call must tell the caller WHICH
+# kind of failure it was, over real gRPC. See test_client_error_codes.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-client-error-codes
+PORT=9014
+
+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_client_error_codes" test_client_error_codes.cpp \
+    -I"$ROOT/client/include" -I"$ROOT/build/client" \
+    -L"$ROOT/build/client" -lsmartbotic-db-client -lspdlog -lfmt
+
+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_client_error_codes"
+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 - client error codes e2e passed"

+ 56 - 0
tests/load_test/test_relations_client_e2e.cpp

@@ -85,6 +85,62 @@ int main() {
 
     ck(c.setRelationsEnforced("workflows", true), "re-enable relations_enforced");
 
+    // ---- Part 3a: the READ path, in the three states a consumer has to be
+    // able to tell apart (v2.11.4).
+    //
+    // A consumer reported relations_enforced as write-only after looking for
+    // it on CollectionInfo, where it has never been: it is served by
+    // GetCollectionConfig. The read existed, but nothing asserted the three
+    // steps below in order, and nothing at all covered a read that FAILS -
+    // getRelationsEnforced() answers `true` there, which is right for code
+    // relying on enforcement and wrong for anything displaying the setting.
+    ck(c.getRelationsEnforced("workflows"), "getRelationsEnforced reads back true after re-enabling");
+
+    auto never = c.tryGetRelationsEnforced("never_configured_coll");
+    ck(never.has_value() && *never,
+       "a collection never configured reads as enforced, not as unknown");
+    ck(!c.hasCollectionConfig("never_configured_coll"),
+       "reading the setting does not create a config record");
+
+    ck(c.setRelationsEnforced("workflows", false), "disable again for the read-back");
+    auto off = c.tryGetRelationsEnforced("workflows");
+    ck(off.has_value() && !*off, "tryGetRelationsEnforced reads back false");
+
+    ck(c.setRelationsEnforced("workflows", true), "enable again for the read-back");
+    auto on = c.tryGetRelationsEnforced("workflows");
+    ck(on.has_value() && *on, "tryGetRelationsEnforced reads back true");
+
+    // A precision-only configure must leave the reading alone: the flag is
+    // `optional` on the wire precisely so this cannot switch it off.
+    {
+        Client::CollectionConfig precisionOnly;
+        precisionOnly.timestampPrecision = "ms";
+        ck(c.setRelationsEnforced("workflows", false), "disable before a precision-only configure");
+        ck(c.configureCollection("workflows", precisionOnly), "precision-only configure accepted");
+        auto after = c.tryGetRelationsEnforced("workflows");
+        ck(after.has_value() && !*after,
+           "a precision-only configure does not flip relations_enforced back on");
+        ck(c.setRelationsEnforced("workflows", true), "restore relations_enforced");
+    }
+
+    // A read that cannot reach the server must not CLAIM a value. Nothing
+    // listens on port 1; the short timeout only keeps the test quick. Either
+    // way of declining to answer is accepted here - what is pinned is that
+    // the caller is never handed `true` or `false` for a setting nobody read.
+    {
+        Client dead({.address = "127.0.0.1:1", .timeoutMs = 500, .project = "acme"});
+        dead.connect();
+        bool claimed = false;
+        try {
+            claimed = dead.tryGetRelationsEnforced("workflows").has_value();
+        } catch (const std::exception&) {
+            claimed = false;
+        }
+        ck(!claimed, "tryGetRelationsEnforced does not invent a value when the read fails");
+        ck(dead.getRelationsEnforced("workflows"),
+           "getRelationsEnforced keeps failing toward the enforced default");
+    }
+
     // ---- Part 3b: DescribeDelete over the boundary, with project
     // qualification. Only exercised in the `default` project by tests/T5's
     // own unit coverage; this is the first time it goes through a real

+ 57 - 0
tests/load_test/test_relations_client_e2e.sh

@@ -72,5 +72,62 @@ if [[ $RC -ne 0 ]]; then
     exit $RC
 fi
 
+# v2.11.4 - the CLI must be able to READ relations_enforced, not only set it.
+# `configure-relations <collection> <on|off>` was the only relations-enforcement
+# command, so an operator could change the setting and never see it; `info`
+# did not print it either. Each read below is checked in BOTH states, so a
+# command that printed a constant would fail one of them.
+echo "=== CLI read path ==="
+CLI() {
+    LD_LIBRARY_PATH="$ROOT/build/client" "$ROOT/build/cli/smartbotic-db-cli" \
+        --address "127.0.0.1:$PORT" --project acme "$@" 2>&1
+}
+CLI_FAIL=0
+expect() {  # expect <description> <pattern> <output>
+    if grep -q -- "$2" <<<"$3"; then
+        echo "  ok: $1"
+    else
+        echo "  FAIL: $1"
+        echo "    wanted: $2"
+        echo "    got:    $3"
+        CLI_FAIL=1
+    fi
+}
+
+expect "configure-relations with no value reports on" \
+    "relations_enforced=on" "$(CLI configure-relations workflows)"
+expect "info reports relations_enforced on" \
+    "relations_enforced: on" "$(CLI info workflows)"
+
+expect "configure-relations off is accepted" \
+    "relations_enforced=off" "$(CLI configure-relations workflows off)"
+expect "configure-relations with no value reports off" \
+    "relations_enforced=off" "$(CLI configure-relations workflows)"
+expect "info reports relations_enforced off" \
+    "relations_enforced: off" "$(CLI info workflows)"
+
+expect "configure-relations on is accepted" \
+    "relations_enforced=on" "$(CLI configure-relations workflows on)"
+expect "info reports relations_enforced on again" \
+    "relations_enforced: on" "$(CLI info workflows)"
+
+# A read against a server that is not there must say so rather than print a
+# state. Port 1 has no listener.
+DEAD_OUT="$(LD_LIBRARY_PATH="$ROOT/build/client" "$ROOT/build/cli/smartbotic-db-cli" \
+    --address 127.0.0.1:1 --project acme configure-relations workflows 2>&1 || true)"
+if grep -q "relations_enforced=on\|relations_enforced=off" <<<"$DEAD_OUT"; then
+    echo "  FAIL: configure-relations printed a state it could not have read"
+    echo "    got: $DEAD_OUT"
+    CLI_FAIL=1
+else
+    echo "  ok: configure-relations prints no state when the server is unreachable"
+fi
+
+if [[ $CLI_FAIL -ne 0 ]]; then
+    echo ""
+    echo "FAILED - CLI read path"
+    exit 1
+fi
+
 echo ""
 echo "OK — relations client/server e2e passed"

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä