ソースを参照

feat: database client 2.13.0, and a size refusal stops saying "retry"

Pins DB_CLIENT_VERSION 2.12.0-1 -> 2.13.0-1 in both places it is
written. The pin was already out of step: packages were built against
2.12.0 headers while prod ran a 2.12.3 server. Needs --rebuild-base,
since the client is baked into the Docker base image.

ResourceExhausted had ONE answer for four unrelated refusals, and 429
"wait" was wrong for one of them. The database now names them, and the
classification lives in its library, so we branch on `reason` and never
on gRPC's wording:

  message_too_large -> 422 message_too_large
  memory_pressure   -> 429 memory_pressure
  no reason         -> 429 rate_limited (a real rate limit, or the
                       database's export concurrency cap)

422 for a size refusal because no amount of waiting shrinks a payload,
and 500 would blame us for a definite, explainable refusal. The slug is
deliberately NOT `body_too_large`, though we already use that name in
the function runtime: the limit applies in EITHER direction, and a
stored row can grow past it through repeated patches until it can no
longer be read back - measured on a scratch server, 60 MiB insert then
patches to ~100 MB, after which get() itself fails. A caller hitting
that sent nothing large at all, so a slug naming their body would send
them looking in the wrong place. The database's message carries both
sizes and the direction, so it passes through verbatim.

`memory_pressure` gets its own slug despite sharing 429 and the same
remedy, because the DIAGNOSIS differs: `rate_limited` tells a caller it
is sending too much, which is a false accusation when the database is
the one short of memory, and would have it throttle a client that was
never the problem. Same reasoning as `read_only` having its own slug
while also meaning "wait".

CollectionRegistry::get loses its workaround entirely. It read twice
and then asked healthCheck() before daring to report absence, all to
compensate for Client::get returning nothing for both "absent" and
"transport failed" - the ambiguity that cost a consumer a 6-minute
ingest by surfacing as an unretryable 404. 2.13.0 throws on a failed
read and answers nothing only for a genuine absence, so the workaround
is deleted rather than kept: a retry that can no longer distinguish
anything is a slower wrong answer, and leaving it would hide the real
behaviour from the next reader. The message is kept, because "cannot
determine whether collection 'x' exists" says which question went
unanswered where a generic 503 would not.

The existing test caught this during the upgrade and needed no edit:
its assertions were right and the code was wrong, which is what it was
written for.

868 tests pass against the v2.13.0 tag, with the installed header
verified by diff against the tagged source rather than by grep.
fszontagh 1 ヶ月 前
親
コミット
5e80f08400
6 ファイル変更、143 行追加、33 行削除
  1. 1 1
      api/llms.txt
  2. 1 1
      packaging/Dockerfile.base
  3. 1 1
      packaging/build.sh
  4. 30 30
      src/collection_registry.cpp
  5. 37 0
      src/db_errors.cpp
  6. 73 0
      tests/test_db_errors.cpp

+ 1 - 1
api/llms.txt

@@ -67,7 +67,7 @@ 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.
 
-  **Other slugs worth branching on.** From the database: `read_only` **503** (the database is refusing writes), `db_unavailable` **503**, `rate_limited` **429** raised by the DATABASE under pressure (distinct from a key's scope rate limit, same status), `internal` **500**. On the routes: `exists` **422** (duplicate collection name), `bad_project` **422**, `last_admin` **422** (refusing to remove the last admin key), `not_vector` **422** (a vector op on a json collection), `dimension_mismatch` **422**, `ambiguous_body` **422**, `file_too_large` **422**, `vector_replace_unsafe` **422**. On `/fn/*`: `function_error` **500** and `method_not_allowed` **405**. On function writes: `no_runner` and `runner_unreachable` both **503**; invoke answers **409** `function_invalid` or `function_disabled`. Inside a function: `jobs_unavailable` **503**, `job_depth_exceeded` **422**, `unsupported_combination` **422**, `body_too_large` **422**, `not_json` **422**, `embedding_timeout` **504**, `fetch_timeout` **504**.
+  **Other slugs worth branching on.** From the database: `read_only` **503** (the database is refusing writes), `db_unavailable` **503**, `rate_limited` **429** raised by the DATABASE under pressure (distinct from a key's scope rate limit, same status), `message_too_large` **422** when a call is refused for size by the transport itself - it is **422 and not 429** because waiting cannot shrink a payload, and it is not named after your body because the limit applies in either direction: a stored document can grow past it through repeated PATCHes until it can no longer be read back, so you may have sent nothing large at all. The message carries both sizes and says which direction it was, and `memory_pressure` **429** when the database's admission control is refusing writes because IT is short of memory - the same remedy as a rate limit (wait, `Retry-After` is set) but deliberately a different slug, because `rate_limited` would have you throttle a client that was never the problem, `internal` **500**. On the routes: `exists` **422** (duplicate collection name), `bad_project` **422**, `last_admin` **422** (refusing to remove the last admin key), `not_vector` **422** (a vector op on a json collection), `dimension_mismatch` **422**, `ambiguous_body` **422**, `file_too_large` **422**, `vector_replace_unsafe` **422**. On `/fn/*`: `function_error` **500** and `method_not_allowed` **405**. On function writes: `no_runner` and `runner_unreachable` both **503**; invoke answers **409** `function_invalid` or `function_disabled`. Inside a function: `jobs_unavailable` **503**, `job_depth_exceeded` **422**, `unsupported_combination` **422**, `body_too_large` **422**, `not_json` **422**, `embedding_timeout` **504**, `fetch_timeout` **504**.
 
   **Write failures carry their cause.** A value already held by a unique index is **409** `duplicate_values`, while a document **id** that is already taken is **409** `duplicate_id` (different remedies: change the value, versus choose another id or upsert with `PUT`) (the same slug `POST /indexes` returns), and `error.details` names the index: **`field`** when one field collided or **`fields`** when several, **`values`** (an OBJECT of the colliding field/value pairs, not a bare `value`), `conflicting_document_id` (the document already holding it), and `relation` or `current_version` where they apply. 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 failed conditional write is **409** `version_conflict`. A missing collection is **404** only when its absence is CONFIRMED: if the database cannot be reached the answer is **503**, never a 404, so a 404 is always safe to treat as definitive and unretryable. 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. **On a `kind=vector` collection, a PUT whose body carries no vector is refused **422** `vector_replace_unsafe`.** A replace discards the stored embedding and the caller cannot prevent it, because no read returns the vector - so there is nothing to put back. Use `PATCH` for fields, or `POST .../vectors` to store a document together with its vector.
 

+ 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.12.0-1
+ARG DB_CLIENT_VERSION=2.13.0-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

+ 1 - 1
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.12.0-1}"
+DB_CLIENT_VERSION="${DB_CLIENT_VERSION:-2.13.0-1}"
 BUILD_JOBS="${BUILD_JOBS:-$(nproc)}"
 DEB_REPO_DIR="${DEB_REPO_DIR:-/data/dev/smartbotics/smartbotics-deb-repo}"
 

+ 30 - 30
src/collection_registry.cpp

@@ -1,4 +1,5 @@
 #include "collection_registry.hpp"
+#include "db_errors.hpp"
 
 #include "errors.hpp"
 
@@ -44,40 +45,39 @@ bool CollectionRegistry::add(const std::string& project, const CollectionMeta& m
 
 std::optional<CollectionMeta> CollectionRegistry::get(const std::string& project,
                                                        const std::string& name) {
-    const std::string c = coll(project);
-    if (auto doc = db_.client().get(c, name)) return CollectionMeta::fromJson(*doc);
-
-    // An empty answer from the client is AMBIGUOUS: `Client::get` returns
-    // nullopt both for "no such document" and for a transport failure, which it
-    // only logs. (It throws for PERMISSION_DENIED precisely so a denial cannot
-    // look like no data; the same reasoning was never extended to UNAVAILABLE.)
+    // Since database client 2.13.0 this is simply honest: a read whose "nothing
+    // there" value is also a valid answer THROWS on a failed call, and returns
+    // nullopt only for a genuine absence. So nullopt means absent, and that is
+    // the whole of it.
     //
-    // Left alone, that ambiguity reaches a caller as 404 "no such collection"
-    // for a collection that exists - and a 404 is unretryable BY DESIGN for a
+    // What used to be here, and why it is gone: `Client::get` returned nullopt
+    // BOTH for "no such document" and for a transport failure, which it only
+    // logged. Left alone that reached a caller as 404 "no such collection" for
+    // a collection that exists - and a 404 is unretryable BY DESIGN for a
     // careful client, because adding it to a retry set would retry every
     // genuine absence. A consumer lost a 6-minute ingest of an 8 GB mailbox to
-    // exactly this, and the collection was present before and after.
-    //
-    // So: ask again. A genuine absence answers nullopt twice and costs one
-    // cheap registry read on a path that was already going to 404. A transient
-    // failure almost always succeeds on the second call, which is both the
-    // correct answer AND cheaper for the caller than a retryable error.
-    if (auto retried = db_.client().get(c, name)) {
-        spdlog::warn("registry lookup for {}:{} failed once and succeeded on retry - a transient "
-                     "database failure was about to be reported as 'no such collection'",
-                     project, name);
-        return CollectionMeta::fromJson(*retried);
+    // exactly that, with the collection present before and after. We worked
+    // around it by reading twice and then asking healthCheck() before daring to
+    // report absence. The database took the report and fixed it at the source,
+    // so the workaround is deleted rather than kept "just in case": a retry
+    // that cannot distinguish anything is just a slower wrong answer, and
+    // keeping it would hide the real behaviour from the next reader.
+    try {
+        if (auto doc = db_.client().get(coll(project), name)) return CollectionMeta::fromJson(*doc);
+        return std::nullopt;
+    } catch (const smartbotic::database::Client::Error& e) {
+        // Keep the message that says what we could not determine. The global
+        // handler would also map this to 503 now, but generically: "cannot
+        // determine whether collection 'x' exists" tells the caller which
+        // question went unanswered, and that is worth preserving on the one
+        // path where a wrong answer is an unretryable 404.
+        ApiError mapped = apiErrorFor(e);
+        if (mapped.code == ErrCode::Unavailable)
+            throw ApiError(ErrCode::Unavailable, "db_error",
+                           "cannot determine whether collection '" + name +
+                               "' exists: the database is not reachable");
+        throw mapped;
     }
-
-    // Still empty. Either it really is absent, or the database is properly
-    // down - and those must not share an answer. healthCheck() is the only
-    // thing that can tell them apart here, and it is asked ONLY on this path,
-    // so a hot lookup never pays for it.
-    if (!db_.client().healthCheck())
-        throw ApiError(ErrCode::Unavailable, "db_error",
-                       "cannot determine whether collection '" + name +
-                           "' exists: the database is not reachable");
-    return std::nullopt;
 }
 
 std::vector<CollectionMeta> CollectionRegistry::list(const std::string& project) {

+ 37 - 0
src/db_errors.cpp

@@ -61,6 +61,43 @@ ApiError translate(Code code, const std::string& message, const std::string& not
         case Code::OutOfRange:
             return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::ResourceExhausted:
+            // THREE unrelated refusals share this code: a rate limit, memory
+            // pressure, and gRPC's own size limit. Only the first two are worth
+            // waiting for, and 429 tells a caller to wait - which for an
+            // oversized message is advice that can never come true, however
+            // long it waits.
+            //
+            // The reason arrives with database 2.13.0, which classifies the
+            // size case inside the client, so we branch on `reason` and never
+            // on the message text (the rule that already saved us on
+            // version_conflict).
+            if (reason == "message_too_large")
+                // NOT `body_too_large`: the limit bites in EITHER direction,
+                // and a stored row can exceed it without any request doing so -
+                // repeated patches grow one until it can no longer be read
+                // back, which we measured. So the caller may not have sent
+                // anything large at all, and a slug blaming their body would
+                // misdirect them. The database's own message carries the two
+                // sizes and says which direction it was, so it is passed
+                // through verbatim.
+                //
+                // 422 rather than 429 because nothing about waiting helps, and
+                // rather than 500 because this is a definite, explainable
+                // refusal and not a fault on our side.
+                return ApiError(ErrCode::Unprocessable, "message_too_large", message, details);
+            if (reason == "memory_pressure")
+                // Same status and the same remedy as a rate limit - wait - but
+                // NOT the same diagnosis, which is why it gets its own slug.
+                // `rate_limited` tells a caller it is sending too much, and
+                // that is a false accusation when the server is the one short
+                // of memory: it would have them throttle a client that was
+                // never the problem. Same reasoning as `read_only` having its
+                // own slug despite also meaning "wait". A stable reason from
+                // the database's admission control, not matched text.
+                return ApiError(ErrCode::TooManyRequests, "memory_pressure", message);
+            // No reason: a genuine rate limit, or the database's export
+            // concurrency cap. Both are "wait", so this arm is correct for
+            // them and must stay the fallback rather than a guess at one.
             return ApiError(ErrCode::TooManyRequests, "rate_limited", message);
         case Code::Aborted:
             // A stale version on a conditional write. The caller must RE-READ

+ 73 - 0
tests/test_db_errors.cpp

@@ -192,4 +192,77 @@ TEST(DbErrors, ARateLimitFromTheDatabaseIsA429SoItCanCarryRetryAfter) {
     EXPECT_EQ(svapi::httpStatus(a.code), 429);
 }
 
+// --- ResourceExhausted covers three unrelated refusals (database 2.13.0) ----
+
+TEST(DbErrors, AnOversizedMessageIs422NotAWaitAndRetry429) {
+    // The whole point: 429 tells a caller to wait, and no amount of waiting
+    // shrinks a payload. The database classifies the size case itself from
+    // 2.13.0, so we branch on the reason rather than on gRPC's wording.
+    const svapi::ApiError e =
+        svapi::apiErrorFor(detail(Code::ResourceExhausted, "message_too_large",
+                                  "Sent message larger than max (105906234 vs. 104857600)"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 422);
+    EXPECT_EQ(e.slug, "message_too_large");
+    // The database's sentence carries both sizes AND the direction, so it must
+    // reach the caller rather than being replaced by wording of our own.
+    EXPECT_NE(std::string(e.what()).find("104857600"), std::string::npos);
+}
+
+TEST(DbErrors, AGenuineRateLimitStillWaits) {
+    // The other side of the branch: without that reason this is a real rate
+    // limit or memory pressure, where 429 and Retry-After are correct.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::ResourceExhausted, "",
+                                                        "too many requests"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 429);
+    EXPECT_EQ(e.slug, "rate_limited");
+    EXPECT_EQ(e.code, svapi::ErrCode::TooManyRequests)
+        << "the global handler keys Retry-After off this code";
+}
+
+TEST(DbErrors, AnUnknownResourceExhaustedReasonKeepsTheBroaderAnswer) {
+    // A future reason we do not know must not be guessed into the narrow 422.
+    EXPECT_EQ(svapi::httpStatus(
+                  svapi::apiErrorFor(detail(Code::ResourceExhausted, "something_new")).code),
+              429);
+}
+
+TEST(DbErrors, TheSizeRefusalIsNotBlamedOnTheCallersBody) {
+    // Deliberately NOT `body_too_large`. The limit bites in either direction,
+    // and a stored row can exceed it without any single request doing so -
+    // repeated patches grow one until it cannot be read back, measured on a
+    // scratch server. So the caller may have sent nothing large at all.
+    const svapi::ApiError e =
+        svapi::apiErrorFor(detail(Code::ResourceExhausted, "message_too_large",
+                                  "Sent message larger than max (104857726 vs. 104857600)"));
+    EXPECT_NE(e.slug, "body_too_large")
+        << "a slug naming the caller's body misdirects them when it was the RESPONSE "
+           "that could not fit";
+    EXPECT_EQ(e.slug, "message_too_large");
+}
+
+TEST(DbErrors, MemoryPressureIsNotTheCallersFaultAndSaysSo) {
+    // The database's admission control refuses writes under memory pressure
+    // with this code and a stable reason. 429 and "wait" are right, but
+    // reporting it as `rate_limited` would tell a caller it is sending too
+    // much and have it throttle a client that was never the problem. Same
+    // reason `read_only` has its own slug while also meaning "wait".
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::ResourceExhausted,
+                                                        "memory_pressure", "under pressure"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 429);
+    EXPECT_EQ(e.slug, "memory_pressure");
+    EXPECT_EQ(e.code, svapi::ErrCode::TooManyRequests)
+        << "must keep the code the global handler attaches Retry-After to";
+}
+
+TEST(DbErrors, TheExportConcurrencyCapFallsInTheWaitArm) {
+    // The database's cap on simultaneous exports answers this code with NO
+    // reason, so it must land on the general "wait" answer rather than being
+    // mistaken for a size refusal. Asserted because the fallback arm is the
+    // one that quietly absorbs anything new.
+    const svapi::ApiError e =
+        svapi::apiErrorFor(detail(Code::ResourceExhausted, "", "too many concurrent exports"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 429);
+    EXPECT_EQ(e.slug, "rate_limited");
+}
+
 } // namespace