瀏覽代碼

fix(errors): carry database failure classification into the HTTP status

A unique-index violation answered 500 internal. The database had classified it
correctly all along - ALREADY_EXISTS, with a precise message - but the client
dropped the code on the way out and every failure arrived as a bare
runtime_error, which the global handler turned into 500. A caller could not
tell its own mistake from a server fault without matching on message text, and
500 is the one status it is entitled to retry blindly or page a human about.

Client 2.11.4 fixes that at the source. This pins to it and maps the codes in
one place (db_errors.hpp):

  AlreadyExists      -> 409 duplicate_values   (the slug POST /indexes returns)
  FailedPrecondition -> 422 relation_violation
  NotFound           -> 404
  PermissionDenied   -> 403
  InvalidArgument    -> 422
  ResourceExhausted  -> 429
  Unavailable/Deadline/Aborted/Unknown -> 503
  anything else      -> 500

Unknown is 503 rather than 500 because that is the code the client uses for
in-band refusals carrying no gRPC status - version conflict, read-only mode,
memory pressure - all of which the caller can retry or wait out.

ErrorCode::Ok on a call that returned false means the operation did not apply,
not that something failed, so it maps to 404. Without that case a plain missing
document returned 500 with an empty message: worse than the bug being fixed,
on a far more common path. Caught by the regression test asserting that
deleting a missing document still answers 404.

The throwing calls (insert) catch Client::Error; update, patch and remove use
the new Failure& overloads, which exist because those calls report through a
return value and cannot start throwing without turning every existing
`if (!db.update(...))` into an uncaught exception.

Delete had a second defect the codes expose: it called describeDelete on EVERY
failure and then answered 404 regardless, so a transport error during a delete
reported "no such document". It now asks for impacts only when the database
says a precondition failed, and reports the real cause otherwise.

Also, relations_enforced is readable now (tryGetRelationsEnforced), so the
collection GET returns it and the web UI's fire-and-forget buttons become a
real toggle. The field is omitted when the server cannot determine it, and
absence is NOT disabled - the panel renders three states, not two.

168/168 via packaging/devstack/run-tests.sh.
fszontagh 1 月之前
父節點
當前提交
ef2e85275e

+ 2 - 1
CLAUDE.md

@@ -60,7 +60,8 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **Client ABI pin:** the server deb is compiled against `DB_CLIENT_VERSION` (`packaging/Dockerfile.base`, default 2.11.3-1 = what prod runs). Every 2.x client shares one SONAME, so a deb built against a newer client installs fine and only segfaults on the next restart - keep the pin equal to the deploy target, and ship a DB upgrade and a vectorapi rebuild together.
 - **The apt repo drops superseded versions on publish**, so `pkg=<old version>` is uninstallable afterwards. Old `.deb`s survive in `$DEB_REPO_DIR/dist`; `build.sh` vendors the pinned client from there into `packaging/vendor/`, and a prod rollback needs them scp'd to the target first.
 - **The Void dev host can no longer build the C++ natively.** Void moved to protobuf 35 / gRPC 1.83; protobuf 35 removed `google/protobuf/map_field_inl.h`, which the database's generated protos include, so `libsmartbotic-db-client` neither compiles nor links there (the installed `.so` still wants `libgrpc++.so.1.61`). Release builds are unaffected because they run in the Debian 13 image. For local backend work use `packaging/devstack`; `ctest` cannot run on this host.
