database_service.cpp 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621
  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. // Deprecation log. These knobs control MemoryStore eviction, which
  1558. // is still active for the MemoryStore-side mirror but does NOT bound
  1559. // RSS since v2.0 (LMDB mmap is the dominant RSS contributor). The
  1560. // substrate-level equivalent is the LMDB env mapsize and the OS page
  1561. // cache.
  1562. //
  1563. // They disappear when the write-handler migration deletes MemoryStore
  1564. // (docs/ROADMAP.md, "Pending"). An earlier revision of this comment
  1565. // promised a v2.1 rename to `buffer_pool_size_mb` "per the Phase C
  1566. // plan"; that plan was superseded by LMDB before it was written, no
  1567. // such knob exists, and the rename is not planned.
  1568. for (const char* deprecated : {"max_memory_mb",
  1569. "eviction_threshold_percent",
  1570. "eviction_target_percent",
  1571. "eviction_check_interval_ms",
  1572. "eviction_chunk_size",
  1573. "eviction_chunk_pause_ms",
  1574. "max_eviction_passes_per_trigger",
  1575. "hot_write_floor_ms",
  1576. "memory_priority"}) {
  1577. if (memory.contains(deprecated)) {
  1578. spdlog::warn("v2.0 deprecation: storage.memory.{} is deprecated "
  1579. "and will be removed in v2.1. v2.0 RSS is bounded "
  1580. "by the LMDB env mapsize + OS page cache, not by "
  1581. "MemoryStore eviction. Setting still applied to "
  1582. "the MemoryStore mirror for back-compat.",
  1583. deprecated);
  1584. }
  1585. }
  1586. config.maxMemoryMb = memory.value("max_memory_mb", config.maxMemoryMb);
  1587. config.evictionThresholdPercent = memory.value("eviction_threshold_percent", config.evictionThresholdPercent);
  1588. config.evictionTargetPercent = memory.value("eviction_target_percent", config.evictionTargetPercent);
  1589. config.evictionCheckIntervalMs = memory.value("eviction_check_interval_ms", config.evictionCheckIntervalMs);
  1590. // NEW v1.7.0 eviction tuning (schema-only in T2; runtime use lands in T3/T4)
  1591. config.evictionChunkSize = memory.value("eviction_chunk_size", config.evictionChunkSize);
  1592. config.evictionChunkPauseMs = memory.value("eviction_chunk_pause_ms", config.evictionChunkPauseMs);
  1593. config.maxEvictionPassesPerTrigger = memory.value("max_eviction_passes_per_trigger", config.maxEvictionPassesPerTrigger);
  1594. config.hotWriteFloorMs = memory.value("hot_write_floor_ms", config.hotWriteFloorMs);
  1595. config.memorySoftPercent = memory.value("memory_soft_percent", config.memorySoftPercent);
  1596. config.memoryHardPercent = memory.value("memory_hard_percent", config.memoryHardPercent);
  1597. config.memoryEmergencyPercent = memory.value("memory_emergency_percent", config.memoryEmergencyPercent);
  1598. // v1.7.0 T10 — eviction burst event threshold
  1599. config.evictionBurstThreshold = memory.value("eviction_burst_threshold", config.evictionBurstThreshold);
  1600. // v2.4.3 — eviction drain cap (0 disables)
  1601. config.evictionMaxEpisodePercent = memory.value("eviction_max_episode_percent", config.evictionMaxEpisodePercent);
  1602. }
  1603. // v2.11.0 close-out — TTL sweep budgets. Its own block rather than
  1604. // `memory`, because these bound expiry work per sweep, not memory.
  1605. if (db.contains("ttl")) {
  1606. auto& ttl = db["ttl"];
  1607. config.ttlMaxCandidatesPerSweep =
  1608. ttl.value("max_candidates_per_sweep", config.ttlMaxCandidatesPerSweep);
  1609. config.ttlMaxBlockedRetriesPerSweep =
  1610. ttl.value("max_blocked_retries_per_sweep", config.ttlMaxBlockedRetriesPerSweep);
  1611. config.ttlBlockedRetrySweeps =
  1612. ttl.value("blocked_retry_sweeps", config.ttlBlockedRetrySweeps);
  1613. config.ttlBlockedSummarySweeps =
  1614. ttl.value("blocked_summary_sweeps", config.ttlBlockedSummarySweeps);
  1615. }
  1616. // Persistence settings
  1617. if (db.contains("persistence")) {
  1618. auto& persistence = db["persistence"];
  1619. config.walSyncIntervalMs = persistence.value("wal_sync_interval_ms", config.walSyncIntervalMs);
  1620. config.snapshotIntervalSec = persistence.value("snapshot_interval_sec", config.snapshotIntervalSec);
  1621. config.compressionEnabled = persistence.value("compression", "lz4") != "none";
  1622. // Snapshot durability (NEW in v1.6.1)
  1623. if (persistence.contains("snapshots")) {
  1624. const auto& snap = persistence["snapshots"];
  1625. config.persistenceConfig.validateAfterWrite = snap.value("validate_after_write", config.persistenceConfig.validateAfterWrite);
  1626. config.persistenceConfig.cleanupOnlyIfVerified = snap.value("cleanup_only_if_verified", config.persistenceConfig.cleanupOnlyIfVerified);
  1627. }
  1628. // Recovery (NEW in v1.6.1)
  1629. if (persistence.contains("recovery")) {
  1630. const auto& rec = persistence["recovery"];
  1631. std::string modeStr = rec.value("mode", std::string("normal"));
  1632. try {
  1633. config.persistenceConfig.recoveryMode = recoveryModeFromString(modeStr);
  1634. } catch (const std::exception& e) {
  1635. spdlog::warn("Invalid recovery.mode '{}', defaulting to 'normal': {}",
  1636. modeStr, e.what());
  1637. config.persistenceConfig.recoveryMode = RecoveryMode::Normal;
  1638. }
  1639. config.persistenceConfig.autoEscalate = rec.value("auto_escalate", config.persistenceConfig.autoEscalate);
  1640. config.persistenceConfig.allowEmptyOnFreshInstall = rec.value("allow_empty_on_fresh_install", config.persistenceConfig.allowEmptyOnFreshInstall);
  1641. }
  1642. }
  1643. // File settings
  1644. if (db.contains("files")) {
  1645. auto& files = db["files"];
  1646. config.maxFileSizeMb = files.value("max_file_size_mb", config.maxFileSizeMb);
  1647. // v2.8.0 — this interval now drives the file EXPIRY sweep as well
  1648. // as orphan cleanup, so accept the plainer name too. The original
  1649. // key kept working; nothing read either of them before 2.8.0
  1650. // because there was no sweeper thread at all.
  1651. config.fileCleanupIntervalSec =
  1652. files.value("cleanup_orphans_interval_sec", config.fileCleanupIntervalSec);
  1653. config.fileCleanupIntervalSec =
  1654. files.value("cleanup_interval_sec", config.fileCleanupIntervalSec);
  1655. // v2.8.0 — default retention per file type. The analogue of a
  1656. // collection's defaultTtlSeconds, so retention is an operator
  1657. // setting rather than something every uploader must remember.
  1658. //
  1659. // "default_ttl_seconds": {
  1660. // "acme:generated": 86400, // one project, one type
  1661. // "generated": 604800, // any project
  1662. // "acme:*": 2592000, // every type in one project
  1663. // "*": 0 // everything (0 = keep)
  1664. // }
  1665. if (files.contains("default_ttl_seconds") &&
  1666. files["default_ttl_seconds"].is_object()) {
  1667. for (const auto& [k, v] : files["default_ttl_seconds"].items()) {
  1668. if (v.is_number_unsigned()) {
  1669. config.fileDefaultTtlByType[k] = v.get<uint32_t>();
  1670. }
  1671. }
  1672. }
  1673. if (files.contains("allowed_types")) {
  1674. for (const auto& type : files["allowed_types"]) {
  1675. config.allowedFileTypes.push_back(type.get<std::string>());
  1676. }
  1677. }
  1678. }
  1679. // Encryption settings
  1680. if (db.contains("encryption")) {
  1681. auto& encryption = db["encryption"];
  1682. config.encryptionEnabled = encryption.value("enabled", config.encryptionEnabled);
  1683. config.autoGenerateKey = encryption.value("auto_generate_key", config.autoGenerateKey);
  1684. std::string keyFile = encryption.value("key_file", "");
  1685. if (keyFile.find("${HOME}") != std::string::npos) {
  1686. const char* home = std::getenv("HOME");
  1687. if (home) {
  1688. size_t pos = keyFile.find("${HOME}");
  1689. keyFile.replace(pos, 7, home);
  1690. }
  1691. }
  1692. config.keyFilePath = keyFile;
  1693. }
  1694. // Replication settings
  1695. if (db.contains("replication")) {
  1696. auto& replication = db["replication"];
  1697. config.replicationEnabled = replication.value("enabled", config.replicationEnabled);
  1698. config.conflictResolution = replication.value("conflict_resolution", config.conflictResolution);
  1699. if (replication.contains("peers")) {
  1700. for (const auto& peer : replication["peers"]) {
  1701. config.peerAddresses.push_back(peer.get<std::string>());
  1702. }
  1703. }
  1704. }
  1705. // gRPC settings (v1.6.2 — concurrency cap + configurable message sizes)
  1706. if (db.contains("grpc")) {
  1707. const auto& grpc = db["grpc"];
  1708. config.grpc.maxReceiveMessageSizeMb =
  1709. grpc.value("max_receive_message_size_mb", config.grpc.maxReceiveMessageSizeMb);
  1710. config.grpc.maxSendMessageSizeMb =
  1711. grpc.value("max_send_message_size_mb", config.grpc.maxSendMessageSizeMb);
  1712. config.grpc.resourceQuotaMemoryMb =
  1713. grpc.value("resource_quota_memory_mb", config.grpc.resourceQuotaMemoryMb);
  1714. config.grpc.maxConcurrentSubscribeStreams =
  1715. grpc.value("max_concurrent_subscribe_streams", config.grpc.maxConcurrentSubscribeStreams);
  1716. config.grpc.maxConcurrentFileStreams =
  1717. grpc.value("max_concurrent_file_streams", config.grpc.maxConcurrentFileStreams);
  1718. }
  1719. }
  1720. // v2.4 back-compat shim. If no listeners[] was provided, synthesize
  1721. // one from the legacy bind_address + rpc_port fields. This is what
  1722. // every existing v2.3 deployment will hit on first v2.4 boot —
  1723. // their configs don't know about listeners[] yet, and they get
  1724. // exactly the same listener they had before.
  1725. if (config.listeners.empty()) {
  1726. ListenerConfig legacy;
  1727. legacy.bind = config.bindAddress;
  1728. legacy.port = config.rpcPort;
  1729. legacy.tls.enabled = false;
  1730. legacy.auth.required = false;
  1731. config.listeners.push_back(std::move(legacy));
  1732. }
  1733. return config;
  1734. }
  1735. void DatabaseService::setupComponents() {
  1736. // v2.3 multi-project storage substrate.
  1737. //
  1738. // Each project lives at `<dataDir>/projects/<name>/env/`. The default
  1739. // project always exists and is what v2.0-v2.2 clients (which don't
  1740. // address projects) implicitly use.
  1741. //
  1742. // Pre-2.3 installs have their data at the legacy `<dataDir>/env/`
  1743. // path. migrateLegacyEnvToDefaultProject() detects that layout and
  1744. // atomically moves it under `projects/default/env/` before the
  1745. // registry opens.
  1746. migrateLegacyEnvToDefaultProject();
  1747. try {
  1748. constexpr size_t kMapSize = 4ULL << 30; // 4 GiB per project; LMDB grows lazily.
  1749. constexpr uint32_t kMaxDbs = 1024;
  1750. projects_ = std::make_unique<smartbotic::db::storage::ProjectStoreRegistry>(
  1751. config_.dataDirectory / "projects", kMapSize, kMaxDbs);
  1752. const auto opened = projects_->openExisting();
  1753. spdlog::info("v2.3 storage: opened {} project env(s): [{}]",
  1754. opened.size(),
  1755. [&opened]() {
  1756. std::string s;
  1757. for (size_t i = 0; i < opened.size(); ++i) {
  1758. if (i) s += ", ";
  1759. s += opened[i];
  1760. }
  1761. return s;
  1762. }());
  1763. } catch (const std::exception& e) {
  1764. spdlog::error("v2.3 storage: failed to open project registry at '{}': {} -- "
  1765. "service cannot start without LMDB; bailing",
  1766. (config_.dataDirectory / "projects").string(), e.what());
  1767. projects_.reset();
  1768. throw;
  1769. }
  1770. // Create memory store with eviction config
  1771. MemoryStore::Config storeConfig;
  1772. storeConfig.nodeId = config_.nodeId;
  1773. storeConfig.maxMemoryBytes = config_.maxMemoryMb * 1024ULL * 1024ULL;
  1774. storeConfig.evictionThresholdPercent = config_.evictionThresholdPercent;
  1775. storeConfig.evictionTargetPercent = config_.evictionTargetPercent;
  1776. storeConfig.evictionCheckIntervalMs = config_.evictionCheckIntervalMs;
  1777. // NEW v1.7.0 eviction tuning (wired in T2; consumed in T3/T4).
  1778. storeConfig.evictionChunkSize = config_.evictionChunkSize;
  1779. storeConfig.evictionChunkPauseMs = config_.evictionChunkPauseMs;
  1780. storeConfig.maxEvictionPassesPerTrigger = config_.maxEvictionPassesPerTrigger;
  1781. storeConfig.hotWriteFloorMs = config_.hotWriteFloorMs;
  1782. storeConfig.memorySoftPercent = config_.memorySoftPercent;
  1783. storeConfig.memoryHardPercent = config_.memoryHardPercent;
  1784. storeConfig.memoryEmergencyPercent = config_.memoryEmergencyPercent;
  1785. storeConfig.evictionBurstThreshold = config_.evictionBurstThreshold;
  1786. storeConfig.evictionMaxEpisodePercent = config_.evictionMaxEpisodePercent;
  1787. // v2.11.0 close-out — TTL sweep budgets (storage.ttl).
  1788. storeConfig.ttlMaxCandidatesPerSweep = config_.ttlMaxCandidatesPerSweep;
  1789. storeConfig.ttlMaxBlockedRetriesPerSweep = config_.ttlMaxBlockedRetriesPerSweep;
  1790. storeConfig.ttlBlockedRetrySweeps = config_.ttlBlockedRetrySweeps;
  1791. storeConfig.ttlBlockedSummarySweeps = config_.ttlBlockedSummarySweeps;
  1792. store_ = std::make_unique<MemoryStore>(storeConfig);
  1793. // Create view manager (cache loaded in initialize() after persistence recovery)
  1794. view_manager_ = std::make_unique<ViewManager>(*store_);
  1795. // Create per-collection config manager and attach it to the store so the
  1796. // write paths route document timestamp stamps through it.
  1797. config_manager_ = std::make_unique<CollectionConfigManager>(*store_);
  1798. // v2.8.0 — access policy. Constructed here; its cache is loaded after
  1799. // recovery alongside the view and collection-config caches.
  1800. policy_manager_ = std::make_unique<PolicyManager>(*store_);
  1801. // v2.11.0 T6a — relation declarations. Constructed here; its cache is
  1802. // loaded after recovery alongside the view/config/policy caches.
  1803. relation_manager_ = std::make_unique<RelationManager>(*store_);
  1804. store_->setConfigManager(config_manager_.get());
  1805. // v1.9.0 — disk-resident version history. Replaces the in-heap
  1806. // `CollectionData::versionHistory` deques that were the dominant
  1807. // source of the Zoe untracked-RSS gap. One file per collection at
  1808. // `<dataDir>/history/<collection>.hlog`. Lifecycle: constructed
  1809. // here, wired into the store immediately so snapshot deserializer
  1810. // can migrate pre-v1.9 in-memory history blocks straight to disk.
  1811. HistoryStore::Config histConfig;
  1812. histConfig.dataDir = config_.dataDirectory;
  1813. history_store_ = std::make_unique<HistoryStore>(histConfig);
  1814. store_->setHistoryStore(history_store_.get());
  1815. // v2.3 — wire the LMDB mirror INTO MemoryStore with a project
  1816. // resolver. Every write that flows through store_ commits to the
  1817. // right per-project LMDB env BEFORE the per-collection lock releases.
  1818. if (projects_) {
  1819. auto* registry = projects_.get();
  1820. store_->setDocumentStoreMirror(
  1821. [registry](std::string_view project) -> smartbotic::db::storage::DocumentStore* {
  1822. return registry->getOrCreate(project);
  1823. },
  1824. &mirror_healthy_,
  1825. &mirror_drift_count_);
  1826. mirror_pending_ = std::make_unique<smartbotic::db::storage::MirrorPendingLog>(
  1827. std::filesystem::path(config_.dataDirectory) / "mirror-pending.log");
  1828. store_->setMirrorFailureSink([this](const std::string& collection, const std::string& id) {
  1829. recordMirrorFailure(collection, id);
  1830. });
  1831. }
  1832. // Create persistence manager. Start from any persistenceConfig values the
  1833. // caller (config loader / CLI parser) has already populated — including
  1834. // recoveryMode — and overlay the top-level convenience fields.
  1835. PersistenceManager::Config persistConfig = config_.persistenceConfig;
  1836. persistConfig.dataDir = config_.dataDirectory;
  1837. persistConfig.walSyncIntervalMs = config_.walSyncIntervalMs;
  1838. persistConfig.snapshotIntervalSec = config_.snapshotIntervalSec;
  1839. persistConfig.compressionEnabled = config_.compressionEnabled;
  1840. persistConfig.nodeId = config_.nodeId;
  1841. // Mirror the resolved recoveryMode back into our Config so downstream code
  1842. // (logging, RPC handlers) can inspect config_.persistenceConfig.recoveryMode
  1843. // without having to reach into the PersistenceManager.
  1844. config_.persistenceConfig = persistConfig;
  1845. persistence_ = std::make_unique<PersistenceManager>(persistConfig);
  1846. // Connect store callbacks to persistence - uses setPersistCallback for WAL logging
  1847. store_->setPersistCallback([this](const std::string& collection, const std::string& id,
  1848. const std::optional<Document>& doc, EventType eventType,
  1849. const std::optional<std::string>& actor) {
  1850. // Log to WAL based on event type. v1.7.4: capture the assigned WAL
  1851. // sequence and record it on the store so eviction stubs can carry
  1852. // a real seq (instead of doc.version, which was useless as a
  1853. // `fromSequence` hint and forced a full WAL scan on every fault).
  1854. uint64_t walSeq = 0;
  1855. switch (eventType) {
  1856. case EventType::INSERT:
  1857. if (doc) walSeq = persistence_->logInsert(collection, *doc);
  1858. break;
  1859. case EventType::UPDATE:
  1860. if (doc) walSeq = persistence_->logUpdate(collection, *doc);
  1861. break;
  1862. case EventType::DELETE:
  1863. persistence_->logDelete(collection, id);
  1864. break;
  1865. default:
  1866. break;
  1867. }
  1868. if (walSeq > 0 && (eventType == EventType::INSERT || eventType == EventType::UPDATE)) {
  1869. store_->recordWalSequence(collection, id, walSeq);
  1870. }
  1871. // v2.0 dual-write — moved INTO MemoryStore::mirrorWriteToDocStore so
  1872. // that it runs UNDER the per-collection write lock. That closes the
  1873. // race window where readers could see a doc in MemoryStore but not
  1874. // yet in LMDB. The callback now does only WAL + replication + events.
  1875. // v2.11.0 T12 review (C2) — replication + events extracted into
  1876. // notifyReplicationAndEvents() so relations/relation_cascade.cpp can
  1877. // drive them explicitly too. See that method's doc comment.
  1878. notifyReplicationAndEvents(collection, id, doc, eventType, actor);
  1879. });
  1880. // Set up document load callback for LRU eviction recovery.
  1881. //
  1882. // v1.7.4: walSequence is now a real WAL sequence (set by the persist
  1883. // callback below at append time, not the per-doc version counter).
  1884. // Pass `walSequence - 1` as the exclusive `fromSequence` so replay
  1885. // returns entries with seq >= walSequence — the doc's last write is
  1886. // exactly at walSequence, so the very first hit is the one we want.
  1887. // For docs whose seq is unknown (0 — e.g. loaded from a snapshot
  1888. // that predates v1.7.4), fall back to the full-WAL scan from 0.
  1889. store_->setDocumentLoadCallback([this](const std::string& collection,
  1890. const std::string& id,
  1891. uint64_t walSequence) -> std::optional<Document> {
  1892. // v2.21.0 - LMDB first. The WAL scan below finds an evicted document
  1893. // only while the WAL still holds its last write; a snapshot truncates
  1894. // that, so a document still evicted at the NEXT snapshot could not be
  1895. // read and was written as absent ("will be missing from the
  1896. // snapshot"). The next boot then came up without it while LMDB still
  1897. // had it: 7,219 such rows on one production instance. LMDB holds
  1898. // every write to an evicted document (a write reloads it first), so it
  1899. // is the right source while the mirror is healthy with no drift; the
  1900. // WAL stays the fallback for system collections and a degraded mirror.
  1901. if (projects_ && mirror_healthy_.load(std::memory_order_relaxed) &&
  1902. mirror_drift_count_.load(std::memory_order_relaxed) == 0) {
  1903. try {
  1904. const auto pc = smartbotic::database::parseProjectCollection(collection);
  1905. if (!pc.collection.empty() && pc.collection.front() != '_') {
  1906. if (auto* ds = docStore(pc.project)) {
  1907. if (auto doc = ds->get(pc.collection, id)) {
  1908. doc->collection = collection;
  1909. return doc;
  1910. }
  1911. }
  1912. }
  1913. } catch (const std::exception& e) {
  1914. spdlog::warn("evicted {}/{}: LMDB read failed ({}); trying the WAL",
  1915. collection, id, e.what());
  1916. }
  1917. }
  1918. uint64_t fromSequence = walSequence > 0 ? walSequence - 1 : 0;
  1919. return persistence_->loadDocument(collection, id, fromSequence);
  1920. });
  1921. // Create encryption manager
  1922. EncryptionManager::Config encryptConfig;
  1923. encryptConfig.enabled = config_.encryptionEnabled;
  1924. encryptConfig.keyFilePath = config_.keyFilePath;
  1925. encryptConfig.autoGenerateKey = config_.autoGenerateKey;
  1926. encryption_ = std::make_unique<EncryptionManager>(encryptConfig);
  1927. // Create event manager
  1928. EventManager::Config eventConfig;
  1929. eventConfig.nodeId = config_.nodeId;
  1930. events_ = std::make_unique<EventManager>(eventConfig);
  1931. // Create file manager
  1932. FileManager::Config fileConfig;
  1933. fileConfig.filesDir = config_.dataDirectory / "files";
  1934. fileConfig.maxFileSizeMb = config_.maxFileSizeMb;
  1935. fileConfig.allowedMimeTypes = config_.allowedFileTypes;
  1936. fileConfig.cleanupIntervalSec = config_.fileCleanupIntervalSec;
  1937. fileConfig.defaultTtlSecondsByType = config_.fileDefaultTtlByType;
  1938. files_ = std::make_unique<FileManager>(fileConfig);
  1939. // Create replication manager
  1940. ReplicationManager::Config replConfig;
  1941. replConfig.nodeId = config_.nodeId;
  1942. replConfig.peerAddresses = config_.peerAddresses;
  1943. replConfig.conflictResolution = config_.conflictResolution;
  1944. replication_ = std::make_unique<ReplicationManager>(replConfig);
  1945. // Wire replication entry apply callback
  1946. replication_->setEntryApplyCallback([this](const databasepb::ReplicationEntry& entry) {
  1947. applyReplicatedEntry(entry);
  1948. });
  1949. // Create gRPC implementations
  1950. storageImpl_ = std::make_unique<DatabaseGrpcImpl>(
  1951. *this, *store_, *persistence_, *events_, *files_, *encryption_, *view_manager_, *config_manager_,
  1952. *policy_manager_, *relation_manager_
  1953. );
  1954. // v2.7.0 — hand the impl the union of every listener's keys so it can
  1955. // resolve a principal per call. A token is only accepted if some listener's
  1956. // auth processor accepted it, so the union cannot widen authentication; it
  1957. // only names what was already authenticated.
  1958. {
  1959. std::vector<smartbotic::database::auth::PrincipalResolver::NamedKey> all;
  1960. for (const auto& l : config_.listeners) {
  1961. for (const auto& k : l.auth.keys) all.push_back({k.name, k.key});
  1962. }
  1963. storageImpl_->setPrincipalKeys(std::move(all));
  1964. }
  1965. // v1.6.2 — wire the streaming-RPC concurrency limits from GrpcConfig.
  1966. storageImpl_->setStreamLimits(
  1967. config_.grpc.maxConcurrentSubscribeStreams,
  1968. config_.grpc.maxConcurrentFileStreams);
  1969. storageImpl_->setMaxSendBytes(
  1970. static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024); // v2.13.0
  1971. // v2.13.1 - a stored row must stay readable: the largest body a write may
  1972. // leave behind is the send limit less room for metadata and a vector sent
  1973. // alongside (16 KB at dimension 4096). Enforced on insert/update/upsert/
  1974. // batch bodies and on the RESULT of a patch.
  1975. {
  1976. constexpr size_t kReadMargin = 256 * 1024;
  1977. const size_t send = static_cast<size_t>(config_.grpc.maxSendMessageSizeMb) * 1024 * 1024;
  1978. store_->setMaxDocumentBytes(send > 2 * kReadMargin ? send - kReadMargin : send / 2);
  1979. }
  1980. // v2.16.0 - collection schemas. The check sees the body as the store holds
  1981. // it, so it validates a copy: read metadata and `_vector` removed (neither
  1982. // is a user field), sensitive fields decrypted (a rule about a value must
  1983. // judge the value, not its ciphertext).
  1984. store_->setSchemaCheck([this](const std::string& collection, const nlohmann::json& body) {
  1985. auto entry = schemas_.get(CollectionConfigManager::canonicalKey(collection));
  1986. if (!entry) return;
  1987. const nlohmann::json copy = schemaView(body);
  1988. size_t total = 0;
  1989. auto violations = entry->compiled->validate(copy, 10, &total);
  1990. if (violations.empty()) return;
  1991. const std::string summary = smartbotic::db::schema::summarize(violations, total);
  1992. if (entry->audit) {
  1993. // Rate-limited: an audit run on a busy collection must not flood
  1994. // the log. The counter is exact.
  1995. const uint64_t n = entry->auditViolations.fetch_add(1) + 1;
  1996. if (n <= 20 || (n & (n - 1)) == 0) {
  1997. spdlog::warn("v2.16 schema AUDIT: a write to {} does not conform ({} so far): {}",
  1998. collection, n, summary);
  1999. }
  2000. return;
  2001. }
  2002. entry->refusals.fetch_add(1);
  2003. std::vector<std::string> paths;
  2004. for (const auto& v : violations) paths.push_back(v.path);
  2005. throw SchemaViolation(collection, "schema violation: " + summary, std::move(paths));
  2006. });
  2007. replicationImpl_ = std::make_unique<DatabaseReplicationGrpcImpl>(
  2008. *store_, *replication_, *persistence_
  2009. );
  2010. }
  2011. void DatabaseService::notifyReplicationAndEvents(const std::string& collection,
  2012. const std::string& id,
  2013. const std::optional<Document>& doc,
  2014. EventType eventType,
  2015. const std::optional<std::string>& actor) {
  2016. // Queue for replication broadcast
  2017. if (replication_ && config_.replicationEnabled) {
  2018. databasepb::ReplicationEntry entry;
  2019. entry.set_collection(collection);
  2020. entry.set_document_id(id);
  2021. // v1.8.0 — stamp our nodeId so peers can attribute the write to
  2022. // its actual origin. Pre-v1.8 broadcasts left this empty, which
  2023. // is now treated by receivers as "legacy / unknown origin".
  2024. entry.set_node_id(config_.nodeId);
  2025. entry.set_global_timestamp(
  2026. std::chrono::duration_cast<std::chrono::milliseconds>(
  2027. std::chrono::system_clock::now().time_since_epoch()
  2028. ).count());
  2029. switch (eventType) {
  2030. case EventType::INSERT:
  2031. entry.set_op(databasepb::OP_INSERT);
  2032. // Send the full Document envelope (id, collection, data,
  2033. // version, timestamps, encryption state). The follower's
  2034. // applyReplicatedEntry uses Document::fromJson() which
  2035. // expects this envelope — sending only doc->data silently
  2036. // dropped every user field on the other side.
  2037. if (doc) entry.set_data(doc->toJson().dump());
  2038. break;
  2039. case EventType::UPDATE:
  2040. entry.set_op(databasepb::OP_UPDATE);
  2041. if (doc) entry.set_data(doc->toJson().dump());
  2042. break;
  2043. case EventType::DELETE:
  2044. entry.set_op(databasepb::OP_DELETE);
  2045. break;
  2046. default:
  2047. break;
  2048. }
  2049. replication_->queueForReplication(entry);
  2050. }
  2051. // Publish event
  2052. if (events_) {
  2053. DatabaseEvent event;
  2054. event.type = eventType;
  2055. event.collection = collection;
  2056. event.documentId = id;
  2057. event.timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
  2058. std::chrono::system_clock::now().time_since_epoch()
  2059. ).count();
  2060. event.nodeId = config_.nodeId;
  2061. if (actor) {
  2062. event.actor = *actor;
  2063. } else if (doc) {
  2064. event.actor = doc->updatedBy;
  2065. }
  2066. if (doc) {
  2067. event.data = doc->data();
  2068. }
  2069. events_->publish(event);
  2070. }
  2071. }
  2072. void DatabaseService::applyReplicatedEntry(const databasepb::ReplicationEntry& entry) {
  2073. try {
  2074. // v1.8.0 — also append the replicated entry to the local WAL, tagged
  2075. // with the originating node's id. This is what makes follower-side
  2076. // recovery (eviction → WAL fallback, restart → WAL replay) preserve
  2077. // replicated documents. Echo amplification is prevented by:
  2078. // - GetEntriesSince emitting walEntry.nodeId (not local node id)
  2079. // - SyncProtocol skipping entries whose origin is the peer itself
  2080. // both implemented in the same v1.8.0 cycle.
  2081. const std::string origin = entry.node_id().empty()
  2082. ? config_.nodeId // legacy peer (pre-1.8) — best-guess local
  2083. : entry.node_id();
  2084. switch (entry.op()) {
  2085. case databasepb::OP_INSERT:
  2086. case databasepb::OP_UPDATE:
  2087. case databasepb::OP_UPSERT: {
  2088. if (entry.data().empty()) {
  2089. spdlog::warn("Replication entry has no data for op {}", static_cast<int>(entry.op()));
  2090. return;
  2091. }
  2092. auto json = smartbotic::db::parse_to_nlohmann(entry.data());
  2093. Document doc = Document::fromJson(json);
  2094. doc.id = entry.document_id();
  2095. doc.nodeId = entry.node_id();
  2096. // loadDocument bypasses the persist-and-broadcast callback to avoid
  2097. // re-replicating; we explicitly write to the WAL right after with
  2098. // the origin-aware overload so eviction/WAL recovery still works.
  2099. store_->loadDocument(entry.collection(), doc);
  2100. // v2.3.1 — also mirror to LMDB. loadDocument bypasses the
  2101. // MemoryStore persist callback that normally drives the
  2102. // dual-write mirror; in v2.0-v2.2 the mirror was a side
  2103. // channel and reads still hit MemoryStore, so the bypass
  2104. // was harmless. In v2.3 reads are LMDB-first, so a
  2105. // follower that only filled MemoryStore would return
  2106. // empty Find/Get for every replicated doc. Route the
  2107. // entry through the same project-aware mirror the write
  2108. // handlers use.
  2109. if (projects_) {
  2110. auto pc = smartbotic::database::parseProjectCollection(
  2111. entry.collection());
  2112. if (auto* ds = projects_->getOrCreate(pc.project)) {
  2113. std::optional<Document> opt_doc(doc);
  2114. const uint64_t drift_before =
  2115. mirror_drift_count_.load(std::memory_order_relaxed);
  2116. struct RecordOnDrift { // v2.21.0 - however the block exits
  2117. DatabaseService* self; const std::string& c; const std::string& id;
  2118. uint64_t before;
  2119. ~RecordOnDrift() {
  2120. if (self->mirror_drift_count_.load(std::memory_order_relaxed) > before)
  2121. self->recordMirrorFailure(c, id);
  2122. }
  2123. } recordOnDrift{this, entry.collection(), doc.id, drift_before};
  2124. try {
  2125. smartbotic::db::storage::applyDualWriteMirror(
  2126. ds, mirror_healthy_, mirror_drift_count_,
  2127. pc.collection, doc.id, opt_doc, EventType::INSERT);
  2128. } catch (const smartbotic::db::storage::UniqueViolation& e) {
  2129. // v2.11.0 T11 finding 1 — deliberate choice, not an
  2130. // accident of the generic catch below. By this
  2131. // point store_->loadDocument() above has ALREADY
  2132. // put the row into MemoryStore (loadDocument
  2133. // bypasses the persist callback specifically to
  2134. // avoid re-replicating), so unlike every
  2135. // client-facing write path there is no "reject the
  2136. // whole operation" available: the origin node
  2137. // already committed this write and every other
  2138. // follower is expected to converge to it too.
  2139. // Undoing loadDocument here would silently diverge
  2140. // this follower's data from the rest of the
  2141. // cluster over a constraint that may not even
  2142. // exist on the origin (this follower could have
  2143. // declared the unique field locally, after the
  2144. // fact — replication carries no guarantee the
  2145. // origin shares this node's config). So
  2146. // MemoryStore keeps the row — it is the true
  2147. // record of what replication decided — and the
  2148. // mirror is marked unhealthy ON PURPOSE: this is
  2149. // exactly the pre-T11 swallow-and-flip outcome,
  2150. // chosen deliberately for this one caller so an
  2151. // operator sees the drift (and LMDB-first reads
  2152. // fall back to MemoryStore, which has the answer)
  2153. // rather than nothing signalling a permanent gap
  2154. // between the two stores.
  2155. spdlog::error(
  2156. "v2.11 replication: unique constraint violated 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. } catch (const smartbotic::db::storage::MissingParentReference& e) {
  2164. // v2.11.0 T13 — same deliberate swallow-and-flip as
  2165. // the UniqueViolation catch just above, for the same
  2166. // reason: loadDocument() has already committed this
  2167. // row into MemoryStore, the origin already accepted
  2168. // the write, and this follower may not even have the
  2169. // same validate_on_write declaration (or the same
  2170. // parent data) as the origin did at the time it
  2171. // wrote. MemoryStore keeps the row; the mirror is
  2172. // marked unhealthy on purpose so an operator sees
  2173. // the drift and reads fall back to MemoryStore
  2174. // rather than the two stores silently disagreeing.
  2175. spdlog::error(
  2176. "v2.11 replication: validate_on_write rejected applying "
  2177. "{}/{}: {} - MemoryStore holds the row, LMDB does not; "
  2178. "marking the mirror unhealthy so reads fall back instead "
  2179. "of silently disagreeing with MemoryStore",
  2180. entry.collection(), doc.id, e.what());
  2181. mirror_healthy_.store(false, std::memory_order_release);
  2182. mirror_drift_count_.fetch_add(1, std::memory_order_relaxed);
  2183. }
  2184. }
  2185. }
  2186. if (persistence_) {
  2187. uint64_t walSeq = (entry.op() == databasepb::OP_INSERT)
  2188. ? persistence_->logInsert(entry.collection(), doc, origin)
  2189. : persistence_->logUpdate(entry.collection(), doc, origin);
  2190. if (walSeq > 0) {
  2191. store_->recordWalSequence(entry.collection(), doc.id, walSeq);
  2192. }
  2193. }
  2194. spdlog::trace("Applied replicated {} to {}/{} from {}",
  2195. entry.op() == databasepb::OP_INSERT ? "insert" :
  2196. entry.op() == databasepb::OP_UPDATE ? "update" : "upsert",
  2197. entry.collection(), entry.document_id(), entry.node_id());
  2198. break;
  2199. }
  2200. case databasepb::OP_DELETE: {
  2201. store_->remove(entry.collection(), entry.document_id());
  2202. if (persistence_) {
  2203. persistence_->logDelete(entry.collection(), entry.document_id(), origin);
  2204. }
  2205. spdlog::trace("Applied replicated delete to {}/{} from {}",
  2206. entry.collection(), entry.document_id(), entry.node_id());
  2207. break;
  2208. }
  2209. case databasepb::OP_CREATE_COLLECTION: {
  2210. CollectionOptions options;
  2211. store_->createCollection(entry.collection(), options);
  2212. if (persistence_) {
  2213. persistence_->logCreateCollection(entry.collection(), options, origin);
  2214. }
  2215. spdlog::trace("Applied replicated create collection {} from {}",
  2216. entry.collection(), entry.node_id());
  2217. break;
  2218. }
  2219. case databasepb::OP_DROP_COLLECTION: {
  2220. store_->dropCollection(entry.collection());
  2221. if (persistence_) {
  2222. persistence_->logDropCollection(entry.collection(), origin);
  2223. }
  2224. spdlog::trace("Applied replicated drop collection {} from {}",
  2225. entry.collection(), entry.node_id());
  2226. break;
  2227. }
  2228. default:
  2229. spdlog::warn("Unknown replication operation type: {}", static_cast<int>(entry.op()));
  2230. break;
  2231. }
  2232. } catch (const std::exception& e) {
  2233. spdlog::error("Failed to apply replicated entry: {}", e.what());
  2234. }
  2235. }
  2236. void DatabaseService::startGrpcServer() {
  2237. if (config_.listeners.empty()) {
  2238. // Should never hit — parseConfig's back-compat shim always
  2239. // synthesises at least one. Defend anyway.
  2240. throw std::runtime_error("startGrpcServer: no listeners configured");
  2241. }
  2242. const int64_t mb = 1024 * 1024;
  2243. spdlog::info("gRPC config: recv={}MB send={}MB quota={}MB subs={} files={}",
  2244. config_.grpc.maxReceiveMessageSizeMb,
  2245. config_.grpc.maxSendMessageSizeMb,
  2246. config_.grpc.resourceQuotaMemoryMb,
  2247. config_.grpc.maxConcurrentSubscribeStreams,
  2248. config_.grpc.maxConcurrentFileStreams);
  2249. grpcServers_.reserve(config_.listeners.size());
  2250. for (const auto& listener : config_.listeners) {
  2251. const std::string addr = listener.bind + ":" + std::to_string(listener.port);
  2252. grpc::ServerBuilder builder;
  2253. // v2.4 — choose credentials per listener. Plaintext for
  2254. // tls.enabled=false; SslServerCredentials with the operator's
  2255. // cert+key (or an auto-generated self-signed pair) for true.
  2256. std::shared_ptr<grpc::ServerCredentials> creds;
  2257. if (listener.tls.enabled) {
  2258. std::filesystem::path cert_path = listener.tls.cert_path;
  2259. std::filesystem::path key_path = listener.tls.key_path;
  2260. // Resolve cert+key. If either is missing/unreadable AND
  2261. // auto_self_signed_if_missing is set, generate a pair.
  2262. const bool cert_ok = !cert_path.empty()
  2263. && std::filesystem::exists(cert_path);
  2264. const bool key_ok = !key_path.empty()
  2265. && std::filesystem::exists(key_path);
  2266. if (!cert_ok || !key_ok) {
  2267. if (!listener.tls.auto_self_signed_if_missing) {
  2268. throw std::runtime_error(
  2269. "TLS listener " + addr +
  2270. ": cert or key missing and auto_self_signed_if_missing=false");
  2271. }
  2272. const auto out_dir = config_.dataDirectory / "tls";
  2273. auto gen = smartbotic::database::tls_util::generateSelfSignedCert(
  2274. out_dir, listener.bind);
  2275. cert_path = gen.cert_path;
  2276. key_path = gen.key_path;
  2277. spdlog::warn(
  2278. "TLS listener {}: no operator cert at '{}' (or key at '{}'); "
  2279. "auto-generated self-signed cert at '{}' (key '{}'). "
  2280. "OK for dev. For production, drop a real cert + key at "
  2281. "the configured cert_path/key_path.",
  2282. addr,
  2283. listener.tls.cert_path.string(),
  2284. listener.tls.key_path.string(),
  2285. cert_path.string(),
  2286. key_path.string());
  2287. }
  2288. auto slurp = [](const std::filesystem::path& p) {
  2289. std::ifstream f(p);
  2290. if (!f) throw std::runtime_error("read " + p.string());
  2291. std::stringstream ss; ss << f.rdbuf();
  2292. return ss.str();
  2293. };
  2294. grpc::SslServerCredentialsOptions sslOpts;
  2295. grpc::SslServerCredentialsOptions::PemKeyCertPair kp;
  2296. kp.private_key = slurp(key_path);
  2297. kp.cert_chain = slurp(cert_path);
  2298. sslOpts.pem_key_cert_pairs.push_back(std::move(kp));
  2299. creds = grpc::SslServerCredentials(sslOpts);
  2300. } else {
  2301. creds = grpc::InsecureServerCredentials();
  2302. }
  2303. // v2.4 Stage D — attach the bearer-token auth processor when
  2304. // the listener requires it. The processor validates the
  2305. // `authorization: Bearer <key>` metadata against the listener's
  2306. // configured keys list. gRPC rejects with UNAUTHENTICATED
  2307. // (no per-handler code needed).
  2308. if (listener.auth.required) {
  2309. if (listener.auth.keys.empty()) {
  2310. throw std::runtime_error(
  2311. "Listener " + addr + ": auth.required=true but auth.keys is empty");
  2312. }
  2313. // v2.7.0 — a key name is a principal, so it must be unambiguous.
  2314. // Refuse at startup rather than resolving a policy against a name
  2315. // that means two different callers.
  2316. {
  2317. std::set<std::string> seen;
  2318. for (const auto& k : listener.auth.keys) {
  2319. if (k.name != smartbotic::database::auth::kPrincipalUnnamed &&
  2320. smartbotic::database::auth::isReservedPrincipal(k.name)) {
  2321. throw std::runtime_error(
  2322. "Listener " + addr + ": auth key name '" + k.name +
  2323. "' is reserved. `anonymous` denotes an unauthenticated "
  2324. "caller and `unnamed` denotes a legacy bare key; a real "
  2325. "key must not be able to impersonate either in a policy.");
  2326. }
  2327. if (!seen.insert(k.name).second &&
  2328. k.name != smartbotic::database::auth::kPrincipalUnnamed) {
  2329. throw std::runtime_error(
  2330. "Listener " + addr + ": duplicate auth key name '" +
  2331. k.name + "'. A principal must identify one caller, "
  2332. "otherwise a policy written against it is ambiguous.");
  2333. }
  2334. }
  2335. }
  2336. if (!listener.tls.enabled) {
  2337. // gRPC ABORTS the process if an auth metadata processor is
  2338. // attached to insecure credentials
  2339. // (insecure_server_credentials.cc: "assertion failed: 0").
  2340. // This used to be a WARN, which meant a plaintext+auth listener
  2341. // looked merely inadvisable in the config and then killed the
  2342. // server on start with an unexplained assert. Refuse it here
  2343. // with a message that says what to do instead.
  2344. throw std::runtime_error(
  2345. "Listener " + addr + ": auth.required=true requires "
  2346. "tls.enabled=true. gRPC does not support an auth metadata "
  2347. "processor on insecure credentials and will abort the "
  2348. "process. Enable TLS for this listener (set "
  2349. "tls.auto_self_signed_if_missing for a local dev cert), or "
  2350. "drop auth and rely on binding to loopback.");
  2351. }
  2352. std::vector<smartbotic::database::auth::BearerAuthProcessor::NamedKey> nk;
  2353. nk.reserve(listener.auth.keys.size());
  2354. for (const auto& k : listener.auth.keys) nk.push_back({k.name, k.key});
  2355. creds->SetAuthMetadataProcessor(
  2356. std::make_shared<smartbotic::database::auth::BearerAuthProcessor>(
  2357. std::move(nk)));
  2358. }
  2359. builder.AddListeningPort(addr, creds);
  2360. builder.RegisterService(storageImpl_.get());
  2361. builder.RegisterService(replicationImpl_.get());
  2362. builder.SetMaxReceiveMessageSize(
  2363. static_cast<int>(config_.grpc.maxReceiveMessageSizeMb * mb));
  2364. builder.SetMaxSendMessageSize(
  2365. static_cast<int>(config_.grpc.maxSendMessageSizeMb * mb));
  2366. grpc::ResourceQuota quota("smartbotic-db-" + addr);
  2367. quota.Resize(config_.grpc.resourceQuotaMemoryMb * mb);
  2368. builder.SetResourceQuota(quota);
  2369. auto server = builder.BuildAndStart();
  2370. if (!server) {
  2371. throw std::runtime_error("Failed to start gRPC server on " + addr);
  2372. }
  2373. // v2.4 Stage B log line — listener identity printed so operators
  2374. // know exactly which interface is exposed with which policy.
  2375. // Stage C/D will extend with TLS + auth status.
  2376. spdlog::info("gRPC listener up: {} (tls={}, auth_required={})",
  2377. addr,
  2378. listener.tls.enabled ? "true" : "false",
  2379. listener.auth.required ? "true" : "false");
  2380. grpcServers_.push_back(std::move(server));
  2381. }
  2382. }
  2383. void DatabaseService::stopGrpcServer() {
  2384. // ⚠ Shutdown() WITHOUT a deadline waits for every in-flight RPC to return,
  2385. // and it does NOT cancel them. `Subscribe` never returns on its own: its
  2386. // handler parks in `while (!context->IsCancelled())`, and that context is
  2387. // cancelled only when the client goes away or a shutdown DEADLINE expires.
  2388. // So a single connected subscriber - the normal state of any consumer using
  2389. // events - hung this call forever.
  2390. //
  2391. // The cost is not just a slow stop. `stop()` calls this FIRST and takes the
  2392. // final snapshot AFTER it, so the hang blocked the snapshot; systemd then
  2393. // SIGKILLed at TimeoutStopSec=300, and the next boot recovered by WAL-only
  2394. // replay, which trips auto read-only mode and needs an operator `unlock`.
  2395. // A graceful restart therefore looked like a crash to the next boot.
  2396. //
  2397. // With a deadline, gRPC cancels whatever is still running once it expires,
  2398. // the Subscribe loops observe IsCancelled() and unwind, and shutdown
  2399. // proceeds. The deadline is ABSOLUTE and shared across listeners, so the
  2400. // total wait is bounded by the grace period rather than by
  2401. // grace × listener count.
  2402. //
  2403. // Five seconds: long enough for an ordinary unary RPC in flight to finish
  2404. // (they are milliseconds), short enough that it is invisible next to the
  2405. // final snapshot, which is the part of shutdown that legitimately takes
  2406. // time (~70 s on the largest known dataset).
  2407. // v2.11.2 — tell the parked streaming handlers to return BEFORE asking gRPC
  2408. // to shut down. Subscribe has no work of its own; it waits for the stream to
  2409. // end. Without this signal it learned of the stop only when the deadline
  2410. // below expired and gRPC cancelled it, so every stop paid the full grace
  2411. // period. With it, the streams are usually gone before Shutdown is even
  2412. // called and the deadline is what it should be: a backstop, not the
  2413. // mechanism.
  2414. if (storageImpl_) {
  2415. storageImpl_->beginShutdown();
  2416. }
  2417. constexpr auto kShutdownGrace = std::chrono::seconds(5);
  2418. const auto deadline = std::chrono::system_clock::now() + kShutdownGrace;
  2419. for (auto& server : grpcServers_) {
  2420. if (server) server->Shutdown(deadline);
  2421. }
  2422. grpcServers_.clear();
  2423. }
  2424. } // namespace smartbotic::database