浏览代码

fix(documents): accept the {data:...} wrapper on PUT and PATCH, and stop dropping siblings

POST unwrapped a `{"data":{...}}` body; PUT and PATCH did not. A client that
inserted with the wrapper and updated with the same shape stored the wrapper
itself as a literal field, and nothing said so: no error, and the document only
looked wrong later, when every filter on the real fields matched nothing.

The docs are where this came from. llms.txt and openapi.json documented the
wrapper for POST and gave PUT/PATCH a bare object with no hint one existed, so
using one shape throughout was the natural reading.

All three verbs now share documentBody():

- `{"data":{...}}` and a bare document both store identical content.
- `id` is never a field. POST reads the document id from the body, PUT and
  PATCH from the URL, and it is stripped from what gets stored.
- `data` alongside any other top-level key is 422 ambiguous_body. POST
  previously took body["data"] and discarded the siblings silently, which is
  data loss on the insert path that nobody had noticed; making PUT and PATCH
  unwrap would have spread it to them. Merging the siblings instead would have
  invented a rule the API never promised and silently moved existing callers'
  fields under `data`, breaking their filters - so this errors rather than
  reshapes.
- A document whose own top-level field is called `data` is still writable by
  nesting it once: {"data":{"data":...}}.

Reported against a stats service that re-ran an insert-then-update cycle. Two
details of that report are worth correcting for the record: PUT replaces, so a
repeated run does not nest progressively - the damage is one wrong level, not
unbounded growth; and the silent sibling drop on POST was not part of the
report but is the more dangerous half.

packaging/devstack/run-tests.sh builds and runs the suite in Debian 13 with a
real database in the container, because the Void dev host cannot build the C++
at all (protobuf 35 removed a header the generated protos include). It is how
these tests were run: 164/164.
fszontagh 1 月之前
父节点
当前提交
f6598b12a4
共有 6 个文件被更改,包括 210 次插入 和 10 次删除
  1. 1 0
      CLAUDE.md
  2. 5 3
      api/llms.txt
  3. 14 3
      api/openapi.json
  4. 54 0
      packaging/devstack/run-tests.sh
  5. 46 4
      src/handlers/documents.cpp
  6. 90 0
      tests/test_api_integration.cpp

+ 1 - 0
CLAUDE.md

@@ -61,6 +61,7 @@ docker run -d --name svapi-dev -p 8080:8080 -e SMARTBOTIC_VECTORAPI_KEY=dev svap
 - **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`.
+- **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`.
 

+ 5 - 3
api/llms.txt

@@ -65,10 +65,12 @@ Collection names may not start with `_` or the reserved prefix `vectorapi_`.
 
 Arbitrary JSON CRUD under a `kind=json` collection.
 
-- `POST  /api/v1/projects/{project}/collections/{name}/documents` `{data:{...}}` - Insert a document. Returns `{id}`. Optional `?ttl_seconds=N` query param sets an expiry; absent means no expiry.
+- `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.
+
+  **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}` - Replace a document (full upsert).
-- `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` - Partially update a document (merge fields). Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
+- `PUT   /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Replace a document (full upsert). Accepts the same two body shapes as POST.
+- `PATCH /api/v1/projects/{project}/collections/{name}/documents/{id}` `{data:{...}}` or `{...}` - Partially update a document (merge fields); accepts the same two body shapes as POST, and merges the fields INSIDE a `data` wrapper rather than a field called `data`. Optional `?ttl_seconds=N`: **omitted leaves the existing expiry untouched**; `ttl_seconds=0` **clears** it (document becomes permanent) - do not assume 0 means "no change".
 - `DELETE /api/v1/projects/{project}/collections/{name}/documents/{id}` - Delete a document. Returns **409** `relation_restricted` (with `error.details.impacts`) if a restrict relation has children referencing it; see delete-impact below to preview this first.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents` - Find documents.
 - `GET   /api/v1/projects/{project}/collections/{name}/documents/{id}/delete-impact` - Preview what deleting this document would affect, without deleting it: `{would_be_blocked, impacts:[{relation, child_collection, child_field, on_delete, child_count, sample_child_ids, blocks}]}`. Read-only; follows the collection's read grant (a scoped key with a read rule may call it).

+ 14 - 3
api/openapi.json

@@ -626,10 +626,15 @@
             "application/json": {
               "schema": {
                 "type": "object",
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. `id` here is the document id, not a field, and is stripped from what is stored.",
                 "properties": {
+                  "id": {
+                    "type": "string",
+                    "description": "Optional document id; generated when omitted"
+                  },
                   "data": {
                     "type": "object",
-                    "description": "Arbitrary JSON document payload"
+                    "description": "The document, when using the wrapper shape"
                   }
                 }
               }
@@ -707,7 +712,10 @@
           "required": true,
           "content": {
             "application/json": {
-              "schema": { "type": "object" }
+              "schema": {
+                "type": "object",
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. An `id` in the body is ignored: the URL supplies it."
+              }
             }
           }
         },
@@ -736,7 +744,10 @@
           "required": true,
           "content": {
             "application/json": {
-              "schema": { "type": "object" }
+              "schema": {
+                "type": "object",
+                "description": "Either {\"data\":{...}} or the document itself; both store identical content. A `data` key alongside any other top-level field (other than `id`) returns 422 ambiguous_body instead of silently dropping those fields. To store a document whose own top-level field is called `data`, nest it once: {\"data\":{\"data\":...}}. PATCH merges the fields INSIDE the wrapper, not a field called `data`. An `id` in the body is ignored: the URL supplies it."
+              }
             }
           }
         },

+ 54 - 0
packaging/devstack/run-tests.sh

@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# Build and run the C++ test suite in Debian 13, because the Void dev host
+# cannot: 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.
+#
+# Runs smartbotic-database inside the same container, so the ApiFixture
+# integration tests actually execute instead of GTEST_SKIP()ing.
+#
+#   packaging/devstack/run-tests.sh                 # whole suite
+#   packaging/devstack/run-tests.sh 'ApiFixture.*'  # a ctest -R filter
+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}"
+FILTER="${1:-}"
+
+docker image inspect "$BASE_IMAGE" >/dev/null 2>&1 || {
+    echo "base image $BASE_IMAGE missing; build it with packaging/build.sh --rebuild-base" >&2
+    exit 1
+}
+[[ -f "$DB_DEB" ]] || { echo "database deb not found: $DB_DEB" >&2; exit 1; }
+
+# The build tree is kept inside the container (a named volume) rather than in
+# the repo: objects built against Debian's toolchain must never be mixed with
+# whatever the host left in build/.
+docker run --rm \
+    -v "$REPO:/src:ro" \
+    -v svapi-testbuild:/build \
+    -v "$DB_DEB:/tmp/db.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
+        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
+            (exec 3<>/dev/tcp/127.0.0.1/9004) 2>/dev/null && break
+            sleep 1
+        done
+        (exec 3<>/dev/tcp/127.0.0.1/9004) 2>/dev/null || { echo "database never came up:"; tail -20 /tmp/db.log; exit 1; }
+
+        cmake -B /build -G Ninja -DCMAKE_BUILD_TYPE=Release \
+              -DBUILD_TESTS=ON -DBUILD_WEBUI=OFF -S /src
+        cmake --build /build -j"$(nproc)"
+        if [[ -n "${CTEST_FILTER:-}" ]]; then
+            ctest --test-dir /build --output-on-failure -R "$CTEST_FILTER"
+        else
+            ctest --test-dir /build --output-on-failure
+        fi
+    '

+ 46 - 4
src/handlers/documents.cpp

@@ -3,11 +3,53 @@
 #include "filters.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