-- **`relations_enforced` is write-only over the API.** `setRelationsEnforced` exists but the client's `CollectionInfo` carries no field for it, so nothing can read the current value back - the web UI therefore offers Enforce / Do-not-enforce as actions rather than a toggle. Fix upstream by adding it to `CollectionInfo`.
+- **`relations_enforced` is readable since client 2.11.4** via `tryGetRelationsEnforced()`, which DECLINES to answer on a failed read rather than defaulting (`getRelationsEnforced()` is the fail-to-enforced variant, for code deciding whether it may rely on enforcement). The collection GET surfaces it, omitting the field when undetermined - absence never means disabled, so the web UI renders three states, not two.
+- **Database failures keep their classification** (`db_errors.hpp`, client 2.11.4). `Client::Error::code()` on the throwing calls and the `Failure&` overloads on `update`/`patch`/`remove` feed one `translate()`: AlreadyExists → 409 `duplicate_values`, FailedPrecondition → 422 `relation_violation`, NotFound → 404, Unavailable/DeadlineExceeded/Unknown → 503, everything else → 500. **`ErrorCode::Ok` on a call that returned false means "did not apply", not an error** - map it to 404, or a plain missing document becomes a 500 with an empty message.
 - **Document write bodies accept two shapes, via one reader.** `documentBody()` in `handlers/documents.cpp` is used by POST, PUT and PATCH: it unwraps `{"data":{...}}`, strips `id` (the document's identity, from the body on POST and from the URL on PUT/PATCH), and rejects `data` alongside any other top-level key with **422** `ambiguous_body`. Before 0.3.3 only POST unwrapped, so a `{"data":...}` PUT stored the wrapper as a literal field and a `data`-plus-siblings POST dropped the siblings silently. A literal top-level `data` field is still writable as `{"data":{"data":...}}`.
 - **Monaco** is bundled locally (`webui/src/monacoSetup.ts`) so the editor works offline — do not revert to the CDN loader.
 - systemd unit is `Type=notify`; the binary must be built with `libsystemd` (it is, when `libsystemd-dev` is present) or change to `Type=exec`.

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.3.2
+0.3.3

+ 3 - 0
api/llms.txt

@@ -67,6 +67,8 @@ Arbitrary JSON CRUD under a `kind=json` collection.
 
 - `POST  /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` or `{...}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
 
+  **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values` (the same slug `POST /indexes` returns). A reference to a parent that does not exist, or a delete a `restrict` relation refuses, is **422** `relation_violation` (a blocked delete additionally returns **409** `relation_restricted` with the impact list). A missing document is **404**; the database being unreachable, read-only or under memory pressure is **503**. A **500** now means a genuine server fault, not a rejected write.
+
   **Body shape (the same on POST, PUT and PATCH).** Send either the document wrapped as `{"data":{...}}` or the document on its own; both store identical content. `id` is never a field: POST reads the document id from the top level of the body, PUT and PATCH from the URL, and it is stripped from what gets stored. A `data` key next to any other top-level field (other than `id`) is **422** `ambiguous_body` rather than silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: `{"data":{"data":...}}`.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}` - Fetch a document by ID.
 - `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace a document (full upsert). Accepts the same two body shapes as POST.
@@ -108,6 +110,7 @@ Relation names are per-project and **unqualified**: requests and responses alway
 - `GET    /api/v1/projects/{project}/relations` - List relations in the project.
 - `GET    /api/v1/projects/{project}/relations/{name}` - Get a relation by name.
 - `DELETE /api/v1/projects/{project}/relations/{name}` - Drop a relation by name.
+- `GET    /api/v1/projects/{project}/collections/{name}` also returns `relations_enforced` (bool). It is **absent** when the server could not determine it, which never means disabled.
 - `PUT    /api/v1/projects/{project}/collections/{name}/relations-enforced` `{enforced}` - Enable/disable relation enforcement on a collection. **`relations_enforced` is read on the collection you are deleting FROM (the PARENT side of the relation), not on the child collection holding the reference.** Disabling it on the child has no effect on deletes issued against the parent; set it on the parent to let its deletes bypass restrict relations.
 
 ## RAG vectors

