test_relation_index.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // v2.11.0 T2 — relation reverse index tests.
  2. //
  3. // Storage-only: this exercises LmdbDocumentStore::relation_index_{add,remove,
  4. // child_count,children} directly. No document-write hooks (Task 3), no
  5. // enforcement (Task 4) are involved.
  6. //
  7. // test_index_created_at_runtime_is_visible_after_reopen is THE regression
  8. // test for this task: since v2.8.1 the read path serves only from the primed
  9. // dbi cache, so a sub-db created at runtime is invisible to every later read
  10. // in the process unless cacheCommittedDbi() runs after commit. Removing that
  11. // call from relation_index_add must fail this test.
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <cstdio>
  15. #include <filesystem>
  16. #include <iostream>
  17. #include <string>
  18. #include <unistd.h>
  19. #include <vector>
  20. #include <nlohmann/json.hpp>
  21. #include "document.hpp"
  22. #include "storage/document_store_lmdb.hpp"
  23. #include "storage/lmdb_env.hpp"
  24. namespace fs = std::filesystem;
  25. using smartbotic::database::Document;
  26. using smartbotic::db::storage::LmdbDocumentStore;
  27. using smartbotic::db::storage::LmdbEnv;
  28. using smartbotic::db::storage::LmdbEnvOpts;
  29. namespace {
  30. int g_pass = 0;
  31. int g_fail = 0;
  32. void check(bool cond, const char* msg) {
  33. if (cond) {
  34. ++g_pass;
  35. } else {
  36. ++g_fail;
  37. std::cerr << "FAIL: " << msg << "\n";
  38. }
  39. }
  40. std::string make_tmpdir(const char* tag) {
  41. static std::atomic<int> counter{0};
  42. std::string path = "/tmp/relidx-test-" + std::to_string(::getpid()) + "-" +
  43. std::to_string(counter.fetch_add(1)) + "-" + tag;
  44. std::error_code ec;
  45. fs::remove_all(path, ec);
  46. return path;
  47. }
  48. struct TmpEnv {
  49. std::string path;
  50. LmdbEnv env;
  51. explicit TmpEnv(const char* tag)
  52. : path(make_tmpdir(tag)),
  53. env(LmdbEnvOpts{path, 64ULL << 20, 256, 126, false}) {}
  54. ~TmpEnv() {
  55. std::error_code ec;
  56. fs::remove_all(path, ec);
  57. }
  58. TmpEnv(const TmpEnv&) = delete;
  59. TmpEnv& operator=(const TmpEnv&) = delete;
  60. };
  61. // -------------------------------------------------------------------------
  62. // DUPSORT shape, per the re-validated design.
  63. void test_children_of_a_parent_are_a_dup_set() {
  64. TmpEnv t("relidx");
  65. LmdbDocumentStore store(t.env);
  66. check(store.relation_index_add("r1", "wf-1", "exec-a"), "added a child");
  67. check(store.relation_index_add("r1", "wf-1", "exec-b"), "and another");
  68. check(store.relation_index_add("r1", "wf-2", "exec-c"), "under a second parent");
  69. // THE operation restrict and DescribeDelete need: a count without reading
  70. // the children. mdb_cursor_count makes it O(1)-ish.
  71. check(store.relation_index_child_count("r1", "wf-1") == 2, "two children of wf-1");
  72. check(store.relation_index_child_count("r1", "wf-2") == 1, "one child of wf-2");
  73. check(store.relation_index_child_count("r1", "wf-none") == 0,
  74. "an unreferenced parent has none, and that is not an error");
  75. auto kids = store.relation_index_children("r1", "wf-1", 10);
  76. std::sort(kids.begin(), kids.end());
  77. check(kids == std::vector<std::string>{"exec-a", "exec-b"}, "children listed");
  78. // Removing one pair must not remove the sibling.
  79. check(store.relation_index_remove("r1", "wf-1", "exec-a"), "removed one pair");
  80. check(store.relation_index_child_count("r1", "wf-1") == 1, "the sibling survives");
  81. // Idempotent: re-adding the same pair is a no-op, not a duplicate.
  82. store.relation_index_add("r1", "wf-1", "exec-b");
  83. check(store.relation_index_child_count("r1", "wf-1") == 1, "no duplicate posting");
  84. // A distinct relation is a distinct sub-db: same parent id, no crosstalk.
  85. check(store.relation_index_child_count("r2", "wf-1") == 0,
  86. "a different relation's index is independent");
  87. // Removing a pair that was never present is reported, not thrown.
  88. check(!store.relation_index_remove("r1", "wf-1", "exec-does-not-exist"),
  89. "removing an absent pair returns false rather than throwing");
  90. check(!store.relation_index_remove("r1", "wf-none", "exec-a"),
  91. "removing under an absent parent returns false rather than throwing");
  92. }
  93. // The failure this repo is most likely to reproduce. Since v2.8.1 reads serve
  94. // only from the primed dbi cache, so a sub-db created at runtime is invisible
  95. // unless registered after commit - and relations would silently not enforce.
  96. void test_index_created_at_runtime_is_visible_after_reopen() {
  97. const std::string path = make_tmpdir("relidx-visible");
  98. const LmdbEnvOpts opts{path, 64ULL << 20, 256, 126, false};
  99. {
  100. LmdbEnv env(opts);
  101. LmdbDocumentStore store(env);
  102. store.relation_index_add("r1", "wf-1", "exec-a");
  103. // Same process, no reopen: must be visible immediately.
  104. check(store.relation_index_child_count("r1", "wf-1") == 1,
  105. "visible in the process that created it - this is what "
  106. "cacheCommittedDbi() buys");
  107. }
  108. LmdbEnv env2(opts);
  109. LmdbDocumentStore store2(env2); // priming runs in the constructor
  110. check(store2.relation_index_child_count("r1", "wf-1") == 1,
  111. "and after a restart, via prime_dbi_cache()");
  112. std::error_code ec;
  113. fs::remove_all(path, ec);
  114. }
  115. // v2.11.0 T7 — declaring a relation over a collection that ALREADY has rows
  116. // must index those pre-existing rows, not just ones written afterwards.
  117. // This is the exact bug the task brief calls out: without a bootstrap scan,
  118. // declaring a relation over populated data leaves every existing child
  119. // invisible to enforcement while looking like it worked.
  120. void test_build_relation_index_covers_pre_existing_rows() {
  121. TmpEnv t("relbuild-basic");
  122. LmdbDocumentStore store(t.env);
  123. // Rows exist BEFORE the relation is ever declared - no set_relations()
  124. // call has happened, so put() below does not touch the reverse index at
  125. // all. This is exactly "declare a relation on a populated collection".
  126. auto put = [&](const std::string& id, const nlohmann::json& data) {
  127. Document d; d.id = id; d.collection = "executions"; d.set_data(data);
  128. store.put("executions", id, d);
  129. };
  130. put("e1", {{"workflowId", "wf-1"}});
  131. put("e2", {{"workflowId", "wf-1"}});
  132. put("e3", {{"workflowId", "wf-2"}});
  133. put("e4", {{"other", 1}}); // no reference - must not count
  134. put("e5", {{"workflowId", nullptr}}); // null - must not count
  135. check(store.relation_index_child_count("exec_wf", "wf-1") == 0,
  136. "before the bootstrap scan, the reverse index knows nothing - this "
  137. "is the bug: a declared relation would silently protect nothing");
  138. const uint64_t indexed = store.build_relation_index("exec_wf", "executions", "workflowId");
  139. check(indexed == 3, "3 rows had a resolvable reference (e4/e5 excluded)");
  140. check(store.relation_index_child_count("exec_wf", "wf-1") == 2,
  141. "both pre-existing children of wf-1 are now indexed");
  142. check(store.relation_index_child_count("exec_wf", "wf-2") == 1,
  143. "and wf-2's child");
  144. auto kids = store.relation_index_children("exec_wf", "wf-1", 10);
  145. std::sort(kids.begin(), kids.end());
  146. check(kids == std::vector<std::string>{"e1", "e2"}, "correct children listed");
  147. // Idempotent: re-running the scan (e.g. re-declaring the relation) must
  148. // not double the postings, the same MDB_NODUPDATA guarantee build_index
  149. // already relies on.
  150. const uint64_t reindexed = store.build_relation_index("exec_wf", "executions", "workflowId");
  151. check(reindexed == 3, "the re-scan still visits the same 3 rows");
  152. check(store.relation_index_child_count("exec_wf", "wf-1") == 2,
  153. "no duplicate postings from re-running the scan");
  154. check(store.relation_index_child_count("exec_wf", "wf-2") == 1,
  155. "no duplicate postings on wf-2 either");
  156. check(store.relation_index_exists("exec_wf"),
  157. "the sub-db now exists - relation_index_exists distinguishes this "
  158. "from 'declared but never built'");
  159. check(!store.relation_index_exists("never_declared"),
  160. "an unrelated relation's sub-db was never created");
  161. }
  162. // An array-valued child field must contribute one posting per element, same
  163. // as the write-path maintainRelations() - the bootstrap scan must not
  164. // diverge from ongoing maintenance.
  165. void test_build_relation_index_handles_array_valued_field() {
  166. TmpEnv t("relbuild-array");
  167. LmdbDocumentStore store(t.env);
  168. Document n; n.id = "n1"; n.collection = "nodes";
  169. n.set_data({{"config", {{"credentialIds", {"c1", "c2"}}}}});
  170. store.put("nodes", "n1", n);
  171. const uint64_t indexed =
  172. store.build_relation_index("node_creds", "nodes", "config.credentialIds");
  173. check(indexed == 1, "one row contributed (it has two postings, one row)");
  174. check(store.relation_index_child_count("node_creds", "c1") == 1, "array element 1");
  175. check(store.relation_index_child_count("node_creds", "c2") == 1, "array element 2");
  176. }
  177. // A relation over a collection that does not exist yet (or is empty) must
  178. // not throw, and must not fabricate a sub-db that then confuses
  179. // relation_index_exists.
  180. void test_build_relation_index_over_absent_collection() {
  181. TmpEnv t("relbuild-absent");
  182. LmdbDocumentStore store(t.env);
  183. const uint64_t indexed = store.build_relation_index("exec_wf", "executions", "workflowId");
  184. check(indexed == 0, "nothing to index in a collection that was never written");
  185. }
  186. // v2.11.0 T7 — check_relation_dangling: a genuinely dangling reference (a
  187. // child row referencing a parent id that does not exist) must be reported,
  188. // with the correct count and sample child ids; a live reference must not be
  189. // flagged.
  190. void test_check_relation_dangling_finds_missing_parents() {
  191. TmpEnv t("relcheck-basic");
  192. LmdbDocumentStore store(t.env);
  193. auto putParent = [&](const std::string& id) {
  194. Document d; d.id = id; d.collection = "workflows"; d.set_data({{"name", id}});
  195. store.put("workflows", id, d);
  196. };
  197. auto putChild = [&](const std::string& id, const std::string& wf) {
  198. Document d; d.id = id; d.collection = "executions";
  199. d.set_data({{"workflowId", wf}});
  200. store.put("executions", id, d);
  201. };
  202. // wf-1 exists and is referenced - not dangling.
  203. putParent("wf-1");
  204. putChild("e1", "wf-1");
  205. putChild("e2", "wf-1");
  206. // wf-missing is referenced but was NEVER written as a parent - dangling.
  207. putChild("e3", "wf-missing");
  208. putChild("e4", "wf-missing");
  209. putChild("e5", "wf-missing");
  210. store.build_relation_index("exec_wf", "executions", "workflowId");
  211. auto result = store.check_relation_dangling("exec_wf", "workflows", 100);
  212. check(result.total == 1, "exactly one dangling parent id");
  213. check(result.entries.size() == 1, "and it is reported (well under the cap)");
  214. if (!result.entries.empty()) {
  215. const auto& d = result.entries[0];
  216. check(d.parentId == "wf-missing", "names the missing parent");
  217. check(d.childCount == 3, "counts all three referencing children");
  218. check(d.sampleChildIds.size() == 3, "samples all three (under the 5-sample cap)");
  219. std::vector<std::string> sorted = d.sampleChildIds;
  220. std::sort(sorted.begin(), sorted.end());
  221. check(sorted == std::vector<std::string>{"e3", "e4", "e5"}, "correct sample ids");
  222. }
  223. // check_relation_dangling must mutate nothing - the index and parent
  224. // collection are exactly as they were.
  225. check(store.relation_index_child_count("exec_wf", "wf-missing") == 3,
  226. "the check did not remove or alter the dangling postings");
  227. check(store.count("workflows") == 1, "the check did not create a phantom parent row");
  228. }
  229. // A relation with no dangling references reports zero, and never invents
  230. // one for a value that legitimately exists.
  231. void test_check_relation_dangling_clean_relation() {
  232. TmpEnv t("relcheck-clean");
  233. LmdbDocumentStore store(t.env);
  234. Document p; p.id = "wf-1"; p.collection = "workflows"; p.set_data({{"name", "wf-1"}});
  235. store.put("workflows", "wf-1", p);
  236. Document c; c.id = "e1"; c.collection = "executions";
  237. c.set_data({{"workflowId", "wf-1"}});
  238. store.put("executions", "e1", c);
  239. store.build_relation_index("exec_wf", "executions", "workflowId");
  240. auto result = store.check_relation_dangling("exec_wf", "workflows", 100);
  241. check(result.total == 0, "no dangling references");
  242. check(result.entries.empty(), "nothing reported");
  243. }
  244. // A relation that was declared but never built (no build_relation_index /
  245. // relation_index_add call at all) has no sub-db - check_relation_dangling
  246. // must report "nothing to say" rather than treating an absent index as
  247. // "everything is dangling".
  248. void test_check_relation_dangling_never_built_reports_nothing() {
  249. TmpEnv t("relcheck-unbuilt");
  250. LmdbDocumentStore store(t.env);
  251. Document c; c.id = "e1"; c.collection = "executions";
  252. c.set_data({{"workflowId", "wf-1"}});
  253. store.put("executions", "e1", c); // no relation declared/built at all
  254. auto result = store.check_relation_dangling("exec_wf", "workflows", 100);
  255. check(result.total == 0, "an unbuilt index has nothing to report - not a false positive");
  256. check(result.entries.empty(), "nothing reported");
  257. }
  258. // The `maxResults` cap bounds the returned samples but `total` must still be
  259. // exact - a caller must never be able to mistake a capped list for the
  260. // complete one.
  261. void test_check_relation_dangling_respects_cap_but_total_is_exact() {
  262. TmpEnv t("relcheck-capped");
  263. LmdbDocumentStore store(t.env);
  264. for (int i = 0; i < 5; ++i) {
  265. Document c; c.id = "e" + std::to_string(i); c.collection = "executions";
  266. c.set_data({{"workflowId", "wf-missing-" + std::to_string(i)}});
  267. store.put("executions", "e" + std::to_string(i), c);
  268. }
  269. store.build_relation_index("exec_wf", "executions", "workflowId");
  270. auto result = store.check_relation_dangling("exec_wf", "workflows", 2);
  271. check(result.total == 5, "total counts every dangling parent, not just the capped sample");
  272. check(result.entries.size() == 2, "entries is capped at maxResults");
  273. }
  274. } // namespace
  275. int main() {
  276. std::cout << "=== test_relation_index ===\n";
  277. test_children_of_a_parent_are_a_dup_set();
  278. test_index_created_at_runtime_is_visible_after_reopen();
  279. test_build_relation_index_covers_pre_existing_rows();
  280. test_build_relation_index_handles_array_valued_field();
  281. test_build_relation_index_over_absent_collection();
  282. test_check_relation_dangling_finds_missing_parents();
  283. test_check_relation_dangling_clean_relation();
  284. test_check_relation_dangling_never_built_reports_nothing();
  285. test_check_relation_dangling_respects_cap_but_total_is_exact();
  286. std::cout << "passed: " << g_pass << ", failed: " << g_fail << "\n";
  287. return g_fail == 0 ? 0 : 1;
  288. }