Browse Source

build: 0.13.0 - collection schema, the index-route fixes, and the client pin

1259/1259 green. curl 8.23.0 is still not out (upstream is 8.22.0; it ships
14 Oct), so this is everything else that was ready.

Moves DB_CLIENT_VERSION to 2.17.2-1 and both Depends floors to >= 2.17.2.
That is required rather than optional: the schema handler cannot compile
against 2.14.0 headers, and every 2.x client shares one soname, so leaving
the floor low would let apt install a binary against a client that cannot
resolve the calls. Prod already runs 2.17.2-1, so the floor is satisfied
there - which is why this was unsafe yesterday and is safe today. Built with
--rebuild-base; the stale help text claiming a 2.11.4-1 default is corrected.

Contents:
- the optional per-collection JSON Schema, four routes plus the web UI panel
- encrypted_field on the INDEX route, via the FailureDetail overloads that
  upstream added rather than growing CreateIndexResult. An index on a field
  the database stores encrypted used to fall through to 503 db_error - "retry
  as-is" for something no retry can fix, the mirror of the FailedPrecondition
  bug. Now 422 encrypted_field. The duplicate-values path is unchanged and
  tested, because the new reason branch must not swallow the in-band case.
- the index-values route stops accepting parameters it cannot honour. offset,
  page, cursor, sort, fields, after and skip are 422 unknown_option naming
  what was sent and what is accepted. ?offset=N previously answered 200 with
  the FIRST page, so a caller paginating looped forever believing it was
  progressing. An incidental parameter - a cache-buster, a proxy's addition -
  is still ignored rather than refused: refusing offset is the point,
  refusing _=1760000000 would be a regression.
- truncated on that route, ALWAYS present, so an absent truncated means only
  "older than 0.13.0" and never "complete". No invented total: nothing counts
  distinct values, and a number we could not stand behind is worse than none.

BREAKING for one shape: a caller sending offset to index-values now gets 422
where it previously got a silently wrong 200. That is the fix, and consumers
are being told before the deploy rather than after.

Also: encrypted_field stops being dormant, because the client pin is what was
holding it. Docs say so rather than still promising it for "when the pin
moves".
fszontagh 1 tháng trước cách đây
mục cha
commit
953479409b

+ 1 - 1
VERSION

@@ -1 +1 @@
-0.12.0
+0.13.0

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 1 - 1
api/llms.txt


+ 23 - 4
api/openapi.json

@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "smartbotic-vectorapi",
-    "version": "0.12.0",
+    "version": "0.13.0",
     "description": "General-purpose REST API fronting smartbotic-database. Supports multi-project namespacing and multi-key authorization with per-project grants."
   },
   "components": {
@@ -2325,7 +2325,7 @@
       ],
       "get": {
         "summary": "Distinct values of an indexed field, with per-value counts",
-        "description": "Index-dependent by design, not an error: returns an empty values list with HTTP 200 when `field` has no index, and also for array-valued fields, whose index keys are the individual array elements rather than the field's own value. Follows the collection's read grant, so a scoped key with a read rule on this collection may call it. Use order=desc&limit=1 to get the maximum value.",
+        "description": "Distinct values of an indexed field with their counts. Index-dependent: an empty list for an unindexed field and for array-valued fields. limit is 1..1000 (default 100). THIS ROUTE IS NOT PAGINATED AND HAS NO TOTAL: offset, page, cursor, sort, fields, after and skip are refused 422 unknown_option, naming what was sent and what is accepted - previously ?offset=N answered 200 with the first page, so a caller paginating looped forever. An incidental parameter such as a cache-buster is still ignored rather than refused. truncated is ALWAYS present, true or false, so an absent truncated means only a server older than 0.13.0 and never 'complete'; limit echoes the cap when truncated is true. There is no total: nothing counts distinct values, and a field with more distinct values than the cap returns a partial facet whose counts sum to less than the collection.",
         "operationId": "indexFieldValues",
         "parameters": [
           {
@@ -2355,11 +2355,15 @@
         ],
         "responses": {
           "200": {
-            "description": "Distinct values with counts (possibly empty; see description)",
+            "description": "Distinct values with counts",
             "content": {
               "application/json": {
                 "schema": {
                   "type": "object",
+                  "required": [
+                    "values",
+                    "truncated"
+                  ],
                   "properties": {
                     "values": {
                       "type": "array",
@@ -2372,6 +2376,14 @@
                           }
                         }
                       }
+                    },
+                    "truncated": {
+                      "type": "boolean",
+                      "description": "Always present. True when there may be more values than returned."
+                    },
+                    "limit": {
+                      "type": "integer",
+                      "description": "The cap that bit; present only when truncated is true."
                     }
                   }
                 }
@@ -2385,7 +2397,14 @@
             "description": "Forbidden"
           },
           "422": {
-            "description": "Validation error (limit out of 1..1000 range or non-numeric)"
+            "description": "unknown_option - a parameter this route cannot honour (offset, page, cursor, sort, fields, after, skip), or validation for a limit outside 1..1000",
+            "content": {
+              "application/json": {
+                "schema": {
+                  "$ref": "#/components/schemas/Error"
+                }
+              }
+            }
           },
           "429": {
             "description": "Too Many Requests (rate-limited scoped key)"

+ 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.14.0-1
+ARG DB_CLIENT_VERSION=2.17.2-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.14.0-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.17.2-1}"
 BUILD_JOBS="${BUILD_JOBS:-$(nproc)}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
 
@@ -122,7 +122,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.4-1)
+                       the deploy target (default: 2.17.2-1)
 EOF
     exit 0
 }