+ 5 - 1
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.3.2",
+    "version": "0.3.3",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -42,6 +42,10 @@
       "CollectionMeta": {
         "type": "object",
         "properties": {
+          "relations_enforced": {
+            "type": "boolean",
+            "description": "Whether deletes from this collection are checked against the relations naming it as parent. Returned only on the single-collection GET, and ABSENT when the server could not determine it - absence never means disabled. Set it with PUT .../relations-enforced."
+          },
           "name": { "type": "string" },
           "kind": { "type": "string", "enum": ["json", "vector"] },
           "vector_dimension": { "type": "integer", "minimum": 1 },

+ 1 - 1
packaging/Dockerfile.base

@@ -28,7 +28,7 @@ RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
 # only segfaults on the next service restart. Keep this equal to the client
 # version installed on the deploy target; when the target's DB moves, bump this
 # and ship both together.
-ARG DB_CLIENT_VERSION=2.11.3-1
+ARG DB_CLIENT_VERSION=2.11.4-1
 
 # Publishing a new client re-indexes the apt pool, so the pinned version is
 # often no longer installable from the repo. build.sh copies the matching .debs

+ 2 - 2
packaging/build.sh

@@ -21,7 +21,7 @@ BASE_IMAGE_NAME="smartbotic-vectorapi-build-base:debian13"
 # Client version the server deb is compiled against. Must equal the version
 # installed on the deploy target: every 2.x client shares one SONAME, so a
 # mismatch installs cleanly and only segfaults on the next service restart.
-DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.11.3-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.11.4-1}"
 BUILD_JOBS="${BUILD_JOBS:-$(nproc)}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
 
@@ -104,7 +104,7 @@ Environment variables:
   BUILD_JOBS           Parallel build jobs (default: nproc)
   DEB_REPO_DIR         Path to smartbotics-deb-repo (default: /data/dev/smartbotics/smartbotics-deb-repo)
   DB_CLIENT_VERSION    libsmartbotic-db-client version to build against; must match
-                       the deploy target (default: 2.11.3-1)
+                       the deploy target (default: 2.11.4-1)
 EOF
     exit 0
 }

+ 10 - 3
packaging/devstack/run-tests.sh

@@ -14,7 +14,11 @@ set -euo pipefail
 REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
 BASE_IMAGE="${BASE_IMAGE:-smartbotic-vectorapi-build-base:debian13}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
-DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.11.3-1_amd64.deb}"
+DB_DEB="${DB_DEB:-$DEB_REPO_DIR/dist/smartbotic-database_2.11.4-1_amd64.deb}"
+# The base image pins a client version; tests must compile against the same one
+# the release does, so the dev package is installed here rather than assumed.
+CLIENT_DEV_DEB="${CLIENT_DEV_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client-dev_2.11.4-1_amd64.deb}"
+CLIENT_DEB="${CLIENT_DEB:-$DEB_REPO_DIR/dist/libsmartbotic-db-client_2.11.4-1_amd64.deb}"
 FILTER="${1:-}"
 
 docker image inspect "$BASE_IMAGE" >/dev/null 2>&1 || {
@@ -30,11 +34,14 @@ docker run --rm \
     -v "$REPO:/src:ro" \
     -v svapi-testbuild:/build \
     -v "$DB_DEB:/tmp/db.deb:ro" \
+    -v "$CLIENT_DEB:/tmp/client.deb:ro" \
+    -v "$CLIENT_DEV_DEB:/tmp/client-dev.deb:ro" \
     -e "CTEST_FILTER=$FILTER" \
     "$BASE_IMAGE" bash -euo pipefail -c '
         apt-get update -qq >/dev/null
-        apt-get install -y -qq --no-install-recommends /tmp/db.deb >/dev/null 2>&1 || \
-            dpkg -i /tmp/db.deb >/dev/null 2>&1 || true
+        apt-get install -y -qq --no-install-recommends \
+            /tmp/client.deb /tmp/client-dev.deb /tmp/db.deb >/dev/null 2>&1 || \
+            dpkg -i /tmp/client.deb /tmp/client-dev.deb /tmp/db.deb >/dev/null 2>&1 || true
         mkdir -p /var/lib/smartbotic-database
         /usr/bin/smartbotic-database --config /etc/smartbotic-database/config.json >/tmp/db.log 2>&1 &
         for i in $(seq 1 60); do

+ 1 - 0
src/CMakeLists.txt

@@ -1,6 +1,7 @@
 add_library(vectorapi_core STATIC
     config.cpp
     errors.cpp
+    db_errors.cpp
     json_http.cpp
     filters.cpp
     db_gateway.cpp

+ 61 - 0
src/db_errors.cpp

@@ -0,0 +1,61 @@
+#include "db_errors.hpp"
+
+namespace svapi {
+namespace {
+
+using Code = smartbotic::database::Client::ErrorCode;
+
+/// One mapping, shared by both entry points.
+///
+/// `duplicate_values` deliberately matches what POST /indexes already returns
+/// for the same condition, so a caller sees one slug for "this value is taken"
+/// however it was hit.
+ApiError translate(Code code, const std::string& message, const std::string& notFoundMessage) {
+    switch (code) {
+        // The call reported failure but the database raised nothing: on
+        // update/patch/remove that means the document was simply not there.
+        // The message is empty in this case, so it must not be surfaced.
+        case Code::Ok:
+            return ApiError(ErrCode::NotFound, "not_found", notFoundMessage);
+        case Code::AlreadyExists:
+            return ApiError(ErrCode::Conflict, "duplicate_values", message);
+        case Code::FailedPrecondition:
+            // A child pointing at a parent that does not exist, or a delete a
+            // restrict relation refuses. The caller can fix both.
+            return ApiError(ErrCode::Unprocessable, "relation_violation", message);
+        case Code::NotFound:
+            return ApiError(ErrCode::NotFound, "not_found", notFoundMessage);
+        case Code::PermissionDenied:
+            return ApiError(ErrCode::Forbidden, "forbidden", message);
+        case Code::InvalidArgument:
+        case Code::OutOfRange:
+            return ApiError(ErrCode::Unprocessable, "validation", message);
+        case Code::ResourceExhausted:
+            return ApiError(ErrCode::TooManyRequests, "rate_limited", message);
+        case Code::Unavailable:
+        case Code::DeadlineExceeded:
+        case Code::Aborted:
+            return ApiError(ErrCode::Unavailable, "db_unavailable", message);
+        // Unknown covers the in-band refusals that carry no code: a version
+        // conflict, read-only mode, memory pressure. The message says which,
+        // and none of them is a server fault, so 503 rather than 500 - the
+        // caller can retry a version conflict or wait out read-only mode.
+        case Code::Unknown:
+            return ApiError(ErrCode::Unavailable, "db_error", message);
+        default:
+            return ApiError(ErrCode::Internal, "internal", message);
+    }
+}
+
+}  // namespace
+
+ApiError apiErrorFor(const smartbotic::database::Client::Failure& f,
+                     const std::string& notFoundMessage) {
+    return translate(f.code, f.message, notFoundMessage);
+}
+
+ApiError apiErrorFor(const smartbotic::database::Client::Error& e) {
+    return translate(e.code(), e.what(), "no such document");
+}
+
+}  // namespace svapi

+ 31 - 0
src/db_errors.hpp

@@ -0,0 +1,31 @@
+#pragma once
+#include "errors.hpp"
+#include <smartbotic/database/client.hpp>
+#include <string>
+
+namespace svapi {
+
+/// Translating a database failure into an HTTP-facing one.
+///
+/// The database classifies failures - a duplicate is ALREADY_EXISTS, a dangling
+/// reference or a restricted delete is FAILED_PRECONDITION - and client 2.11.4
+/// finally carries that classification out, either as a typed exception or in a
+/// `Client::Failure`. Before it, everything arrived as a bare runtime_error and
+/// the global handler turned the lot into 500, so a caller could not tell its
+/// own mistake from a server fault without matching on message text.
+///
+/// Keep the mapping here, in one place, so every handler answers alike.
+
+/// Build the ApiError for a database failure reported through a return value
+/// (`update`, `patch`, `patchWithTtl`, `remove` take a `Failure&` overload).
+///
+/// `notFoundMessage` is used when the database says NotFound, which on these
+/// calls means the document is simply not there.
+ApiError apiErrorFor(const smartbotic::database::Client::Failure& f,
+                     const std::string& notFoundMessage = "no such document");
+
+/// Build the ApiError for a database failure that threw (`insert`, `upsert`,
+/// the find/search calls).
+ApiError apiErrorFor(const smartbotic::database::Client::Error& e);
+
+} // namespace svapi

+ 5 - 0
src/handlers/collections.cpp

@@ -96,6 +96,11 @@ void registerCollectionRoutes(ApiServer& s) {
         const std::string qc = qualify(project, name);
         e["document_count"] = d->db.client().count(qc);
         if (auto info = d->db.client().getCollectionInfo(qc)) e["size_bytes"] = info->sizeBytes;
+        // tryGetRelationsEnforced (client 2.11.4) declines to answer rather than
+        // defaulting when the read fails, which is what a UI showing the setting
+        // needs: omitted means "could not be determined", never "disabled".
+        if (auto enforced = d->db.client().tryGetRelationsEnforced(qc))
+            e["relations_enforced"] = *enforced;
         sendJson(res, 200, e);
     });
 

+ 28 - 15
src/handlers/documents.cpp

@@ -1,4 +1,5 @@
 #include "collection_registry.hpp"
+#include "db_errors.hpp"
 #include "errors.hpp"
 #include "filters.hpp"
 #include "json_http.hpp"
@@ -81,7 +82,12 @@ void registerDocumentRoutes(ApiServer& s) {
         std::string id = body.value("id", "");
         nlohmann::json data = documentBody(body);
         const uint32_t ttl = ttlParam(req).value_or(0);
-        std::string newId = d->db.client().insert(c, data, id, ttl);
+        std::string newId;
+        try {
+            newId = d->db.client().insert(c, data, id, ttl);
+        } catch (const smartbotic::database::Client::Error& e) {
+            throw apiErrorFor(e);
+        }
         if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
         sendJson(res, 201, {{"id", newId}});
     });
@@ -115,33 +121,40 @@ void registerDocumentRoutes(ApiServer& s) {
         if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
         nlohmann::json patchBody = documentBody(bodyJson(req));
         const auto ttl = ttlParam(req);
-        uint64_t v = ttl ? d->db.client().patchWithTtl(c, id, patchBody, *ttl)
-                          : d->db.client().patch(c, id, patchBody);
-        if (v == 0) throw ApiError(ErrCode::Unavailable, "db_error", "patch failed");
+        smartbotic::database::Client::Failure failure;
+        uint64_t v = ttl ? d->db.client().patchWithTtl(c, id, patchBody, *ttl, failure)
+                          : d->db.client().patch(c, id, patchBody, failure);
+        if (v == 0) throw apiErrorFor(failure, "no such document");
         sendJson(res, 200, {{"id", id}, {"version", v}});
     });
 
     svr.Put(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         std::string c = scoped(d, req, 1, 2, KeyOp::Update); std::string id = req.matches[3];
         if (!d->db.client().exists(c, id)) throw ApiError(ErrCode::NotFound, "not_found", "no such document");
-        if (!d->db.client().update(c, id, documentBody(bodyJson(req))))
-            throw ApiError(ErrCode::Unavailable, "db_error", "update failed");
+        smartbotic::database::Client::Failure failure;
+        if (!d->db.client().update(c, id, documentBody(bodyJson(req)), failure))
+            throw apiErrorFor(failure, "no such document");
         sendJson(res, 200, {{"id", id}});
     });
 
     svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/documents/([^/]+))", [d](const httplib::Request& req, httplib::Response& res) {
         std::string c = scoped(d, req, 1, 2, KeyOp::Delete); std::string id = req.matches[3];
         std::string project = req.matches[1];
-        std::string err;
-        if (!d->db.client().remove(c, id, err)) {
+        smartbotic::database::Client::Failure failure;
+        if (!d->db.client().remove(c, id, failure)) {
             // A restrict relation is the one refusal a caller can act on, so it
-            // gets 409 plus the impact list rather than a generic failure.
-            auto why = d->db.client().describeDelete(c, id);
-            if (why.success && why.wouldBeBlocked)
-                throw ApiError(ErrCode::Conflict, "relation_restricted",
-                               "delete blocked by a relation",
-                               {{"impacts", impactsJson(project, why)}});
-            throw ApiError(ErrCode::NotFound, "not_found", "no such document");
+            // gets 409 plus the impact list rather than a generic failure. Only
+            // ask for the impacts when the database says a precondition failed;
+            // previously every failure took this path and then answered 404,
+            // which was wrong for a transport error.
+            if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
+                auto why = d->db.client().describeDelete(c, id);
+                if (why.success && why.wouldBeBlocked)
+                    throw ApiError(ErrCode::Conflict, "relation_restricted",
+                                   "delete blocked by a relation",
+                                   {{"impacts", impactsJson(project, why)}});
+            }
+            throw apiErrorFor(failure, "no such document");
         }
         sendJson(res, 200, {{"deleted", id}});
     });

