database_service.cpp 130 KB

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