+ 1 - 1
packaging/deb/templates/control.runner

@@ -12,7 +12,7 @@ Description: Smartbotic VectorAPI - server-side function runner
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.14.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
+Depends: libsmartbotic-db-client (>= 2.17.2), libssl3t64, libsystemd0, libspdlog1.15, tzdata, ca-certificates, libidn2-0
 Recommends: smartbotic-vectorapi (= {{VERSION}})
 Breaks: smartbotic-vectorapi (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 1 - 1
packaging/deb/templates/control.server

@@ -10,7 +10,7 @@ Description: Smartbotic VectorAPI — REST API for RAG vectors and JSON
 Homepage: https://smartbotics.ai
 Section: contrib/utils
 Priority: optional
-Depends: libsmartbotic-db-client (>= 2.14.0), libssl3t64, libsystemd0, libspdlog1.15, tzdata
+Depends: libsmartbotic-db-client (>= 2.17.2), libssl3t64, libsystemd0, libspdlog1.15, tzdata
 Recommends: smartbotic-vectorapi-webui (= {{VERSION}})
 Breaks: smartbotic-vectorapi-runner (<< {{UPSTREAM_VERSION}})
 Installed-Size: {{INSTALLED_SIZE}}

+ 88 - 8
src/handlers/indexes.cpp

@@ -16,7 +16,31 @@ namespace {
 /// the generic 503 - a caller that must now de-duplicate its data needs the
 /// examples whichever form it used.
 ApiError indexDeclineError(const smartbotic::database::Client::CreateIndexResult& r,
+                           const smartbotic::database::Client::FailureDetail& f,
                            const std::string& what) {
+    // A PERMANENT refusal must not be reported as a transient one. Database
+    // 2.17.0 refuses an index on a field it stores encrypted, and before the
+    // FailureDetail overloads existed that arrived here indistinguishable from
+    // an outage and fell through to 503 `db_error` - whose whole meaning is
+    // "retry as-is", for something no retry can ever fix. That is the mirror
+    // of the FailedPrecondition bug: this one told a caller its own permanent
+    // mistake was our outage, so it would wait forever instead of changing the
+    // field.
+    //
+    // Upstream deliberately added `FailureDetail&` OVERLOADS rather than
+    // growing CreateIndexResult: that struct is returned BY VALUE, so adding a
+    // member changes its size under one soname, which is what crashed a
+    // consumer in 2.7.1. We asked for the field and were right to be refused.
+    if (!f.reason.empty() || f.code != smartbotic::database::Client::ErrorCode::Ok) {
+        // An IN-BAND refusal (status OK, success=false) arrives as code
+        // Unknown with no reason, and the duplicate-values case below still
+        // owns that path - so only translate when there is something to
+        // translate.
+        if (f.reason == "encrypted_field" ||
+            f.code == smartbotic::database::Client::ErrorCode::InvalidArgument ||
+            f.code == smartbotic::database::Client::ErrorCode::FailedPrecondition)
+            return apiErrorFor(f, "no such collection");
+    }
     if (!r.duplicateExamples.empty()) {
         nlohmann::json ex = nlohmann::json::array();
         for (const auto& id : r.duplicateExamples) ex.push_back(id);
@@ -63,9 +87,10 @@ void registerIndexRoutes(ApiServer& s) {
             throw ApiError(ErrCode::NotFound, "not_found", "collection not found");
 
         if (want.composite()) {
-            auto r = d->db.client().createCompositeUniqueIndex(qc, want.fields);
+            smartbotic::database::Client::FailureDetail f;
+            auto r = d->db.client().createCompositeUniqueIndex(qc, want.fields, f);
             if (!r.success)
-                throw indexDeclineError(r, "the combination of fields");
+                throw indexDeclineError(r, f, "the combination of fields");
             nlohmann::json out = compositeJson(want.fields);
             out["rows_indexed"] = r.rowsIndexed;
             out["already_existed"] = r.alreadyExisted;
@@ -75,9 +100,10 @@ void registerIndexRoutes(ApiServer& s) {
 
         const std::string& field = want.field;
         if (want.unique) {
-            auto r = d->db.client().createUniqueIndex(qc, field);
+            smartbotic::database::Client::FailureDetail f;
+            auto r = d->db.client().createUniqueIndex(qc, field, f);
             if (!r.success)
-                throw indexDeclineError(r, "field '" + field + "'");
+                throw indexDeclineError(r, f, "field '" + field + "'");
             sendJson(res, 201, {{"field", field}, {"unique", true},
                                 {"rows_indexed", r.rowsIndexed},
                                 {"already_existed", r.alreadyExisted}});
@@ -93,8 +119,13 @@ void registerIndexRoutes(ApiServer& s) {
         }
 
         uint64_t rows = 0;
-        if (!d->db.client().createIndex(qc, field, rows))
-            throw ApiError(ErrCode::Unavailable, "db_error", "failed to create index");
+        smartbotic::database::Client::FailureDetail f;
+        if (!d->db.client().createIndex(qc, field, rows, f)) {
+            // The non-unique path had no way to report a reason at all before
+            // 2.17.2, so an encrypted field here was a flat 503.
+            smartbotic::database::Client::CreateIndexResult empty;
+            throw indexDeclineError(empty, f, "field '" + field + "'");
+        }
         sendJson(res, 201, {{"field", field}, {"unique", false},
                             {"rows_indexed", rows}, {"already_existed", alreadyExisted}});
     });
@@ -188,10 +219,44 @@ void registerIndexRoutes(ApiServer& s) {
         std::string project = req.matches[1], coll = req.matches[2], field = req.matches[3];
         requireCapability(*d, k, req, project, coll, KeyOp::Read);
 
+        // REFUSE a parameter a caller sends EXPECTING AN EFFECT that this route
+        // does not implement. Measured on prod: `?offset=1000` answered 200
+        // with the FIRST page, because the handler reads only `limit` and
+        // `order` and the client's indexValues() has no offset to honour - so
+        // a caller paginating looped forever believing it was progressing. A
+        // 200 with the wrong answer to a well-formed request, which is exactly
+        // what the search body refuses as `unknown_option`; that lesson was
+        // applied to the handler where it was learned and not to this one.
+        //
+        // NOT a blanket refusal of unknown query params, deliberately. Every
+        // key in a JSON body is deliberate, but a query string legitimately
+        // collects things nobody meant as options - a cache-buster, a proxy's
+        // addition, a UI's `_=<timestamp>` - so refusing everything unknown
+        // would be a regression. Refusing `offset` is the point; refusing
+        // `_=1760000000` is not.
+        static constexpr const char* kPretenders[] = {"offset", "page", "cursor",
+                                                      "sort", "fields", "after", "skip"};
+        std::vector<std::string> pretending;
+        for (const char* k : kPretenders)
+            if (req.has_param(k)) pretending.push_back(k);
+        if (!pretending.empty()) {
+            std::string names;
+            for (size_t i = 0; i < pretending.size(); ++i)
+                names += (i ? ", " : "") + pretending[i];
+            throw ApiError(ErrCode::Unprocessable, "unknown_option",
+                           "this route does not support " + names +
+                               ". It is not paginated and has no total: it returns at most "
+                               "`limit` distinct values (max 1000) and sets `truncated` when "
+                               "there may be more. Accepted parameters are `limit` and `order`.",
+                           {{"unsupported", pretending},
+                            {"accepted", nlohmann::json::array({"limit", "order"})}});
+        }
+
+        constexpr uint32_t kValuesLimitCap = 1000;
         uint32_t limit = 100;
         if (req.has_param("limit")) {
             unsigned long wide = std::strtoul(req.get_param_value("limit").c_str(), nullptr, 10);
-            if (wide == 0 || wide > 1000)
+            if (wide == 0 || wide > kValuesLimitCap)
                 throw ApiError(ErrCode::Unprocessable, "validation", "limit must be 1..1000");
             limit = (uint32_t)wide;
         }
@@ -200,7 +265,22 @@ void registerIndexRoutes(ApiServer& s) {
         auto vals = d->db.client().indexValues(qualify(project, coll), field, limit, ascending);
         nlohmann::json out = nlohmann::json::array();
         for (const auto& v : vals) out.push_back({{"value", v.value}, {"count", v.count}});
-        sendJson(res, 200, {{"values", out}});
+        // `truncated` is emitted UNCONDITIONALLY, true or false, never omitted -
+        // the same rule as `filter_mode` and `scan_capped`, so an ABSENT field
+        // means exactly one thing: a server older than this release. Emitting
+        // it only when true would recreate the ambiguity those two were fixed
+        // for. It was the absence of any such flag that let a consumer read a
+        // 1000-value page summing to 72% of a collection as a DATA anomaly on
+        // one field rather than a limit of this route - it looks like a field
+        // problem because only high-cardinality fields cross the cap.
+        //
+        // There is deliberately NO total: the client offers no distinct-value
+        // count and count() counts rows, not distinct values. A number we
+        // cannot stand behind would be worse than saying there is none.
+        const bool truncated = vals.size() >= limit;
+        nlohmann::json body = {{"values", out}, {"truncated", truncated}};
+        if (truncated) body["limit"] = limit;
+        sendJson(res, 200, body);
     });
 
     svr.Delete(R"(/api/v1/projects/([^/]+)/collections/([^/]+)/indexes/([^/]+))",

+ 132 - 0
tests/test_api_integration.cpp

@@ -4007,3 +4007,135 @@ TEST_F(ApiFixture, SchemaRoutesRefuseUnknownOptionsAndReportTheirOwnSlugs) {
                      "application/json")->status, 201);
     c.Delete(base.c_str());
 }
+
+// --- the index-values route: refuse what we cannot honour -------------------
+//
+// `?offset=1000` used to answer 200 with the FIRST page, because the handler
+// reads only `limit` and `order` and the client has no offset to honour. A
+// caller paginating looped forever believing it was progressing. The 0.10.3
+// lesson - an unknown option is refused, not ignored - had been applied to the
+// search body and not to its neighbour.
+TEST_F(ApiFixture, IndexValuesRefusesParamsItCannotHonourButIgnoresIncidentalOnes) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/idxvals";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "idxvals"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    for (int i = 0; i < 15; ++i)
+        c.Post((base + "/documents").c_str(),
+               nlohmann::json{{"id", "d" + std::to_string(i)},
+                              {"tag", "t" + std::to_string(i)}}.dump(), "application/json");
+    ASSERT_EQ(c.Post((base + "/indexes").c_str(),
+                     nlohmann::json{{"field", "tag"}}.dump(), "application/json")->status, 201);
+
+    // Each of these is something a caller sends EXPECTING an effect.
+    for (const char* q : {"offset=5", "page=2", "cursor=abc", "sort=tag", "fields=tag",
+                          "after=t1", "skip=3"}) {
+        auto res = c.Get((base + "/indexes/tag/values?limit=5&" + q).c_str());
+        ASSERT_TRUE(res) << q;
+        ASSERT_EQ(res->status, 422) << q << ": " << res->body;
+        auto err = nlohmann::json::parse(res->body)["error"];
+        EXPECT_EQ(err.value("code", ""), "unknown_option") << q;
+        // Names what it refused AND what it accepts, because the usual cause
+        // is a plausible spelling of something that does not exist here.
+        EXPECT_FALSE(err["details"]["unsupported"].empty()) << q;
+        EXPECT_FALSE(err["details"]["accepted"].empty()) << q;
+    }
+    // Every offender is named at once rather than one per round trip.
+    auto both = c.Get((base + "/indexes/tag/values?offset=1&page=2").c_str());
+    ASSERT_EQ(both->status, 422);
+    EXPECT_EQ(nlohmann::json::parse(both->body)["error"]["details"]["unsupported"].size(), 2u);
+
+    // AND a blanket refusal would be a regression: a query string legitimately
+    // collects cache-busters and proxy additions that nobody meant as options.
+    auto incidental = c.Get((base + "/indexes/tag/values?limit=5&_=1760000000").c_str());
+    ASSERT_TRUE(incidental);
+    EXPECT_EQ(incidental->status, 200) << "an incidental param must not be refused: "
+                                       << incidental->body;
+    c.Delete(base.c_str());
+}
+
+TEST_F(ApiFixture, IndexValuesAlwaysReportsTruncatedSoAbsenceMeansOnlyOldServer) {
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/idxtrunc";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "idxtrunc"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    for (int i = 0; i < 12; ++i)
+        c.Post((base + "/documents").c_str(),
+               nlohmann::json{{"id", "d" + std::to_string(i)},
+                              {"tag", "t" + std::to_string(i)}}.dump(), "application/json");
+    ASSERT_EQ(c.Post((base + "/indexes").c_str(),
+                     nlohmann::json{{"field", "tag"}}.dump(), "application/json")->status, 201);
+
+    // Truncated: fewer returned than exist.
+    auto cut = c.Get((base + "/indexes/tag/values?limit=5").c_str());
+    ASSERT_EQ(cut->status, 200) << cut->body;
+    auto bc = nlohmann::json::parse(cut->body);
+    EXPECT_TRUE(bc.value("truncated", false)) << cut->body;
+    EXPECT_EQ(bc.value("limit", 0u), 5u) << "the cap rides along when truncated";
+
+    // NOT truncated - and the field is still PRESENT and false. Emitting it
+    // only when true would recreate the ambiguity `scan_capped` and
+    // `filter_mode` were fixed for: absence must mean exactly one thing, "a
+    // server older than this release", never "complete".
+    auto full = c.Get((base + "/indexes/tag/values?limit=100").c_str());
+    ASSERT_EQ(full->status, 200) << full->body;
+    auto bf = nlohmann::json::parse(full->body);
+    ASSERT_TRUE(bf.contains("truncated")) << "must be present even when false: " << full->body;
+    EXPECT_FALSE(bf.value("truncated", true));
+    EXPECT_FALSE(bf.contains("limit")) << "the cap is only meaningful when truncated";
+    c.Delete(base.c_str());
+}
+
+// An index on a field the database stores ENCRYPTED is a PERMANENT refusal.
+// It used to arrive indistinguishable from an outage and fall through to 503
+// `db_error` - "retry as-is" for something no retry can fix, which is the
+// mirror of the FailedPrecondition bug. Fixed upstream as FailureDetail
+// OVERLOADS rather than new CreateIndexResult fields, because that struct is
+// returned by value and growing it changes its size under one soname.
+TEST_F(ApiFixture, AnIndexOnAnEncryptedFieldIsRefusedPermanentlyNotAs503) {
+    if (!db_->client().serverSupports(
+            smartbotic::database::Client::Capability::kEncryptionAtRest)) {
+        GTEST_SKIP() << "database has no encryption-at-rest capability";
+    }
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections/idxenc";
+    c.Delete(base.c_str());
+    ASSERT_EQ(c.Post(("/api/v1/projects/" + project_ + "/collections").c_str(),
+                     nlohmann::json{{"name", "idxenc"}, {"kind", "json"}}.dump(),
+                     "application/json")->status, 201);
+    // `token` matches the database's built-in sensitive names at any depth, so
+    // it is stored as ciphertext in every collection.
+    ASSERT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "a"}, {"token", "secret-ish"}}.dump(),
+                     "application/json")->status, 201);
+
+    for (bool unique : {false, true}) {
+        auto res = c.Post((base + "/indexes").c_str(),
+                          nlohmann::json{{"field", "token"}, {"unique", unique}}.dump(),
+                          "application/json");
+        ASSERT_TRUE(res);
+        // 422, NOT 503: the caller must change the field, and waiting never helps.
+        ASSERT_EQ(res->status, 422) << "unique=" << unique << ": " << res->body;
+        EXPECT_EQ(nlohmann::json::parse(res->body)["error"].value("code", ""), "encrypted_field")
+            << "unique=" << unique << ": " << res->body;
+    }
+
+    // The duplicate-values refusal must still report itself as such - the new
+    // reason branch must not swallow the in-band case.
+    ASSERT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "x"}, {"sku", "S"}}.dump(), "application/json")->status,
+              201);
+    ASSERT_EQ(c.Post((base + "/documents").c_str(),
+                     nlohmann::json{{"id", "y"}, {"sku", "S"}}.dump(), "application/json")->status,
+              201);
+    auto dup = c.Post((base + "/indexes").c_str(),
+                      nlohmann::json{{"field", "sku"}, {"unique", true}}.dump(),
+                      "application/json");
+    ASSERT_EQ(dup->status, 409) << dup->body;
+    EXPECT_EQ(nlohmann::json::parse(dup->body)["error"].value("code", ""), "duplicate_values");
+    c.Delete(base.c_str());
+}

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác