Переглянути джерело

perf: open a collection once per process, not in front of every write

ctx.jobs.enqueue was THREE gRPC round trips. FunctionJobQueue::enqueue called
ensure() every time, and ensure() does getCollectionInfo plus a find(limit:1)
probe before the upsert ever runs - so two of the three existed only to re-open
a collection that was already open, against default:vectorapi_function_jobs,
which is shared by every project and measures 95,425 rows on prod.

FunctionRunLogStore::append had the same shape, and it is worse placed: it sits
on the caller's critical path, after the function's answer already exists.

Neither probe could ever discover anything on a later call. Re-opening guards
against THIS PROCESS never having touched the collection - a per-process need
by definition - and both binaries already call jobQueue.ensure() at startup,
with the server ensuring every project's run log there too. So this deletes
waste rather than trading anything away. The run log latches per PROJECT, not
on one flag, because a project created after startup has no collection yet and
its first recorded run is what creates one.

The latch is set AFTER the database work. A latch set before it would turn one
unreachable-database moment into a collection this process never opens again.

The test COUNTS the round trip, because the outcome is identical with and
without the latch, and it reads the rows back in the same test - a count of one
would also pass if append had stopped writing at all. Reverting the latch turns
both new tests red; that was checked, not assumed. 1375/1375 pass.

What this does NOT establish: that these round trips account for the 150-300 ms
of unattributed /fn overhead, or that they caused any particular timeout. Three
round trips is counted; which one expires under load is not. Found while
answering a consumer whose end-of-call ctx.jobs.enqueue hit the 5000 ms
DbGateway deadline and silently lost one call from long-term memory - 499 runs
in that same window succeeded at p50 90 ms, so the deadline is not attributed.
fszontagh 2 тижнів тому
батько
коміт
63e42c6d70

+ 12 - 0
src/function_jobs.cpp

