|
|
@@ -0,0 +1,345 @@
|
|
|
+// v2.14.0 client/server boundary test: similaritySearch with filters.
|
|
|
+//
|
|
|
+// Requested by smartbotic-vectorapi, which emulated a filtered vector search
|
|
|
+// by widening an unfiltered one and intersecting in its own process: 3.2 s for
|
|
|
+// a 0.26 s search, and past its 10000-candidate cap the answer could be short.
|
|
|
+//
|
|
|
+// THE ORACLE: an unfiltered search with topK = every row is the full ranking.
|
|
|
+// Restricted to the ids find() returns for the same filters, its first topK is
|
|
|
+// what a filtered search must return - same ids, same order, BIT-identical
|
|
|
+// scores, same bodies. That pins exactness (the true top-K among matching
|
|
|
+// rows, not a filtered slice of the unfiltered top-K) and that find() and a
|
|
|
+// filtered search agree on which rows match, for every operator.
|
|
|
+//
|
|
|
+// Phases, run by test_filtered_similarity.sh:
|
|
|
+// write - seed the collections.
|
|
|
+// check - every operator and a conjunction against the oracle, several
|
|
|
+// queries and topK values; fewer matches than topK; no match; a
|
|
|
+// field no row carries; minScore after the filter; ties ordered by
|
|
|
+// id; vector-less matching rows; the same answers once an index
|
|
|
+// serves the filter.
|
|
|
+// old <addr> - against a pre-2.14.0 server: filters are refused with
|
|
|
+// `filters_unsupported`, never answered unfiltered; no filters
|
|
|
+// still works.
|
|
|
+
|
|
|
+#include <smartbotic/database/client.hpp>
|
|
|
+
|
|
|
+#include <cstring>
|
|
|
+#include <iostream>
|
|
|
+#include <random>
|
|
|
+#include <set>
|
|
|
+#include <string>
|
|
|
+#include <vector>
|
|
|
+
|
|
|
+using namespace smartbotic::database;
|
|
|
+using F = Client::Filter;
|
|
|
+using SR = Client::SimilarityResult;
|
|
|
+static int pass = 0, fail = 0;
|
|
|
+static void ck(bool c, const std::string& m) {
|
|
|
+ if (c) { ++pass; } else { ++fail; std::cerr << "FAIL: " << m << "\n"; }
|
|
|
+}
|
|
|
+
|
|
|
+static std::string gAddr = "127.0.0.1:9024";
|
|
|
+static const uint32_t kDim = 8;
|
|
|
+static const int kRows = 300;
|
|
|
+static const int kNoVecFrom = 290; // rows 290..299 are written WITHOUT a vector
|
|
|
+
|
|
|
+static std::vector<float> randVec(uint32_t seed) {
|
|
|
+ std::mt19937 rng(seed);
|
|
|
+ std::normal_distribution<float> nd(0.f, 1.f);
|
|
|
+ std::vector<float> v(kDim);
|
|
|
+ for (auto& x : v) x = nd(rng);
|
|
|
+ return v;
|
|
|
+}
|
|
|
+static std::string rid(int i) {
|
|
|
+ char b[16];
|
|
|
+ std::snprintf(b, sizeof b, "r%03d", i);
|
|
|
+ return b;
|
|
|
+}
|
|
|
+static std::string deptOf(int i) {
|
|
|
+ if (i % 25 == 0) return "rare"; // 12 rows with a vector: 0, 25, ..., 275
|
|
|
+ static const char* d[] = {"a", "b", "c"};
|
|
|
+ return d[i % 3];
|
|
|
+}
|
|
|
+
|
|
|
+static Client::Config cfg() {
|
|
|
+ Client::Config c;
|
|
|
+ c.address = gAddr;
|
|
|
+ c.project = "fs";
|
|
|
+ return c;
|
|
|
+}
|
|
|
+
|
|
|
+static int write() {
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+ ck(c.createCollection("kb", 0, false, 0, kDim), "create kb (dim 8)");
|
|
|
+ for (int i = 0; i < kRows; ++i) {
|
|
|
+ nlohmann::json d = {
|
|
|
+ {"dept", deptOf(i)},
|
|
|
+ {"n", i},
|
|
|
+ {"tags", nlohmann::json::array({"t" + std::to_string(i % 5), "all"})},
|
|
|
+ {"title", "Doc " + std::to_string(i) + " body"},
|
|
|
+ {"meta", {{"note", i % 7 == 0 ? "Gamma ray" : "plain"}}},
|
|
|
+ };
|
|
|
+ if (i % 2 == 0) d["opt"] = true;
|
|
|
+ // The last rows match filters but have no vector: never offered.
|
|
|
+ if (i >= kNoVecFrom) d["dept"] = "rare";
|
|
|
+ else d["_vector"] = randVec(100 + i);
|
|
|
+ c.insert("kb", d, rid(i));
|
|
|
+ }
|
|
|
+ // Ties: three rows with the SAME vector, inserted out of id order.
|
|
|
+ const auto tv = randVec(7);
|
|
|
+ for (const char* id : {"tie_b", "tie_c", "tie_a"}) {
|
|
|
+ c.insert("kb", {{"dept", "tie"}, {"n", -1}, {"_vector", tv}}, id);
|
|
|
+ }
|
|
|
+ ck(c.createCollection("plain"), "create plain (no dimension)");
|
|
|
+ c.insert("plain", {{"dept", "a"}}, "p1");
|
|
|
+ return 0;
|
|
|
+}
|
|
|
+
|
|
|
+static std::set<std::string> findIds(Client& c, const std::vector<F>& filters) {
|
|
|
+ Client::QueryOptions o;
|
|
|
+ o.filters = filters;
|
|
|
+ o.limit = 100000;
|
|
|
+ std::set<std::string> ids;
|
|
|
+ for (const auto& d : c.find("kb", o, {"_id"})) ids.insert(d.value("_id", ""));
|
|
|
+ return ids;
|
|
|
+}
|
|
|
+
|
|
|
+static std::vector<SR> oracle(Client& c, const std::vector<float>& q,
|
|
|
+ const std::vector<F>& filters, uint32_t topK, float minScore) {
|
|
|
+ const auto all = c.similaritySearch("kb", q, 100000, minScore);
|
|
|
+ const auto ids = findIds(c, filters);
|
|
|
+ std::vector<SR> out;
|
|
|
+ for (const auto& r : all) {
|
|
|
+ if (out.size() >= topK) break;
|
|
|
+ if (ids.count(r.id)) out.push_back(r);
|
|
|
+ }
|
|
|
+ return out;
|
|
|
+}
|
|
|
+
|
|
|
+static bool sameBits(float a, float b) { return std::memcmp(&a, &b, sizeof a) == 0; }
|
|
|
+
|
|
|
+static void ordered(const std::vector<SR>& r, const std::string& what) {
|
|
|
+ bool ok = true;
|
|
|
+ for (size_t i = 1; i < r.size(); ++i) {
|
|
|
+ if (r[i - 1].score < r[i].score) ok = false;
|
|
|
+ if (r[i - 1].score == r[i].score && !(r[i - 1].id < r[i].id)) ok = false;
|
|
|
+ }
|
|
|
+ ck(ok, what + ": strictly descending, ties by id");
|
|
|
+}
|
|
|
+
|
|
|
+// Returns the filtered result so a caller can assert more about it.
|
|
|
+static std::vector<SR> against(Client& c, const std::string& what, const std::vector<float>& q,
|
|
|
+ const std::vector<F>& filters, uint32_t topK,
|
|
|
+ float minScore = 0.0f) {
|
|
|
+ const auto got = c.similaritySearch("kb", q, topK, minScore, filters);
|
|
|
+ const auto want = oracle(c, q, filters, topK, minScore);
|
|
|
+ bool same = got.size() == want.size();
|
|
|
+ for (size_t i = 0; same && i < got.size(); ++i) {
|
|
|
+ same = got[i].id == want[i].id && sameBits(got[i].score, want[i].score) &&
|
|
|
+ got[i].data == want[i].data;
|
|
|
+ }
|
|
|
+ ck(same, what + " k=" + std::to_string(topK) + ": equals the oracle (" +
|
|
|
+ std::to_string(got.size()) + " vs " + std::to_string(want.size()) + ")");
|
|
|
+ ordered(got, what);
|
|
|
+ return got;
|
|
|
+}
|
|
|
+
|
|
|
+static int check() {
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+
|
|
|
+ struct Case {
|
|
|
+ std::string name;
|
|
|
+ std::vector<F> filters;
|
|
|
+ };
|
|
|
+ const std::vector<Case> cases = {
|
|
|
+ {"eq", {F::eq("dept", "b")}},
|
|
|
+ {"ne", {F::ne("dept", "a")}},
|
|
|
+ {"gt", {F::gt("n", 150)}},
|
|
|
+ {"gte", {F::gte("n", 150)}},
|
|
|
+ {"lt", {F::lt("n", 40)}},
|
|
|
+ {"lte", {F::lte("n", 40)}},
|
|
|
+ {"in", {F::in("dept", nlohmann::json::array({"b", "rare"}))}},
|
|
|
+ {"contains", {F::contains("tags", "t3")}},
|
|
|
+ {"exists", {F::exists("opt", true)}},
|
|
|
+ {"not-exists", {F::exists("opt", false)}},
|
|
|
+ {"regex", {F::regex("title", "^Doc 1[0-9] ")}},
|
|
|
+ {"search", {F::search("", "gamma")}},
|
|
|
+ {"and", {F::eq("dept", "b"), F::gt("n", 100)}},
|
|
|
+ {"and-contains", {F::contains("tags", "all"), F::lt("n", 60)}},
|
|
|
+ };
|
|
|
+ const std::vector<uint32_t> ks = {1, 5, 50, 500};
|
|
|
+ for (uint32_t qs = 0; qs < 3; ++qs) {
|
|
|
+ const auto q = randVec(9000 + qs);
|
|
|
+ for (const auto& cs : cases) {
|
|
|
+ for (uint32_t k : ks) against(c, cs.name + " q" + std::to_string(qs), q, cs.filters, k);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // Sanity that the oracle is not vacuous: each case matches something,
|
|
|
+ // and "search" really searches nested values case-insensitively.
|
|
|
+ for (const auto& cs : cases) ck(!findIds(c, cs.filters).empty(), cs.name + " matches rows");
|
|
|
+
|
|
|
+ const auto q = randVec(4242);
|
|
|
+
|
|
|
+ // 1. Fewer matches than topK: all of them, and only those with a vector.
|
|
|
+ // minScore -1 admits every cosine; at the usual 0.0 a row scoring below
|
|
|
+ // zero is trimmed (minScore applies after the filter, as unfiltered).
|
|
|
+ {
|
|
|
+ const auto r = against(c, "rare", q, {F::eq("dept", "rare")}, 500, -1.0f);
|
|
|
+ ck(r.size() == 12, "rare: the 12 rows with a vector, not the 10 without (got " +
|
|
|
+ std::to_string(r.size()) + ")");
|
|
|
+ bool noVecLeak = true;
|
|
|
+ for (const auto& x : r) if (x.id >= rid(kNoVecFrom)) noVecLeak = false;
|
|
|
+ ck(noVecLeak, "rare: rows without a vector are never offered");
|
|
|
+ const auto z = against(c, "rare minScore 0", q, {F::eq("dept", "rare")}, 500);
|
|
|
+ size_t nonneg = 0;
|
|
|
+ for (const auto& x : r) if (x.score >= 0.0f) ++nonneg;
|
|
|
+ ck(z.size() == nonneg && nonneg < r.size(),
|
|
|
+ "rare at minScore 0: exactly the non-negative scores (" + std::to_string(z.size()) +
|
|
|
+ " of " + std::to_string(r.size()) + ")");
|
|
|
+ }
|
|
|
+ // Exactness is not trivially satisfied: the filtered top-12 reaches rows
|
|
|
+ // that an unfiltered top-12 does not contain.
|
|
|
+ {
|
|
|
+ const auto f = c.similaritySearch("kb", q, 12, 0.0f, {F::eq("dept", "rare")});
|
|
|
+ const auto u = c.similaritySearch("kb", q, 12);
|
|
|
+ std::set<std::string> uids;
|
|
|
+ for (const auto& x : u) uids.insert(x.id);
|
|
|
+ size_t outside = 0;
|
|
|
+ for (const auto& x : f) if (!uids.count(x.id)) ++outside;
|
|
|
+ ck(outside > 0, "filtered top-K reaches past the unfiltered top-K (" +
|
|
|
+ std::to_string(outside) + " rows)");
|
|
|
+ }
|
|
|
+ // 2. Scores bit-identical to the unfiltered search, row by row.
|
|
|
+ {
|
|
|
+ const auto f = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("dept", "c")});
|
|
|
+ const auto all = c.similaritySearch("kb", q, 100000);
|
|
|
+ bool ok = !f.empty();
|
|
|
+ for (const auto& x : f) {
|
|
|
+ bool found = false;
|
|
|
+ for (const auto& y : all) {
|
|
|
+ if (y.id == x.id) { found = sameBits(x.score, y.score); break; }
|
|
|
+ }
|
|
|
+ ok = ok && found;
|
|
|
+ }
|
|
|
+ ck(ok, "scores bit-identical to the unfiltered search");
|
|
|
+ }
|
|
|
+ // 3. A filter matching nothing: empty, not an error.
|
|
|
+ {
|
|
|
+ bool threw = false;
|
|
|
+ std::vector<SR> r;
|
|
|
+ try { r = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("dept", "zzz")}); }
|
|
|
+ catch (...) { threw = true; }
|
|
|
+ ck(!threw && r.empty(), "no match: empty, no throw");
|
|
|
+ }
|
|
|
+ // 5. A field no row carries: empty, never everything.
|
|
|
+ {
|
|
|
+ const auto r = c.similaritySearch("kb", q, 500, 0.0f, {F::eq("nosuchfield", "x")});
|
|
|
+ ck(r.empty(), "absent field: empty");
|
|
|
+ }
|
|
|
+ // minScore trims AFTER the filter.
|
|
|
+ {
|
|
|
+ const auto r = against(c, "minScore", q, {F::eq("dept", "b")}, 500, 0.3f);
|
|
|
+ bool ok = !r.empty();
|
|
|
+ for (const auto& x : r) ok = ok && x.score >= 0.3f;
|
|
|
+ ck(ok, "minScore: every returned score >= 0.3");
|
|
|
+ }
|
|
|
+ // 4. Ties: same vector, ordered by id, and the cut keeps the lower ids -
|
|
|
+ // filtered AND unfiltered.
|
|
|
+ {
|
|
|
+ const auto tq = randVec(7);
|
|
|
+ const auto f = c.similaritySearch("kb", tq, 2, 0.0f, {F::eq("dept", "tie")});
|
|
|
+ ck(f.size() == 2 && f[0].id == "tie_a" && f[1].id == "tie_b",
|
|
|
+ "ties (filtered): tie_a, tie_b");
|
|
|
+ const auto u = c.similaritySearch("kb", tq, 2);
|
|
|
+ ck(u.size() == 2 && u[0].id == "tie_a" && u[1].id == "tie_b",
|
|
|
+ "ties (unfiltered): tie_a, tie_b");
|
|
|
+ ck(f.size() == 2 && sameBits(f[0].score, f[1].score), "ties really tie");
|
|
|
+ }
|
|
|
+ // An explicitly project-qualified name means the same collection.
|
|
|
+ {
|
|
|
+ const auto a = c.similaritySearch("kb", q, 20, 0.0f, {F::eq("dept", "b")});
|
|
|
+ const auto b = c.similaritySearch("fs:kb", q, 20, 0.0f, {F::eq("dept", "b")});
|
|
|
+ bool same = a.size() == b.size() && !a.empty();
|
|
|
+ for (size_t i = 0; same && i < a.size(); ++i) same = a[i].id == b[i].id;
|
|
|
+ ck(same, "qualified name: same answer");
|
|
|
+ }
|
|
|
+ // Empty filters through the new overload is the plain search.
|
|
|
+ {
|
|
|
+ const auto a = c.similaritySearch("kb", q, 30, 0.0f, std::vector<F>{});
|
|
|
+ const auto b = c.similaritySearch("kb", q, 30);
|
|
|
+ bool same = a.size() == b.size() && a.size() == 30;
|
|
|
+ for (size_t i = 0; same && i < a.size(); ++i) {
|
|
|
+ same = a[i].id == b[i].id && sameBits(a[i].score, b[i].score);
|
|
|
+ }
|
|
|
+ ck(same, "empty filters: same as the plain search");
|
|
|
+ }
|
|
|
+ // A collection without a vector dimension: empty, not an error.
|
|
|
+ {
|
|
|
+ bool threw = false;
|
|
|
+ std::vector<SR> r;
|
|
|
+ try { r = c.similaritySearch("plain", q, 5, 0.0f, {F::eq("dept", "a")}); }
|
|
|
+ catch (...) { threw = true; }
|
|
|
+ ck(!threw && r.empty(), "no-vector collection: empty, no throw");
|
|
|
+ }
|
|
|
+
|
|
|
+ // The same answers once an index serves the filter.
|
|
|
+ ck(c.createIndex("kb", "dept"), "create index on dept");
|
|
|
+ ck(c.createIndex("kb", "tags"), "create index on tags");
|
|
|
+ for (uint32_t qs = 0; qs < 3; ++qs) {
|
|
|
+ const auto iq = randVec(9100 + qs);
|
|
|
+ against(c, "indexed rare", iq, {F::eq("dept", "rare")}, 500);
|
|
|
+ against(c, "indexed eq", iq, {F::eq("dept", "b")}, 7);
|
|
|
+ against(c, "indexed in", iq, {F::in("dept", nlohmann::json::array({"rare", "tie"}))}, 50);
|
|
|
+ against(c, "indexed contains", iq, {F::contains("tags", "t1")}, 5);
|
|
|
+ against(c, "indexed and", iq, {F::eq("dept", "rare"), F::gt("n", 100)}, 500);
|
|
|
+ against(c, "indexed miss", iq, {F::eq("dept", "zzz")}, 5);
|
|
|
+ // EQ with a scalar on an array field: the index names every row whose
|
|
|
+ // array CONTAINS it, but EQ compares the whole array, so nothing
|
|
|
+ // matches - only re-judging each candidate gets this right.
|
|
|
+ const auto arr = against(c, "indexed eq-on-array", iq, {F::eq("tags", "t1")}, 50);
|
|
|
+ ck(arr.empty(), "indexed eq-on-array: index candidates are re-judged (empty)");
|
|
|
+ }
|
|
|
+ return 0;
|
|
|
+}
|
|
|
+
|
|
|
+// Against a pre-2.14.0 server.
|
|
|
+static int old() {
|
|
|
+ Client c(cfg());
|
|
|
+ if (!c.connect()) { ck(false, "old: connect"); return 0; }
|
|
|
+ c.createCollection("kb", 0, false, 0, kDim);
|
|
|
+ for (int i = 0; i < 20; ++i) {
|
|
|
+ c.upsert("kb", {{"dept", deptOf(i)}, {"_vector", randVec(100 + i)}}, rid(i));
|
|
|
+ }
|
|
|
+ const auto q = randVec(1);
|
|
|
+ bool refused = false;
|
|
|
+ std::string reason;
|
|
|
+ try {
|
|
|
+ (void)c.similaritySearch("kb", q, 5, 0.0f, {F::eq("dept", "rare")});
|
|
|
+ } catch (const Client::FailedPrecondition& e) {
|
|
|
+ refused = true;
|
|
|
+ if (const auto* d = Client::errorDetail(e)) reason = d->reason;
|
|
|
+ } catch (...) {
|
|
|
+ }
|
|
|
+ ck(refused, "old server: filtered search refused, not answered unfiltered");
|
|
|
+ ck(reason == "filters_unsupported", "old server: reason filters_unsupported (got '" +
|
|
|
+ reason + "')");
|
|
|
+ ck(c.similaritySearch("kb", q, 5).size() == 5, "old server: plain search still works");
|
|
|
+ ck(c.similaritySearch("kb", q, 5, 0.0f, std::vector<F>{}).size() == 5,
|
|
|
+ "old server: empty filters still work");
|
|
|
+ return 0;
|
|
|
+}
|
|
|
+
|
|
|
+int main(int argc, char** argv) {
|
|
|
+ const std::string phase = argc > 1 ? argv[1] : "";
|
|
|
+ if (argc > 2) gAddr = argv[2];
|
|
|
+ if (phase == "write") write();
|
|
|
+ else if (phase == "check") check();
|
|
|
+ else if (phase == "old") old();
|
|
|
+ else { std::cerr << "usage: write|check|old [addr]\n"; return 2; }
|
|
|
+ std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
|
|
|
+ return fail == 0 ? 0 : 1;
|
|
|
+}
|