+#include <string>
+#include <vector>
 #include <cstdlib>
 #include <limits>
 #include <optional>
 namespace svapi {
 namespace {
+
+/// The document carried by a write request, accepting both shapes:
+///
+///   {"data": {...}}   a wrapper, unwrapped here
+///   {...}             the document itself
+///
+/// `id` is never a field: POST takes the document id from the body, PUT and
+/// PATCH from the URL, so it is removed either way.
+///
+/// A `data` key next to any OTHER top-level key is refused. Taking body["data"]
+/// and discarding the siblings loses them silently, which is how a caller ends
+/// up missing fields with nothing in the response to say so.
+///
+/// A document whose own top-level field is named `data` is still writable by
+/// nesting it once: {"data": {"data": ...}}.
+nlohmann::json documentBody(const nlohmann::json& body) {
+    if (!body.is_object())
+        throw ApiError(ErrCode::Unprocessable, "validation", "body must be a JSON object");
+
+    if (body.contains("data")) {
+        std::vector<std::string> siblings;
+        for (auto it = body.begin(); it != body.end(); ++it)
+            if (it.key() != "data" && it.key() != "id") siblings.push_back(it.key());
+        if (!siblings.empty()) {
+            std::string list;
+            for (const auto& k : siblings) list += (list.empty() ? "" : ", ") + k;
+            throw ApiError(ErrCode::Unprocessable, "ambiguous_body",
+                           "'data' is treated as a wrapper and must be the only top-level field, "
+                           "but found alongside: " + list +
+                           ". Send the document on its own, or nest it as {\"data\":{\"data\":...}}.");
+        }
+        nlohmann::json data = body["data"];
+        if (data.is_object() && data.contains("id")) data.erase("id");
+        return data;
+    }
+
+    nlohmann::json doc = body;
+    if (doc.contains("id")) doc.erase("id");
+    return doc;
+}
 // Authorize + verify the collection exists; returns the qualified collection name.
 std::string scoped(ServerDeps* d, const httplib::Request& req, int projIdx, int collIdx, KeyOp op) {
     ApiKey k = requireKey(*d, req);
@@ -37,8 +79,7 @@ void registerDocumentRoutes(ApiServer& s) {
         std::string c = scoped(d, req, 1, 2, KeyOp::Insert);
         auto body = bodyJson(req);
         std::string id = body.value("id", "");
-        nlohmann::json data = body.contains("data") ? body["data"] : body;
-        if (data.is_object() && data.contains("id")) data.erase("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);
         if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
@@ -72,7 +113,7 @@ void registerDocumentRoutes(ApiServer& s) {
     svr.Patch(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");
-        nlohmann::json patchBody = bodyJson(req);
+        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);
@@ -83,7 +124,8 @@ void registerDocumentRoutes(ApiServer& s) {
     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, bodyJson(req))) throw ApiError(ErrCode::Unavailable, "db_error", "update failed");
+        if (!d->db.client().update(c, id, documentBody(bodyJson(req))))
+            throw ApiError(ErrCode::Unavailable, "db_error", "update failed");
         sendJson(res, 200, {{"id", id}});
     });
 

+ 90 - 0
tests/test_api_integration.cpp

@@ -1606,3 +1606,93 @@ TEST_F(ApiFixture, VectorSearchFilteredScoresMatchUnfilteredScores) {
     ASSERT_GT(plain, 0.0);
     EXPECT_NEAR(plain, filtered, 1e-6);
 }
+
+// --- document body shape: {data:{...}} vs a bare document --------------------
+
+namespace {
+// The stored document minus the server's own _-prefixed metadata.
+nlohmann::json storedFields(const nlohmann::json& doc) {
+    nlohmann::json out = nlohmann::json::object();
+    for (auto it = doc.begin(); it != doc.end(); ++it)
+        if (it.key().rfind("_", 0) != 0) out[it.key()] = it.value();
+    return out;
+}
+}  // namespace
+
+TEST_F(ApiFixture, DocumentWrapperIsUnwrappedOnEveryWriteVerb) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","shapes"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/shapes/documents";
+    auto read = [&](const std::string& id) {
+        auto r = c.Get((docs + "/" + id).c_str());
+        EXPECT_EQ(r->status, 200);
+        const nlohmann::json parsed = nlohmann::json::parse(r->body);
+        return storedFields(parsed);
+    };
+
+    // POST accepts both shapes already.
+    ASSERT_EQ(c.Post(docs.c_str(),
+        nlohmann::json{{"id","w"},{"data",{{"k","x"},{"n",1}}}}.dump(), "application/json")->status, 201);
+    EXPECT_EQ(read("w"), (nlohmann::json{{"k","x"},{"n",1}}));
+
+    ASSERT_EQ(c.Post(docs.c_str(),
+        nlohmann::json{{"id","f"},{"k","x"},{"n",1}}.dump(), "application/json")->status, 201);
+    EXPECT_EQ(read("f"), (nlohmann::json{{"k","x"},{"n",1}}));
+
+    // PUT must unwrap too, instead of storing the wrapper as a literal field.
+    ASSERT_EQ(c.Put((docs + "/w").c_str(),
+        nlohmann::json{{"data",{{"k","x"},{"n",2}}}}.dump(), "application/json")->status, 200);
+    EXPECT_EQ(read("w"), (nlohmann::json{{"k","x"},{"n",2}}))
+        << "PUT stored the {data:...} wrapper instead of unwrapping it";
+
+    ASSERT_EQ(c.Put((docs + "/f").c_str(),
+        nlohmann::json{{"k","x"},{"n",3}}.dump(), "application/json")->status, 200);
+    EXPECT_EQ(read("f"), (nlohmann::json{{"k","x"},{"n",3}}));
+
+    // PATCH merges the unwrapped fields, not a nested `data` object.
+    ASSERT_EQ(c.Patch((docs + "/f").c_str(),
+        nlohmann::json{{"data",{{"n",4}}}}.dump(), "application/json")->status, 200);
+    EXPECT_EQ(read("f"), (nlohmann::json{{"k","x"},{"n",4}}))
+        << "PATCH merged a literal `data` field instead of the fields inside it";
+}
+
+TEST_F(ApiFixture, DataAlongsideSiblingKeysIsRejected) {
+    // Taking body["data"] and discarding the siblings loses data silently, and
+    // the intent is genuinely ambiguous. Refuse it on every verb.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","amb"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/amb/documents";
+    ASSERT_EQ(c.Post(docs.c_str(), nlohmann::json{{"id","seed"},{"k","x"}}.dump(),
+                     "application/json")->status, 201);
+
+    const std::string ambiguous = nlohmann::json{{"data",{{"k","x"}}},{"extra",99}}.dump();
+    auto post = c.Post(docs.c_str(), ambiguous, "application/json");
+    EXPECT_EQ(post->status, 422) << post->body;
+    auto put = c.Put((docs + "/seed").c_str(), ambiguous, "application/json");
+    EXPECT_EQ(put->status, 422) << put->body;
+    auto patch = c.Patch((docs + "/seed").c_str(), ambiguous, "application/json");
+    EXPECT_EQ(patch->status, 422) << patch->body;
+
+    // The seed document is untouched by the rejected writes.
+    const nlohmann::json after = nlohmann::json::parse(c.Get((docs + "/seed").c_str())->body);
+    EXPECT_EQ(storedFields(after), (nlohmann::json{{"k","x"}}));
+}
+
+TEST_F(ApiFixture, ALiteralDataFieldCanStillBeStored) {
+    // The unwrap would otherwise make a top-level field named `data`
+    // unreachable; nesting it once is the escape hatch.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    ASSERT_EQ(c.Post(base.c_str(), nlohmann::json{{"name","lit"},{"kind","json"}}.dump(),
+                     "application/json")->status, 201);
+    const std::string docs = base + "/lit/documents";
+    ASSERT_EQ(c.Post(docs.c_str(),
+        nlohmann::json{{"id","d"},{"data",{{"data",{{"inner",1}}}}}}.dump(),
+        "application/json")->status, 201);
+    const nlohmann::json got = nlohmann::json::parse(c.Get((docs + "/d").c_str())->body);
+    EXPECT_EQ(storedFields(got), (nlohmann::json{{"data",{{"inner",1}}}}));
+}