ソースを参照

fix: client 2.13.1, a deadline-bounded startup, and four honest refusals

Database client 2.12.0 -> wait, 2.13.0 -> 2.13.1-1 in both places. Needs
--rebuild-base. 2.13.1 fixes the two defects our pre-release run found.

THE STARTUP WAIT IS NOW BOUNDED BY WALL TIME, not by an attempt count.
`for (i = 0; i < 30 && !db.connect(); ++i) sleep(1s)` carried an unstated
assumption about what one attempt costs. Client 2.13.0 and earlier
returned from connect() immediately on an unreachable server - it only
built the stub - so that loop cost ~30 s. 2.13.1 makes connect() WAIT up
to its timeout (5 s for us), so the same loop costs up to 180 s against
systemd's 90 s TimeoutStartSec: SIGTERMed mid-loop, "start operation
timed out" instead of a clean "database not reachable" plus exit 1, with
restart churn. And not a rare path - the postinst starts the service
while the database is still down on every upgrade.

Replaced with an explicit deadline in a pure, clock-injected helper
(db_await.hpp) shared by both binaries, because swapping 30 for a
smaller number would be the same bug awaiting the next change in what an
attempt costs. Six tests, the central one simulating 5 s attempts and
asserting the budget holds; they bracket from both sides, so a loop that
exited at once or ran thirty times both fail.

FOUR MAPPING CORRECTIONS. ResourceExhausted and DeadlineExceeded each
covered several unrelated refusals under one answer:

  message_too_large  -> 422 (was 429 "wait", which can never help)
  memory_pressure    -> 429 memory_pressure, its own slug: the remedy is
                        the same but the DIAGNOSIS is not, and
                        rate_limited tells a caller it is sending too
                        much when the database is the one short of memory
  document_too_large -> 422 with its own slug, since the remedy is
                        "store less", not "fix a malformed field"
  outcome_unknown    -> 504, NOT 503. A write that timed out may already
                        have applied, and 503 means "retry as-is" -
                        dangerous advice. 504 says the upstream ran out
                        of time without implying the retry is safe, and
                        the message tells the caller to re-read first.
                        A read that times out stays 503: nothing
                        happened, so retrying as-is is correct.

A `*` SCOPE RULE NO LONGER REACHES A RESERVED NAME. collMatches treats a
trailing `*` as a prefix match, and for the pattern `*` that prefix is
zero-length - so `*` matched the reserved `_files` as well as every real
collection, which is neither what anyone writing `*` means nor what the
docs describe. Harmless while `_files` only widened a read a `*` rule
already had; not harmless the moment a reserved prefix grants the right
to ACT. Checked prod before changing it: none of the seven keys there
holds a `*` rule, so nothing loses access. A test asserts the rule
against a prefix that does not exist yet, so the next reserved name
inherits the protection instead of re-breaking the precedent.

A VECTORLESS INSERT INTO A VECTOR COLLECTION IS REFUSED, in both the
HTTP route and ctx.collections(...).insert() - the same operation, and
closing one door while leaving the other open would move the defect
somewhere harder to notice. Such a row reads back perfectly and can
never be found by a search. Reported from production with the only
symptom it has: a 12448-document collection whose three indexed facets
each summed to 12447. `text` satisfies the guard, because a row with
text gets embedded and IS searchable - refusing that would have broken
ordinary ingest, which the integration test asserts.

`scanned` IS NOW ALWAYS EMITTED, including 0. Suppressing it at zero
meant a caller could not tell "no candidate walk happened" from "this
server cannot tell me about truncation at all", which is the same
silent-default problem scan_capped exists to prevent. Absence now means
exactly one thing. `scan_cap` stays conditional because the condition is
the useful one - present whenever scan_capped is true - and that
guarantee is now documented rather than left to be measured.

884 tests pass against the v2.13.1 tag, with the installed header
verified by diff against the tagged source.
fszontagh 1 ヶ月 前
親
コミット
ef760bdec5

