test_subdb_identity.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // v2.4.4 — sub-db identity sentinel tests.
  2. //
  3. // Regression cover for the production incident in which an invalidated
  4. // MDB_dbi was reused after LMDB reassigned its slot, so writes aimed at
  5. // `image_hashes` landed in `executions` and succeeded silently. 31 documents
  6. // across smartbotic-automation ended up in a sub-db other than the one they
  7. // declared. See storage/subdb_identity.hpp for the full mechanism.
  8. //
  9. // The core test is `misbound_handle_is_refused`: it reproduces the misbinding
  10. // directly by handing the verifier a handle for a different sub-db, which is
  11. // what a stale cache entry amounts to.
  12. #include <cassert>
  13. #include <atomic>
  14. #include <filesystem>
  15. #include <iostream>
  16. #include <cstdio>
  17. #include <set>
  18. #include <string>
  19. #include <unistd.h>
  20. #include <lmdb.h>
  21. #include <nlohmann/json.hpp>
  22. #include "document.hpp"
  23. #include "storage/document_store_lmdb.hpp"
  24. #include "storage/lmdb_env.hpp"
  25. #include "storage/lmdb_txn.hpp"
  26. #include "storage/subdb_identity.hpp"
  27. namespace fs = std::filesystem;
  28. using smartbotic::database::Document;
  29. using smartbotic::db::storage::is_identity_key;
  30. using smartbotic::db::storage::kSubdbIdentityKey;
  31. using smartbotic::db::storage::LmdbDocumentStore;
  32. using smartbotic::db::storage::LmdbEnv;
  33. using smartbotic::db::storage::LmdbEnvOpts;
  34. using smartbotic::db::storage::read_subdb_identity;
  35. using smartbotic::db::storage::ReadTxn;
  36. using smartbotic::db::storage::verify_subdb_identity;
  37. using smartbotic::db::storage::write_subdb_identity;
  38. using smartbotic::db::storage::WriteTxn;
  39. namespace {
  40. int g_pass = 0;
  41. int g_fail = 0;
  42. void check(bool cond, const char* msg) {
  43. if (cond) {
  44. ++g_pass;
  45. } else {
  46. ++g_fail;
  47. std::cerr << "FAIL: " << msg << "\n";
  48. }
  49. }
  50. std::string make_tmpdir(const char* tag) {
  51. static std::atomic<int> counter{0};
  52. std::string path = "/tmp/subdb-identity-test-" + std::to_string(::getpid()) +
  53. "-" + std::to_string(counter.fetch_add(1)) + "-" + tag;
  54. std::error_code ec;
  55. fs::remove_all(path, ec);
  56. return path;
  57. }
  58. struct TmpEnv {
  59. std::string path;
  60. LmdbEnv env;
  61. explicit TmpEnv(const char* tag)
  62. : path(make_tmpdir(tag)),
  63. env(LmdbEnvOpts{path, 64ULL << 20, 256, 126, false}) {}
  64. ~TmpEnv() {
  65. std::error_code ec;
  66. fs::remove_all(path, ec);
  67. }
  68. TmpEnv(const TmpEnv&) = delete;
  69. TmpEnv& operator=(const TmpEnv&) = delete;
  70. };
  71. // Open (creating) a named sub-db inside a write txn and return its handle.
  72. unsigned int open_subdb(WriteTxn& txn, const char* name) {
  73. MDB_dbi dbi = 0;
  74. int rc = mdb_dbi_open(txn.raw(), name, MDB_CREATE, &dbi);
  75. assert(rc == MDB_SUCCESS);
  76. (void)rc;
  77. return dbi;
  78. }
  79. Document make_doc(const std::string& id, const std::string& collection) {
  80. Document d;
  81. d.id = id;
  82. d.collection = collection;
  83. d.set_data(nlohmann::json{{"seenCount", 1}, {"who", collection}});
  84. return d;
  85. }
  86. // -------------------------------------------------------------------------
  87. void test_sentinel_roundtrip() {
  88. TmpEnv t("roundtrip");
  89. {
  90. WriteTxn w(t.env);
  91. unsigned int dbi = open_subdb(w, "image_hashes");
  92. write_subdb_identity(w, dbi, "image_hashes");
  93. w.commit();
  94. }
  95. {
  96. WriteTxn w(t.env);
  97. unsigned int dbi = open_subdb(w, "image_hashes");
  98. bool threw = false;
  99. try {
  100. verify_subdb_identity(w, dbi, "image_hashes");
  101. } catch (const std::exception&) {
  102. threw = true;
  103. }
  104. check(!threw, "matching sentinel must verify without throwing");
  105. w.commit();
  106. }
  107. {
  108. ReadTxn r(t.env);
  109. MDB_dbi dbi = 0;
  110. mdb_dbi_open(r.raw(), "image_hashes", 0, &dbi);
  111. check(read_subdb_identity(r, dbi) == "image_hashes",
  112. "read_subdb_identity returns the stamped name");
  113. }
  114. }
  115. // THE regression test. A stale cache entry is, in effect, a handle that
  116. // addresses someone else's sub-db. Hand the verifier exactly that.
  117. void test_misbound_handle_is_refused() {
  118. TmpEnv t("misbound");
  119. unsigned int executions_dbi = 0;
  120. {
  121. WriteTxn w(t.env);
  122. unsigned int ih = open_subdb(w, "image_hashes");
  123. write_subdb_identity(w, ih, "image_hashes");
  124. executions_dbi = open_subdb(w, "executions");
  125. write_subdb_identity(w, executions_dbi, "executions");
  126. w.commit();
  127. }
  128. WriteTxn w(t.env);
  129. // Re-open so the handle is valid in this txn, then deliberately verify it
  130. // under the WRONG name — the production misbinding, reproduced.
  131. unsigned int exec = open_subdb(w, "executions");
  132. bool threw = false;
  133. std::string msg;
  134. try {
  135. verify_subdb_identity(w, exec, "image_hashes");
  136. } catch (const std::exception& e) {
  137. threw = true;
  138. msg = e.what();
  139. }
  140. check(threw, "handle for 'executions' verified as 'image_hashes' must throw");
  141. check(msg.find("image_hashes") != std::string::npos &&
  142. msg.find("executions") != std::string::npos,
  143. "misbinding error names both the requested and actual sub-db");
  144. w.abort();
  145. }
  146. // Existing deployments have sub-dbs with no sentinel. Those must keep working.
  147. void test_unstamped_subdb_is_permitted() {
  148. TmpEnv t("unstamped");
  149. WriteTxn w(t.env);
  150. unsigned int dbi = open_subdb(w, "legacy");
  151. bool threw = false;
  152. try {
  153. verify_subdb_identity(w, dbi, "legacy");
  154. } catch (const std::exception&) {
  155. threw = true;
  156. }
  157. check(!threw, "sub-db without a sentinel must verify (absence is unknown, not wrong)");
  158. w.commit();
  159. }
  160. void test_identity_key_predicate() {
  161. check(is_identity_key(kSubdbIdentityKey), "sentinel key recognised");
  162. check(!is_identity_key("__subdb_identity__"),
  163. "same text without the leading NUL is NOT the sentinel");
  164. check(!is_identity_key("e63c1b90"), "a document id is not the sentinel");
  165. check(kSubdbIdentityKey[0] == '\0',
  166. "sentinel must start with NUL so it cannot collide with a doc id");
  167. }
  168. // The sentinel is an implementation detail: it must never surface through the
  169. // DocumentStore API as a document, nor inflate a count.
  170. void test_sentinel_invisible_through_store() {
  171. TmpEnv t("invisible");
  172. LmdbDocumentStore store(t.env);
  173. store.put("image_hashes", "aaa", make_doc("aaa", "image_hashes"));
  174. store.put("image_hashes", "bbb", make_doc("bbb", "image_hashes"));
  175. check(store.count("image_hashes") == 2,
  176. "count() must exclude the identity sentinel");
  177. smartbotic::database::Query q;
  178. q.limit = 100;
  179. auto res = store.scan("image_hashes", q);
  180. check(res.documents.size() == 2, "scan() must exclude the identity sentinel");
  181. check(res.total_matched == 2, "scan() total_matched must exclude the sentinel");
  182. for (const auto& d : res.documents) {
  183. check(d.id == "aaa" || d.id == "bbb",
  184. "scan() must not surface the sentinel as a document");
  185. }
  186. // And it really is on disk.
  187. ReadTxn r(t.env);
  188. MDB_dbi dbi = 0;
  189. int rc = mdb_dbi_open(r.raw(), "image_hashes", 0, &dbi);
  190. check(rc == MDB_SUCCESS, "sub-db exists");
  191. check(read_subdb_identity(r, dbi) == "image_hashes",
  192. "store.put() stamps the sentinel on first write");
  193. }
  194. // A vector sub-db gets stamped with its own (prefixed) name, and scan_vectors
  195. // must skip the sentinel rather than trying to read it as float32 bytes.
  196. void test_vector_subdb_sentinel() {
  197. TmpEnv t("vectors");
  198. LmdbDocumentStore store(t.env);
  199. store.put_vector("emb", "v1", {1.0f, 2.0f, 3.0f});
  200. store.put_vector("emb", "v2", {4.0f, 5.0f, 6.0f});
  201. int seen = 0;
  202. bool bad = false;
  203. store.scan_vectors("emb", [&](std::string_view id, const float*, size_t n) {
  204. ++seen;
  205. if (n != 3) bad = true;
  206. if (is_identity_key(id)) bad = true;
  207. });
  208. check(seen == 2, "scan_vectors must skip the sentinel");
  209. check(!bad, "scan_vectors must not decode the sentinel as float data");
  210. ReadTxn r(t.env);
  211. MDB_dbi dbi = 0;
  212. mdb_dbi_open(r.raw(), "_vectors_emb", 0, &dbi);
  213. check(read_subdb_identity(r, dbi) == "_vectors_emb",
  214. "vector sub-db is stamped with its prefixed name");
  215. }
  216. // v2.4.4 Count is LMDB-first. Unfiltered it uses count(); filtered it uses
  217. // scan() with limit=0 and reads total_matched. Pin that contract: total_matched
  218. // is computed BEFORE pagination, so limit=0 must still report the true total
  219. // while returning no documents.
  220. void test_scan_limit_zero_reports_total() {
  221. TmpEnv t("counting");
  222. LmdbDocumentStore store(t.env);
  223. for (int i = 0; i < 5; ++i) {
  224. Document d;
  225. d.id = "id" + std::to_string(i);
  226. d.collection = "things";
  227. d.set_data(nlohmann::json{{"kind", i < 3 ? "alpha" : "beta"}});
  228. store.put("things", d.id, d);
  229. }
  230. smartbotic::database::Query q;
  231. q.limit = 0;
  232. auto all = store.scan("things", q);
  233. check(all.total_matched == 5, "limit=0 reports the full total");
  234. check(all.documents.empty(), "limit=0 returns no documents");
  235. check(store.count("things") == 5, "unfiltered count matches");
  236. smartbotic::database::Query fq;
  237. fq.limit = 0;
  238. smartbotic::database::Filter f;
  239. f.field = "kind";
  240. f.op = smartbotic::database::FilterOp::EQ;
  241. f.value = "alpha";
  242. fq.filters.push_back(f);
  243. auto filtered = store.scan("things", fq);
  244. check(filtered.total_matched == 3,
  245. "filtered limit=0 reports the matching total, not the collection size");
  246. }
  247. // v2.7.1 — the unfiltered/unsorted fast path in scan() must agree with the
  248. // general path exactly. It exists because the general path decoded every
  249. // document in the collection to return `limit` of them, so cost tracked total
  250. // bytes rather than page size (382ms to return one 510-byte document from a
  251. // 414 MB collection on a live instance). Any divergence here is a paging bug.
  252. void test_scan_fast_path_matches_general_path() {
  253. TmpEnv t("fastpath");
  254. LmdbDocumentStore store(t.env);
  255. for (int i = 0; i < 25; ++i) {
  256. Document d;
  257. char buf[16];
  258. std::snprintf(buf, sizeof(buf), "id%02d", i);
  259. d.id = buf;
  260. d.collection = "things";
  261. d.set_data(nlohmann::json{{"n", i}, {"kind", i % 2 ? "odd" : "even"}});
  262. store.put("things", d.id, d);
  263. }
  264. // total_matched and has_more must match what a full count says.
  265. smartbotic::database::Query page;
  266. page.limit = 10;
  267. page.offset = 0;
  268. auto p0 = store.scan("things", page);
  269. check(p0.documents.size() == 10, "fast path returns exactly `limit` docs");
  270. check(p0.total_matched == 25, "fast path total_matched excludes the sentinel");
  271. check(p0.has_more, "has_more true when more remain");
  272. page.offset = 20;
  273. auto p2 = store.scan("things", page);
  274. check(p2.documents.size() == 5, "final page returns the remainder");
  275. check(p2.total_matched == 25, "total_matched stable across pages");
  276. check(!p2.has_more, "has_more false on the last page");
  277. page.offset = 25;
  278. auto p3 = store.scan("things", page);
  279. check(p3.documents.empty(), "offset past the end returns nothing");
  280. check(p3.total_matched == 25, "and still reports the true total");
  281. // Paging must cover every document exactly once, in a stable order.
  282. std::set<std::string> seen;
  283. for (uint32_t off = 0; off < 25; off += 7) {
  284. smartbotic::database::Query q;
  285. q.limit = 7;
  286. q.offset = off;
  287. for (const auto& d : store.scan("things", q).documents) seen.insert(d.id);
  288. }
  289. check(seen.size() == 25, "paging the whole collection yields every document once");
  290. // A filter forces the general path; it must still be correct.
  291. smartbotic::database::Query fq;
  292. fq.limit = 100;
  293. smartbotic::database::Filter f;
  294. f.field = "kind";
  295. f.op = smartbotic::database::FilterOp::EQ;
  296. f.value = "odd";
  297. fq.filters.push_back(f);
  298. auto filtered = store.scan("things", fq);
  299. check(filtered.total_matched == 12, "filtered path still counts matches, not rows");
  300. // A sort also forces the general path.
  301. smartbotic::database::Query sq;
  302. sq.limit = 3;
  303. sq.sort = smartbotic::database::Sort{"n", true};
  304. auto sorted = store.scan("things", sq);
  305. check(sorted.documents.size() == 3, "sorted path paginates");
  306. check(sorted.total_matched == 25, "sorted path totals all rows");
  307. check(sorted.documents[0].data().value("n", -1) == 24,
  308. "descending sort really sorted (fast path must not swallow sorts)");
  309. // limit=0 keeps meaning "no documents, but a true total" - the contract
  310. // Count depends on (see test_scan_limit_zero_reports_total).
  311. smartbotic::database::Query zq;
  312. zq.limit = 0;
  313. auto z = store.scan("things", zq);
  314. check(z.documents.empty(), "limit=0 returns no documents on the fast path");
  315. check(z.total_matched == 25, "limit=0 still reports the true total");
  316. }
  317. // v2.8.0 — a WRITE that aborts must not poison the collection.
  318. //
  319. // This is the v2.4.3 EINVAL bug in a third failure mode, observed live in
  320. // production on 2.7.1: `find` on smartbotic-automation:workflows failed with
  321. // "LMDB cursor_open: Invalid argument" on every attempt while every other
  322. // collection was fine, and a restart was the only cure.
  323. //
  324. // Cause: open_for_write() cached the MDB_dbi immediately after mdb_dbi_open,
  325. // BEFORE the caller committed. LMDB keeps a handle private to the opening
  326. // transaction until it commits and CLOSES it if that transaction aborts - so any
  327. // write that threw after the handle was cached (a failed mdb_put, a sentinel
  328. // mismatch, a WriteTxn destructing uncommitted) left a closed handle in the
  329. // cache, and every later operation on that collection failed EINVAL for the rest
  330. // of the process's life.
  331. //
  332. // The abort is induced honestly here, with a key past LMDB's 511-byte limit, so
  333. // the test exercises the same path a real failed write takes.
  334. void test_aborted_write_does_not_poison_the_collection() {
  335. TmpEnv t("abortpoison");
  336. LmdbDocumentStore store(t.env);
  337. // Force a write that opens the sub-db and then fails: an oversized key makes
  338. // mdb_put return MDB_BAD_VALSIZE, which throws, so the WriteTxn aborts.
  339. const std::string huge_id(600, 'k');
  340. bool threw = false;
  341. try {
  342. store.put("poisoned", huge_id, make_doc(huge_id, "poisoned"));
  343. } catch (const std::exception&) {
  344. threw = true;
  345. }
  346. check(threw, "an oversized key really does fail the write");
  347. // The collection must still be usable. Before the fix, every one of these
  348. // failed with EINVAL because the cache held a handle LMDB had closed.
  349. bool ok_put = true;
  350. try {
  351. store.put("poisoned", "good", make_doc("good", "poisoned"));
  352. } catch (const std::exception&) {
  353. ok_put = false;
  354. }
  355. check(ok_put, "a later WRITE to the same collection still works");
  356. bool ok_read = true;
  357. try {
  358. smartbotic::database::Query q;
  359. q.limit = 10;
  360. auto res = store.scan("poisoned", q);
  361. check(res.documents.size() == 1, "and the document written after the abort is there");
  362. } catch (const std::exception&) {
  363. ok_read = false;
  364. }
  365. check(ok_read, "a later SCAN of the same collection still works (cursor_open)");
  366. bool ok_count = true;
  367. try {
  368. check(store.count("poisoned") == 1, "count is right after the abort");
  369. } catch (const std::exception&) {
  370. ok_count = false;
  371. }
  372. check(ok_count, "and count() does not throw");
  373. check(store.get("poisoned", "good").has_value(), "get() works after the abort");
  374. }
  375. } // namespace
  376. int main() {
  377. std::cout << "=== test_subdb_identity ===\n";
  378. test_sentinel_roundtrip();
  379. test_misbound_handle_is_refused();
  380. test_unstamped_subdb_is_permitted();
  381. test_identity_key_predicate();
  382. test_sentinel_invisible_through_store();
  383. test_vector_subdb_sentinel();
  384. test_scan_limit_zero_reports_total();
  385. test_scan_fast_path_matches_general_path();
  386. test_aborted_write_does_not_poison_the_collection();
  387. std::cout << "passed: " << g_pass << ", failed: " << g_fail << "\n";
  388. return g_fail == 0 ? 0 : 1;
  389. }