@@ -107,6 +107,13 @@ nlohmann::json FunctionJob::toJson() const {
 FunctionJobQueue::FunctionJobQueue(DbGateway& db) : db_(db) {}
 
 void FunctionJobQueue::ensure() {
+    // Once per process. Re-opening a collection defends against THIS PROCESS
+    // never having touched it, so repeating it per call cannot discover
+    // anything - and this ran in front of every enqueue, which made one
+    // ctx.jobs.enqueue three round trips instead of one.
+    std::lock_guard<std::mutex> lock(ensure_mu_);
+    if (ensured_) return;
+
     const std::string c = coll();
     if (!db_.client().getCollectionInfo(c).has_value())
         db_.client().createCollection(c, 0, /*encrypted*/ false, 0, 0);
@@ -118,6 +125,11 @@ void FunctionJobQueue::ensure() {
     Client::QueryOptions probe;
     probe.limit = 1;
     (void)db_.client().find(c, probe);
+
+    // Last, so a throw above leaves this false and the next call retries. A
+    // latch set before the work would turn one unreachable-database moment into
+    // a collection this process never opens again.
+    ensured_ = true;
 }
 
 std::string FunctionJobQueue::enqueue(const FunctionJob& job) {

+ 18 - 0
src/function_jobs.hpp

@@ -1,6 +1,7 @@
 #pragma once
 #include "db_gateway.hpp"
 #include <nlohmann/json.hpp>
+#include <mutex>
 #include <optional>
 #include <string>
 #include <vector>
@@ -117,6 +118,18 @@ public:
     /// Create the queue collection (idempotent), and re-open it so find()
     /// surfaces rows after a restart - the same trap CollectionRegistry::
     /// bootstrap exists for.
+    ///
+    /// Does its database work ONCE PER PROCESS and is a no-op afterwards. Both
+    /// binaries already call this at startup, and re-opening a collection is a
+    /// per-process need by definition: the thing it defends against is this
+    /// process never having touched the collection. It was being paid on every
+    /// enqueue instead - two round trips (getCollectionInfo plus a find probe)
+    /// in front of every single upsert, against a collection shared by every
+    /// project and measured at 95,425 rows on prod.
+    ///
+    /// A FAILED attempt does not latch, so a database that was unreachable on
+    /// the first call is retried on the next rather than leaving the collection
+    /// permanently unopened.
     void ensure();
 
     /// Enqueue. Returns the job id, or empty on failure.
@@ -175,6 +188,11 @@ public:
 
 private:
     DbGateway& db_;
+    /// Guards `ensured_` only. Held across the database work so two threads
+    /// racing the first enqueue do the open once rather than twice; after that
+    /// it is an uncontended bool read.
+    std::mutex ensure_mu_;
+    bool ensured_ = false;
     std::string coll() const { return qualify("default", "vectorapi_function_jobs"); }
 };
 

+ 10 - 0
src/function_run_log.cpp

@@ -88,9 +88,19 @@ FunctionRunLogStore::FunctionRunLogStore(DbGateway& db, uint32_t keepPerFunction
     : db_(db), keep_(keepPerFunction) {}
 
 void FunctionRunLogStore::ensure(const std::string& project) {
+    // Once per project per process - see the header. This ran on every append,
+    // so every recorded run paid a getCollectionInfo it could not learn
+    // anything from, on the path a caller is waiting on.
+    std::lock_guard<std::mutex> lock(ensure_mu_);
+    if (ensured_.count(project) != 0) return;
+
     const std::string c = coll(project);
     if (!db_.client().getCollectionInfo(c).has_value())
         db_.client().createCollection(c, 0, false, 0, 0);
+
+    // Last, so a throw above leaves the project unlatched and the next append
+    // tries again.
+    ensured_.insert(project);
 }
 
 void FunctionRunLogStore::append(const std::string& project, const FunctionRunLog& entry) {

+ 20 - 0
src/function_run_log.hpp

@@ -1,7 +1,9 @@
 #pragma once
 #include "db_gateway.hpp"
 #include <nlohmann/json.hpp>
+#include <mutex>
 #include <string>
+#include <unordered_set>
 #include <vector>
 
 namespace svapi {
@@ -50,6 +52,18 @@ public:
     /// a host that configured something else.
     uint32_t keepPerFunction() const { return keep_; }
 
+    /// Create this project's run-log collection (idempotent) and re-open it.
+    ///
+    /// Does its database work ONCE PER PROJECT PER PROCESS and is a no-op
+    /// afterwards. `append` calls it, so it was costing a getCollectionInfo in
+    /// front of every recorded run - and `recordRun` sits on the caller's
+    /// critical path, after the function's answer already exists. Re-opening
+    /// guards against this process never having touched the collection, which
+    /// one call settles for good.
+    ///
+    /// Per PROJECT rather than a single flag because a project created after
+    /// startup has no collection yet, and its first recorded run is what
+    /// creates one. A FAILED attempt does not latch.
     void ensure(const std::string& project);
     void append(const std::string& project, const FunctionRunLog& entry);
     std::vector<FunctionRunLog> list(const std::string& project, const std::string& functionId,
@@ -58,6 +72,12 @@ public:
 private:
     DbGateway& db_;
     uint32_t keep_;
+    /// Guards `ensured_` only, and is held across the database work so two
+    /// threads racing a project's first run do the open once. Append is called
+    /// from httplib's request threads and from the runner's pool, so this is
+    /// genuinely concurrent.
+    std::mutex ensure_mu_;
+    std::unordered_set<std::string> ensured_;
     std::string coll(const std::string& project) const {
         return qualify(project, "vectorapi_function_runs");
     }

+ 41 - 1
tests/test_function_run_log.cpp

@@ -22,8 +22,12 @@ namespace {
 /// collection -> document id -> body.
 std::map<std::string, std::map<std::string, json>> g_db;
 std::map<std::string, bool> g_created;
+/// Round trips, counted. `ensure()` is supposed to open a collection once per
+/// process; counting the call is the only way to assert that, because the
+/// outcome is identical either way.
+int g_getCollectionInfoCalls = 0;
 
-void resetDb() { g_db.clear(); g_created.clear(); }
+void resetDb() { g_db.clear(); g_created.clear(); g_getCollectionInfoCalls = 0; }
 
 }  // namespace
 
@@ -36,6 +40,7 @@ bool Client::createCollection(const std::string& name, uint32_t, bool, uint32_t,
 }
 
 std::optional<Client::CollectionInfo> Client::getCollectionInfo(const std::string& name) {
+    ++g_getCollectionInfoCalls;
     if (!g_created.count(name)) return std::nullopt;
     CollectionInfo info;
     info.name = name;
@@ -209,6 +214,41 @@ TEST_F(FunctionRunLogTest, ProjectsDoNotShareARunLog) {
     EXPECT_EQ(store.list("p1", "fn", 10)[0].runId, "a");
 }
 
+// `append` calls `ensure`, so before the latch every recorded run paid a
+// getCollectionInfo in front of its upsert - on the path a caller is waiting
+// on, after the function's answer already exists.
+//
+// This counts the round trip rather than observing an outcome, because the
+// outcome is identical with and without the latch. The two EXPECTs below are a
+// pair and neither works alone: the count alone would also pass if `append`
+// had stopped touching the database at all, which is why the rows are read
+// back in the same test.
+TEST_F(FunctionRunLogTest, TheCollectionIsOpenedOncePerProjectHoweverManyRunsAreRecorded) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 100);
+    for (int i = 0; i < 25; ++i) store.append("p1", entry("r" + std::to_string(i), "fn", static_cast<uint64_t>(i)));
+
+    EXPECT_EQ(g_getCollectionInfoCalls, 1) << "one open per project, not one per append";
+    // The pairing: the saving came from not re-asking, NOT from not writing.
+    EXPECT_EQ(store.list("p1", "fn", 100).size(), 25u);
+}
+
+// The latch is per PROJECT rather than a single flag, because a project created
+// after startup has no collection yet and its first recorded run is what
+// creates one. Collapsing it to one bool would make that project's log depend
+// on whether some OTHER project had been written to first.
+TEST_F(FunctionRunLogTest, ANewProjectIsStillOpenedAfterAnotherProjectWasLatched) {
+    svapi::FunctionRunLogStore store(fakeGateway(), 100);
+    store.append("p1", entry("a", "fn", 1));
+    ASSERT_EQ(g_getCollectionInfoCalls, 1);
+
+    store.append("p2", entry("b", "fn", 2));
+    EXPECT_EQ(g_getCollectionInfoCalls, 2) << "a second project must get its own open";
+    EXPECT_EQ(store.list("p2", "fn", 100).size(), 1u);
+    // And the first project is not re-opened by the second project's arrival.
+    store.append("p1", entry("c", "fn", 3));
+    EXPECT_EQ(g_getCollectionInfoCalls, 2);
+}
+
 }  // namespace
 
 TEST(FunctionRunLogRecord, CarriesResponseHeadersSoAStoredRunRendersLikeAnEnvelope) {