|
|
@@ -0,0 +1,370 @@
|
|
|
+// v2.13.0 client/server boundary test: reading stored vectors back, and
|
|
|
+// exporting a collection so that the export is a real backup.
|
|
|
+//
|
|
|
+// Requested by smartbotic-vectorapi: nothing returned a stored embedding, so an
|
|
|
+// export of a vector collection would silently produce rows that re-import as
|
|
|
+// unsearchable JSON. Phases, run by test_export.sh:
|
|
|
+// write - seed: rows with vectors, rows written without, rows whose vector
|
|
|
+// an update removed, rows a patch left alone, a body carrying the
|
|
|
+// six reserved read-metadata names, a collection with no dimension.
|
|
|
+// check - get/find WithVector; the export contract (header, clamp, order,
|
|
|
+// count, states, exact vectors); THE ROUND TRIP (export -> insert
|
|
|
+// into an empty collection -> same fields, same vectors, each row
|
|
|
+// its own nearest neighbour, fresh metadata); resume; refusals; the
|
|
|
+// file Failure& overloads; a throwing event handler.
|
|
|
+// after - after a restart, the states are unchanged (the has-vector marker
|
|
|
+// persisted through WAL/snapshot and the LMDB envelope).
|
|
|
+// race - exports run while vectors are being inserted: every row a stream
|
|
|
+// sees must be PRESENT. Before 2.13.0 a document and its vector were
|
|
|
+// two commits, so a snapshot between them saw the row without it.
|
|
|
+// down - server stopped: every new call reports Unavailable.
|
|
|
+
|
|
|
+#include <smartbotic/database/client.hpp>
|
|
|
+
|
|
|
+#include <algorithm>
|
|
|
+#include <atomic>
|
|
|
+#include <chrono>
|
|
|
+#include <iostream>
|
|
|
+#include <random>
|
|
|
+#include <set>
|
|
|
+#include <string>
|
|
|
+#include <thread>
|
|
|
+#include <vector>
|
|
|
+
|
|
|
+using namespace smartbotic::database;
|
|
|
+using VS = Client::VectorState;
|
|
|
+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 const char* kAddr = "127.0.0.1:9023";
|
|
|
+static const uint32_t kDim = 4;
|
|
|
+
|
|
|
+static std::vector<float> vecFor(int i) {
|
|
|
+ std::mt19937 rng(1000 + i);
|
|
|
+ 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 id3(const char* p, int i) {
|
|
|
+ char b[16];
|
|
|
+ std::snprintf(b, sizeof b, "%s%03d", p, i);
|
|
|
+ return b;
|
|
|
+}
|
|
|
+static nlohmann::json userFields(nlohmann::json d) {
|
|
|
+ for (const char* k : {"_id", "_version", "_created_at", "_updated_at", "_created_by",
|
|
|
+ "_updated_by", "_vector"}) {
|
|
|
+ d.erase(k);
|
|
|
+ }
|
|
|
+ return d;
|
|
|
+}
|
|
|
+
|
|
|
+struct Export {
|
|
|
+ Client::ExportHeader header;
|
|
|
+ std::vector<Client::ExportRow> rows;
|
|
|
+ Client::ExportSummary summary;
|
|
|
+};
|
|
|
+static Export runExport(Client& c, const std::string& coll, bool vectors,
|
|
|
+ const std::string& after = "", size_t stopAfter = 0,
|
|
|
+ uint32_t batchRows = 0) {
|
|
|
+ Export e;
|
|
|
+ e.summary = c.exportCollection(
|
|
|
+ coll, vectors, after, [&](const Client::ExportHeader& h) { e.header = h; },
|
|
|
+ [&](Client::ExportRow&& r) {
|
|
|
+ e.rows.push_back(std::move(r));
|
|
|
+ return stopAfter == 0 || e.rows.size() < stopAfter;
|
|
|
+ },
|
|
|
+ batchRows);
|
|
|
+ return e;
|
|
|
+}
|
|
|
+
|
|
|
+static Client::Config cfg() {
|
|
|
+ Client::Config c;
|
|
|
+ c.address = kAddr;
|
|
|
+ c.project = "ex";
|
|
|
+ return c;
|
|
|
+}
|
|
|
+
|
|
|
+static int write() {
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+ ck(c.createCollection("vecs", 0, false, 0, kDim), "create vecs (dim 4)");
|
|
|
+ for (int i = 0; i < 400; ++i) {
|
|
|
+ c.insert("vecs", {{"n", i}, {"s", "row " + std::to_string(i)}, {"_vector", vecFor(i)}},
|
|
|
+ id3("v", i));
|
|
|
+ }
|
|
|
+ for (int i = 0; i < 40; ++i) c.insert("vecs", {{"n", 1000 + i}}, id3("w", i));
|
|
|
+ for (int i = 0; i < 20; ++i) {
|
|
|
+ c.insert("vecs", {{"n", 2000 + i}, {"_vector", vecFor(2000 + i)}}, id3("u", i));
|
|
|
+ ck(c.update("vecs", id3("u", i), {{"n", 2000 + i}, {"updated", true}}),
|
|
|
+ "update without _vector");
|
|
|
+ }
|
|
|
+ for (int i = 0; i < 20; ++i) {
|
|
|
+ c.insert("vecs", {{"n", 3000 + i}, {"_vector", vecFor(3000 + i)}}, id3("p", i));
|
|
|
+ Client::FailureDetail fd;
|
|
|
+ ck(c.patch("vecs", id3("p", i), {{"patched", true}}, fd) > 0, "patch without _vector");
|
|
|
+ }
|
|
|
+ // A body carrying the six read-metadata names - what a read handed back
|
|
|
+ // and written again looks like.
|
|
|
+ c.insert("vecs", {{"n", 5000}, {"_id", "fake"}, {"_version", 99}, {"_created_at", 5},
|
|
|
+ {"_updated_at", 6}, {"_created_by", "mallory"}, {"_updated_by", "mallory"},
|
|
|
+ {"_vector", vecFor(5000)}},
|
|
|
+ "shadow");
|
|
|
+ ck(c.createCollection("plain"), "create plain (no dimension)");
|
|
|
+ for (int i = 0; i < 3; ++i) c.insert("plain", {{"n", i}}, id3("q", i));
|
|
|
+ return 0;
|
|
|
+}
|
|
|
+
|
|
|
+static void check() {
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+
|
|
|
+ // --- get / find WithVector
|
|
|
+ auto g = c.get("vecs", "v007", Client::WithVector{});
|
|
|
+ ck(g && g->contains("_vector") && (*g)["_vector"].get<std::vector<float>>() == vecFor(7),
|
|
|
+ "get WithVector returns the exact stored vector");
|
|
|
+ auto plainGet = c.get("vecs", "v007");
|
|
|
+ ck(plainGet && !plainGet->contains("_vector"), "plain get does not return the vector");
|
|
|
+ auto gw = c.get("vecs", "w003", Client::WithVector{});
|
|
|
+ ck(gw && !gw->contains("_vector"), "get WithVector on a row with no vector: no _vector key");
|
|
|
+ auto gu = c.get("vecs", "u003", Client::WithVector{});
|
|
|
+ ck(gu && !gu->contains("_vector"), "an update without _vector removed the vector");
|
|
|
+ auto gp = c.get("vecs", "p003", Client::WithVector{});
|
|
|
+ ck(gp && (*gp)["_vector"].get<std::vector<float>>() == vecFor(3003) && (*gp)["patched"] == true,
|
|
|
+ "a patch without _vector kept the vector");
|
|
|
+ auto f = c.find("vecs", Client::QueryOptions{.filters = {Client::Filter::lt("n", 5)}},
|
|
|
+ Client::WithVector{});
|
|
|
+ bool fv = f.size() == 5;
|
|
|
+ for (auto& d : f) {
|
|
|
+ fv = fv && d.contains("_vector") &&
|
|
|
+ d["_vector"].get<std::vector<float>>() == vecFor(d["n"].get<int>());
|
|
|
+ }
|
|
|
+ ck(fv, "find WithVector returns each row's vector");
|
|
|
+
|
|
|
+ // --- reserved names in a write body are not stored
|
|
|
+ auto sh = c.get("vecs", "shadow");
|
|
|
+ ck(sh && (*sh)["_id"] == "shadow" && (*sh)["_version"] == 1 && (*sh)["_created_by"] == "",
|
|
|
+ "read metadata on a row written with fake metadata is the real metadata");
|
|
|
+
|
|
|
+ // --- the export contract
|
|
|
+ const auto exportStart = std::chrono::system_clock::now();
|
|
|
+ auto e = runExport(c, "vecs", true, "", 0, 100000);
|
|
|
+ const uint64_t total = 400 + 40 + 20 + 20 + 1;
|
|
|
+ ck(e.header.vectorDimension == kDim, "header: dimension");
|
|
|
+ ck(e.header.vectorDtype == "float32-le", "header: dtype");
|
|
|
+ ck(e.header.batchRowsEffective == 1024, "header: batch_rows 100000 clamped to 1024");
|
|
|
+ ck(e.header.maxStreamSeconds == 600, "header: stream cap");
|
|
|
+ ck(e.header.rowsAtSnapshot == total, "header: rows at snapshot");
|
|
|
+ ck(e.summary.complete && e.summary.rowsSent == total && e.rows.size() == total,
|
|
|
+ "complete, every row delivered, rowsSent == rowsAtSnapshot");
|
|
|
+ bool ordered = true;
|
|
|
+ for (size_t i = 1; i < e.rows.size(); ++i) ordered = ordered && e.rows[i - 1].id < e.rows[i].id;
|
|
|
+ ck(ordered, "rows in id order, no duplicates");
|
|
|
+ ck(!e.rows.empty() && e.summary.lastId == e.rows.back().id, "lastId is the last row");
|
|
|
+
|
|
|
+ int present = 0, none = 0, other = 0;
|
|
|
+ bool exact = true, idsMatch = true, noShadow = true;
|
|
|
+ for (auto& r : e.rows) {
|
|
|
+ idsMatch = idsMatch && r.document["_id"] == r.id;
|
|
|
+ if (r.id == "shadow") {
|
|
|
+ const std::string dump = r.document.dump();
|
|
|
+ noShadow = dump.find("mallory") == std::string::npos && r.document["_version"] == 1;
|
|
|
+ }
|
|
|
+ const char p = r.id[0];
|
|
|
+ if (p == 'v' || p == 'p' || r.id == "shadow") {
|
|
|
+ if (r.vectorState == VS::Present) ++present; else ++other;
|
|
|
+ const int n = r.document["n"].get<int>();
|
|
|
+ exact = exact && r.vector == vecFor(n);
|
|
|
+ } else {
|
|
|
+ if (r.vectorState == VS::None) ++none; else ++other;
|
|
|
+ exact = exact && r.vector.empty();
|
|
|
+ }
|
|
|
+ exact = exact && !r.document.contains("_vector");
|
|
|
+ }
|
|
|
+ ck(present == 421 && none == 60 && other == 0, "states: 421 present, 60 none, nothing else (" +
|
|
|
+ std::to_string(present) + "/" + std::to_string(none) + "/" + std::to_string(other) + ")");
|
|
|
+ ck(exact, "every vector byte-identical; vector is in row.vector, not the document");
|
|
|
+ ck(idsMatch, "each row's document carries its own _id");
|
|
|
+ ck(noShadow, "no stored shadow metadata in the exported row");
|
|
|
+
|
|
|
+ // --- THE ROUND TRIP: export -> insert into an empty collection
|
|
|
+ ck(c.createCollection("vecs_copy", 0, false, 0, kDim), "create vecs_copy (dim 4)");
|
|
|
+ for (auto& r : e.rows) {
|
|
|
+ nlohmann::json body = r.document;
|
|
|
+ if (r.vectorState == VS::Present) body["_vector"] = r.vector;
|
|
|
+ c.insert("vecs_copy", body, r.id);
|
|
|
+ }
|
|
|
+ auto e2 = runExport(c, "vecs_copy", true);
|
|
|
+ ck(e2.summary.complete && e2.rows.size() == e.rows.size(), "copy has every row");
|
|
|
+ bool same = e2.rows.size() == e.rows.size();
|
|
|
+ bool fresh = same;
|
|
|
+ for (size_t i = 0; same && i < e.rows.size(); ++i) {
|
|
|
+ same = e2.rows[i].id == e.rows[i].id &&
|
|
|
+ userFields(e2.rows[i].document) == userFields(e.rows[i].document) &&
|
|
|
+ e2.rows[i].vectorState == e.rows[i].vectorState &&
|
|
|
+ e2.rows[i].vector == e.rows[i].vector;
|
|
|
+ fresh = fresh && e2.rows[i].document["_version"] == 1 &&
|
|
|
+ e2.rows[i].document["_created_at"].get<uint64_t>() >
|
|
|
+ e.rows[i].document["_created_at"].get<uint64_t>();
|
|
|
+ }
|
|
|
+ ck(same, "round trip: same ids, same fields, same states, byte-identical vectors");
|
|
|
+ ck(fresh, "restored rows carry FRESH metadata (version 1, newer timestamps)");
|
|
|
+ int nearest = 0;
|
|
|
+ for (int i = 0; i < 400; i += 8) {
|
|
|
+ auto hits = c.similaritySearch("vecs_copy", vecFor(i), 1);
|
|
|
+ if (!hits.empty() && hits[0].id == id3("v", i)) ++nearest;
|
|
|
+ }
|
|
|
+ ck(nearest == 50, "round trip: each sampled row is its own nearest neighbour (" +
|
|
|
+ std::to_string(nearest) + "/50)");
|
|
|
+ (void)exportStart;
|
|
|
+
|
|
|
+ // --- resume
|
|
|
+ auto part = runExport(c, "vecs", false, "", 150);
|
|
|
+ ck(!part.summary.complete && part.summary.rowsSent == 150 && part.summary.lastId == part.rows.back().id,
|
|
|
+ "a handler returning false stops after that row; lastId names it");
|
|
|
+ auto rest = runExport(c, "vecs", false, part.summary.lastId);
|
|
|
+ ck(rest.header.rowsAtSnapshot == total - 150 && rest.summary.complete,
|
|
|
+ "resume counts and completes the rest");
|
|
|
+ std::set<std::string> ids;
|
|
|
+ for (auto& r : part.rows) ids.insert(r.id);
|
|
|
+ for (auto& r : rest.rows) ids.insert(r.id);
|
|
|
+ ck(ids.size() == total && part.rows.size() + rest.rows.size() == total,
|
|
|
+ "first part + resume = every row exactly once");
|
|
|
+ bool unspecified = true;
|
|
|
+ for (auto& r : part.rows) unspecified = unspecified && r.vectorState == VS::Unspecified && r.vector.empty();
|
|
|
+ ck(unspecified, "without vectors: no state, no bytes");
|
|
|
+
|
|
|
+ // --- refusals
|
|
|
+ bool refused = false;
|
|
|
+ std::string reason;
|
|
|
+ try { runExport(c, "plain", true); }
|
|
|
+ catch (const Client::Error& err) {
|
|
|
+ refused = err.code() == Client::ErrorCode::InvalidArgument;
|
|
|
+ if (auto* d = Client::errorDetail(err)) reason = d->reason;
|
|
|
+ }
|
|
|
+ ck(refused && reason == "no_vector_index",
|
|
|
+ "vectors from a collection with no dimension: InvalidArgument, reason no_vector_index");
|
|
|
+ auto pl = runExport(c, "plain", false);
|
|
|
+ ck(pl.summary.complete && pl.rows.size() == 3, "a dimension-0 collection exports without vectors");
|
|
|
+ bool nf = false;
|
|
|
+ try { runExport(c, "no_such_coll", false); }
|
|
|
+ catch (const Client::Error& err) { nf = err.code() == Client::ErrorCode::NotFound; }
|
|
|
+ ck(nf, "export of a missing collection throws NotFound");
|
|
|
+
|
|
|
+ // --- file calls report a reason
|
|
|
+ Client::Failure ff;
|
|
|
+ ck(!c.setFileTtl("no-such-file", 60, ff) && ff.code == Client::ErrorCode::NotFound,
|
|
|
+ "setFileTtl on a missing file: false, NotFound");
|
|
|
+ Client::Failure fd;
|
|
|
+ ck(!c.deleteFile("no-such-file", fd) && fd.code == Client::ErrorCode::NotFound,
|
|
|
+ "deleteFile on a missing file: false, NotFound");
|
|
|
+
|
|
|
+ // --- a throwing event handler drops its event, not the process
|
|
|
+ std::atomic<int> seen{0};
|
|
|
+ auto sub = c.subscribeEvents({"evt"}, [&](const Client::Event&) {
|
|
|
+ if (seen.fetch_add(1) == 0) throw std::runtime_error("handler bug");
|
|
|
+ });
|
|
|
+ std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
|
|
+ c.insert("evt", {{"a", 1}}, "e1");
|
|
|
+ c.insert("evt", {{"a", 2}}, "e2");
|
|
|
+ for (int i = 0; i < 50 && seen.load() < 2; ++i) {
|
|
|
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
|
|
+ }
|
|
|
+ ck(seen.load() == 2, "after a handler threw, the next event still arrived (" +
|
|
|
+ std::to_string(seen.load()) + ")");
|
|
|
+ sub.reset();
|
|
|
+}
|
|
|
+
|
|
|
+static void after() {
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+ auto e = runExport(c, "vecs", true);
|
|
|
+ int present = 0, none = 0, other = 0;
|
|
|
+ for (auto& r : e.rows) {
|
|
|
+ if (r.vectorState == VS::Present) ++present;
|
|
|
+ else if (r.vectorState == VS::None) ++none;
|
|
|
+ else ++other;
|
|
|
+ }
|
|
|
+ ck(e.summary.complete && present == 421 && none == 60 && other == 0,
|
|
|
+ "after a restart the states are unchanged (" + std::to_string(present) + "/" +
|
|
|
+ std::to_string(none) + "/" + std::to_string(other) + ")");
|
|
|
+ auto g = c.get("vecs", "v011", Client::WithVector{});
|
|
|
+ ck(g && (*g)["_vector"].get<std::vector<float>>() == vecFor(11), "vector readable after restart");
|
|
|
+}
|
|
|
+
|
|
|
+static void race() {
|
|
|
+ Client w(cfg());
|
|
|
+ w.connect();
|
|
|
+ w.createCollection("race", 0, false, 0, kDim);
|
|
|
+ std::atomic<bool> done{false};
|
|
|
+ std::thread writer([&]() {
|
|
|
+ for (int i = 0; i < 3000; ++i) {
|
|
|
+ w.insert("race", {{"n", i}, {"_vector", vecFor(i)}}, id3("x", i % 1000) + "-" +
|
|
|
+ std::to_string(i));
|
|
|
+ }
|
|
|
+ done = true;
|
|
|
+ });
|
|
|
+ Client c(cfg());
|
|
|
+ c.connect();
|
|
|
+ int exports = 0, rows = 0, notPresent = 0;
|
|
|
+ while (!done.load()) {
|
|
|
+ try {
|
|
|
+ auto e = runExport(c, "race", true);
|
|
|
+ ++exports;
|
|
|
+ rows += static_cast<int>(e.rows.size());
|
|
|
+ for (auto& r : e.rows) {
|
|
|
+ if (r.vectorState != VS::Present) {
|
|
|
+ if (notPresent < 5) {
|
|
|
+ std::cerr << " row " << r.id << " state " << static_cast<int>(r.vectorState) << "\n";
|
|
|
+ }
|
|
|
+ ++notPresent;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (const Client::Error& err) {
|
|
|
+ if (err.code() != Client::ErrorCode::NotFound) throw; // collection not created yet
|
|
|
+ }
|
|
|
+ }
|
|
|
+ writer.join();
|
|
|
+ std::cout << "race: " << exports << " exports, " << rows << " rows seen\n";
|
|
|
+ ck(exports >= 3, "several exports ran during the inserts");
|
|
|
+ ck(notPresent == 0, "no export saw a row without its vector (" + std::to_string(notPresent) + ")");
|
|
|
+}
|
|
|
+
|
|
|
+static void down() {
|
|
|
+ Client::Config cf = cfg();
|
|
|
+ cf.timeoutMs = 700;
|
|
|
+ cf.maxRetries = 0;
|
|
|
+ cf.writeRetries = 0;
|
|
|
+ Client c(cf);
|
|
|
+ c.connect();
|
|
|
+ auto code = [](auto fn) {
|
|
|
+ try { fn(); } catch (const Client::Error& e) { return e.code(); } catch (...) {}
|
|
|
+ return Client::ErrorCode::Ok;
|
|
|
+ };
|
|
|
+ ck(code([&] { (void)c.get("vecs", "v001", Client::WithVector{}); }) == Client::ErrorCode::Unavailable,
|
|
|
+ "down: get WithVector throws Unavailable");
|
|
|
+ ck(code([&] { (void)c.find("vecs", Client::QueryOptions{}, Client::WithVector{}); }) ==
|
|
|
+ Client::ErrorCode::Unavailable,
|
|
|
+ "down: find WithVector throws Unavailable");
|
|
|
+ ck(code([&] { runExport(c, "vecs", true); }) == Client::ErrorCode::Unavailable,
|
|
|
+ "down: export throws Unavailable");
|
|
|
+ Client::Failure f1, f2;
|
|
|
+ ck(!c.setFileTtl("x", 60, f1) && f1.code == Client::ErrorCode::Unavailable,
|
|
|
+ "down: setFileTtl reports Unavailable, not NotFound");
|
|
|
+ ck(!c.deleteFile("x", f2) && f2.code == Client::ErrorCode::Unavailable,
|
|
|
+ "down: deleteFile reports Unavailable, not NotFound");
|
|
|
+}
|
|
|
+
|
|
|
+int main(int argc, char** argv) {
|
|
|
+ const std::string phase = argc > 1 ? argv[1] : "";
|
|
|
+ if (phase == "write") write();
|
|
|
+ else if (phase == "check") check();
|
|
|
+ else if (phase == "after") after();
|
|
|
+ else if (phase == "race") race();
|
|
|
+ else if (phase == "down") down();
|
|
|
+ else { std::cerr << "usage: write|check|after|race|down\n"; return 2; }
|
|
|
+ std::cout << phase << ": " << pass << " passed, " << fail << " failed\n";
|
|
|
+ return fail == 0 ? 0 : 1;
|
|
|
+}
|