+ 7 - 1
src/handlers/vectors.cpp

@@ -1,6 +1,7 @@
 #include "collection_registry.hpp"
 #include "embedding_cache.hpp"
 #include "embeddings.hpp"
+#include "db_errors.hpp"
 #include "errors.hpp"
 #include "filters.hpp"
 #include "project_settings.hpp"
@@ -96,7 +97,12 @@ void registerVectorRoutes(ApiServer& s) {
         if (!doc.is_object()) doc = nlohmann::json::object();
         if (body.contains("text")) doc["text"] = body["text"];
         doc["_vector"] = vec;
-        std::string newId = d->db.client().insert(qualify(project, name), doc, body.value("id", ""));
+        std::string newId;
+        try {
+            newId = d->db.client().insert(qualify(project, name), doc, body.value("id", ""));
+        } catch (const smartbotic::database::Client::Error& e) {
+            throw apiErrorFor(e);
+        }
         if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
         sendJson(res, 201, {{"id", newId}});
     });

+ 105 - 0
tests/test_api_integration.cpp

@@ -1696,3 +1696,108 @@ TEST_F(ApiFixture, ALiteralDataFieldCanStillBeStored) {
     const nlohmann::json got = nlohmann::json::parse(c.Get((docs + "/d").c_str())->body);
     EXPECT_EQ(storedFields(got), (nlohmann::json{{"data",{{"inner",1}}}}));
 }
+
+// --- database failures carry their classification to the HTTP status ---------
+
+TEST_F(ApiFixture, UniqueViolationIsConflictNotInternal) {
+    // The database answers ALREADY_EXISTS for a duplicate; before client 2.11.4
+    // that classification was lost and every caller saw 500 internal.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","uq"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/uq/documents";
+    ASSERT_EQ(c.Post((base + "/uq/indexes").c_str(),
+        nlohmann::json{{"field","sku"},{"unique",true}}.dump(), "application/json")->status, 201);
+
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","one"},{"sku","A"}}.dump(),
+                     "application/json")->status, 201);
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","two"},{"sku","B"}}.dump(),
+                     "application/json")->status, 201);
+
+    // INSERT colliding on the unique field.
+    auto dup = c.Post(docs.c_str(), nlohmann::json{{"id","three"},{"sku","A"}}.dump(), "application/json");
+    ASSERT_TRUE(dup);
+    EXPECT_EQ(dup->status, 409) << dup->body;
+    EXPECT_EQ(nlohmann::json::parse(dup->body)["error"]["code"], "duplicate_values");
+
+    // PUT moving an existing document onto a taken value.
+    auto put = c.Put((docs + "/two").c_str(), nlohmann::json{{"sku","A"}}.dump(), "application/json");
+    ASSERT_TRUE(put);
+    EXPECT_EQ(put->status, 409) << put->body;
+    EXPECT_EQ(nlohmann::json::parse(put->body)["error"]["code"], "duplicate_values");
+
+    // PATCH doing the same.
+    auto patch = c.Patch((docs + "/two").c_str(), nlohmann::json{{"sku","A"}}.dump(), "application/json");
+    ASSERT_TRUE(patch);
+    EXPECT_EQ(patch->status, 409) << patch->body;
+    EXPECT_EQ(nlohmann::json::parse(patch->body)["error"]["code"], "duplicate_values");
+}
+
+TEST_F(ApiFixture, MissingParentReferenceIsUnprocessableNotInternal) {
+    // validate_on_write makes the database answer FAILED_PRECONDITION for a
+    // child pointing at a parent that does not exist. That is the caller's
+    // doing, not a server fault.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    for (const char* n : {"par", "chi"})
+        ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name",n},{"kind","json"}}.dump(),
+                         "application/json")->status, 201);
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/relations").c_str(),
+        nlohmann::json{{"name","chi_par"},{"parent","par"},{"child","chi"},
+                       {"child_field","par_id"},{"on_delete","restrict"},
+                       {"validate_on_write",true}}.dump(), "application/json")->status, 201);
+
+    auto orphan = c.Post((base + "/chi/documents").c_str(),
+        nlohmann::json{{"par_id","does-not-exist"}}.dump(), "application/json");
+    ASSERT_TRUE(orphan);
+    EXPECT_GE(orphan->status, 400) << orphan->body;
+    EXPECT_LT(orphan->status, 500) << "a dangling reference is the caller's fault: " << orphan->body;
+}
+
+TEST_F(ApiFixture, DeletingAMissingDocumentStaysNotFound) {
+    // Guards the delete path while its failure handling gains codes: a plain
+    // missing document must keep answering 404, not a database error.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","del"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    auto r = c.Delete((base + "/del/documents/nope").c_str());
+    ASSERT_TRUE(r);
+    EXPECT_EQ(r->status, 404) << r->body;
+}
+
+TEST_F(ApiFixture, CollectionReportsRelationsEnforced) {
+    // Before client 2.11.4 nothing could read this back, so the web UI could
+    // only offer it as a fire-and-forget action.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","enf"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string one = base + "/enf";
+
+    auto readFlag = [&]() -> std::optional<bool> {
+        auto r = c.Get(one.c_str());
+        EXPECT_EQ(r->status, 200);
+        const nlohmann::json j = nlohmann::json::parse(r->body);
+        if (!j.contains("relations_enforced")) return std::nullopt;
+        return j["relations_enforced"].get<bool>();
+    };
+
+    // Never configured: enforcement is the default, and it is readable.
+    auto initial = readFlag();
+    ASSERT_TRUE(initial.has_value()) << "relations_enforced missing from the collection response";
+    EXPECT_TRUE(*initial);
+
+    ASSERT_EQ(c.Put((one + "/relations-enforced").c_str(),
+        nlohmann::json{{"enforced",false}}.dump(), "application/json")->status, 200);
+    auto off = readFlag();
+    ASSERT_TRUE(off.has_value());
+    EXPECT_FALSE(*off) << "the collection still reports enforcement after disabling it";
+
+    ASSERT_EQ(c.Put((one + "/relations-enforced").c_str(),
+        nlohmann::json{{"enforced",true}}.dump(), "application/json")->status, 200);
+    auto on = readFlag();
+    ASSERT_TRUE(on.has_value());
+    EXPECT_TRUE(*on);
+}

