database_service.cpp 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400
  1. #include "database_service.hpp"
  2. #include "json_parse.hpp"
  3. #include "project_addressing.hpp"
  4. #include "storage/secondary_index.hpp"
  5. #include "storage/document_store.hpp"
  6. #include "storage/document_store_lmdb.hpp"
  7. #include "storage/dual_write_mirror.hpp"
  8. #include "relations/relation_cascade.hpp"
  9. #include "relations/relation_enforcement.hpp"
  10. #include "auth/auth_interceptor.hpp"
  11. #include "auth/principal.hpp"
  12. #include "tls/cert_generator.hpp"
  13. #include <fstream>
  14. #include <sstream>
  15. #include <map>
  16. #include <set>
  17. #include <algorithm>
  18. #include <chrono>
  19. #include <iterator>
  20. #include "storage/lmdb_env.hpp"
  21. #include "storage/migrate_v1_to_v2.hpp"
  22. #include "storage/project_store.hpp"
  23. #include "storage/subdb_placement.hpp"
  24. #include <grpcpp/grpcpp.h>
  25. #include <grpcpp/resource_quota.h>
  26. #include <spdlog/spdlog.h>
  27. #include <fstream>
  28. #ifdef HAVE_SYSTEMD
  29. #include <systemd/sd-daemon.h>
  30. #endif
  31. #if defined(__GLIBC__) && !defined(__APPLE__)
  32. #include <malloc.h>
  33. #endif
  34. namespace smartbotic::database {
  35. DatabaseService::DatabaseService(Config config)
  36. : config_(std::move(config))
  37. {
  38. }
  39. DatabaseService::~DatabaseService() {
  40. stop();
  41. }
  42. std::string DatabaseService::readOnlyReason() const {
  43. std::lock_guard<std::mutex> lock(reason_mutex_);
  44. return read_only_reason_;
  45. }
  46. void DatabaseService::setReadOnly(bool value, const std::string& reason) {
  47. {
  48. std::lock_guard<std::mutex> lock(reason_mutex_);
  49. read_only_reason_ = value ? reason : "";
  50. }
  51. bool prev = read_only_.exchange(value, std::memory_order_acq_rel);
  52. if (prev != value) {
  53. if (value) {
  54. spdlog::error("Database entered READ-ONLY mode: {}", reason);
  55. } else {
  56. spdlog::info("Database unlocked -- writes accepted");
  57. }
  58. }
  59. }
  60. bool DatabaseService::initialize() {
  61. spdlog::info("Initializing database service (node: {})", config_.nodeId);
  62. try {
  63. // Create data directory if needed
  64. std::error_code ec;
  65. std::filesystem::create_directories(config_.dataDirectory, ec);
  66. if (ec) {
  67. spdlog::error("Failed to create data directory: {}", ec.message());
  68. return false;
  69. }
  70. setupComponents();
  71. // Initialize encryption
  72. if (config_.encryptionEnabled) {
  73. if (!encryption_->initialize()) {
  74. spdlog::error("Failed to initialize encryption");
  75. return false;
  76. }
  77. }
  78. // Recover from persistence
  79. recovery_outcome_ = persistence_->recover(*store_);
  80. #if defined(__GLIBC__) && !defined(__APPLE__)
  81. // v1.9.3 — release freelist pages accumulated during recovery. v1.9.1
  82. // added trim at end of loadSnapshot, but the WAL replay phase that
  83. // runs afterward (`persistence_->recover`'s `replayWal` step) also
  84. // burns through GBs of small Document JSON allocations whose pages
  85. // sit on the per-thread freelist with no subsequent allocation to
  86. // shake them loose. On Zoe (docs/incidents/2026-04-22-zoe-rss-exceeds-budget.md update 15:05)
  87. // this was 5.7 GB at 23 min uptime — fully reclaimable via
  88. // malloc_trim, just nothing called it. Paired with the periodic
  89. // every-5-minute trim in MemoryStore::logMemoryCheck, so any
  90. // post-boot bloat that escapes this trim gets cleaned up shortly.
  91. ::malloc_trim(0);
  92. #endif
  93. if (recovery_outcome_.isFailure()) {
  94. const std::string modeStr =
  95. recoveryModeToString(config_.persistenceConfig.recoveryMode);
  96. spdlog::error("");
  97. spdlog::error("+------------------------------------------------------------------+");
  98. spdlog::error("| RECOVERY REFUSED |");
  99. spdlog::error("| |");
  100. spdlog::error("| Mode: {}", modeStr);
  101. spdlog::error("| Expected snapshot: {}", recovery_outcome_.expectedSnapshot.string());
  102. spdlog::error("| Reason: {}", recovery_outcome_.failureReason);
  103. spdlog::error("| |");
  104. spdlog::error("| Snapshots available: {}", recovery_outcome_.snapshotsAvailable);
  105. spdlog::error("| Snapshots attempted: {}", recovery_outcome_.snapshotsAttempted);
  106. spdlog::error("| |");
  107. spdlog::error("| To escalate, restart with one of: |");
  108. spdlog::error("| --recovery-mode=snapshot_fallback Try older snapshots |");
  109. spdlog::error("| --recovery-mode=wal_only Replay WAL only (slow) |");
  110. spdlog::error("| --recovery-mode=best_effort Try all of the above |");
  111. spdlog::error("| --recovery-mode=force_empty Start empty (LAST RESORT) |");
  112. spdlog::error("| |");
  113. spdlog::error("| Or set in config.json: \"recovery\": {{ \"mode\": \"<mode>\" }} |");
  114. spdlog::error("| |");
  115. spdlog::error("| PRESERVE /var/lib/smartbotic-database/ BEFORE ESCALATING. |");
  116. spdlog::error("+------------------------------------------------------------------+");
  117. throw std::runtime_error("recovery failed; refusing to start");
  118. }
  119. // Auto-readonly mode on non-trivial recovery
  120. if (recovery_outcome_.isNonTrivial() && !force_readwrite_) {
  121. std::string reason;
  122. switch (recovery_outcome_.kind) {
  123. case RecoveryOutcome::Kind::SnapshotFellBack:
  124. reason = "fell back to snapshot " +
  125. recovery_outcome_.snapshotUsed.filename().string() +
  126. " because " +
  127. recovery_outcome_.expectedSnapshot.filename().string() +
  128. " failed: " + recovery_outcome_.failureReason;
  129. break;
  130. case RecoveryOutcome::Kind::WalOnlyReplay:
  131. reason = "WAL-only replay, no snapshot loaded (" +
  132. std::to_string(recovery_outcome_.walEntriesReplayed) +
  133. " entries)";
  134. break;
  135. case RecoveryOutcome::Kind::ForcedEmpty:
  136. reason = "forced empty by operator (--recovery-mode=force_empty)";
  137. break;
  138. default:
  139. reason = "non-trivial recovery";
  140. break;
  141. }
  142. reason += ". Run `smartbotic-db-cli unlock` to accept this state, "
  143. "or restart with --force-readwrite to bypass this check.";
  144. setReadOnly(true, reason);
  145. spdlog::error("");
  146. spdlog::error("+------------------------------------------------------------------+");
  147. spdlog::error("| [ERROR] Database booted in READ-ONLY mode after non-trivial |");
  148. spdlog::error("| recovery. |");
  149. spdlog::error("| |");
  150. spdlog::error("| Reason: {}", reason);
  151. spdlog::error("| |");
  152. spdlog::error("| Writes will be REJECTED until you acknowledge this state: |");
  153. spdlog::error("| smartbotic-db-cli unlock # live, no restart |");
  154. spdlog::error("| smartbotic-database --force-readwrite # on next restart |");
  155. spdlog::error("+------------------------------------------------------------------+");
  156. }
  157. // Set replication sequence after recovery (WAL sequence is now known)
  158. replication_->setSequence(persistence_->currentWalSequence());
  159. // v1.8.0 — start the persistence manager before loadFromStore /
  160. // migrations so any system-collection writes those phases produce
  161. // (view docs, _collection_meta entries, _migrations recordings)
  162. // reach the WAL like normal mutations. Pre-v1.8, persistence_ was
  163. // started later in start(), which silently dropped those writes
  164. // (running_=false → logInsert no-op). That meant migrated views
  165. // only "survived" because the runner re-created them every boot,
  166. // and a manually-created view that landed during the racy startup
  167. // window (before full readiness) could be lost.
  168. if (!persistence_->start()) {
  169. spdlog::error("Failed to start persistence manager before migrations");
  170. return false;
  171. }
  172. // Load view definitions from the _views system collection (which is now
  173. // populated by the persistence recovery above).
  174. view_manager_->loadFromStore();
  175. // Load per-collection configs from the _collection_meta system collection.
  176. // Must happen AFTER persistence recovery and BEFORE migrations so any
  177. // migration-created documents are stamped with the correct precision.
  178. config_manager_->loadFromStore();
  179. policy_manager_->loadFromStore();
  180. relation_manager_->loadFromStore();
  181. applyRelationDeclarations();
  182. // v2.11.0 close-out — teach the TTL sweeper about relations. Installed
  183. // HERE, after loadFromStore() and the arming pass, deliberately: the
  184. // hook consults the declaration cache and the reverse index, and an
  185. // expiry that fired before either was ready would have decided from an
  186. // empty cache. Until this line the sweeper behaves exactly as it did
  187. // pre-v2.11.0 (which is also what every unit fixture that never
  188. // installs the hook keeps doing).
  189. store_->setTtlExpiryRelationHook(
  190. [this](const std::string& qualifiedCollection, const std::string& id,
  191. bool firstAttempt) {
  192. return ttlExpiryRelationDecision(qualifiedCollection, id, firstAttempt);
  193. });
  194. // v2.9.0 — re-apply persisted index declarations to each project's LMDB
  195. // store. This is load-bearing, not bookkeeping: the declaration is what
  196. // makes the write path maintain an index, and the planner consults an
  197. // index purely on the declaration's word. If this step were skipped, a
  198. // restart would leave indexes recorded but unmaintained, and queries
  199. // would be served from a frozen index - stale rows returned as current,
  200. // with nothing logged.
  201. applyIndexDeclarations();
  202. applySchemaDeclarations(); // v2.16.0
  203. // v2.11.0 final review (finding 4) — THE POST-REPLAY RE-MIRROR PASS
  204. // RUNS HERE, and the position is load-bearing.
  205. //
  206. // PersistenceManager::recover() (above, before any of the arming
  207. // steps) only collects the id list. The pass writes documents through
  208. // LmdbDocumentStore::put(), which reads indexed_fields(),
  209. // unique_fields() and relations() LIVE and maintains every index
  210. // inside the document's own write transaction. Run from inside
  211. // recover(), all three maps were still empty, so it repaired the
  212. // document and left every posting derived from it stale: an
  213. // index-served query then returns the row under its OLD value and
  214. // misses it under its new one - silently wrong rows, which is exactly
  215. // what putting maintainIndexes() inside the transaction exists to
  216. // prevent, and which bit any install with a v2.9 index declared
  217. // whether or not it uses relations. It also made the reverse-index
  218. // half of relation_cascade.hpp's convergence claim false, and made
  219. // UniqueViolation (and therefore the pass's own retry phase)
  220. // unreachable.
  221. //
  222. // Must be after applyRelationDeclarations() AND
  223. // applyIndexDeclarations(); backfillIntoDocStore() below already sits
  224. // at this point for the same reason. Never throws.
  225. persistence_->runPendingRemirror(*store_, recovery_outcome_);
  226. // Run migrations if enabled
  227. if (config_.migrations.enabled && !config_.migrations.directory.empty()) {
  228. if (!runMigrations()) {
  229. if (config_.migrations.failOnError) {
  230. spdlog::error("Failed to run migrations");
  231. return false;
  232. }
  233. spdlog::warn("Some migrations failed, continuing anyway");
  234. }
  235. }
  236. // v2.0 Stage 4 — synchronous backfill into doc_store_ before
  237. // serving. Without this, only post-boot writes land in LMDB and
  238. // the read-flip downstream would see an empty mirror.
  239. backfillIntoDocStore();
  240. // v2.4.4 — placement audit. Reports documents sitting in a sub-db
  241. // other than the one they declare, which is the signature of a
  242. // misbound MDB_dbi (see storage/subdb_identity.hpp). Read-only and
  243. // advisory: it never blocks startup, because a misplacement is a
  244. // data-location problem an operator repairs offline with
  245. // `smartbotic-db-cli reconcile-subdbs`, not a reason to refuse
  246. // service on the other 99% of the dataset.
  247. // 2.20.1 - each remaining boot step logs its start, so a boot that
  248. // dies here (a production crash loop on 2026-10-19 died about 3 s
  249. // after the backfill line, with nothing logged) shows which step.
  250. spdlog::info("Boot: sub-db placement audit");
  251. auditSubdbPlacement();
  252. // v2.20.2 - rows LMDB holds that MemoryStore does not (readable, and
  253. // before 2.20.2 not writable), and the reverse. Read-only, advisory.
  254. spdlog::info("Boot: memory/disk key audit");
  255. auditMemoryDiskKeys();
  256. // v2.6.0 — stamp `project: "default"` onto file records written before
  257. // files were namespaced. Idempotent, and advisory: a file-metadata
  258. // stamp is not a reason to refuse service, so failures warn only.
  259. if (files_) {
  260. spdlog::info("Boot: file records");
  261. try {
  262. const uint32_t stamped = files_->stampMissingProjects();
  263. if (stamped > 0) {
  264. spdlog::info("v2.6.0 file migration: stamped {} legacy file "
  265. "record(s) with project 'default'", stamped);
  266. } else {
  267. spdlog::debug("v2.6.0 file migration: no legacy file records");
  268. }
  269. } catch (const std::exception& e) {
  270. spdlog::warn("v2.6.0 file migration failed: {}", e.what());
  271. }
  272. }
  273. // v2.11.0 close-out — LAST ACT OF THE BOOT PATH, and the position is
  274. // load-bearing. Everything above that can bump the drift counter (the
  275. // post-replay re-mirror pass, backfillIntoDocStore(), a malformed
  276. // legacy collection key) is now behind the baseline, so
  277. // mirrorDriftSinceReady() reports only drift a LIVE write caused.
  278. // Destructive relation policies gate on that, not on the raw counter:
  279. // see MemoryStore::markMirrorDriftBaseline() for the trap this closes
  280. // (one unrepairable row disabling every cascade/set_null delete and
  281. // every CreateRelation for the process's life, with an error message
  282. // telling the operator to restart, which re-incurs it). Reads keep
  283. // gating on the RAW counter - a stale row genuinely means MemoryStore
  284. // is ahead, and that fallback must stay.
  285. // v2.17.0 - encrypt what must be encrypted, and remove the plaintext
  286. // copies, before anything can read or replicate them.
  287. spdlog::info("Boot: encryption at rest");
  288. migrateEncryptionAtRest();
  289. store_->markMirrorDriftBaseline();
  290. if (store_->mirrorDriftBaseline() > 0) {
  291. spdlog::warn("mirror drift at READY: {} - accrued on the boot path (see the "
  292. "ERROR lines above for the exact rows). Reads for this process "
  293. "will be served from MemoryStore rather than LMDB. Destructive "
  294. "relation policies are NOT disabled by this, but the rows named "
  295. "above are still stale in LMDB until each is rewritten through "
  296. "an ordinary write; a restart re-attempts and, if the cause "
  297. "persists, re-incurs the same count.",
  298. store_->mirrorDriftBaseline());
  299. }
  300. spdlog::info("Database service initialized successfully");
  301. return true;
  302. } catch (const std::exception& e) {
  303. spdlog::error("Failed to initialize database service: {}", e.what());
  304. return false;
  305. }
  306. }
  307. void DatabaseService::migrateLegacyEnvToDefaultProject() {
  308. const auto legacy = config_.dataDirectory / "env";
  309. const auto target = config_.dataDirectory / "projects" /
  310. smartbotic::database::kDefaultProject / "env";
  311. std::error_code ec;
  312. const bool legacy_exists = std::filesystem::exists(legacy, ec);
  313. const bool target_exists = std::filesystem::exists(target, ec);
  314. if (!legacy_exists) return; // fresh install or already migrated
  315. if (target_exists) {
  316. spdlog::error("v2.3 storage: both legacy '{}' and new '{}' exist — "
  317. "refusing to start. Inspect manually; the safe move is "
  318. "to either delete the legacy dir (if you confirm it's a "
  319. "leftover) or stop and contact ops.",
  320. legacy.string(), target.string());
  321. throw std::runtime_error("v2.3 storage migration: ambiguous layout");
  322. }
  323. std::filesystem::create_directories(target.parent_path(), ec);
  324. if (ec) {
  325. throw std::runtime_error("v2.3 storage migration: cannot create '"
  326. + target.parent_path().string() + "': " + ec.message());
  327. }
  328. std::filesystem::rename(legacy, target, ec);
  329. if (ec) {
  330. throw std::runtime_error("v2.3 storage migration: rename '"
  331. + legacy.string() + "' -> '"
  332. + target.string() + "' failed: " + ec.message());
  333. }
  334. spdlog::info("v2.3 storage: migrated legacy env '{}' -> '{}' (default project)",
  335. legacy.string(), target.string());
  336. }
  337. smartbotic::db::storage::DocumentStore* DatabaseService::docStore() noexcept {
  338. return docStore(smartbotic::database::kDefaultProject);
  339. }
  340. smartbotic::db::storage::DocumentStore*
  341. DatabaseService::docStore(std::string_view project) noexcept {
  342. if (!projects_) return nullptr;
  343. return projects_->get(project);
  344. }
  345. std::vector<std::string> DatabaseService::listProjects() const {
  346. if (!projects_) return {};
  347. return projects_->listOnDisk();
  348. }
  349. bool DatabaseService::createProject(const std::string& name, std::string& error) {
  350. if (!projects_) {
  351. error = "project registry not initialized";
  352. return false;
  353. }
  354. return projects_->create(name, error);
  355. }
  356. bool DatabaseService::dropProject(const std::string& name, std::string& error) {
  357. if (!projects_) {
  358. error = "project registry not initialized";
  359. return false;
  360. }
  361. // v2.11.0 close-out — capture the relation declarations belonging to this
  362. // project BEFORE the drop. Relations are validated same-project at
  363. // creation (no LMDB transaction spans two envs), so `child` and `parent`
  364. // are always in the same project as `name` itself; listRelations(name)
  365. // therefore names every declaration the drop invalidates. Captured first
  366. // because listRelations needs the project to still be nameable and, more
  367. // importantly, because un-arming needs the store to still exist.
  368. std::vector<RelationInfo> doomed;
  369. if (relation_manager_) {
  370. try {
  371. doomed = relation_manager_->listRelations(name);
  372. } catch (const std::exception& e) {
  373. spdlog::warn("v2.11 relations: could not enumerate relations of project '{}' "
  374. "before dropping it ({}); its declarations may be left behind",
  375. name, e.what());
  376. }
  377. }
  378. if (!projects_->drop(name, error)) return false;
  379. // v2.12.2 - collection configs live in the GLOBAL `_collection_meta`, not
  380. // in the project's env, so dropping the env left every one of the project's
  381. // declarations behind - and a recreated project silently inherited them.
  382. // The index sub-dbs went with the env; only the records remain to remove.
  383. if (config_manager_) {
  384. const std::string prefix = name + ":";
  385. size_t removed = 0;
  386. for (const auto& [key, cfg] : config_manager_->allConfigs()) {
  387. if (key.rfind(prefix, 0) == 0 && config_manager_->removeConfig(key)) ++removed;
  388. }
  389. if (removed > 0) {
  390. spdlog::info("dropProject '{}': removed {} collection config(s)", name, removed);
  391. }
  392. }
  393. // ---- The drop succeeded; the declarations now point at a namespace that
  394. // no longer exists. Sweep them out of the global `_relations` collection
  395. // and un-arm each affected child collection.
  396. //
  397. // Order (drop first, sweep second) is deliberate: the registry is the one
  398. // that refuses "default" and rejects unknown names, so sweeping first would
  399. // destroy declarations for a project whose drop then failed. The cost of
  400. // this order is that the per-project store is usually already gone by the
  401. // time we try to un-arm, which makes the un-arm a no-op - correct, since a
  402. // store that no longer exists cannot be maintaining a reverse index. It
  403. // still runs, because ProjectStoreRegistry may hold a live
  404. // LmdbDocumentStore for a re-created project of the same name.
  405. //
  406. // ⚠ Advisory, never fatal: the project IS dropped at this point, and a
  407. // leftover declaration is litter, not corruption (its child and parent
  408. // collections are both gone, so nothing can be enforced against them). A
  409. // failure here must not report the drop as failed.
  410. for (const auto& r : doomed) {
  411. try {
  412. std::string err;
  413. if (!relation_manager_->dropRelation(r.name, err)) {
  414. spdlog::warn("v2.11 relations: could not drop declaration '{}' left by "
  415. "dropped project '{}': {}", r.name, name, err);
  416. continue;
  417. }
  418. const auto rc = resolveCollection(r.child);
  419. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  420. docStore(rc.project));
  421. if (lmdb != nullptr) {
  422. // Empty list = "this collection has no relations", which is what
  423. // set_relations replaces the previous list with. Every relation
  424. // of a dropped project goes, so clearing the child wholesale is
  425. // exactly right here (unlike DropRelation, which must re-arm the
  426. // survivors).
  427. lmdb->set_relations(rc.collection, {});
  428. }
  429. spdlog::info("v2.11 relations: dropped declaration '{}' with the project '{}'",
  430. r.name, name);
  431. } catch (const std::exception& e) {
  432. spdlog::warn("v2.11 relations: could not clean up declaration '{}' after "
  433. "dropping project '{}': {}", r.name, name, e.what());
  434. }
  435. }
  436. // ⚠ KNOWN, NOT FIXED HERE (v2.11.0 close-out): _views, _policies and
  437. // _collection_meta have the SAME gap - ProjectStoreRegistry::drop() removes
  438. // the project's env and nothing else, so a dropped project leaves its view
  439. // definitions, access policies and per-collection configs behind in those
  440. // global system collections too. Not a shared fix: each manager keys and
  441. // caches differently (ViewManager keys `<project>:<name>`, PolicyManager
  442. // `<project>:<principal>`, CollectionConfigManager `<project>:<collection>`
  443. // and canonicalises the cache key only), so each needs its own sweep, and
  444. // PolicyManager's has a security dimension this one does not (a re-created
  445. // project inheriting a stale policy). Scoped out deliberately; recorded so
  446. // it is not rediscovered as new.
  447. return true;
  448. }
  449. bool DatabaseService::runMigrations() {
  450. if (!config_.migrations.enabled) {
  451. return true;
  452. }
  453. MigrationRunner::Config migrationConfig;
  454. migrationConfig.directory = config_.migrations.directory;
  455. migrationConfig.autoApply = config_.migrations.autoApply;
  456. migrationConfig.failOnError = config_.migrations.failOnError;
  457. migrationRunner_ = std::make_unique<MigrationRunner>(
  458. *store_, *view_manager_, *relation_manager_, migrationConfig);
  459. migrationRunner_->setDocumentPreparer([this](const std::string& collection, Document& doc) {
  460. encryption_->encryptSensitiveFields(doc, encryptionRuleFor(collection)); // v2.17.0
  461. });
  462. const bool ok = migrationRunner_->runMigrations();
  463. // v2.11.0 close-out — a `create_relation` migration op only PERSISTS the
  464. // declaration. Arming the write path and building the reverse index over
  465. // rows that already exist is what applyRelationDeclarations() does, and it
  466. // has already run for this boot (initialize() calls it before migrations),
  467. // so without this a migration-declared relation would maintain no reverse
  468. // index and enforce nothing until the NEXT restart - the "declared but not
  469. // enforcing" state this feature's self-heal exists to make unreachable.
  470. // Idempotent and cheap: re-arming an already-armed child replaces an
  471. // identical list, and the bootstrap loop skips any relation whose index
  472. // sub-db already exists. Runs even when the migration run reported failure,
  473. // because a partially-applied run may still have created a relation.
  474. applyRelationDeclarations(/*afterMigrations=*/true);
  475. return ok;
  476. }
  477. nlohmann::json DatabaseService::schemaView(const nlohmann::json& body) const {
  478. nlohmann::json copy = body;
  479. if (copy.is_object()) {
  480. stripReservedFields(copy);
  481. copy.erase("_vector");
  482. }
  483. encryption_->decryptTree(copy);
  484. return copy;
  485. }
  486. DatabaseService::AtRestStats DatabaseService::encryptCollectionAtRest(const std::string& collection) {
  487. AtRestStats st;
  488. if (!encryption_ || !encryption_->isEnabled()) return st;
  489. const EncryptionRule rule = encryptionRuleFor(collection);
  490. const auto transform = [&](nlohmann::json& body) { return encryption_->encryptTree(body, rule); };
  491. // LMDB holds every row (MemoryStore may have evicted some); find the rows
  492. // that still hold plaintext, then rewrite each under the collection lock.
  493. smartbotic::db::storage::DocumentStore* ds = nullptr;
  494. std::string bare;
  495. // The names MemoryStore may hold this collection's rows under: the
  496. // qualified form and, in the default project, the bare one (see
  497. // MemoryStore::encryptionOptionsFor). Both map to the same LMDB sub-db.
  498. std::vector<std::string> names{collection};
  499. try {
  500. const auto rc = smartbotic::database::resolveCollection(collection);
  501. ds = docStore(rc.project);
  502. bare = rc.collection;
  503. if (rc.qualified != collection) names.push_back(rc.qualified);
  504. if (rc.project == smartbotic::database::kDefaultProject && rc.collection != collection) {
  505. names.push_back(rc.collection);
  506. }
  507. } catch (const std::exception&) {
  508. }
  509. std::vector<std::string> ids;
  510. if (ds != nullptr) {
  511. ds->export_scan(bare, "", false, nullptr, [](uint64_t) {},
  512. [&](Document&& d, smartbotic::db::storage::DocumentStore::ExportVectorState,
  513. const float*, size_t) -> bool {
  514. ++st.scanned;
  515. EncryptionManager::TreeAudit a;
  516. encryption_->auditTree(d.data(), rule, a);
  517. if (a.plaintextRequired > 0) ids.push_back(d.id);
  518. return true;
  519. });
  520. }
  521. for (const auto& id : ids) {
  522. int r = -1;
  523. for (const auto& n : names) {
  524. r = store_->rewriteBodyInPlace(n, id, transform);
  525. if (r != -1) break;
  526. }
  527. if (r == 1) {
  528. ++st.rewritten;
  529. } else if (r == -1 && ds != nullptr) {
  530. // Not in MemoryStore at all: the LMDB row is the only copy.
  531. if (auto d = ds->get(bare, id)) {
  532. nlohmann::json b = d->data();
  533. if (transform(b)) {
  534. d->set_data(b);
  535. d->encrypted = true;
  536. ds->put(bare, id, *d);
  537. ++st.lmdbOnly;
  538. }
  539. }
  540. }
  541. }
  542. if (history_store_) {
  543. for (const auto& n : names) {
  544. st.versions += history_store_->rewrite(n, [&](DocumentVersion& v) {
  545. nlohmann::json b = v.data();
  546. if (!transform(b)) return false;
  547. v.set_data(b);
  548. v.encrypted = true;
  549. return true;
  550. });
  551. }
  552. }
  553. return st;
  554. }
  555. void DatabaseService::requestResealAtNextBoot(const std::string& project) {
  556. std::ofstream(config_.dataDirectory / "encryption-reseal.pending", std::ios::app)
  557. << (project.empty() ? "*" : project) << "\n";
  558. }
  559. void DatabaseService::migrateEncryptionAtRest() {
  560. namespace fs = std::filesystem;
  561. const fs::path marker = config_.dataDirectory / "encryption-at-rest.v1";
  562. const fs::path reseal = config_.dataDirectory / "encryption-reseal.pending";
  563. std::error_code ec;
  564. const bool firstRun = !fs::exists(marker, ec);
  565. const bool resealPending = fs::exists(reseal, ec);
  566. if (!encryption_ || !encryption_->isEnabled()) {
  567. if (firstRun) spdlog::warn("v2.17 at-rest: encryption is disabled; nothing is encrypted at rest");
  568. return;
  569. }
  570. if (!firstRun && !resealPending) return;
  571. AtRestStats total;
  572. if (firstRun) {
  573. spdlog::warn("v2.17 at-rest: one-time migration - encrypting values stored in plaintext "
  574. "that must be encrypted (encrypted collections, sensitive_fields, the "
  575. "sensitive name patterns at any depth)");
  576. std::set<std::string> done; // canonical names: aliases share one LMDB sub-db
  577. for (const auto& coll : store_->listCollections()) {
  578. if (coll.empty() || coll[0] == '_') continue;
  579. std::string canonical = coll;
  580. try {
  581. canonical = smartbotic::database::resolveCollection(coll).qualified;
  582. } catch (const std::exception&) {
  583. }
  584. if (!done.insert(canonical).second) continue;
  585. #ifdef HAVE_SYSTEMD
  586. // Each collection is a scan plus a history rewrite: on a large
  587. // dataset the whole pass outlasts TimeoutStartSec. Same protocol
  588. // the v1 migration and recovery use.
  589. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  590. sd_notify(0, ("STATUS=Encrypting at rest: " + canonical).c_str());
  591. #endif
  592. const auto s = encryptCollectionAtRest(canonical);
  593. total.scanned += s.scanned;
  594. total.rewritten += s.rewritten;
  595. total.lmdbOnly += s.lmdbOnly;
  596. total.versions += s.versions;
  597. if (s.rewritten + s.lmdbOnly + s.versions > 0) {
  598. spdlog::warn("v2.17 at-rest: {}: {} row(s) and {} history version(s) encrypted "
  599. "(of {} row(s) scanned)", canonical, s.rewritten + s.lmdbOnly, s.versions,
  600. s.scanned);
  601. }
  602. }
  603. spdlog::warn("v2.17 at-rest: {} row(s) scanned, {} encrypted in place ({} LMDB-only), "
  604. "{} history version(s) encrypted", total.scanned,
  605. total.rewritten + total.lmdbOnly, total.lmdbOnly, total.versions);
  606. }
  607. // The seal: the rewrite replaced plaintext in the live stores, but older
  608. // snapshots, the WAL and LMDB's freed pages still hold it.
  609. std::string err;
  610. size_t snaps = 0, wals = 0;
  611. if (!persistence_->sealAfterRewrite(*store_, err, snaps, wals)) {
  612. spdlog::error("v2.17 at-rest: seal FAILED ({}); old plaintext copies remain in the WAL / "
  613. "snapshots. Serving continues; the next boot retries.", err);
  614. requestResealAtNextBoot();
  615. return;
  616. }
  617. // v2.17.2 - which envs to compact. The first run compacts every project.
  618. // A reseal compacts only the projects named in the pending file; "*" (a
  619. // failure path) or a pre-2.17.2 file (its content was "1") means all.
  620. // 2.17.1 compacted every project on any reseal: a 262 MB env the upgrade
  621. // never touched cost 2.5 minutes of a restart and reclaimed nothing.
  622. bool compactAll = firstRun;
  623. std::set<std::string> toCompact;
  624. if (!firstRun) {
  625. std::ifstream in(reseal);
  626. std::string line;
  627. while (std::getline(in, line)) {
  628. if (line.empty()) continue;
  629. if (line == "*" || line == "1") compactAll = true;
  630. else toCompact.insert(line);
  631. }
  632. if (toCompact.empty()) compactAll = true;
  633. }
  634. size_t compacted = 0;
  635. for (const auto& p : projects_->listOpen()) {
  636. if (!compactAll && !toCompact.count(p)) continue;
  637. ++compacted;
  638. uint64_t before = 0, after = 0;
  639. std::string cerr;
  640. if (projects_->compact(p, before, after, cerr)) {
  641. spdlog::info("v2.17 at-rest: project '{}' compacted, {} -> {} bytes", p, before, after);
  642. } else {
  643. spdlog::error("v2.17 at-rest: project '{}' compaction failed: {} - freed pages may "
  644. "still hold old plaintext; the next boot retries", p, cerr);
  645. requestResealAtNextBoot(p);
  646. applyIndexDeclarations();
  647. applyRelationDeclarations(/*afterMigrations=*/true);
  648. return;
  649. }
  650. }
  651. // Compaction reopened every env: per-store arming must be applied again.
  652. applyIndexDeclarations();
  653. applyRelationDeclarations(/*afterMigrations=*/true);
  654. std::ofstream(marker) << "encrypted at rest by 2.17.0\n";
  655. fs::remove(reseal, ec);
  656. spdlog::warn("v2.17 at-rest: sealed - {} old snapshot(s) and {} WAL file(s) removed, {} "
  657. "project(s) compacted{}. Copies made BEFORE this boot (backups, pre-upgrade copies, "
  658. "replicas, disk blocks) are outside the database's reach.", snaps, wals, compacted,
  659. compactAll ? " (all)" : "");
  660. }
  661. void DatabaseService::applySchemaDeclarations() {
  662. size_t armed = 0;
  663. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  664. if (!cfg.schema) continue;
  665. auto compiled = smartbotic::db::schema::compile(*cfg.schema);
  666. if (!compiled.schema) {
  667. // Loud: the record says this collection is constrained and it is
  668. // not. Only a hand-edited record can get here (the RPC refuses
  669. // anything that does not compile).
  670. spdlog::error("v2.16 schema: the schema stored for {} does not compile ({}); "
  671. "it is NOT enforced until it is set again", qualified, compiled.error);
  672. continue;
  673. }
  674. auto entry = std::make_shared<smartbotic::db::schema::SchemaEntry>();
  675. entry->compiled = compiled.schema;
  676. entry->source = *cfg.schema;
  677. entry->audit = cfg.schemaMode == "audit";
  678. schemas_.set(qualified, entry);
  679. ++armed;
  680. spdlog::info("v2.16 schema: {} armed ({})", qualified, entry->audit ? "audit" : "enforce");
  681. }
  682. if (armed > 0) spdlog::info("v2.16 schema: {} collection schema(s) armed", armed);
  683. }
  684. void DatabaseService::applyIndexDeclarations() {
  685. size_t applied = 0;
  686. for (const auto& [qualified, cfg] : config_manager_->allConfigs()) {
  687. if (cfg.indexedFields.empty() && cfg.compositeUniques.empty()) continue;
  688. try {
  689. const auto rc = resolveCollection(qualified);
  690. auto* ds = docStore(rc.project);
  691. auto* lmdb =
  692. dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  693. if (lmdb == nullptr) continue;
  694. // v2.17.0 - an index over a field stored encrypted indexes
  695. // ciphertext under random IVs: lookups never hit and a unique
  696. // constraint never fires. Such declarations are disarmed (neither
  697. // maintained nor consulted) and named, so the operator drops them.
  698. CollectionCfg armed = cfg;
  699. if (encryption_ && encryption_->isEnabled()) {
  700. const EncryptionRule rule = encryptionRuleFor(qualified);
  701. const auto enc = [&](const std::string& f) {
  702. return !isReservedField(f) && encryption_->isEncryptedPath(f, rule);
  703. };
  704. const auto strip = [&](std::vector<std::string>& v, const char* what) {
  705. for (auto it = v.begin(); it != v.end();) {
  706. if (enc(*it)) {
  707. spdlog::error("v2.17 encryption: {} on {}#{} is DISARMED - the field is "
  708. "stored encrypted. Drop it.", what, qualified, *it);
  709. it = v.erase(it);
  710. } else {
  711. ++it;
  712. }
  713. }
  714. };
  715. strip(armed.indexedFields, "index");
  716. strip(armed.uniqueFields, "unique constraint");
  717. for (auto it = armed.compositeUniques.begin(); it != armed.compositeUniques.end();) {
  718. if (std::any_of(it->begin(), it->end(), enc)) {
  719. spdlog::error("v2.17 encryption: a composite unique constraint on {} is "
  720. "DISARMED - one of its fields is stored encrypted. Drop it.",
  721. qualified);
  722. it = armed.compositeUniques.erase(it);
  723. } else {
  724. ++it;
  725. }
  726. }
  727. }
  728. lmdb->set_indexed_fields(rc.collection, armed.indexedFields);
  729. // v2.11.0 T11 — arm uniqueFields the same way. This is the fix
  730. // for the exact failure mode the type was built to avoid:
  731. // uniqueFields has been persisted since T8 with no RPC or proto
  732. // surface, which was safe (nothing consulted it); now that
  733. // set_unique_fields is reachable, a restart that skipped this
  734. // call would silently stop enforcing a constraint every write
  735. // handler still advertises as active.
  736. lmdb->set_unique_fields(rc.collection, armed.uniqueFields);
  737. // v2.12.0 - composite constraints, armed the same way and for the
  738. // same reason: skipping this would stop enforcing a constraint the
  739. // record still declares. Self-healed below if its sub-db is gone.
  740. lmdb->set_composite_uniques(rc.collection, armed.compositeUniques);
  741. for (const auto& cf : armed.compositeUniques) {
  742. if (lmdb->has_composite_unique_subdb(rc.collection, cf)) continue;
  743. uint64_t rows = 0;
  744. auto dupes = lmdb->build_composite_unique(rc.collection, cf, rows);
  745. if (dupes.empty()) {
  746. spdlog::warn("v2.12 composite unique: rebuilt {}#({}) over {} row(s) - "
  747. "declared but its sub-db was absent",
  748. qualified, smartbotic::db::storage::composite_display_name(cf), rows);
  749. } else {
  750. // Cannot happen through the API (declaring over duplicates is
  751. // refused). If it does, say so loudly: the constraint stays
  752. // declared and armed, but rows already violating it exist.
  753. spdlog::error("v2.12 composite unique: {}#({}) is declared but {} "
  754. "existing value combination(s) violate it (e.g. document "
  755. "'{}'); its index could not be rebuilt. Writes that would "
  756. "add another duplicate are still refused.",
  757. qualified, smartbotic::db::storage::composite_display_name(cf),
  758. dupes.size(), dupes.front().sample_id);
  759. }
  760. }
  761. ++applied;
  762. spdlog::info("v2.9 index: {} field(s) active on {} ({} unique)",
  763. cfg.indexedFields.size(), qualified, cfg.uniqueFields.size());
  764. // Self-heal a declared index whose sub-db is absent. That happens
  765. // when the KEY FORMAT VERSION in the sub-db prefix changes (v2.9.1
  766. // unified the numeric encoding, so `_idx_` became `_idx2_`), and it
  767. // would otherwise leave the declaration pointing at nothing: writes
  768. // would maintain the new index correctly, but rows written BEFORE the
  769. // upgrade would have no postings, so an indexed query would silently
  770. // return only the newer ones. Rebuilding is the only safe reading.
  771. for (const auto& field : armed.indexedFields) {
  772. if (lmdb->index_stats(rc.collection, field).has_value()) continue;
  773. const uint64_t rows = lmdb->build_index(rc.collection, field);
  774. spdlog::warn("v2.9 index: rebuilt {}#{} over {} row(s) - the index "
  775. "was declared but its sub-db was absent (key format "
  776. "change or a manual removal)",
  777. qualified, field, rows);
  778. }
  779. } catch (const std::exception& e) {
  780. // Advisory per collection: one unparseable name must not stop the
  781. // rest from being armed. Loud, because a missing declaration means
  782. // that collection's index silently stops being maintained.
  783. spdlog::error("v2.9 index: could not apply declarations for {}: {}",
  784. qualified, e.what());
  785. }
  786. }
  787. if (applied > 0) {
  788. spdlog::info("v2.9 index: applied declarations for {} collection(s)", applied);
  789. }
  790. }
  791. MemoryStore::TtlExpiryAction DatabaseService::ttlExpiryRelationDecision(
  792. const std::string& qualifiedCollection, const std::string& id, bool firstAttempt) {
  793. using Action = MemoryStore::TtlExpiryAction;
  794. // Thin binder over relations/relation_cascade.cpp's ttlExpiryDecision() -
  795. // the policy itself lives there so it is unit-testable against the same
  796. // fixtures the cascade tests use, without a DatabaseService. All this does
  797. // is resolve the per-project LMDB store and supply the replication/events
  798. // notifier.
  799. if (!relation_manager_ || !config_manager_ || !store_ || !persistence_) {
  800. return Action::Proceed;
  801. }
  802. if (qualifiedCollection.empty() || qualifiedCollection[0] == '_') return Action::Proceed;
  803. try {
  804. const auto rc = resolveCollection(qualifiedCollection);
  805. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
  806. docStore(rc.project));
  807. // No LMDB substrate means no reverse index to consult, so the
  808. // pre-v2.11.0 behaviour is all that is available.
  809. if (lmdb == nullptr) return Action::Proceed;
  810. // Replication + Subscribe events, driven per mutation - the same wiring
  811. // DatabaseGrpcImpl::performRelationCascade() uses. Without it a
  812. // TTL-driven cascade would be invisible to followers and subscribers,
  813. // and a follower that never saw the child deletions diverges
  814. // permanently (the v2.3.1 class of bug).
  815. // v2.12.0 - an expiry has no caller, so every event this cascade
  816. // produces carries an explicitly EMPTY actor. Letting it default
  817. // would report a nulled child's previous writer as the cause.
  818. auto notify = [this](const std::string& coll, const std::string& docId,
  819. const std::optional<Document>& doc, EventType eventType) {
  820. notifyReplicationAndEvents(coll, docId, doc, eventType, std::string{});
  821. };
  822. // firstAttempt -> the refusal (if any) is logged at WARN; a retry of an
  823. // already-reported document logs at DEBUG. The sweeper owns that
  824. // decision because it is the only thing that knows the document has
  825. // been refused before.
  826. return smartbotic::database::ttlExpiryDecision(
  827. *relation_manager_, *lmdb, *persistence_, *store_, *config_manager_,
  828. qualifiedCollection, id, notify, firstAttempt);
  829. } catch (const std::exception& e) {
  830. // Never expire a parent whose children could not be evaluated.
  831. spdlog::error("TTL expiry of '{}/{}': could not resolve its storage ({}) - the "
  832. "document is left in place and will be retried",
  833. qualifiedCollection, id, e.what());
  834. return Action::Skip;
  835. }
  836. }
  837. void DatabaseService::applyRelationDeclarations(bool afterMigrations) {
  838. // Group by (project, bare child collection) — set_relations() is a
  839. // per-collection call on that project's LmdbDocumentStore and replaces
  840. // whatever was declared before, so every relation sharing a child
  841. // collection must land in one call.
  842. std::unordered_map<std::string,
  843. std::vector<smartbotic::db::storage::RelationRef>> byChild;
  844. // Track which project each grouping key belongs to alongside the bare
  845. // collection name, since the map key alone doesn't carry it.
  846. std::unordered_map<std::string, std::pair<std::string, std::string>> keyToProjectCollection;
  847. for (const auto& r : relation_manager_->listRelations()) {
  848. try {
  849. const auto rn = resolveCollection(r.name);
  850. const auto rc = resolveCollection(r.child);
  851. // v2.11.0 T13 — parent resolved to its bare name, same reasoning
  852. // as armRelationsForChild's mirror of this construction.
  853. const auto pc = resolveCollection(r.parent);
  854. const std::string key = rc.project + ":" + rc.collection;
  855. // v2.11.0 T13 round 2 — snapshot relationsEnforced at boot-time
  856. // arming, same reasoning as armRelationsForChild's mirror of
  857. // this construction. `key` is already the qualified child name
  858. // configFor expects.
  859. const bool enforced = config_manager_->configFor(key).relationsEnforced;
  860. byChild[key].push_back(smartbotic::db::storage::RelationRef{
  861. rn.collection, r.childField, pc.collection, r.validateOnWrite, enforced});
  862. keyToProjectCollection[key] = {rc.project, rc.collection};
  863. } catch (const std::exception& e) {
  864. // Advisory per relation: one unparseable declaration must not
  865. // stop the rest from being armed. Loud, because a skipped
  866. // relation silently maintains no reverse index for its child.
  867. spdlog::error("v2.11 relations: could not apply declaration '{}': {}",
  868. r.name, e.what());
  869. }
  870. }
  871. size_t applied = 0;
  872. for (const auto& [key, refs] : byChild) {
  873. const auto& [project, collection] = keyToProjectCollection[key];
  874. try {
  875. // ⚠ v2.11.0 close-out — getOrCreate, not get(), on the POST-MIGRATION
  876. // pass. docStore() is projects_->get(), which does NOT create an env,
  877. // and a `create_relation` migration in a project that has never been
  878. // written to has no env yet: the declaration persisted, this pass
  879. // skipped it, and the relation maintained no reverse index and
  880. // enforced NOTHING until the next restart - the exact
  881. // "declared but not enforcing" state the op was added to avoid, just
  882. // narrowed to new projects. A migration declaring a relation IS a
  883. // statement that the project exists, and the mirror resolver would
  884. // getOrCreate the same env on the first write anyway.
  885. //
  886. // The BOOT pass deliberately keeps get(): creating envs there would
  887. // resurrect the env of a project whose declarations are merely stale.
  888. auto* ds = (afterMigrations && projects_)
  889. ? projects_->getOrCreate(project)
  890. : docStore(project);
  891. auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(ds);
  892. if (lmdb == nullptr) continue;
  893. lmdb->set_relations(collection, refs);
  894. ++applied;
  895. spdlog::info("v2.11 relations: {} relation(s) active with child '{}:{}'",
  896. refs.size(), project, collection);
  897. // v2.11.0 T7 self-heal — mirrors applyIndexDeclarations()'s
  898. // rebuild of a declared-but-absent index sub-db, for the same
  899. // reason: a relation whose reverse index sub-db is missing is
  900. // exactly the "declared but not enforcing" bug this task exists
  901. // to close. Reachable paths that leave a relation in this state:
  902. // a snapshot/backup restored from before the sub-db existed, or
  903. // an operator manually dropping the `_relidx1_*` sub-db (there
  904. // is no dropRelation-only-the-index tool). CreateRelation's own
  905. // bootstrap scan (see database_grpc_impl.cpp) covers the normal
  906. // declare-time path; this covers everything else.
  907. //
  908. // ⚠ v2.11.0 close-out (review minor 2) — the SAME code path is the
  909. // NORMAL, expected one for a relation a migration just declared:
  910. // migrations run after this pass, so runMigrations() calls it again
  911. // and the brand-new relation legitimately has no sub-db yet. Logging
  912. // "declared but its sub-db was absent (restored snapshot or a manual
  913. // removal)" at WARN there describes a fault that did not happen.
  914. // `afterMigrations` distinguishes the two so the text and the level
  915. // match the event.
  916. for (const auto& ref : refs) {
  917. if (lmdb->relation_index_exists(ref.name)) continue;
  918. const uint64_t rows =
  919. lmdb->build_relation_index(ref.name, collection, ref.childField);
  920. if (afterMigrations) {
  921. spdlog::info("v2.11 relations: built the reverse index for '{}' over {} "
  922. "existing row(s) in '{}:{}' - a migration declared this "
  923. "relation on this boot",
  924. ref.name, rows, project, collection);
  925. } else {
  926. spdlog::warn("v2.11 relations: rebuilt '{}' over {} row(s) in '{}:{}' - the "
  927. "relation was declared but its reverse index sub-db was absent "
  928. "(restored snapshot predating it, or a manual removal)",
  929. ref.name, rows, project, collection);
  930. }
  931. }
  932. } catch (const std::exception& e) {
  933. spdlog::error("v2.11 relations: could not apply declarations for '{}:{}': {}",
  934. project, collection, e.what());
  935. }
  936. }
  937. if (applied > 0) {
  938. spdlog::info("v2.11 relations: applied declarations for {} child collection(s)", applied);
  939. }
  940. }
  941. void DatabaseService::auditSubdbPlacement() {
  942. if (!projects_) return;
  943. for (const auto& name : projects_->listOpen()) {
  944. auto h = projects_->getHandle(name);
  945. if (!h.env) continue;
  946. try {
  947. // audit_env(), NOT audit(). The path-taking overload opens a
  948. // second MDB_env on the same file; closing it would drop the
  949. // POSIX record locks this process already holds for `h.env`
  950. // (POSIX locks are per-process, and closing any fd on a file
  951. // releases all of them), leaving every later mdb_txn_begin
  952. // failing EINVAL. Borrow the open handle instead.
  953. const auto rep = smartbotic::db::storage::audit_env(h.env->raw(), name);
  954. if (rep.misplaced.empty()) {
  955. spdlog::debug("placement audit: project '{}' consistent ({} rows)",
  956. name, rep.rows_scanned);
  957. continue;
  958. }
  959. // Summarise per (physical -> declared home) pair; one line per
  960. // affected document would be unreadable at scale.
  961. std::map<std::string, uint64_t> pairs;
  962. for (const auto& m : rep.misplaced) {
  963. ++pairs[m.physical_subdb + " -> " + m.home_subdb];
  964. }
  965. spdlog::error("placement audit: project '{}' has {} document(s) in the "
  966. "wrong sub-db. Reads served from LMDB will not find them "
  967. "under their own collection. Repair offline with: "
  968. "smartbotic-db-cli reconcile-subdbs --env {} --project {} --apply",
  969. name, rep.misplaced.size(), h.env->path(), name);
  970. for (const auto& [pair, count] : pairs) {
  971. spdlog::error("placement audit: {} document(s) {}", count, pair);
  972. }
  973. } catch (const std::exception& e) {
  974. // Advisory only — a failed audit must not take the service down.
  975. spdlog::warn("placement audit: project '{}' could not be audited: {}",
  976. name, e.what());
  977. }
  978. }
  979. }
  980. void DatabaseService::auditMemoryDiskKeys() {
  981. if (!projects_ || !store_) return;
  982. namespace sd = smartbotic::database;
  983. const auto started = std::chrono::steady_clock::now();
  984. // LMDB sub-db ("project:collection") -> the MemoryStore names that feed
  985. // it. A default-project collection may also live under its bare legacy
  986. // name; both resolve to one sub-db, so both count as "in memory".
  987. std::map<std::string, std::vector<std::string>> memNames;
  988. for (const auto& name : store_->listCollections()) {
  989. try {
  990. auto rc = sd::resolveCollection(name);
  991. if (rc.collection.empty() || rc.collection.front() == '_') continue;
  992. memNames[rc.qualified].push_back(name);
  993. } catch (const std::exception&) {
  994. continue; // a malformed legacy key; the backfill already reported it
  995. }
  996. }
  997. const auto samples = [](const std::vector<std::string>& ids) {
  998. std::string out;
  999. for (size_t i = 0; i < ids.size() && i < 10; ++i) {
  1000. if (i) out += ", ";
  1001. out += ids[i];
  1002. }
  1003. if (ids.size() > 10) out += ", ...";
  1004. return out;
  1005. };
  1006. uint64_t diskOnlyTotal = 0, memOnlyTotal = 0, compared = 0;
  1007. for (const auto& project : projects_->listOpen()) {
  1008. auto* ds = docStore(project);
  1009. if (!ds) continue;
  1010. std::set<std::string> collections;
  1011. try {
  1012. for (auto& c : ds->list_collections()) collections.insert(std::move(c));
  1013. } catch (const std::exception& e) {
  1014. spdlog::warn("key audit: project '{}' could not be listed: {}", project, e.what());
  1015. continue;
  1016. }
  1017. const std::string prefix = project + sd::kProjectSeparator;
  1018. for (const auto& [qualified, names] : memNames) {
  1019. if (qualified.rfind(prefix, 0) == 0) collections.insert(qualified.substr(prefix.size()));
  1020. }
  1021. for (const auto& coll : collections) {
  1022. if (coll.empty() || coll.front() == '_') continue;
  1023. const std::string qualified = prefix + coll;
  1024. try {
  1025. auto disk = ds->list_ids(coll);
  1026. if (!disk) continue; // backend cannot list
  1027. std::vector<std::string> mem;
  1028. if (auto it = memNames.find(qualified); it != memNames.end()) {
  1029. for (const auto& n : it->second) {
  1030. for (auto& id : store_->getDocumentIds(n)) mem.push_back(std::move(id));
  1031. for (auto& id : store_->getEvictedDocumentIds(n)) mem.push_back(std::move(id));
  1032. }
  1033. }
  1034. std::sort(mem.begin(), mem.end());
  1035. mem.erase(std::unique(mem.begin(), mem.end()), mem.end());
  1036. std::sort(disk->begin(), disk->end()); // already key order; cheap insurance
  1037. std::vector<std::string> diskOnly, memOnly;
  1038. std::set_difference(disk->begin(), disk->end(), mem.begin(), mem.end(),
  1039. std::back_inserter(diskOnly));
  1040. std::set_difference(mem.begin(), mem.end(), disk->begin(), disk->end(),
  1041. std::back_inserter(memOnly));
  1042. ++compared;
  1043. if (!diskOnly.empty()) {
  1044. diskOnlyTotal += diskOnly.size();
  1045. spdlog::error("key audit: {}: {} row(s) on disk but not in memory - reads "
  1046. "find them; before 2.20.2 every write said not-found and an "
  1047. "insert of the id overwrote them; a write now loads them. "
  1048. "ids: {}", qualified, diskOnly.size(), samples(diskOnly));
  1049. }
  1050. if (!memOnly.empty()) {
  1051. memOnlyTotal += memOnly.size();
  1052. spdlog::error("key audit: {}: {} row(s) in memory but not on disk - writes "
  1053. "find them, reads served from disk do not. ids: {}",
  1054. qualified, memOnly.size(), samples(memOnly));
  1055. }
  1056. } catch (const std::exception& e) {
  1057. spdlog::warn("key audit: {} could not be audited: {}", qualified, e.what());
  1058. }
  1059. }
  1060. }
  1061. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  1062. std::chrono::steady_clock::now() - started).count();
  1063. if (diskOnlyTotal == 0 && memOnlyTotal == 0) {
  1064. spdlog::info("key audit: {} collection(s) consistent ({} ms)", compared, ms);
  1065. } else {
  1066. spdlog::error("key audit: {} collection(s) compared, {} row(s) on disk only, {} in "
  1067. "memory only ({} ms). Changes nothing; see the lines above.",
  1068. compared, diskOnlyTotal, memOnlyTotal, ms);
  1069. }
  1070. }
  1071. bool DatabaseService::backfillIntoDocStore() {
  1072. if (!projects_) {
  1073. // Registry open failed earlier; nothing to back-fill into.
  1074. return true;
  1075. }
  1076. // v2.3 — MemoryStore stores collection keys in qualified form
  1077. // ("project:collection"). For the default project (back-compat
  1078. // path) the marker check operates on the default env. Skip when
  1079. // already migrated.
  1080. auto handle = projects_->getHandle(smartbotic::database::kDefaultProject);
  1081. if (handle.env) {
  1082. try {
  1083. if (smartbotic::db::storage::migration_complete(*handle.env)) {
  1084. spdlog::info("v2.3 backfill: default project already migrated, skipping");
  1085. return true;
  1086. }
  1087. } catch (const std::exception& e) {
  1088. spdlog::warn("v2.3 backfill: migration_complete probe failed: {} — "
  1089. "treating default env as fresh and proceeding",
  1090. e.what());
  1091. }
  1092. }
  1093. const auto collections = store_->listCollections();
  1094. uint64_t total_docs = 0;
  1095. uint64_t total_failures = 0;
  1096. auto t0 = std::chrono::steady_clock::now();
  1097. for (const auto& qualified : collections) {
  1098. if (qualified.empty() || qualified[0] == '_') continue;
  1099. // Each qualified key parses to (project, collection); route the
  1100. // mirror write to the right project's env.
  1101. smartbotic::database::ProjectCollection pc;
  1102. try {
  1103. pc = smartbotic::database::parseProjectCollection(qualified);
  1104. } catch (const std::exception&) {
  1105. // Legacy unqualified key — treat as default project.
  1106. pc = {std::string(smartbotic::database::kDefaultProject), qualified};
  1107. }
  1108. auto* ds = projects_->getOrCreate(pc.project);
  1109. if (!ds) {
  1110. ++total_failures;
  1111. continue;
  1112. }
  1113. const auto docs = store_->getAllDocuments(qualified);
  1114. for (const auto& doc : docs) {
  1115. std::optional<Document> opt_doc(doc);
  1116. const uint64_t drift_before = mirror_drift_count_.load(std::memory_order_relaxed);
  1117. // v2.11.0 T13 round 2 — UniqueViolation/MissingParentReference are
  1118. // rethrown UNCAUGHT by applyDualWriteMirror (deliberately - see
  1119. // both exceptions' header comments), unlike a genuine mirror
  1120. // fault which is swallowed and only shows up as a drift bump
  1121. // below. Uncaught here would escape this loop, backfillIntoDocStore
  1122. // and initialize() itself, refusing startup over one rejected row.
  1123. // Practically unreachable today - backfill only runs migrating a
  1124. // v1.x dataset, which predates both `_relations` and unique-index
  1125. // declarations - but catching removes that reasoning burden for
  1126. // the next reader, same as any other row here that fails.
  1127. try {
  1128. smartbotic::db::storage::applyDualWriteMirror(
  1129. ds, mirror_healthy_, mirror_drift_count_,
  1130. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1131. } catch (const std::exception& e) {
  1132. spdlog::error("v2.3 backfill: mirror rejected {}/{}: {} - row stays "
  1133. "in MemoryStore only, LMDB does not have it",
  1134. qualified, doc.id, e.what());
  1135. ++total_failures;
  1136. }
  1137. if (mirror_drift_count_.load(std::memory_order_relaxed) > drift_before) {
  1138. ++total_failures;
  1139. }
  1140. ++total_docs;
  1141. if (total_docs % 10000 == 0) {
  1142. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  1143. const std::string status = "STATUS=v2.3 backfill: " +
  1144. std::to_string(total_docs) + " docs mirrored";
  1145. sd_notify(0, status.c_str());
  1146. spdlog::info("v2.3 backfill: {} docs mirrored ({} failures so far)",
  1147. total_docs, total_failures);
  1148. }
  1149. }
  1150. }
  1151. const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  1152. std::chrono::steady_clock::now() - t0).count();
  1153. if (total_failures == 0) {
  1154. // Stamp schema_version=2 on every opened project env. Subsequent
  1155. // boots short-circuit at migration_complete().
  1156. for (const auto& name : projects_->listOpen()) {
  1157. auto h = projects_->getHandle(name);
  1158. if (!h.env) continue;
  1159. try {
  1160. smartbotic::db::storage::mark_migration_complete(*h.env);
  1161. } catch (const std::exception& e) {
  1162. spdlog::warn("v2.3 backfill: schema_version marker write failed for "
  1163. "project '{}': {}", name, e.what());
  1164. }
  1165. }
  1166. spdlog::info("v2.3 backfill: complete — {} docs across {} collections in {} ms",
  1167. total_docs, collections.size(), elapsed);
  1168. } else {
  1169. spdlog::error("v2.3 backfill: completed with {} failures out of {} docs "
  1170. "in {} ms — mirror_healthy_=false, reads must NOT flip to LMDB",
  1171. total_failures, total_docs, elapsed);
  1172. }
  1173. return true;
  1174. }
  1175. void DatabaseService::start() {
  1176. if (running_.exchange(true)) {
  1177. return;
  1178. }
  1179. spdlog::info("Starting database service with {} listener(s)", config_.listeners.size());
  1180. // Start components
  1181. store_->start();
  1182. persistence_->start();
  1183. events_->start();
  1184. files_->start();
  1185. if (config_.replicationEnabled) {
  1186. replication_->start();
  1187. // Set initial local collections for discovery
  1188. replication_->setLocalCollections(store_->listCollections());
  1189. }
  1190. // Start gRPC server
  1191. startGrpcServer();
  1192. spdlog::info("Database service started");
  1193. }
  1194. void DatabaseService::stop() {
  1195. if (!running_.exchange(false)) {
  1196. return;
  1197. }
  1198. spdlog::info("Stopping database service...");
  1199. // Stop gRPC server first
  1200. stopGrpcServer();
  1201. // Stop components in reverse order
  1202. if (replication_) {
  1203. replication_->stop();
  1204. }
  1205. if (files_) {
  1206. files_->stop();
  1207. }
  1208. if (events_) {
  1209. events_->stop();
  1210. }
  1211. if (persistence_ && store_) {
  1212. // v1.8.0 — take a final snapshot on graceful shutdown so the next
  1213. // boot's recovery is "trivial" (snapshot-loaded) instead of "WAL-only
  1214. // replay" which trips auto-readonly mode. This makes ordinary
  1215. // restarts pass through cleanly without needing
  1216. // `smartbotic-db-cli unlock`.
  1217. //
  1218. // v1.8.2 — extend systemd's stop watchdog before doing it. On Zoe
  1219. // (1.85M docs / ~5 GB tracked) the serialize takes ~70 s and the
  1220. // default TimeoutStopSec=30s SIGKILLed the process mid-write, peak
  1221. // RSS hit 11 GB (live state + uncompressed serialize buffer), and
  1222. // the new snapshot never made it to disk anyway. EXTEND_TIMEOUT_USEC
  1223. // tells systemd we're working — same protocol the recovery path
  1224. // uses during startup. Paired with TimeoutStopSec=300 in the unit
  1225. // file as the static cap.
  1226. #ifdef HAVE_SYSTEMD
  1227. sd_notify(0, "EXTEND_TIMEOUT_USEC=600000000");
  1228. sd_notify(0, "STATUS=Writing final snapshot");
  1229. #endif
  1230. try {
  1231. persistence_->forceSnapshot(*store_);
  1232. spdlog::info("Final snapshot taken on shutdown");
  1233. } catch (const std::exception& e) {
  1234. spdlog::warn("Final snapshot on shutdown failed: {} — recovery on next "
  1235. "boot may be WAL-only and trip auto-readonly mode", e.what());
  1236. }
  1237. }
  1238. if (persistence_) {
  1239. persistence_->stop();
  1240. }
  1241. if (store_) {
  1242. store_->stop();
  1243. }
  1244. spdlog::info("Database service stopped");
  1245. }
  1246. void DatabaseService::wait() {
  1247. if (serverThread_.joinable()) {
  1248. serverThread_.join();
  1249. }
  1250. }
  1251. void DatabaseService::signalStop() {
  1252. stopRequested_ = true;
  1253. stop();
  1254. }
  1255. nlohmann::json DatabaseService::getStats() const {
  1256. nlohmann::json stats;
  1257. if (store_) {
  1258. auto storeStats = store_->getStats();
  1259. stats["documents"] = storeStats.totalDocuments;
  1260. stats["collections"] = storeStats.totalCollections;
  1261. stats["memory_bytes"] = storeStats.estimatedMemoryBytes;
  1262. stats["inserts"] = storeStats.insertCount;
  1263. stats["updates"] = storeStats.updateCount;
  1264. stats["deletes"] = storeStats.deleteCount;
  1265. stats["queries"] = storeStats.queryCount;
  1266. }
  1267. if (persistence_) {
  1268. auto persistStats = persistence_->getStats();
  1269. stats["wal_sequence"] = persistStats.walSequence;
  1270. stats["wal_size_bytes"] = persistStats.walSizeBytes;
  1271. stats["snapshot_count"] = persistStats.snapshotCount;
  1272. stats["last_snapshot_sequence"] = persistStats.lastSnapshotSequence;
  1273. }
  1274. if (events_) {
  1275. stats["subscriptions"] = events_->subscriptionCount();
  1276. }
  1277. return stats;
  1278. }
  1279. DatabaseService::Config DatabaseService::loadConfig(const std::filesystem::path& configPath) {
  1280. std::ifstream file(configPath);
  1281. if (!file) {
  1282. throw std::runtime_error("Failed to open config file: " + configPath.string());
  1283. }
  1284. nlohmann::json json;
  1285. file >> json;
  1286. return parseConfig(json);
  1287. }
  1288. DatabaseService::Config DatabaseService::parseConfig(const nlohmann::json& json) {
  1289. Config config;
  1290. // Check for both "storage" and "database" keys for backward compatibility
  1291. const nlohmann::json* dbConfig = nullptr;
  1292. if (json.contains("database")) {
  1293. dbConfig = &json["database"];
  1294. } else if (json.contains("storage")) {
  1295. dbConfig = &json["storage"];
  1296. }
  1297. if (dbConfig) {
  1298. const auto& db = *dbConfig;
  1299. config.nodeId = db.value("node_id", config.nodeId);
  1300. config.bindAddress = db.value("bind_address", config.bindAddress);
  1301. config.rpcPort = db.value("rpc_port", config.rpcPort);
  1302. // v2.4 — parse the per-listener fleet. If "listeners" is set,
  1303. // it overrides the legacy bind_address+rpc_port. Otherwise we
  1304. // synthesise one listener below using those legacy fields.
  1305. if (db.contains("listeners") && db["listeners"].is_array()) {
  1306. for (const auto& l : db["listeners"]) {
  1307. ListenerConfig lc;
  1308. lc.bind = l.value("bind", lc.bind);
  1309. lc.port = l.value("port", lc.port);
  1310. if (l.contains("tls") && l["tls"].is_object()) {
  1311. const auto& t = l["tls"];
  1312. lc.tls.enabled = t.value("enabled", false);
  1313. lc.tls.cert_path = t.value("cert_path", std::string{});
  1314. lc.tls.key_path = t.value("key_path", std::string{});
  1315. lc.tls.auto_self_signed_if_missing =
  1316. t.value("auto_self_signed_if_missing", true);
  1317. }
  1318. if (l.contains("auth") && l["auth"].is_object()) {
  1319. const auto& a = l["auth"];
  1320. lc.auth.required = a.value("required", false);
  1321. if (a.contains("keys") && a["keys"].is_array()) {
  1322. for (const auto& k : a["keys"]) {
  1323. // v2.7.0 — a key is either a bare token (v2.4-v2.6
  1324. // shape) or {"name","key"}. The name becomes the
  1325. // principal that policy is written against; a bare
  1326. // token maps to the reserved `unnamed`, so old
  1327. // configs keep authenticating but cannot be told
  1328. // apart in a policy until they are named.
  1329. if (k.is_string()) {
  1330. lc.auth.keys.push_back(
  1331. {smartbotic::database::auth::kPrincipalUnnamed,
  1332. k.get<std::string>()});
  1333. } else if (k.is_object()) {
  1334. const std::string name = k.value("name", std::string{});
  1335. const std::string key = k.value("key", std::string{});
  1336. if (key.empty()) {
  1337. spdlog::warn("auth: listener {}:{} has a key entry "
  1338. "with no `key` value - skipped",
  1339. lc.bind, lc.port);
  1340. continue;
  1341. }
  1342. lc.auth.keys.push_back(
  1343. {name.empty()
  1344. ? std::string(smartbotic::database::auth::kPrincipalUnnamed)
  1345. : name,
  1346. key});
  1347. }
  1348. }
  1349. }
  1350. }
  1351. config.listeners.push_back(std::move(lc));
  1352. }
  1353. }
  1354. // Expand environment variables in data directory
  1355. std::string dataDir = db.value("data_directory", "");
  1356. if (dataDir.find("${HOME}") != std::string::npos) {
  1357. const char* home = std::getenv("HOME");
  1358. if (home) {
  1359. size_t pos = dataDir.find("${HOME}");
  1360. dataDir.replace(pos, 7, home);
  1361. }
  1362. }
  1363. config.dataDirectory = dataDir;
  1364. // Migrations settings
  1365. if (db.contains("migrations")) {
  1366. auto& migrations = db["migrations"];
  1367. config.migrations.enabled = migrations.value("enabled", config.migrations.enabled);
  1368. config.migrations.autoApply = migrations.value("auto_apply", config.migrations.autoApply);
  1369. config.migrations.failOnError = migrations.value("fail_on_error", config.migrations.failOnError);
  1370. std::string migDir = migrations.value("directory", "");
  1371. if (migDir.find("${HOME}") != std::string::npos) {
  1372. const char* home = std::getenv("HOME");
  1373. if (home) {
  1374. size_t pos = migDir.find("${HOME}");
  1375. migDir.replace(pos, 7, home);
  1376. }
  1377. }
  1378. config.migrations.directory = migDir;
  1379. }
  1380. // Memory eviction settings
  1381. if (db.contains("memory")) {
  1382. auto& memory = db["memory"];
  1383. // Deprecation log. These knobs control MemoryStore eviction, which
  1384. // is still active for the MemoryStore-side mirror but does NOT bound
  1385. // RSS since v2.0 (LMDB mmap is the dominant RSS contributor). The
  1386. // substrate-level equivalent is the LMDB env mapsize and the OS page
  1387. // cache.
  1388. //
  1389. // They disappear when the write-handler migration deletes MemoryStore
  1390. // (docs/ROADMAP.md, "Pending"). An earlier revision of this comment
  1391. // promised a v2.1 rename to `buffer_pool_size_mb` "per the Phase C
  1392. // plan"; that plan was superseded by LMDB before it was written, no
  1393. // such knob exists, and the rename is not planned.
  1394. for (const char* deprecated : {"max_memory_mb",
  1395. "eviction_threshold_percent",
  1396. "eviction_target_percent",
  1397. "eviction_check_interval_ms",
  1398. "eviction_chunk_size",
  1399. "eviction_chunk_pause_ms",
  1400. "max_eviction_passes_per_trigger",
  1401. "hot_write_floor_ms",
  1402. "memory_priority"}) {
  1403. if (memory.contains(deprecated)) {
  1404. spdlog::warn("v2.0 deprecation: storage.memory.{} is deprecated "
  1405. "and will be removed in v2.1. v2.0 RSS is bounded "
  1406. "by the LMDB env mapsize + OS page cache, not by "
  1407. "MemoryStore eviction. Setting still applied to "
  1408. "the MemoryStore mirror for back-compat.",
  1409. deprecated);
  1410. }
  1411. }
  1412. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  1413. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  1414. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  1415. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  1416. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  1417. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  1418. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  1419. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  1420. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  1421. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  1422. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  1423. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  1424. // v1.7.0 T10 — eviction burst event threshold
  1425. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  1426. // v2.4.3 — eviction drain cap (0 disables)
  1427. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  1428. }
  1429. // v2.11.0 close-out — TTL sweep budgets. Its own block rather than
  1430. // `memory`, because these bound expiry work per sweep, not memory.
  1431. if (db.contains("ttl")) {
  1432. auto& ttl = db["ttl"];
  1433. config.ttlMaxCandidatesPerSweep =
  1434. ttl.value("max_candidates_per_sweep", config.ttlMaxCandidatesPerSweep);
  1435. config.ttlMaxBlockedRetriesPerSweep =
  1436. ttl.value("max_blocked_retries_per_sweep", config.ttlMaxBlockedRetriesPerSweep);
  1437. config.ttlBlockedRetrySweeps =
  1438. ttl.value("blocked_retry_sweeps", config.ttlBlockedRetrySweeps);
  1439. config.ttlBlockedSummarySweeps =
  1440. ttl.value("blocked_summary_sweeps", config.ttlBlockedSummarySweeps);
  1441. }
  1442. // Persistence settings
  1443. if (db.contains("persistence")) {
  1444. auto& persistence = db["persistence"];
  1445. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  1446. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  1447. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  1448. // Snapshot durability (NEW in v1.6.1)
  1449. if (persistence.contains("snapshots")) {
  1450. const auto& snap = persistence["snapshots"];
  1451. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  1452. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  1453. }
  1454. // Recovery (NEW in v1.6.1)
  1455. if (persistence.contains("recovery")) {
  1456. const auto& rec = persistence["recovery"];
  1457. std::string modeStr = rec.value("mode", std::string("normal"));
  1458. try {
  1459. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  1460. } catch (const std::exception& e) {
  1461. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  1462. modeStr, e.what());
  1463. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  1464. }
  1465. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  1466. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  1467. }
  1468. }
  1469. // File settings
  1470. if (db.contains("files")) {
  1471. auto& files = db["files"];
  1472. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  1473. // v2.8.0 — this interval now drives the file EXPIRY sweep as well
  1474. // as orphan cleanup, so accept the plainer name too. The original
  1475. // key kept working; nothing read either of them before 2.8.0
  1476. // because there was no sweeper thread at all.
  1477. config.fileCleanupIntervalSec =
  1478. files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  1479. config.fileCleanupIntervalSec =
  1480. files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
  1481. // v2.8.0 — default retention per file type. The analogue of a
  1482. // collection's defaultTtlSeconds, so retention is an operator
  1483. // setting rather than something every uploader must remember.
  1484. //
  1485. // "default_ttl_seconds": {
  1486. // "acme:generated": 86400, // one project, one type
  1487. // "generated": 604800, // any project
  1488. // "acme:*": 2592000, // every type in one project
  1489. // "*": 0 // everything (0 = keep)
  1490. // }
  1491. if (files.contains("default_ttl_seconds") &&
  1492. files["default_ttl_seconds"].is_object()) {
  1493. for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
  1494. if (v.is_number_unsigned()) {
  1495. config.fileDefaultTtlByType[k] = v.get<uint32_t>();
  1496. }
  1497. }
  1498. }
  1499. if (files.contains("allowed_types")) {
  1500. for (const auto& type : files["allowed_types"]) {
  1501. config.allowedFileTypes.push_back(type.get<std::string>());
  1502. }
  1503. }
  1504. }
  1505. // Encryption settings
  1506. if (db.contains("encryption")) {
  1507. auto& encryption = db["encryption"];
  1508. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  1509. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  1510. std::string keyFile = encryption.value("key_file", "");
  1511. if (keyFile.find("${HOME}") != std::string::npos) {
  1512. const char* home = std::getenv("HOME");
  1513. if (home) {
  1514. size_t pos = keyFile.find("${HOME}");
  1515. keyFile.replace(pos, 7, home);
  1516. }
  1517. }
  1518. config.keyFilePath = keyFile;
  1519. }
  1520. // Replication settings
  1521. if (db.contains("replication")) {
  1522. auto& replication = db["replication"];
  1523. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  1524. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  1525. if (replication.contains("peers")) {
  1526. for (const auto& peer : replication["peers"]) {
  1527. config.peerAddresses.push_back(peer.get<std::string>());
  1528. }
  1529. }
  1530. }
  1531. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  1532. if (db.contains("grpc")) {
  1533. const auto& grpc = db["grpc"];
  1534. config.grpc.maxReceiveMessageSizeMb =
  1535. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  1536. config.grpc.maxSendMessageSizeMb =
  1537. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  1538. config.grpc.resourceQuotaMemoryMb =
  1539. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  1540. config.grpc.maxConcurrentSubscribeStreams =
  1541. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  1542. config.grpc.maxConcurrentFileStreams =
  1543. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  1544. }
  1545. }
  1546. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  1547. // one from the legacy bind_address + rpc_port fields. This is what
  1548. // every existing v2.3 deployment will hit on first v2.4 boot —
  1549. // their configs don't know about listeners[] yet, and they get
  1550. // exactly the same listener they had before.
  1551. if (config.listeners.empty()) {
  1552. ListenerConfig legacy;
  1553. legacy.bind = config.bindAddress;
  1554. legacy.port = config.rpcPort;
  1555. legacy.tls.enabled = false;
  1556. legacy.auth.required = false;
  1557. config.listeners.push_back(std::move(legacy));
  1558. }
  1559. return config;
  1560. }
  1561. void DatabaseService::setupComponents() {
  1562. // v2.3 multi-project storage substrate.
  1563. //
  1564. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  1565. // project always exists and is what v2.0-v2.2 clients (which don't
  1566. // address projects) implicitly use.
  1567. //
  1568. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  1569. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  1570. // atomically moves it under `projects/default/env/` before the
  1571. // registry opens.
  1572. migrateLegacyEnvToDefaultProject();
  1573. try {
  1574. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  1575. constexpr uint32_t kMaxDbs = 1024;
  1576. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  1577. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  1578. const auto opened = projects_->openExisting();
  1579. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  1580. opened.size(),
  1581. [&opened]() {
  1582. std::string s;
  1583. for (size_t i = 0; i < opened.size(); ++i) {
  1584. if (i) s += ", ";
  1585. s += opened[i];
  1586. }
  1587. return s;
  1588. }());
  1589. } catch (const std::exception& e) {
  1590. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  1591. "service cannot start without LMDB; bailing",
  1592. (config_.dataDirectory / "projects").string(), e.what());
  1593. projects_.reset();
  1594. throw;
  1595. }
  1596. // Create memory store with eviction config
  1597. MemoryStore::Config storeConfig;
  1598. storeConfig.nodeId = config_.nodeId;
  1599. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  1600. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  1601. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  1602. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  1603. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  1604. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  1605. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  1606. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  1607. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  1608. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  1609. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  1610. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  1611. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  1612. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  1613. // v2.11.0 close-out — TTL sweep budgets (storage.ttl).
  1614. storeConfig.ttlMaxCandidatesPerSweep = config_.ttlMaxCandidatesPerSweep;
  1615. storeConfig.ttlMaxBlockedRetriesPerSweep = config_.ttlMaxBlockedRetriesPerSweep;
  1616. storeConfig.ttlBlockedRetrySweeps = config_.ttlBlockedRetrySweeps;
  1617. storeConfig.ttlBlockedSummarySweeps = config_.ttlBlockedSummarySweeps;
  1618. store_ = std::make_unique<MemoryStore>(storeConfig);
  1619. // Create view manager (cache loaded in initialize() after persistence recovery)
  1620. view_manager_ = std::make_unique<ViewManager>(*store_);
  1621. // Create per-collection config manager and attach it to the store so the
  1622. // write paths route document timestamp stamps through it.
  1623. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  1624. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  1625. // recovery alongside the view and collection-config caches.
  1626. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  1627. // v2.11.0 T6a — relation declarations. Constructed here; its cache is
  1628. // loaded after recovery alongside the view/config/policy caches.
  1629. relation_manager_ = std::make_unique<RelationManager>(*store_);
  1630. store_->setConfigManager(config_manager_.get());
  1631. // v1.9.0 — disk-resident version history. Replaces the in-heap
  1632. // `CollectionData::versionHistory` deques that were the dominant
  1633. // source of the Zoe untracked-RSS gap. One file per collection at
  1634. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  1635. // here, wired into the store immediately so snapshot deserializer
  1636. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  1637. HistoryStore::Config histConfig;
  1638. histConfig.dataDir = config_.dataDirectory;
  1639. history_store_ = std::make_unique<HistoryStore>(histConfig);
  1640. store_->setHistoryStore(history_store_.get());
  1641. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  1642. // resolver. Every write that flows through store_ commits to the
  1643. // right per-project LMDB env BEFORE the per-collection lock releases.
  1644. if (projects_) {
  1645. auto* registry = projects_.get();
  1646. store_->setDocumentStoreMirror(
  1647. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  1648. return registry->getOrCreate(project);
  1649. },
  1650. &mirror_healthy_,
  1651. &mirror_drift_count_);
  1652. }
  1653. // Create persistence manager. Start from any persistenceConfig values the
  1654. // caller (config loader / CLI parser) has already populated — including
  1655. // recoveryMode — and overlay the top-level convenience fields.
  1656. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  1657. persistConfig.dataDir = config_.dataDirectory;
  1658. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  1659. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  1660. persistConfig.compressionEnabled = config_.compressionEnabled;
  1661. persistConfig.nodeId = config_.nodeId;
  1662. // Mirror the resolved recoveryMode back into our Config so downstream code
  1663. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  1664. // without having to reach into the PersistenceManager.
  1665. config_.persistenceConfig = persistConfig;
  1666. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  1667. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  1668. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  1669. const std::optional<Document>& doc, EventType eventType,
  1670. const std::optional<std::string>& actor) {
  1671. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  1672. // sequence and record it on the store so eviction stubs can carry
  1673. // a real seq (instead of doc.version, which was useless as a
  1674. // `fromSequence` hint and forced a full WAL scan on every fault).
  1675. uint64_t walSeq = 0;
  1676. switch (eventType) {
  1677. case EventType::INSERT:
  1678. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  1679. break;
  1680. case EventType::UPDATE:
  1681. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  1682. break;
  1683. case EventType::DELETE:
  1684. persistence_->logDelete(collection, id);
  1685. break;
  1686. default:
  1687. break;
  1688. }
  1689. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  1690. store_->recordWalSequence(collection, id, walSeq);
  1691. }
  1692. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  1693. // that it runs UNDER the per-collection write lock. That closes the
  1694. // race window where readers could see a doc in MemoryStore but not
  1695. // yet in LMDB. The callback now does only WAL + replication + events.
  1696. // v2.11.0 T12 review (C2) — replication + events extracted into
  1697. // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
  1698. // drive them explicitly too. See that method's doc comment.
  1699. notifyReplicationAndEvents(collection, id, doc, eventType, actor);
  1700. });
  1701. // Set up document load callback for LRU eviction recovery.
  1702. //
  1703. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  1704. // callback below at append time, not the per-doc version counter).
  1705. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  1706. // returns entries with seq >= walSequence — the doc's last write is
  1707. // exactly at walSequence, so the very first hit is the one we want.
  1708. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  1709. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  1710. store_->setDocumentLoadCallback([this](const std::string& collection,
  1711. const std::string& id,
  1712. uint64_t walSequence) -> std::optional<Document> {
  1713. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  1714. return persistence_->loadDocument(collection, id, fromSequence);
  1715. });
  1716. // Create encryption manager
  1717. EncryptionManager::Config encryptConfig;
  1718. encryptConfig.enabled = config_.encryptionEnabled;
  1719. encryptConfig.keyFilePath = config_.keyFilePath;
  1720. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  1721. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  1722. // Create event manager
  1723. EventManager::Config eventConfig;
  1724. eventConfig.nodeId = config_.nodeId;
  1725. events_ = std::make_unique<EventManager>(eventConfig);
  1726. // Create file manager
  1727. FileManager::Config fileConfig;
  1728. fileConfig.filesDir = config_.dataDirectory / "files";
  1729. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  1730. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  1731. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  1732. fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
  1733. files_ = std::make_unique<FileManager>(fileConfig);
  1734. // Create replication manager
  1735. ReplicationManager::Config replConfig;
  1736. replConfig.nodeId = config_.nodeId;
  1737. replConfig.peerAddresses = config_.peerAddresses;
  1738. replConfig.conflictResolution = config_.conflictResolution;
  1739. replication_ = std::make_unique<ReplicationManager>(replConfig);
  1740. // Wire replication entry apply callback
  1741. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  1742. applyReplicatedEntry(entry);
  1743. });
  1744. // Create gRPC implementations
  1745. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  1746. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  1747. *policy_manager_, *relation_manager_
  1748. );
  1749. // v2.7.0 — hand the impl the union of every listener's keys so it can
  1750. // resolve a principal per call. A token is only accepted if some listener's
  1751. // auth processor accepted it, so the union cannot widen authentication; it
  1752. // only names what was already authenticated.
  1753. {
  1754. std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
  1755. for (const auto& l : config_.listeners) {
  1756. for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
  1757. }
  1758. storageImpl_->setPrincipalKeys(std::move(all));
  1759. }
  1760. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  1761. storageImpl_->setStreamLimits(
  1762. config_.grpc.maxConcurrentSubscribeStreams,
  1763. config_.grpc.maxConcurrentFileStreams);
  1764. storageImpl_->setMaxSendBytes(
  1765. static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024); // v2.13.0
  1766. // v2.13.1 - a stored row must stay readable: the largest body a write may
  1767. // leave behind is the send limit less room for metadata and a vector sent
  1768. // alongside (16 KB at dimension 4096). Enforced on insert/update/upsert/
  1769. // batch bodies and on the RESULT of a patch.
  1770. {
  1771. constexpr size_t kReadMargin = 256 * 1024;
  1772. const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
  1773. store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
  1774. }
  1775. // v2.16.0 - collection schemas. The check sees the body as the store holds
  1776. // it, so it validates a copy: read metadata and `_vector` removed (neither
  1777. // is a user field), sensitive fields decrypted (a rule about a value must
  1778. // judge the value, not its ciphertext).
  1779. store_->setSchemaCheck([this](const std::string& collection, const nlohmann::json& body) {
  1780. auto entry = schemas_.get(CollectionConfigManager::canonicalKey(collection));
  1781. if (!entry) return;
  1782. const nlohmann::json copy = schemaView(body);
  1783. size_t total = 0;
  1784. auto violations = entry->compiled->validate(copy, 10, &total);
  1785. if (violations.empty()) return;
  1786. const std::string summary = smartbotic::db::schema::summarize(violations, total);
  1787. if (entry->audit) {
  1788. // Rate-limited: an audit run on a busy collection must not flood
  1789. // the log. The counter is exact.
  1790. const uint64_t n = entry->auditViolations.fetch_add(1) + 1;
  1791. if (n <= 20 || (n & (n - 1)) == 0) {
  1792. spdlog::warn("v2.16 schema AUDIT: a write to {} does not conform ({} so far): {}",
  1793. collection, n, summary);
  1794. }
  1795. return;
  1796. }
  1797. entry->refusals.fetch_add(1);
  1798. std::vector<std::string> paths;
  1799. for (const auto& v : violations) paths.push_back(v.path);
  1800. throw SchemaViolation(collection, "schema violation: " + summary, std::move(paths));
  1801. });
  1802. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  1803. *store_, *replication_, *persistence_
  1804. );
  1805. }
  1806. void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
  1807. const std::string& id,
  1808. const std::optional<Document>& doc,
  1809. EventType eventType,
  1810. const std::optional<std::string>& actor) {
  1811. // Queue for replication broadcast
  1812. if (replication_ && config_.replicationEnabled) {
  1813. databasepb::ReplicationEntry entry;
  1814. entry.set_collection(collection);
  1815. entry.set_document_id(id);
  1816. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  1817. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  1818. // is now treated by receivers as "legacy / unknown origin".
  1819. entry.set_node_id(config_.nodeId);
  1820. entry.set_global_timestamp(
  1821. std::chrono::duration_cast<std::chrono::milliseconds>(
  1822. std::chrono::system_clock::now().time_since_epoch()
  1823. ).count());
  1824. switch (eventType) {
  1825. case EventType::INSERT:
  1826. entry.set_op(databasepb::OP_INSERT);
  1827. // Send the full Document envelope (id, collection, data,
  1828. // version, timestamps, encryption state). The follower's
  1829. // applyReplicatedEntry uses Document::fromJson() which
  1830. // expects this envelope — sending only doc->data silently
  1831. // dropped every user field on the other side.
  1832. if (doc) entry.set_data(doc->toJson().dump());
  1833. break;
  1834. case EventType::UPDATE:
  1835. entry.set_op(databasepb::OP_UPDATE);
  1836. if (doc) entry.set_data(doc->toJson().dump());
  1837. break;
  1838. case EventType::DELETE:
  1839. entry.set_op(databasepb::OP_DELETE);
  1840. break;
  1841. default:
  1842. break;
  1843. }
  1844. replication_->queueForReplication(entry);
  1845. }
  1846. // Publish event
  1847. if (events_) {
  1848. DatabaseEvent event;
  1849. event.type = eventType;
  1850. event.collection = collection;
  1851. event.documentId = id;
  1852. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  1853. std::chrono::system_clock::now().time_since_epoch()
  1854. ).count();
  1855. event.nodeId = config_.nodeId;
  1856. if (actor) {
  1857. event.actor = *actor;
  1858. } else if (doc) {
  1859. event.actor = doc->updatedBy;
  1860. }
  1861. if (doc) {
  1862. event.data = doc->data();
  1863. }
  1864. events_->publish(event);
  1865. }
  1866. }
  1867. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  1868. try {
  1869. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  1870. // with the originating node's id. This is what makes follower-side
  1871. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  1872. // replicated documents. Echo amplification is prevented by:
  1873. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  1874. // - SyncProtocol skipping entries whose origin is the peer itself
  1875. // both implemented in the same v1.8.0 cycle.
  1876. const std::string origin = entry.node_id().empty()
  1877. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  1878. : entry.node_id();
  1879. switch (entry.op()) {
  1880. case databasepb::OP_INSERT:
  1881. case databasepb::OP_UPDATE:
  1882. case databasepb::OP_UPSERT: {
  1883. if (entry.data().empty()) {
  1884. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  1885. return;
  1886. }
  1887. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  1888. Document doc = Document::fromJson(json);
  1889. doc.id = entry.document_id();
  1890. doc.nodeId = entry.node_id();
  1891. // loadDocument bypasses the persist-and-broadcast callback to avoid
  1892. // re-replicating; we explicitly write to the WAL right after with
  1893. // the origin-aware overload so eviction/WAL recovery still works.
  1894. store_->loadDocument(entry.collection(), doc);
  1895. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  1896. // MemoryStore persist callback that normally drives the
  1897. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  1898. // channel and reads still hit MemoryStore, so the bypass
  1899. // was harmless. In v2.3 reads are LMDB-first, so a
  1900. // follower that only filled MemoryStore would return
  1901. // empty Find/Get for every replicated doc. Route the
  1902. // entry through the same project-aware mirror the write
  1903. // handlers use.
  1904. if (projects_) {
  1905. auto pc = smartbotic::database::parseProjectCollection(
  1906. entry.collection());
  1907. if (auto* ds = projects_->getOrCreate(pc.project)) {
  1908. std::optional<Document> opt_doc(doc);
  1909. try {
  1910. smartbotic::db::storage::applyDualWriteMirror(
  1911. ds, mirror_healthy_, mirror_drift_count_,
  1912. pc.collection, doc.id, opt_doc, EventType::INSERT);
  1913. } catch (const smartbotic::db::storage::UniqueViolation& e) {
  1914. // v2.11.0 T11 finding 1 — deliberate choice, not an
  1915. // accident of the generic catch below. By this
  1916. // point store_->loadDocument() above has ALREADY
  1917. // put the row into MemoryStore (loadDocument
  1918. // bypasses the persist callback specifically to
  1919. // avoid re-replicating), so unlike every
  1920. // client-facing write path there is no "reject the
  1921. // whole operation" available: the origin node
  1922. // already committed this write and every other
  1923. // follower is expected to converge to it too.
  1924. // Undoing loadDocument here would silently diverge
  1925. // this follower's data from the rest of the
  1926. // cluster over a constraint that may not even
  1927. // exist on the origin (this follower could have
  1928. // declared the unique field locally, after the
  1929. // fact — replication carries no guarantee the
  1930. // origin shares this node's config). So
  1931. // MemoryStore keeps the row — it is the true
  1932. // record of what replication decided — and the
  1933. // mirror is marked unhealthy ON PURPOSE: this is
  1934. // exactly the pre-T11 swallow-and-flip outcome,
  1935. // chosen deliberately for this one caller so an
  1936. // operator sees the drift (and LMDB-first reads
  1937. // fall back to MemoryStore, which has the answer)
  1938. // rather than nothing signalling a permanent gap
  1939. // between the two stores.
  1940. spdlog::error(
  1941. "v2.11 replication: unique constraint violated applying "
  1942. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  1943. "marking the mirror unhealthy so reads fall back instead "
  1944. "of silently disagreeing with MemoryStore",
  1945. entry.collection(), doc.id, e.what());
  1946. mirror_healthy_.store(false, std::memory_order_release);
  1947. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  1948. } catch (const smartbotic::db::storage::MissingParentReference& e) {
  1949. // v2.11.0 T13 — same deliberate swallow-and-flip as
  1950. // the UniqueViolation catch just above, for the same
  1951. // reason: loadDocument() has already committed this
  1952. // row into MemoryStore, the origin already accepted
  1953. // the write, and this follower may not even have the
  1954. // same validate_on_write declaration (or the same
  1955. // parent data) as the origin did at the time it
  1956. // wrote. MemoryStore keeps the row; the mirror is
  1957. // marked unhealthy on purpose so an operator sees
  1958. // the drift and reads fall back to MemoryStore
  1959. // rather than the two stores silently disagreeing.
  1960. spdlog::error(
  1961. "v2.11 replication: validate_on_write rejected applying "
  1962. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  1963. "marking the mirror unhealthy so reads fall back instead "
  1964. "of silently disagreeing with MemoryStore",
  1965. entry.collection(), doc.id, e.what());
  1966. mirror_healthy_.store(false, std::memory_order_release);
  1967. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  1968. }
  1969. }
  1970. }
  1971. if (persistence_) {
  1972. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  1973. ? persistence_->logInsert(entry.collection(), doc, origin)
  1974. : persistence_->logUpdate(entry.collection(), doc, origin);
  1975. if (walSeq > 0) {
  1976. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  1977. }
  1978. }
  1979. spdlog::trace("Applied replicated {} to {}/{} from {}",
  1980. entry.op() == databasepb::OP_INSERT ? "insert" :
  1981. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  1982. entry.collection(), entry.document_id(), entry.node_id());
  1983. break;
  1984. }
  1985. case databasepb::OP_DELETE: {
  1986. store_->remove(entry.collection(), entry.document_id());
  1987. if (persistence_) {
  1988. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  1989. }
  1990. spdlog::trace("Applied replicated delete to {}/{} from {}",
  1991. entry.collection(), entry.document_id(), entry.node_id());
  1992. break;
  1993. }
  1994. case databasepb::OP_CREATE_COLLECTION: {
  1995. CollectionOptions options;
  1996. store_->createCollection(entry.collection(), options);
  1997. if (persistence_) {
  1998. persistence_->logCreateCollection(entry.collection(), options, origin);
  1999. }
  2000. spdlog::trace("Applied replicated create collection {} from {}",
  2001. entry.collection(), entry.node_id());
  2002. break;
  2003. }
  2004. case databasepb::OP_DROP_COLLECTION: {
  2005. store_->dropCollection(entry.collection());
  2006. if (persistence_) {
  2007. persistence_->logDropCollection(entry.collection(), origin);
  2008. }
  2009. spdlog::trace("Applied replicated drop collection {} from {}",
  2010. entry.collection(), entry.node_id());
  2011. break;
  2012. }
  2013. default:
  2014. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  2015. break;
  2016. }
  2017. } catch (const std::exception& e) {
  2018. spdlog::error("Failed to apply replicated entry: {}", e.what());
  2019. }
  2020. }
  2021. void DatabaseService::startGrpcServer() {
  2022. if (config_.listeners.empty()) {
  2023. // Should never hit — parseConfig's back-compat shim always
  2024. // synthesises at least one. Defend anyway.
  2025. throw std::runtime_error("startGrpcServer: no listeners configured");
  2026. }
  2027. const int64_t mb = 1024 * 1024;
  2028. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  2029. config_.grpc.maxReceiveMessageSizeMb,
  2030. config_.grpc.maxSendMessageSizeMb,
  2031. config_.grpc.resourceQuotaMemoryMb,
  2032. config_.grpc.maxConcurrentSubscribeStreams,
  2033. config_.grpc.maxConcurrentFileStreams);
  2034. grpcServers_.reserve(config_.listeners.size());
  2035. for (const auto& listener : config_.listeners) {
  2036. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  2037. grpc::ServerBuilder builder;
  2038. // v2.4 — choose credentials per listener. Plaintext for
  2039. // tls.enabled=false; SslServerCredentials with the operator's
  2040. // cert+key (or an auto-generated self-signed pair) for true.
  2041. std::shared_ptr<grpc::ServerCredentials> creds;
  2042. if (listener.tls.enabled) {
  2043. std::filesystem::path cert_path = listener.tls.cert_path;
  2044. std::filesystem::path key_path = listener.tls.key_path;
  2045. // Resolve cert+key. If either is missing/unreadable AND
  2046. // auto_self_signed_if_missing is set, generate a pair.
  2047. const bool cert_ok = !cert_path.empty()
  2048. && std::filesystem::exists(cert_path);
  2049. const bool key_ok = !key_path.empty()
  2050. && std::filesystem::exists(key_path);
  2051. if (!cert_ok || !key_ok) {
  2052. if (!listener.tls.auto_self_signed_if_missing) {
  2053. throw std::runtime_error(
  2054. "TLS listener " + addr +
  2055. ": cert or key missing and auto_self_signed_if_missing=false");
  2056. }
  2057. const auto out_dir = config_.dataDirectory / "tls";
  2058. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  2059. out_dir, listener.bind);
  2060. cert_path = gen.cert_path;
  2061. key_path = gen.key_path;
  2062. spdlog::warn(
  2063. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  2064. "auto-generated self-signed cert at '{}' (key '{}'). "
  2065. "OK for dev. For production, drop a real cert + key at "
  2066. "the configured cert_path/key_path.",
  2067. addr,
  2068. listener.tls.cert_path.string(),
  2069. listener.tls.key_path.string(),
  2070. cert_path.string(),
  2071. key_path.string());
  2072. }
  2073. auto slurp = [](const std::filesystem::path& p) {
  2074. std::ifstream f(p);
  2075. if (!f) throw std::runtime_error("read " + p.string());
  2076. std::stringstream ss; ss << f.rdbuf();
  2077. return ss.str();
  2078. };
  2079. grpc::SslServerCredentialsOptions sslOpts;
  2080. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  2081. kp.private_key = slurp(key_path);
  2082. kp.cert_chain = slurp(cert_path);
  2083. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  2084. creds = grpc::SslServerCredentials(sslOpts);
  2085. } else {
  2086. creds = grpc::InsecureServerCredentials();
  2087. }
  2088. // v2.4 Stage D — attach the bearer-token auth processor when
  2089. // the listener requires it. The processor validates the
  2090. // `authorization: Bearer <key>` metadata against the listener's
  2091. // configured keys list. gRPC rejects with UNAUTHENTICATED
  2092. // (no per-handler code needed).
  2093. if (listener.auth.required) {
  2094. if (listener.auth.keys.empty()) {
  2095. throw std::runtime_error(
  2096. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  2097. }
  2098. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  2099. // Refuse at startup rather than resolving a policy against a name
  2100. // that means two different callers.
  2101. {
  2102. std::set<std::string> seen;
  2103. for (const auto& k : listener.auth.keys) {
  2104. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  2105. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  2106. throw std::runtime_error(
  2107. "Listener " + addr + ": auth key name '" + k.name +
  2108. "' is reserved. `anonymous` denotes an unauthenticated "
  2109. "caller and `unnamed` denotes a legacy bare key; a real "
  2110. "key must not be able to impersonate either in a policy.");
  2111. }
  2112. if (!seen.insert(k.name).second &&
  2113. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  2114. throw std::runtime_error(
  2115. "Listener " + addr + ": duplicate auth key name '" +
  2116. k.name + "'. A principal must identify one caller, "
  2117. "otherwise a policy written against it is ambiguous.");
  2118. }
  2119. }
  2120. }
  2121. if (!listener.tls.enabled) {
  2122. // gRPC ABORTS the process if an auth metadata processor is
  2123. // attached to insecure credentials
  2124. // (insecure_server_credentials.cc: "assertion failed: 0").
  2125. // This used to be a WARN, which meant a plaintext+auth listener
  2126. // looked merely inadvisable in the config and then killed the
  2127. // server on start with an unexplained assert. Refuse it here
  2128. // with a message that says what to do instead.
  2129. throw std::runtime_error(
  2130. "Listener " + addr + ": auth.required=true requires "
  2131. "tls.enabled=true. gRPC does not support an auth metadata "
  2132. "processor on insecure credentials and will abort the "
  2133. "process. Enable TLS for this listener (set "
  2134. "tls.auto_self_signed_if_missing for a local dev cert), or "
  2135. "drop auth and rely on binding to loopback.");
  2136. }
  2137. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  2138. nk.reserve(listener.auth.keys.size());
  2139. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  2140. creds->SetAuthMetadataProcessor(
  2141. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  2142. std::move(nk)));
  2143. }
  2144. builder.AddListeningPort(addr, creds);
  2145. builder.RegisterService(storageImpl_.get());
  2146. builder.RegisterService(replicationImpl_.get());
  2147. builder.SetMaxReceiveMessageSize(
  2148. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  2149. builder.SetMaxSendMessageSize(
  2150. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  2151. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  2152. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  2153. builder.SetResourceQuota(quota);
  2154. auto server = builder.BuildAndStart();
  2155. if (!server) {
  2156. throw std::runtime_error("Failed to start gRPC server on " + addr);
  2157. }
  2158. // v2.4 Stage B log line — listener identity printed so operators
  2159. // know exactly which interface is exposed with which policy.
  2160. // Stage C/D will extend with TLS + auth status.
  2161. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  2162. addr,
  2163. listener.tls.enabled ? "true" : "false",
  2164. listener.auth.required ? "true" : "false");
  2165. grpcServers_.push_back(std::move(server));
  2166. }
  2167. }
  2168. void DatabaseService::stopGrpcServer() {
  2169. // ⚠ Shutdown() WITHOUT a deadline waits for every in-flight RPC to return,
  2170. // and it does NOT cancel them. `Subscribe` never returns on its own: its
  2171. // handler parks in `while (!context->IsCancelled())`, and that context is
  2172. // cancelled only when the client goes away or a shutdown DEADLINE expires.
  2173. // So a single connected subscriber - the normal state of any consumer using
  2174. // events - hung this call forever.
  2175. //
  2176. // The cost is not just a slow stop. `stop()` calls this FIRST and takes the
  2177. // final snapshot AFTER it, so the hang blocked the snapshot; systemd then
  2178. // SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only
  2179. // replay, which trips auto read-only mode and needs an operator `unlock`.
  2180. // A graceful restart therefore looked like a crash to the next boot.
  2181. //
  2182. // With a deadline, gRPC cancels whatever is still running once it expires,
  2183. // the Subscribe loops observe IsCancelled() and unwind, and shutdown
  2184. // proceeds. The deadline is ABSOLUTE and shared across listeners, so the
  2185. // total wait is bounded by the grace period rather than by
  2186. // grace × listener count.
  2187. //
  2188. // Five seconds: long enough for an ordinary unary RPC in flight to finish
  2189. // (they are milliseconds), short enough that it is invisible next to the
  2190. // final snapshot, which is the part of shutdown that legitimately takes
  2191. // time (~70 s on the largest known dataset).
  2192. // v2.11.2 — tell the parked streaming handlers to return BEFORE asking gRPC
  2193. // to shut down. Subscribe has no work of its own; it waits for the stream to
  2194. // end. Without this signal it learned of the stop only when the deadline
  2195. // below expired and gRPC cancelled it, so every stop paid the full grace
  2196. // period. With it, the streams are usually gone before Shutdown is even
  2197. // called and the deadline is what it should be: a backstop, not the
  2198. // mechanism.
  2199. if (storageImpl_) {
  2200. storageImpl_->beginShutdown();
  2201. }
  2202. constexpr auto kShutdownGrace = std::chrono::seconds(5);
  2203. const auto deadline = std::chrono::system_clock::now() + kShutdownGrace;
  2204. for (auto& server : grpcServers_) {
  2205. if (server) server->Shutdown(deadline);
  2206. }
  2207. grpcServers_.clear();
  2208. }
  2209. } // namespace smartbotic::database