Explorar o código

fix: the database call deadline is configurable, not a hardcoded 5000

DbGateway's timeoutMs was a default argument of 5000 and both binaries took
it, so the per-call gRPC deadline for EVERY database call could not be
changed without a rebuild. Now `database.timeout_ms` in the server's
config.json and in runner.json.

Measured on prod 2026-11-03, and it is caller-visible rather than
theoretical: the first similarity search on novitax:kb_facts (13093 rows,
dim 4096) took 5.134 s, this deadline expired, and the caller got a 503
db_unavailable "Deadline Exceeded" instead of rows that were perfectly
computable - the same search warm is 0.18-0.36 s at 87% CPU.

The cause is one layer down and is NOT ours: smartbotic-database scores
vectors in place in LMDB's memory map, so a first search page-faults ~205 MB
of that collection's data.mdb in from disk, which at the 100-150 MB/s a
droplet volume gives is the 1.4-2.0 s measured on three collections. It is
amplified on prod because every vector is held twice - 616 MiB anonymous in
the server's MemoryStore plus the same bytes again as page cache for the
search - and on a 1973 MB box the file map wins and the anonymous copy is
pushed to swap (RssAnon 403 MB, RssFile 1006 MB, VmSwap 889 MB). Raised with
the database owner, who is proposing to release mirrored vectors.

So this commit fixes no latency. What it fixes is that an operator had no
knob at all.

THE DEFAULT IS DELIBERATELY UNCHANGED at 5000. Raising it here would turn
that 503 into a multi-second 200 for every caller at once, and whether a
slow answer beats a fast failure belongs to the caller: one consumer's retry
set keys on status and would stop retrying, another's postValidate()
discards any non-2xx, and on the one public write path this repo records,
latency is the expensive failure and an error is the cheap one.

Three tests, with the pairing deliberately falsified both ways:
deleting the parse fails ParsesProvidedValues while the pairing stays green,
and replacing the default with 0 when a `database` block is present fails
ADatabaseBlockWithoutATimeoutKeepsTheDefault alone - which is the case worth
pinning, because 0 means "no timeout" to the client and that is the
unbounded call the deadline exists to prevent.

Known limitation, stated in the header rather than glossed: it is still ONE
number for every call kind, so getCollectionInfo and a 13k-row similarity
search share it. Splitting them needs a per-operation map.

1353/1353 tests pass.
fszontagh hai 3 semanas
pai
achega
43db86c181
Modificáronse 6 ficheiros con 67 adicións e 5 borrados
  1. 1 1
      config/config.json
  2. 15 2
      runner/src/main.cpp
  3. 1 0
      src/config.cpp
  4. 29 0
      src/config.hpp
  5. 1 1
      src/main.cpp
  6. 20 1
      tests/test_config.cpp

+ 1 - 1
config/config.json

@@ -1,5 +1,5 @@
 {
   "log_level": "info",
   "http": { "bind_address": "0.0.0.0", "port": 8080 },
-  "database": { "address": "localhost:9004" }
+  "database": { "address": "localhost:9004", "timeout_ms": 5000 }
 }

+ 15 - 2
runner/src/main.cpp

@@ -94,6 +94,17 @@ struct RunnerConfig {
     std::string authToken;
     uint16_t httpPort = 8090;
     std::string dbAddress = "localhost:9004";
+    /// Per-call gRPC deadline for every database call, in milliseconds. Same
+    /// knob as the server's `database.timeout_ms` and the same reasoning (see
+    /// src/config.hpp): it was a hardcoded 5000 in DbGateway's default
+    /// argument, a cold similarity search on prod measured 5.134 s and blew
+    /// it, and the default stays 5000 because turning that failure into a
+    /// multi-second success is the caller's decision rather than ours.
+    ///
+    /// It matters MORE here than on the server: a function holds a pooled
+    /// runtime for the whole of a blocking host call, so a deadline raised
+    /// here is a lease held that much longer by every tenant sharing the pool.
+    uint32_t dbTimeoutMs = 5000;
 
     size_t poolSize = 4;
     size_t memoryLimitBytes = 128u * 1024 * 1024;
@@ -166,8 +177,10 @@ struct RunnerConfig {
         }
         if (j.contains("function_runs_kept"))
             c.functionRunsKept = j.value("function_runs_kept", c.functionRunsKept);
-        if (j.contains("database") && j["database"].is_object())
+        if (j.contains("database") && j["database"].is_object()) {
             c.dbAddress = j["database"].value("address", c.dbAddress);
+            c.dbTimeoutMs = j["database"].value("timeout_ms", c.dbTimeoutMs);
+        }
         if (j.contains("runtime") && j["runtime"].is_object()) {
             const auto& r = j["runtime"];
             c.poolSize = r.value("pool_size", c.poolSize);
@@ -542,7 +555,7 @@ int main(int argc, char** argv) {
         return 1;
     }
 
-    svapi::DbGateway db(cfg.dbAddress);
+    svapi::DbGateway db(cfg.dbAddress, cfg.dbTimeoutMs);
     spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
     // 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

+ 1 - 0
src/config.cpp

@@ -14,6 +14,7 @@ Config Config::fromJson(const nlohmann::json& j) {
     }
     if (j.contains("database") && j["database"].is_object()) {
         c.dbAddress = j["database"].value("address", c.dbAddress);
+        c.dbTimeoutMs = j["database"].value("timeout_ms", c.dbTimeoutMs);
     }
     if (j.contains("functions") && j["functions"].is_object()) {
         const auto& f = j["functions"];

+ 29 - 0
src/config.hpp

@@ -11,6 +11,35 @@ struct Config {
     std::string httpBind  = "0.0.0.0";
     uint16_t    httpPort  = 8080;
     std::string dbAddress = "localhost:9004";
+    /// Per-call gRPC deadline for EVERY database call, in milliseconds.
+    ///
+    /// It was a hardcoded 5000 in `DbGateway`'s default argument and both
+    /// binaries took it, so there was no way to change it without a rebuild.
+    /// Measured on prod 2026-11-03 and that is a real caller-visible failure:
+    /// the FIRST similarity search on a 13093-row dim-4096 collection took
+    /// **5.134 s**, this deadline expired, and the caller got a 503
+    /// `db_unavailable` "Deadline Exceeded" instead of the rows - which were
+    /// perfectly computable, since the same search warm takes 0.18-0.36 s.
+    /// The cause is one layer down (the first search on a vector collection
+    /// allocates a copy of that collection's vectors, about 205 MB there), so
+    /// this number does not fix anything by itself; what it fixes is that an
+    /// operator could not move it at all.
+    ///
+    /// The DEFAULT IS DELIBERATELY UNCHANGED at 5000. Raising it here would
+    /// turn that 503 into a multi-second 200 for every caller at once, and
+    /// whether a slow answer beats a fast failure is the CALLER's question,
+    /// not ours: one consumer's retry set keys on status and would stop
+    /// retrying, another's `postValidate()` discards any non-2xx, and on the
+    /// one public write path recorded in CLAUDE.md latency is the EXPENSIVE
+    /// failure and an error is the cheap one. So this makes the knob exist and
+    /// leaves the decision with whoever sets it.
+    ///
+    /// Known limitation, stated rather than glossed: it is ONE number for
+    /// every call kind, so `getCollectionInfo` and a 13k-row similarity search
+    /// share it. Those want different deadlines and splitting them needs a
+    /// per-operation map, which is a larger change than making the value
+    /// configurable.
+    uint32_t dbTimeoutMs = 5000;
     std::string webuiDir  = "/usr/share/smartbotic-vectorapi/webui";
 
     /// Function runner endpoints ("host:port"). Empty disables the function

+ 1 - 1
src/main.cpp

@@ -54,7 +54,7 @@ int main(int argc, char** argv) {
 
     std::signal(SIGINT, onSignal); std::signal(SIGTERM, onSignal); std::signal(SIGPIPE, SIG_IGN);
 
-    svapi::DbGateway db(cfg.dbAddress);
+    svapi::DbGateway db(cfg.dbAddress, cfg.dbTimeoutMs);
     spdlog::info("connecting to smartbotic-database at {}", cfg.dbAddress);
     // 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

+ 20 - 1
tests/test_config.cpp

@@ -9,19 +9,38 @@ TEST(Config, DefaultsWhenEmpty) {
     EXPECT_EQ(c.httpBind, "0.0.0.0");
     EXPECT_EQ(c.httpPort, 8080);
     EXPECT_EQ(c.dbAddress, "localhost:9004");
+    // The per-call gRPC deadline. 5000 is the value DbGateway hardcoded as a
+    // default argument before this was configurable, and the default is pinned
+    // here BECAUSE it must not drift: moving it silently changes whether a
+    // slow database call reaches a caller as a 503 or as a late 200, which is
+    // a decision for whoever sets it rather than for a release.
+    EXPECT_EQ(c.dbTimeoutMs, 5000u);
 }
 
 TEST(Config, ParsesProvidedValues) {
     auto j = nlohmann::json::parse(R"({
         "log_level":"debug",
         "http":{"bind_address":"127.0.0.1","port":9090},
-        "database":{"address":"db:9004"}
+        "database":{"address":"db:9004","timeout_ms":20000}
     })");
     Config c = Config::fromJson(j);
     EXPECT_EQ(c.logLevel, "debug");
     EXPECT_EQ(c.httpBind, "127.0.0.1");
     EXPECT_EQ(c.httpPort, 9090);
     EXPECT_EQ(c.dbAddress, "db:9004");
+    EXPECT_EQ(c.dbTimeoutMs, 20000u);
+}
+
+// The pairing that makes the test above mean something: a `database` block
+// that names only the address must leave the deadline alone. Without this, a
+// parser that overwrote the timeout with a zero whenever the section was
+// present would still pass - and a zero is "no timeout" to the client, which
+// is the unbounded call the deadline exists to prevent.
+TEST(Config, ADatabaseBlockWithoutATimeoutKeepsTheDefault) {
+    auto j = nlohmann::json::parse(R"({"database":{"address":"other:9004"}})");
+    Config c = Config::fromJson(j);
+    EXPECT_EQ(c.dbAddress, "other:9004");
+    EXPECT_EQ(c.dbTimeoutMs, 5000u);
 }
 
 TEST(Config, IgnoresUnknownKeys) {