ファイルの差分が大きいため隠しています
+ 0 - 1
api/llms.txt


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

+ 17 - 0
src/apikey.cpp

@@ -38,6 +38,23 @@ std::string keyOpToString(KeyOp op) {
 // ---------------------------------------------------------------------------
 
 static bool collMatches(const std::string& pat, const std::string& coll) {
+    // A RESERVED name requires a LITERAL grant and is never reachable by
+    // wildcard. `collMatches("*", x)` is a zero-length prefix comparison, so
+    // before this a rule of `{"collection":"*"}` silently matched the reserved
+    // `_files` pseudo-collection as well as every real collection - which is
+    // not what anyone writing `*` means, and not what the docs describe
+    // ("the reserved pseudo-collection a policy NAMES to grant file access").
+    //
+    // It mattered little while `_files` was the only reserved name and gave
+    // read-only access to project data a `*` rule could already read. It stops
+    // being harmless the moment anything else lives under a reserved prefix:
+    // a connection grant, say, where `*` quietly conferring the right to send
+    // mail as a tenant's owner would be a real escalation rather than a wider
+    // read. Fixing the precedent before extending it.
+    //
+    // `*` keeps meaning "every real collection", which is what it is for.
+    const bool reserved = !coll.empty() && coll.front() == '_';
+    if (reserved) return pat == coll;
     if (!pat.empty() && pat.back() == '*')
         return coll.compare(0, pat.size() - 1, pat, 0, pat.size() - 1) == 0;
     return pat == coll;

+ 55 - 0
src/db_await.hpp

@@ -0,0 +1,55 @@
+#pragma once
+#include <chrono>
+#include <cstdint>
+#include <functional>
+
+/// Waiting for the database at startup, bounded by WALL TIME.
+///
+/// This exists because the previous version bounded the wait by an ATTEMPT
+/// COUNT - `for (i = 0; i < 30 && !db.connect(); ++i) sleep(1s)` - and that
+/// count carried an unstated assumption about how long one attempt costs.
+/// Database client 2.13.0 and earlier returned from connect() immediately on an
+/// unreachable server, because it only built the gRPC stub, so 30 attempts cost
+/// about 30 seconds. In 2.13.1 connect() WAITS up to its configured timeout
+/// (5 s for us) before answering, so the same loop costs up to 180 seconds.
+///
+/// Our units are `Type=notify` with systemd's default `TimeoutStartSec` of 90
+/// seconds, so that loop would be SIGTERMed partway through. A clean
+/// "database not reachable" plus exit 1 - diagnosable, and restarted 3 seconds
+/// later - would become "start operation timed out", killed mid-loop, with
+/// restart churn. Not a rare path either: the package postinst starts the
+/// service while the database is still down on every upgrade.
+///
+/// So the bound is a deadline. Swapping 30 for a smaller number would have been
+/// the same bug waiting for the next change in what an attempt costs.
+///
+/// Pure and clock-injected so the property that broke - "returns within its
+/// budget however slow one attempt is" - can be tested without a database and
+/// without really sleeping.
+namespace svapi {
+
+/// Call `tryConnect` until it succeeds or `budget` has elapsed.
+///
+/// Always attempts at least ONCE, even with a zero budget: a caller asking to
+/// connect wants one honest try, and a zero budget is a configuration choice
+/// about waiting rather than an instruction to skip the work.
+///
+/// `sleepFor` is only called when there is budget left for it, so the function
+/// cannot overshoot by sleeping past its own deadline.
+inline bool awaitConnectable(const std::function<bool()>& tryConnect,
+                             const std::function<std::chrono::steady_clock::time_point()>& now,
+                             const std::function<void(std::chrono::milliseconds)>& sleepFor,
+                             std::chrono::milliseconds budget,
+                             std::chrono::milliseconds betweenAttempts) {
+    const auto deadline = now() + budget;
+    for (;;) {
+        if (tryConnect()) return true;
+        const auto remaining = deadline - now();
+        // No time for another attempt's pause, so no point starting one: the
+        // attempt itself may cost more than everything left.
+        if (remaining <= betweenAttempts) return false;
+        if (betweenAttempts > std::chrono::milliseconds::zero()) sleepFor(betweenAttempts);
+    }
+}
+
+} // namespace svapi

+ 39 - 1
src/db_errors.cpp

@@ -58,6 +58,18 @@ ApiError translate(Code code, const std::string& message, const std::string& not
         case Code::PermissionDenied:
             return ApiError(ErrCode::Forbidden, "forbidden", message);
         case Code::InvalidArgument:
+            // database 2.13.1 refuses a write whose STORED document would grow
+            // past what a read could ever send back, checking the MERGED result
+            // of a patch rather than the request body - which is the case that
+            // matters, because the body was never the thing that crossed the
+            // line. We measured the hole it closes: a 60 MiB insert followed by
+            // patches reached ~100 MB, after which the row could not be read at
+            // all. Its own slug, because the remedy is "store less in this
+            // document", not "fix a malformed field" - which is what a generic
+            // `validation` answer would send a caller looking for.
+            if (reason == "document_too_large")
+                return ApiError(ErrCode::Unprocessable, "document_too_large", message, details);
+            return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::OutOfRange:
             return ApiError(ErrCode::Unprocessable, "validation", message);
         case Code::ResourceExhausted:
@@ -105,8 +117,34 @@ ApiError translate(Code code, const std::string& message, const std::string& not
             // briefly unavailable, retry as-is" - so it gets its own 409 rather
             // than being folded into 503 as it was when it arrived as Unknown.
             return ApiError(ErrCode::Conflict, "version_conflict", message, details);
-        case Code::Unavailable:
         case Code::DeadlineExceeded:
+            // A WRITE that timed out may or may not have been applied, and
+            // database 2.13.1 says so with reason `outcome_unknown`. Our old
+            // answer here was 503, whose entire meaning is "retry as-is" - and
+            // that is dangerous advice for a write that may already have
+            // landed. We measured the shape it describes: a patch reported
+            // DeadlineExceeded after three client retries while the row had
+            // grown by exactly the patched amount every time.
+            //
+            // 504 rather than 503 because it says the upstream ran out of time
+            // WITHOUT implying the retry is safe, and it is already what we
+            // answer for an embedding or fetch timeout. The message carries the
+            // instruction a caller actually needs, which is to RE-READ before
+            // deciding - not to retry and hope.
+            //
+            // A READ that times out is unambiguous and stays 503: nothing
+            // happened, so retrying as-is is exactly right.
+            if (reason == "outcome_unknown")
+                return ApiError(ErrCode::GatewayTimeout, "outcome_unknown",
+                                message.empty()
+                                    ? "the write timed out and may or may not have been applied; "
+                                      "re-read the document before retrying, and do not blindly "
+                                      "retry a write that is not idempotent"
+                                    : message + " - the write may or may not have been applied; "
+                                      "re-read before retrying",
+                                details);
+            return ApiError(ErrCode::Unavailable, "db_unavailable", message);
+        case Code::Unavailable:
             return ApiError(ErrCode::Unavailable, "db_unavailable", message);
         // Unknown no longer covers the in-band refusals - since client 2.12.0
         // each one carries its own code. What is left here is a genuinely

+ 25 - 0
src/handlers/documents.cpp

@@ -90,6 +90,31 @@ void registerDocumentRoutes(ApiServer& s) {
         auto body = bodyJson(req);
         std::string id = body.value("id", "");
         nlohmann::json data = documentBody(body);
+
+        // The sibling of `vector_replace_unsafe` above, arriving through a
+        // different door. A document inserted into a VECTOR collection with
+        // neither a vector nor text to embed reads back perfectly and can
+        // never be found by any search - it has no embedding, and no read path
+        // returns one, so nothing about it looks wrong.
+        //
+        // Reported from production with the arithmetic that exposed it: a
+        // 12448-document collection whose three indexed facets each summed to
+        // 12447, the extra row being a query body posted to this route by
+        // mistake. The consumer spent real time explaining that discrepancy.
+        //
+        // A metadata-only row in a vector collection is invisible to search BY
+        // DEFINITION, so refusing it cannot take away anything anyone could
+        // have been using deliberately. Named both ways out, as the PUT guard
+        // does - and deliberately not repaired by embedding something, which
+        // would spend the project's credit on a request that never asked.
+        if (t.meta.kind == "vector" && !data.contains("_vector") && !data.contains("vector") &&
+            !data.contains("text"))
+            throw ApiError(ErrCode::Unprocessable, "vector_missing",
+                           "a document inserted into a vector collection must carry a vector or "
+                           "text to embed, or it can never be found by a search. Provide 'text', "
+                           "or POST .../vectors to store a document together with its vector, or "
+                           "use a json collection if this row is not meant to be searchable");
+
         const uint32_t ttl = ttlParam(req).value_or(0);
         std::string newId;
         try {

+ 15 - 2
src/handlers/vectors.cpp

@@ -125,8 +125,21 @@ void registerVectorRoutes(ApiServer& s) {
         // `scan_capped` is the one that matters: without it a short answer and
         // a complete one are indistinguishable, and a caller sweeping a
         // filtered set cannot tell it has been given less than matches.
-        nlohmann::json out = {{"results", arr}, {"scan_capped", found.scanCapped}};
-        if (found.scanned > 0) out["scanned"] = found.scanned;
+        // `scanned` is emitted ALWAYS, including 0. It used to be suppressed
+        // when zero, which meant a caller could not tell "no candidate walk
+        // happened" (normal, on an unfiltered search) from "this server
+        // predates the field and cannot tell me about truncation at all" -
+        // and those need different handling. That is the same silent-default
+        // problem `scan_capped` exists to prevent, so emitting 0 makes
+        // absence mean exactly one thing: too old. A consumer found it by
+        // measuring an unfiltered search and getting scan_capped=false with
+        // scanned undefined.
+        nlohmann::json out = {{"results", arr},
+                              {"scan_capped", found.scanCapped},
+                              {"scanned", found.scanned}};
+        // Conditional on purpose, and the condition is the one a caller needs:
+        // whenever `scan_capped` is true this is present, so "if capped, read
+        // the cap" is safe and nobody has to hardcode the number.
         if (found.scanCapped) out["scan_cap"] = kVectorFilterScanCap;
         sendJson(res, 200, out);
     });

+ 9 - 1
src/main.cpp

@@ -1,5 +1,6 @@
 #include "auth.hpp"
 #include "collection_registry.hpp"
+#include "db_await.hpp"
 #include "config.hpp"
 #include "function_events.hpp"
 #include "function_jobs.hpp"
@@ -55,7 +56,14 @@ int main(int argc, char** argv) {
 
     svapi::DbGateway db(cfg.dbAddress);
     spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
-    for (int i = 0; i < 30 && !db.connect(); ++i) std::this_thread::sleep_for(std::chrono::seconds(1));
+    // Bounded by WALL TIME, not by an attempt count - see db_await.hpp. 60 s
+    // sits comfortably inside systemd's 90 s TimeoutStartSec, so an unreachable
+    // database produces a clean diagnostic and exit 1 rather than being killed
+    // mid-loop with a misleading "start operation timed out".
+    svapi::awaitConnectable([&db] { return db.connect(); },
+                            [] { return std::chrono::steady_clock::now(); },
+                            [](std::chrono::milliseconds d) { std::this_thread::sleep_for(d); },
+                            std::chrono::seconds(60), std::chrono::seconds(1));
     if (!db.healthy()) { spdlog::error("database not reachable at {}", cfg.dbAddress); return 1; }
 
     svapi::SettingsStore settings(db);

+ 6 - 0
tests/CMakeLists.txt

@@ -227,6 +227,12 @@ target_include_directories(test_db_errors PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_db_errors PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_db_errors)
 
+# Pure, clock-injected: no database and no real sleeping.
+add_executable(test_db_await test_db_await.cpp)
+target_include_directories(test_db_await PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_db_await PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_db_await)
+
 add_executable(test_file_name test_file_name.cpp)
 target_include_directories(test_file_name PRIVATE ${CMAKE_SOURCE_DIR}/src)
 target_link_libraries(test_file_name PRIVATE vectorapi_core GTest::gtest_main)

+ 50 - 0
tests/test_api_integration.cpp

@@ -2387,6 +2387,56 @@ TEST_F(ApiFixture, ARecycledCollectionNameInheritsNoConstraint) {
 // the vector so a read-modify-write cannot put it back. Measured against the
 // database before fixing: a merge PATCH preserves the vector, an update drops
 // it. On data that cost money to produce.
+TEST_F(ApiFixture, InsertingAVectorlessDocumentIntoAVectorCollectionIsRefused) {
+    // The sibling of the PUT refusal below, through a different door. Reported
+    // from production: a 12448-document collection whose three indexed facets
+    // each summed to 12447, the extra row being a query body posted to the
+    // documents route by mistake. It read back perfectly and could never be
+    // found by a search, which is why the arithmetic was the only symptom.
+    auto c = admin();
+    const std::string base = "/api/v1/projects/" + project_ + "/collections";
+    const std::string ct = "application/json";
+    ASSERT_EQ(c.Post(base.c_str(),
+                     nlohmann::json{{"name","vins"},{"kind","vector"},
+                                    {"vector_dimension",4}}.dump(), ct)->status, 201);
+
+    auto count = [&]() {
+        auto r = c.Get((base + "/vins/documents").c_str());
+        if (!r || r->status != 200) return std::size_t{0};
+        return nlohmann::json::parse(r->body)["documents"].size();
+    };
+    ASSERT_EQ(count(), 0u);
+
+    // Exactly the shape that was reported: a body with no vector and no text.
+    auto bad = c.Post((base + "/vins/documents").c_str(),
+                      nlohmann::json{{"filter",{{"sourceType","email"}}},{"limit",60}}.dump(), ct);
+    ASSERT_TRUE(bad);
+    EXPECT_EQ(bad->status, 422) << bad->body;
+    EXPECT_NE(bad->body.find("vector_missing"), std::string::npos) << bad->body;
+    EXPECT_EQ(count(), 0u) << "the refused insert must not have stored anything";
+
+    // An explicit vector is accepted - the refusal must not block the real
+    // write path, or it would be a far worse bug than the one it fixes.
+    auto withVec = c.Post((base + "/vins/documents").c_str(),
+                          nlohmann::json{{"_vector",{1.0,0.0,0.0,0.5}},{"tag","a"}}.dump(), ct);
+    ASSERT_TRUE(withVec);
+    EXPECT_EQ(withVec->status, 201) << withVec->body;
+
+    // And `text` satisfies it too, because a row with text gets embedded and IS
+    // searchable. Refusing it would have broken ordinary ingest, which is the
+    // common case - so this asserts the guard is not over-broad. The insert may
+    // fail for want of an embedding provider in this environment; what must NOT
+    // happen is a 422 naming vector_missing.
+    auto withText = c.Post((base + "/vins/documents").c_str(),
+                           nlohmann::json{{"text","hello"},{"tag","b"}}.dump(), ct);
+    ASSERT_TRUE(withText);
+    EXPECT_EQ(withText->body.find("vector_missing"), std::string::npos)
+        << "text must satisfy the guard: " << withText->body;
+
+    auto del = c.Delete((base + "/vins").c_str());
+    ASSERT_TRUE(del);
+}
+
 TEST_F(ApiFixture, ReplacingADocumentInAVectorCollectionIsRefused) {
     auto c = admin();
     const std::string base = "/api/v1/projects/" + project_ + "/collections";

+ 54 - 0
tests/test_apikey.cpp

@@ -47,3 +47,57 @@ TEST(ApiKey, NoScopeStaysAbsent) {
     EXPECT_FALSE(ApiKey::fromJson(k.toJson()).scope.has_value());
     EXPECT_FALSE(k.toPublicJson().contains("scope"));
 }
+
+// --- a wildcard must not reach a RESERVED pseudo-collection ----------------
+
+TEST(KeyScopeReserved, AStarRuleDoesNotGrantTheFilesPseudoCollection) {
+    // `collMatches("*", x)` is a zero-length prefix comparison, so before this
+    // a `*` rule matched the reserved `_files` as well as every real
+    // collection. Nobody writing `*` means "and the reserved names too", and
+    // the docs describe `_files` as something a policy NAMES.
+    //
+    // Checked against production before changing it: none of the 7 keys there
+    // holds a `*` rule, so nothing loses access.
+    svapi::KeyScope scope;
+    scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::List}, false});
+    EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr)
+        << "a wildcard must not confer file access implicitly";
+    // The pair that makes the assertion above mean something: `*` must still
+    // match a real collection, or this test would pass against a function that
+    // matched nothing at all.
+    EXPECT_NE(scope.findRule("kb_chunks", svapi::KeyOp::Read), nullptr)
+        << "`*` must still mean every REAL collection";
+}
+
+TEST(KeyScopeReserved, AnExplicitFilesRuleStillWorks) {
+    // The other direction: naming it must keep working, or the feature is gone
+    // rather than narrowed.
+    svapi::KeyScope scope;
+    scope.rules.push_back({"_files", {svapi::KeyOp::Read}, false});
+    EXPECT_NE(scope.findRule("_files", svapi::KeyOp::Read), nullptr);
+    EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Insert), nullptr)
+        << "ops are still honoured on a reserved name";
+}
+
+TEST(KeyScopeReserved, APrefixWildcardDoesNotReachUnderscoreNamesEither) {
+    // Not just the bare `*`: any trailing-wildcard pattern must stop at a
+    // reserved name. `_*` is the one someone would reach for to grant "all the
+    // internal things", and it must not work by accident.
+    for (const char* pat : {"*", "_*", "_f*", "_files*"}) {
+        svapi::KeyScope scope;
+        scope.rules.push_back({pat, {svapi::KeyOp::Read}, false});
+        EXPECT_EQ(scope.findRule("_files", svapi::KeyOp::Read), nullptr) << "pattern " << pat;
+    }
+}
+
+TEST(KeyScopeReserved, ThisIsWhyItMattersForAnythingAddedLater) {
+    // A reserved name reachable by wildcard is harmless while it only widens a
+    // read. It stops being harmless for a grant that lets a function ACT - a
+    // mail connection, say. Asserting the rule generally, with a name that
+    // does not exist yet, so the precedent cannot be re-broken by whoever adds
+    // the next reserved prefix.
+    svapi::KeyScope scope;
+    scope.rules.push_back({"*", {svapi::KeyOp::Read, svapi::KeyOp::Insert}, false});
+    EXPECT_EQ(scope.findRule("_conn:some_mailbox", svapi::KeyOp::Insert), nullptr)
+        << "a future reserved prefix must inherit the literal-grant rule automatically";
+}

+ 104 - 0
tests/test_db_await.cpp

@@ -0,0 +1,104 @@
+#include "db_await.hpp"
+#include <gtest/gtest.h>
+
+// The startup wait, with an injected clock so the property that BROKE can be
+// asserted without a database and without really sleeping.
+//
+// What broke: the wait was bounded by an attempt count, and the cost of one
+// attempt was an unstated assumption about the database client. When client
+// 2.13.1 made connect() block up to 5 s instead of returning immediately, a
+// 30-attempt loop went from ~30 s to ~180 s - past systemd's 90 s
+// TimeoutStartSec, so the process was killed mid-loop and the honest
+// "database not reachable" diagnostic never printed.
+namespace {
+
+using namespace std::chrono_literals;
+using Clock = std::chrono::steady_clock;
+
+/// A fake clock the test advances itself. `sleepFor` advances it, and so does
+/// a connect attempt, which is how a slow attempt is simulated.
+struct FakeTime {
+    Clock::time_point t = Clock::time_point{};
+    Clock::time_point now() const { return t; }
+    void advance(std::chrono::milliseconds d) { t += d; }
+};
+
+TEST(DbAwait, AttemptsOnceEvenWithNoBudget) {
+    FakeTime c;
+    int attempts = 0;
+    const bool got = svapi::awaitConnectable([&] { ++attempts; return false; },
+                                             [&] { return c.now(); },
+                                             [&](std::chrono::milliseconds d) { c.advance(d); },
+                                             0ms, 1s);
+    EXPECT_FALSE(got);
+    EXPECT_EQ(attempts, 1) << "a caller asking to connect wants one honest try";
+}
+
+TEST(DbAwait, ReturnsAsSoonAsItConnects) {
+    FakeTime c;
+    int attempts = 0;
+    const bool got = svapi::awaitConnectable([&] { return ++attempts == 3; },
+                                             [&] { return c.now(); },
+                                             [&](std::chrono::milliseconds d) { c.advance(d); },
+                                             60s, 1s);
+    EXPECT_TRUE(got);
+    EXPECT_EQ(attempts, 3);
+}
+
+TEST(DbAwait, StaysInsideTheBudgetWhenEveryAttemptIsSLOW) {
+    // THE REGRESSION. Each attempt costs 5 s, as a 2.13.1 connect() does
+    // against an unreachable server. The old attempt-count loop would have run
+    // 30 x (5 + 1) = 180 s here. This must not exceed its 60 s budget, because
+    // 90 s is where systemd kills us.
+    FakeTime c;
+    int attempts = 0;
+    const auto start = c.now();
+    const bool got = svapi::awaitConnectable([&] { ++attempts; c.advance(5s); return false; },
+                                             [&] { return c.now(); },
+                                             [&](std::chrono::milliseconds d) { c.advance(d); },
+                                             60s, 1s);
+    EXPECT_FALSE(got);
+    const auto elapsed = c.now() - start;
+    EXPECT_LE(elapsed, 65s) << "overshot its budget by more than one attempt";
+    EXPECT_LT(elapsed, 90s) << "would be SIGTERMed by systemd before reporting anything";
+    EXPECT_LE(attempts, 11) << "a 5 s attempt plus a 1 s pause fits ~10 times into 60 s";
+}
+
+TEST(DbAwait, AnInstantFailureStillRespectsTheBudgetRatherThanSpinning) {
+    // The OLD behaviour, where connect() returned immediately: the pause is
+    // what bounds the attempt rate, and the deadline is what ends it. Without
+    // the pause being charged against the deadline this would spin forever.
+    FakeTime c;
+    int attempts = 0;
+    const bool got = svapi::awaitConnectable([&] { ++attempts; return false; },
+                                             [&] { return c.now(); },
+                                             [&](std::chrono::milliseconds d) { c.advance(d); },
+                                             10s, 1s);
+    EXPECT_FALSE(got);
+    EXPECT_LE(attempts, 11);
+    EXPECT_GE(attempts, 9) << "with instant failures it should use most of its budget";
+}
+
+TEST(DbAwait, NeverSleepsPastItsOwnDeadline) {
+    // If the remaining time is less than one pause, stop rather than sleep
+    // through the deadline - the overshoot is what systemd notices.
+    FakeTime c;
+    const auto start = c.now();
+    (void)svapi::awaitConnectable([&] { c.advance(900ms); return false; },
+                                  [&] { return c.now(); },
+                                  [&](std::chrono::milliseconds d) { c.advance(d); },
+                                  5s, 1s);
+    EXPECT_LE(c.now() - start, 6s);
+}
+
+TEST(DbAwait, AZeroPauseDoesNotSleepAtAll) {
+    // Permitted, for a caller that wants to burn its budget on attempts.
+    FakeTime c;
+    int sleeps = 0;
+    (void)svapi::awaitConnectable([&] { c.advance(1s); return false; },
+                                  [&] { return c.now(); },
+                                  [&](std::chrono::milliseconds) { ++sleeps; }, 3s, 0ms);
+    EXPECT_EQ(sleeps, 0);
+}
+
+} // namespace

+ 54 - 0
tests/test_db_errors.cpp

@@ -265,4 +265,58 @@ TEST(DbErrors, TheExportConcurrencyCapFallsInTheWaitArm) {
     EXPECT_EQ(e.slug, "rate_limited");
 }
 
+// --- database 2.13.1 reasons -----------------------------------------------
+
+TEST(DbErrors, AWriteWhoseOutcomeIsUnknownIsNotA503RetryAsIs) {
+    // The one that matters. 503 means "retry as-is", and for a write that may
+    // ALREADY HAVE APPLIED that is dangerous advice. Measured before the
+    // database fixed it: a patch reported DeadlineExceeded after three client
+    // retries while the row had grown by exactly the patched amount each time.
+    const svapi::ApiError e = svapi::apiErrorFor(
+        detail(Code::DeadlineExceeded, "outcome_unknown", "deadline exceeded"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 504)
+        << "504 says the upstream ran out of time without implying the retry is safe";
+    EXPECT_EQ(e.slug, "outcome_unknown");
+    // The instruction has to reach the caller, not just the status.
+    EXPECT_NE(std::string(e.what()).find("re-read"), std::string::npos)
+        << "the caller must be told to re-read rather than retry";
+}
+
+TEST(DbErrors, AReadThatTimesOutStaysA503) {
+    // The other half, and the reason this is branched rather than switched
+    // wholesale: a read that timed out changed nothing, so "retry as-is" is
+    // exactly the right instruction and 503 is the right status.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::DeadlineExceeded, "", "timed out"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 503);
+    EXPECT_EQ(e.slug, "db_unavailable");
+}
+
+TEST(DbErrors, AnOversizedStoredDocumentIsNotAMalformedField) {
+    // `validation` would send a caller hunting for a bad field. The document is
+    // fine; there is simply too much of it. Separate slug, same 422.
+    const svapi::ApiError e = svapi::apiErrorFor(
+        detail(Code::InvalidArgument, "document_too_large",
+               "stored document would be 104920000 bytes; the limit is 104601600"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 422);
+    EXPECT_EQ(e.slug, "document_too_large");
+    EXPECT_NE(std::string(e.what()).find("104601600"), std::string::npos)
+        << "the database's sizes are the actionable part and must pass through";
+}
+
+TEST(DbErrors, AnOrdinaryInvalidArgumentIsStillPlainValidation) {
+    // The fallback must not be captured by the new branch.
+    const svapi::ApiError e =
+        svapi::apiErrorFor(detail(Code::InvalidArgument, "", "field 'x' is not a number"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 422);
+    EXPECT_EQ(e.slug, "validation");
+}
+
+TEST(DbErrors, UnavailableIsUnaffectedByTheDeadlineBranch) {
+    // Unavailable and DeadlineExceeded used to share one case label. Splitting
+    // them is where a mistake would hide, so assert the untouched one too.
+    const svapi::ApiError e = svapi::apiErrorFor(detail(Code::Unavailable, "", "no addresses"));
+    EXPECT_EQ(svapi::httpStatus(e.code), 503);
+    EXPECT_EQ(e.slug, "db_unavailable");
+}
+
 } // namespace

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません