Browse Source

refactor: one implementation of filtered vector search, one settings name

The filter-then-rank intersection lived inside the /search route's lambda,
so when a function's ctx.collections(...).search() needed the same
behaviour it had to be copied, scan cap and loop included. Two copies of
this is a drift risk the project explicitly promises against: a filter
means the same thing wherever it is written, because the database
evaluates it (CLAUDE.md, "Filters").

Extracted to vectorSearch() and BOTH call sites now use it, so the copy
is gone rather than merely available.

kSettingsCollection gets the same treatment: it was spelled out in
SettingsStore's default argument and again in the runner, which reads the
same two documents through its own gateway. A second spelling of that
name would mean a function silently resolving its embedding config
against a collection nobody writes.
fszontagh 1 month ago
parent
commit
e6efb6ede8
5 changed files with 100 additions and 52 deletions
  1. 3 44
      src/handlers/vectors.cpp
  2. 4 4
      src/settings_store.cpp
  3. 11 4
      src/settings_store.hpp
  4. 49 0
      src/vector_search.cpp
  5. 33 0
      src/vector_search.hpp

+ 3 - 44
src/handlers/vectors.cpp

@@ -7,16 +7,11 @@
 #include "project_settings.hpp"
 #include "json_http.hpp"
 #include "server.hpp"
+#include "vector_search.hpp"
 #include <algorithm>
-#include <unordered_set>
 namespace svapi {
 namespace {
 
-// Upper bound on how deep a filtered search will scan the similarity ranking,
-// and on how many filter-matching ids we fetch. A filtered search stays exact
-// while the collection is within this bound.
-constexpr uint32_t kFilterScanCap = 10000;
-
 // Parse the optional `filters` body field into DB filters. Same grammar and
 // operator set as the documents endpoint, because the DB evaluates them.
 std::vector<smartbotic::database::Client::Filter> parseSearchFilters(const nlohmann::json& body) {
@@ -116,44 +111,8 @@ void registerVectorRoutes(ApiServer& s) {
         auto filters = parseSearchFilters(body);
         const std::string coll = qualify(project, name);
 
-        std::vector<smartbotic::database::Client::SimilarityResult> results;
-        if (filters.empty()) {
-            results = d->db.client().similaritySearch(coll, q, topK, minScore);
-        } else {
-            // The DB evaluates the filters (same engine as /documents), so every
-            // operator behaves identically on both endpoints. It will not return
-            // the stored vectors, so scoring still has to come from
-            // similaritySearch - we intersect the two.
-            smartbotic::database::Client::QueryOptions opts;
-            opts.filters = filters;
-            opts.limit   = kFilterScanCap;
-            std::unordered_set<std::string> allowed;
-            for (const auto& doc : d->db.client().find(coll, opts)) {
-                const std::string id = doc.value("_id", "");
-                if (!id.empty()) allowed.insert(id);
-            }
-            if (!allowed.empty()) {
-                // Walk the ranking from the top, widening until topK matches are
-                // found or the collection is exhausted. Because the scan is in
-                // descending score order, stopping as soon as topK matches are
-                // collected still yields the true topK: anything unseen scores
-                // lower than everything already kept.
-                uint32_t scan = std::max<uint32_t>(topK * 4, 64);
-                while (true) {
-                    auto page = d->db.client().similaritySearch(coll, q, scan, minScore);
-                    results.clear();
-                    for (const auto& r : page) {
-                        if (!allowed.count(r.id)) continue;
-                        results.push_back(r);
-                        if (results.size() >= topK) break;
-                    }
-                    if (results.size() >= topK) break;      // enough matches
-                    if (page.size() < scan) break;          // ranking exhausted
-                    if (scan >= kFilterScanCap) break;      // bounded work
-                    scan = std::min(scan * 4, kFilterScanCap);
-                }
-            }
-        }
+        const std::vector<smartbotic::database::Client::SimilarityResult> results =
+            vectorSearch(d->db.client(), coll, q, topK, minScore, filters);
 
         nlohmann::json arr = nlohmann::json::array();
         for (const auto& r : results) arr.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});

+ 4 - 4
src/settings_store.cpp

@@ -30,7 +30,7 @@ void SettingsStore::reloadProjectsFromDb() {
     auto docs = db_.client().find(coll_, opts);
     auto m = std::make_shared<ProjectMap>();
     for (const auto& d : docs) {
-        ProjectEmbeddingSettings p = ProjectEmbeddingSettings::fromJson(d);
+        ProjectSettings p = ProjectSettings::fromJson(d);
         // The global settings document lives in the same collection and carries
         // no `project` field - that absence is what tells the two apart.
         if (p.project.empty()) continue;
@@ -38,13 +38,13 @@ void SettingsStore::reloadProjectsFromDb() {
         // before the left, so inlining std::move(p) would move the name out
         // from under (*m)[p.project] and file the entry under "".
         const std::string name = p.project;
-        (*m)[name] = std::make_shared<const ProjectEmbeddingSettings>(std::move(p));
+        (*m)[name] = std::make_shared<const ProjectSettings>(std::move(p));
     }
     std::lock_guard<std::mutex> lk(m_);
     projects_ = m;
 }
 
-std::shared_ptr<const ProjectEmbeddingSettings>
+std::shared_ptr<const ProjectSettings>
 SettingsStore::projectSnapshot(const std::string& project) const {
     std::shared_ptr<const ProjectMap> m;
     {
@@ -55,7 +55,7 @@ SettingsStore::projectSnapshot(const std::string& project) const {
     return it == m->end() ? nullptr : it->second;
 }
 
-bool SettingsStore::saveProject(const ProjectEmbeddingSettings& p) {
+bool SettingsStore::saveProject(const ProjectSettings& p) {
     if (p.project.empty()) return false;
     db_.client().upsert(coll_, p.toJson(), projectSettingsDocId(p.project));
     reloadProjectsFromDb();

+ 11 - 4
src/settings_store.hpp

@@ -9,6 +9,13 @@
 
 namespace svapi {
 
+/// The collection holding the global settings document and the per-project
+/// override documents. Named here rather than spelled out at each use: the
+/// runner reads the same two documents through its own gateway, and a second
+/// spelling of this name would mean a function silently resolving its
+/// embedding config against a collection nobody writes.
+constexpr const char* kSettingsCollection = "vectorapi_settings";
+
 /// DB-backed settings store. Holds two things that share one collection and
 /// therefore one change subscription: the global settings document
 /// (`vectorapi_settings/current`) and the per-project embedding overrides
@@ -18,7 +25,7 @@ namespace svapi {
 class SettingsStore {
 public:
     SettingsStore(DbGateway& db,
-                  std::string collection = "vectorapi_settings",
+                  std::string collection = kSettingsCollection,
                   std::string docId     = "current");
 
     /// Ensure the (encrypted) collection exists.  Load or seed the settings
@@ -38,11 +45,11 @@ public:
 
     /// Per-project embedding overrides, or nullptr when the project inherits
     /// everything (thread-safe, lock-free after copy).
-    std::shared_ptr<const ProjectEmbeddingSettings> projectSnapshot(const std::string& project) const;
+    std::shared_ptr<const ProjectSettings> projectSnapshot(const std::string& project) const;
 
     /// Persist one project's overrides (`p.project` names it) and refresh the
     /// project snapshot. Returns true on success.
-    bool saveProject(const ProjectEmbeddingSettings& p);
+    bool saveProject(const ProjectSettings& p);
 
     /// Drop a project's overrides so it inherits the global settings again.
     /// Returns false when the project had no overrides stored.
@@ -57,7 +64,7 @@ private:
     /// Reload every `project_*` document into the project snapshot map.
     void reloadProjectsFromDb();
 
-    using ProjectMap = std::unordered_map<std::string, std::shared_ptr<const ProjectEmbeddingSettings>>;
+    using ProjectMap = std::unordered_map<std::string, std::shared_ptr<const ProjectSettings>>;
 
     DbGateway&   db_;
     std::string  coll_;

+ 49 - 0
src/vector_search.cpp

@@ -0,0 +1,49 @@
+#include "vector_search.hpp"
+#include <algorithm>
+#include <unordered_set>
+
+namespace svapi {
+
+std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+    smartbotic::database::Client& client, const std::string& coll,
+    const std::vector<float>& query, uint32_t topK, float minScore,
+    const std::vector<smartbotic::database::Client::Filter>& filters) {
+    if (filters.empty()) return client.similaritySearch(coll, query, topK, minScore);
+
+    smartbotic::database::Client::QueryOptions opts;
+    opts.filters = filters;
+    opts.limit   = kVectorFilterScanCap;
+    std::unordered_set<std::string> allowed;
+    // Bind the result before iterating: a range-for over a temporary dangles
+    // (CLAUDE.md).
+    const std::vector<nlohmann::json> matched = client.find(coll, opts);
+    for (const auto& doc : matched) {
+        const std::string id = doc.value("_id", "");
+        if (!id.empty()) allowed.insert(id);
+    }
+    std::vector<smartbotic::database::Client::SimilarityResult> results;
+    if (allowed.empty()) return results;
+
+    // Walk the ranking from the top, widening until topK matches are found or
+    // the ranking is exhausted. Because the scan is in descending score order,
+    // stopping as soon as topK matches are collected still yields the true
+    // topK: anything unseen scores lower than everything already kept.
+    uint32_t scan = std::max<uint32_t>(topK * 4, 64);
+    while (true) {
+        const std::vector<smartbotic::database::Client::SimilarityResult> page =
+            client.similaritySearch(coll, query, scan, minScore);
+        results.clear();
+        for (const auto& r : page) {
+            if (!allowed.count(r.id)) continue;
+            results.push_back(r);
+            if (results.size() >= topK) break;
+        }
+        if (results.size() >= topK) break;            // enough matches
+        if (page.size() < scan) break;                // ranking exhausted
+        if (scan >= kVectorFilterScanCap) break;      // bounded work
+        scan = std::min(scan * 4, kVectorFilterScanCap);
+    }
+    return results;
+}
+
+} // namespace svapi

+ 33 - 0
src/vector_search.hpp

@@ -0,0 +1,33 @@
+#pragma once
+#include "db_gateway.hpp"
+#include <smartbotic/database/client.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi {
+
+/// The most candidates a filtered vector search will scan. Bounds the work one
+/// request can cost; a query whose filter matches only deep in the ranking
+/// returns fewer than top_k rather than walking the whole collection.
+constexpr uint32_t kVectorFilterScanCap = 10000;
+
+/// Vector similarity search with optional database-evaluated filters.
+///
+/// ONE implementation on purpose. This is reached from the HTTP route
+/// (`handlers/vectors.cpp`) and from a function's `ctx.collections(...).search()`
+/// in the runner, and the two must not drift: the project guarantees that a
+/// filter means the same thing wherever it is written (CLAUDE.md, "Filters").
+/// When this lived in the route's lambda, the runner had to copy it, cap and
+/// loop included.
+///
+/// `filters` are evaluated by the database, the same engine `/documents` uses,
+/// so every operator behaves identically on both. The database will not return
+/// stored vectors, so scoring still comes from similaritySearch and the two
+/// results are intersected - which means scores are identical to those of an
+/// unfiltered query.
+std::vector<smartbotic::database::Client::SimilarityResult> vectorSearch(
+    smartbotic::database::Client& client, const std::string& qualifiedCollection,
+    const std::vector<float>& query, uint32_t topK, float minScore,
+    const std::vector<smartbotic::database::Client::Filter>& filters);
+
+} // namespace svapi