+ 52 - 27
webui/src/components/RelationsEnforcedPanel.tsx

@@ -1,27 +1,33 @@
 import { useState } from 'react'
-import { useQuery } from '@tanstack/react-query'
-import { ShieldCheck, ShieldOff } from 'lucide-react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { ShieldCheck, ShieldOff, HelpCircle } from 'lucide-react'
 import { api } from '@/api/client'
+import { Toggle } from '@/components/form'
 import { useToastStore } from '@/stores/toastStore'
 import { ApiError } from '@/types'
 
 /// Relation enforcement for one collection.
 ///
-/// This is an ACTION, not a toggle, and deliberately so: the database client
-/// (2.11.3) exposes setRelationsEnforced but CollectionInfo carries no
-/// relations_enforced field, so the server cannot report the current value.
-/// A switch would have to invent a position and would be wrong half the time.
+/// Readable since database client 2.11.4: the collection response carries
+/// `relations_enforced`, and the field is ABSENT when the server could not
+/// determine it - which is never the same as "disabled". So there are three
+/// states to render, not two, and an unknown one must not be drawn as a switch
+/// in the off position.
 export function RelationsEnforcedPanel({
   project,
   collection,
+  enforced,
 }: {
   project: string
   collection: string
+  /// undefined = the server did not report it
+  enforced?: boolean
 }) {
   const push = useToastStore((s) => s.push)
+  const queryClient = useQueryClient()
   const [busy, setBusy] = useState(false)
 
-  // Only meaningful when this collection is a parent in some relation - that is
+  // Only meaningful when this collection is a parent in some relation: that is
   // the side the flag is read on when a delete is issued.
   const { data } = useQuery({
     queryKey: ['relations', project],
@@ -31,11 +37,13 @@ export function RelationsEnforcedPanel({
   const asParent = (data?.relations ?? []).filter((r) => r.parent === collection)
   if (asParent.length === 0) return null
 
-  async function set(enforced: boolean) {
+  async function set(next: boolean) {
     setBusy(true)
     try {
-      await api.setRelationsEnforced(project, collection, enforced)
-      push(`Relation enforcement ${enforced ? 'enabled' : 'disabled'} on ${collection}.`, 'success')
+      await api.setRelationsEnforced(project, collection, next)
+      await queryClient.invalidateQueries({ queryKey: ['collection', project, collection] })
+      await queryClient.invalidateQueries({ queryKey: ['collections', project] })
+      push(`Relation enforcement ${next ? 'enabled' : 'disabled'} on ${collection}.`, 'success')
     } catch (err) {
       push(`Could not change enforcement: ${err instanceof ApiError ? err.message : String(err)}`, 'error')
     } finally {
@@ -54,24 +62,41 @@ export function RelationsEnforcedPanel({
         ({asParent.map((r) => r.name).join(', ')}). Enforcement is read on this, the parent side - setting
         it on the child collection has no effect.
       </p>
-      <p className="mt-1 text-xs text-slate-500">
-        The server cannot report the current setting (the database client exposes no read for it), so these
-        buttons set it rather than showing it.
-      </p>
-      <div className="mt-2 flex items-center gap-2">
-        <button
-          type="button" disabled={busy} onClick={() => void set(true)}
-          className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50"
-        >
-          <ShieldCheck size={14} /> Enforce
-        </button>
-        <button
-          type="button" disabled={busy} onClick={() => void set(false)}
-          className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50"
-        >
-          <ShieldOff size={14} /> Do not enforce
-        </button>
+
+      <div className="mt-2">
+        {enforced === undefined ? (
+          // Unknown: offer the two actions rather than a switch whose position
+          // would be invented.
+          <div className="flex flex-col gap-2">
+            <p className="flex items-center gap-1.5 text-xs text-amber-300">
+              <HelpCircle size={13} /> The server did not report the current setting.
+            </p>
+            <div className="flex items-center gap-2">
+              <button type="button" disabled={busy} onClick={() => void set(true)}
+                className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50">
+                <ShieldCheck size={14} /> Enforce
+              </button>
+              <button type="button" disabled={busy} onClick={() => void set(false)}
+                className="inline-flex items-center gap-1.5 rounded-md border border-slate-600 px-3 py-1.5 text-xs text-slate-200 hover:bg-slate-700 disabled:opacity-50">
+                <ShieldOff size={14} /> Do not enforce
+              </button>
+            </div>
+          </div>
+        ) : (
+          <Toggle
+            checked={enforced}
+            onChange={(next) => { if (!busy) void set(next) }}
+            onLabel="Enforced"
+            offLabel="Not enforced"
+          />
+        )}
       </div>
+
+      {enforced === false && (
+        <p className="mt-2 text-xs text-amber-300">
+          Deletes from this collection bypass its restrict relations while this is off.
+        </p>
+      )}
     </div>
   )
 }

+ 2 - 1
webui/src/pages/Collections.tsx

@@ -338,7 +338,8 @@ function CollectionDetailDrawer({ project, name, onClose }: DetailDrawerProps) {
           <IndexPanel project={project} collection={data.name} />
 
           {/* Relation enforcement (only when this collection is a parent) */}
-          <RelationsEnforcedPanel project={project} collection={data.name} />
+          <RelationsEnforcedPanel project={project} collection={data.name}
+                                  enforced={data.relations_enforced} />
 
           {/* Quick actions */}
           <div className="flex items-center justify-end gap-3 pt-1">

+ 3 - 0
webui/src/types/index.ts

@@ -3,6 +3,9 @@ export interface CollectionMeta {
   name: string; kind: 'json' | 'vector'; vector_dimension: number;
   embedding_model: string; created_at: number;
   document_count?: number; size_bytes?: number;
+  /// Readable since client 2.11.4. Absent means the server could not determine
+  /// it, which is never the same as "disabled".
+  relations_enforced?: boolean
 }
 export type KeyOp = 'read' | 'list' | 'search' | 'insert' | 'update' | 'delete'
 export interface KeyScopeRule {